Removal of one element with the same id



  • There's this:

    <div id="block">
      <p id="p_1">text</p>
      <p id="p_2">text</p>
      <p id="p_3">text</p>
      <p id="p_3">text</p> // <---------
      ....
    </div>
    

    So there can be 2 p with the same id, how can jquery remove the same element and leave the 1st? If there's no way in the id, there's a class version:

    <div id="block">
      <p class="p_1">text</p>
      <p class="p_2">text</p>
      <p class="p_3">text</p>
      <p class="p_3">text</p>
      ....
    </div>
    


  • With classes:

    $('.p_3:not(:first)').remove();
    

    C id e.g.:

    var tmp = $('#p_3').removeAttr('id');
    while ($('#p_3').length) {
        $('#p_3').remove();
    }
    tmp.attr('id', 'p_3');
    

    Completed

    Decision to search and remove repetitive elements id:

    $('[id]').each(function() {
        var idAttr = $(this).attr('id'),
            selector = '[id=' + idAttr + ']';
        if ($(selector).length > 1) {
            $(selector).not(':first').remove();  
        }
    });
    



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2