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>');
});
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".
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.
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.
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.
Use not and has
$('#listItem:not(:has(.greenCheckMark))')
.append('<span class="greenCheckMark"></span>');
You could just look for it?
($('.greenCheckMark', '#listItem').length > 0) ? /* found green check mark in #listItem */ : /* not found */ ;
EDIT: Fixed 'un-relatedness' to question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With