JQuery: determine if an element exists

In my code, I have the following html that is added to the list item when the user clicks on a specific item.

<span class="greenCheckMark"></span> 

Using jQuery, how would I determine if this element existed, and if so, do not add another green checkmark?

 $('.clickedElement').live('click',function(){ //does the green check mark exist? if so then do nothing, else $('#listItem).append('<span class="greenCheckMark"></span>'); }); 
+7
jquery jquery-selectors
source share
4 answers

Use not and has

 $('#listItem:not(:has(.greenCheckMark))') .append('<span class="greenCheckMark"></span>'); 
+12
source share

Could you just find him?

 ($('.greenCheckMark', '#listItem').length > 0) ? /* found green check mark in #listItem */ : /* not found */ ; 

EDIT . The "incompatibility" problem has been fixed.

+1
source share
 $('.clickedElement').live('click',function(){ //does the green check mark exist? if so then do nothing, else if($("#listItem span.greenCheckMark").length != 0) { $('#listItem').append('<span class="greenCheckMark"></span>'); } }); 

Well, after a few changes, this should be what you are looking for.

$("#listItem span.greenCheckMark").length != 0 will return an array of JQuery objects, if this area has a length not equal to 0, then it exists. Make sure that you specifically check where you want to check ( $("span.greenCheckMark").length will check the entire document for green checkmarks).

0
source share

According to your requirements, this will only add a <span> if #listItem does not already contain a <span> with a class from greenCheckMark .

 var listItem = $('#listItem'); if ( !listItem.find('span.greenCheckMark')[0] ) { listItem.append('<span class="greenCheckMark"></span>'); } 
0
source share

All Articles