简体   繁体   中英

How can I loop through every div that starts with a specific string using jQuery?

I am trying to loop through every div that start with the word "Held" and check remove it if it does not exists into another object.

Here is what I have done

$.each($("div[id^='Held']"), function(key, val){
    var divName = $(this).attr('id');
    var uniqueId = divName.replace('Held', '');

    if ($.inArray(uniqueId, data.onHold) === -1){

        $('#' + ivName).remove();
    }
});

I also tried this syntax

$("div[id^='Held']").each(function(key, val){

    var divName = $(this).attr('id');
    var uniqueId = divName.replace('Held', '');

    if ($.inArray(uniqueId, data.onHold) === -1){

        $('#' + ivName).remove();
    }
});

but it is not removing the div as expected

The issue was is when searching in an item is in array. My Array had an object in each one of its value.

Here is what I have done to correct this issue

//This will search for all div with Id starts with "Held" and it will loop through them
$("div[id^='Held']").each(function(){

    var divName = this.id;
    var uniqueId = divName.replace('Held', '');

    if ( isItemExists(uniqueId, data.onHold, 'interactionId') ){
        this.remove();
    }
});

// This function will find a value inside a
function isItemExists(needle, haystack, elementKey){
    return $.grep(haystack, function(item){
      return item.elementKey== needle;
    });
};

I would do it using the key parameter:

var elms = $("div[id^='Held']");

elms.each(function(key, val){

    var divName = $(this).attr('id');
    var uniqueId = divName.replace('Held', '');

    if ($.inArray(uniqueId, data.onHold) === -1){

        elms.eq(key).remove();
    }
});

There's no need to use a selector when you already have the element you want to remove in a variable.

$("div[id^='Held']").each(function(){

    var divName = this.id;
    var uniqueId = divName.replace('Held', '');

    if ($.inArray(uniqueId, data.onHold) === -1){
        $(this).remove();
    }
});

You could also use .filter :

$("div[id^='Held']").filter(function() {
    var uniqueId = this.id.replace('Held', '');
    return $.inArray(uniqueId, data.onHold) === -1;
}).remove();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM