jQuery: Finding duplicate ID's and removing all but the first

前端 未结 8 1552
天涯浪人
天涯浪人 2020-12-13 20:57
    $(\'[id]\').each(function () {

        var ids = $(\'[id=\"\' + this.id + \'\"]\');

        // remove duplicate IDs
        if (ids.length > 1 && id         


        
相关标签:
8条回答
  • 2020-12-13 21:35

    This code is longer than some of the others, but the double-nested loop should make its operation obvious.

    The advantage of this approach is that it only has to scan the DOM to generate the list of elements with an id attribute once, and then uses the same list to find (and remove) the duplicates.

    Elements that were already removed will have parentNode === null so can be skipped while iterating over the array.

    var $elems = $('[id]');
    var n = $elems.length;
    
    for (var i = 0; i < n; ++i) {
        var el = $elems[i];
        if (el.parentNode) {  // ignore elements that aren't in the DOM any more
            var id = el.id;
            for (var j = i + 1; j < n; ++j) {
                var cmp = $elems[j];
                if (cmp.parentNode && (cmp.id === id)) {
                    $(cmp).remove();  // use jQuery to ensure data/events are unbound
                }
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-13 21:36

    Try Using The below function Works fine for me:

     $('#favourities-ajax ul li').each(function(i) {
          $('[id="' + this.id + '"]').slice(1).remove();
          });
    
    0 讨论(0)
提交回复
热议问题