Jquery check if li with id = x already exists in ul

I have a lot of UL with li. Different ULs will have li with the same identifier:

<ul> <li id='1'>this</li> <li id='2'>that</li> </ul> <ul> <li id='1'>this</li> </ul> 

The user can drag li from the list to another, but only if li with the same identifier does not exist. So far I have this:

 $(".container").droppable({ drop: function (event, ui) { var a = $(this).find("li").attr("id", $(ui.draggable).attr('id')); if (a.length == 0) { $.ajax({ ... }); } } }); 

However, when I drop the draggable, it changes the id of all li to the value of the reset li.

Any guidance would be great. Thanks.

+4
source share
2 answers

Using attr() , you actually set the id attribute for any elements matching your find() call. You should use find in the ID that you match.

 $(".container").droppable({ drop: function (event, ui) { var a = $(this).find("#" + $(ui.draggable).attr('id')); if (a.length === 0) { $.ajax({ ... }); } } }); 

Also, as @Diodeus mentions, identifiers should not start with a number. They should also be unique documents, so if you need duplicate / expect identifiers, I would recommend using a different attribute, such as the HTML5 data attribute: http://ejohn.org/blog/html-5-data-attributes/

+1
source

Identifiers cannot begin with numbers and must be unique. For non-identical identifiers, use classes.

You can check if such an element exists:

 if($('#myDIV').length) { } 
+7
source

Source: https://habr.com/ru/post/1347908/


All Articles