Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Detect if element exists

In my code I have the following html that gets appended to a List Item when the user clicks on a specific element.

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

Using jQuery, how would I detect if the element existed, and if so, 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>');
});
like image 931
st4ck0v3rfl0w Avatar asked Jul 29 '10 17:07

st4ck0v3rfl0w


People also ask

How do you check class is exists in jQuery?

jQuery hasClass() Method The hasClass() method checks if any of the selected elements have a specified class name. If ANY of the selected elements has the specified class name, this method will return "true".

How do I check if an element exists with jQuery?

In jQuery, you can use the . length property to check if an element exists. if the element exists, the length property will return the total number of the matched elements.

How do you find if element with specific ID exists or not?

getElementById() to get the ID and store the ID into a variable. Then use JSON. stringify() method on the element (variable that store ID) and compare the element with 'null' string and then identify whether the element exists or not.

How do you check if an element exists or not?

There are two ways to check whether an element in the HTML document exists or not using jQuery. Approach 1: Using the length property in jQuery. If the element exists, then the length property will return the total count of the matched elements with the specified selector.


2 Answers

Use not and has

$('#listItem:not(:has(.greenCheckMark))')
    .append('<span class="greenCheckMark"></span>');
like image 157
Adam Avatar answered Oct 09 '22 05:10

Adam


You could just look for it?

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

EDIT: Fixed 'un-relatedness' to question.

like image 20
TJ Koblentz Avatar answered Oct 09 '22 06:10

TJ Koblentz