1

I want to remove all input labels with same class except one in div #tikersDiv. I got this script but it doesn't work:

  $('#tikersDiv').children('label').each(function(i){
  let removed = $('#id_' + (++i)).children('label').each(function(){
     $(this).remove();
  });
  $(this).append($(removed[0]).html());
  $(this).append($(removed[3]).html());
});
stack
  • 67
  • 7
  • Can't use class name? $('#tiketsDiv').children('.classname').remove(); https://stackoverflow.com/questions/4223141/using-jquery-to-delete-all-elements-with-a-given-id – 이승현 May 21 '22 at 13:55
  • Ids _must_ be unique. Two elements _cannot_ share the same id. Use a class instead. – Andy May 21 '22 at 14:04
  • @이승현 I need to delete all duplicates, not with particular class. All inputs are added with php so there will be much more duplicates in future, all of them should be removed with one function. – stack May 21 '22 at 14:27
  • @Andy I know. That's why I need to delete all duplicates. And yeas, I can select them with class , duplicates have identical class too – stack May 21 '22 at 14:29
  • Then you should fix the output from your PHP so you don't have duplicate ids. – Andy May 21 '22 at 14:30
  • Also see: [Does ID have to be unique in the whole page?](https://stackoverflow.com/questions/9454645/does-id-have-to-be-unique-in-the-whole-page) And the answer has changed since html5. – Yogi May 21 '22 at 14:33
  • @Andy check my solution – stack May 21 '22 at 15:30

1 Answers1

0

Ok, I've got this. If anybody want to remove all child elements with same class except one in div, just use this script. I hope I will help somebody

var classes = $('#tikersDiv label').map(function(){
    return $(this).attr('class');
    }).get();

$.each(classes, function(value, index){
     $('#tikersDiv').find('.' + index + ':not(:eq(0))').remove();
     });
stack
  • 67
  • 7