I’m new to jQuery and I’m trying to insert a new <li> item in the list, but only if this item does not exist already. For example:
<ul id="myList">
<li>Item 1</li>
<li>Item 2</li>
</ul>
That is, “Item 7” should insert, but not “Item 1”. I´m going crazy over statements like these:
-
var ListItems = $('#myList li').find('Something'); -
var ListItems = $('#myList li').html() == 'something'; -
var exist = $('#myList li').each(){ if($(this).html == 'something') return false; });
These pieces of code are only to check if <li> items exist, not to insert in the list. I’m assuming that these options are crazy but I’m trying to learn.
What is the right way? Any advice or suggestions?
Edited to avoid false positives
This will check the elements one by one and the text contained inside must match exactly the text provided.
check example here