How do I check if an element exists if the element is created by .append()
method? $('elemId').length
doesn't work for me.
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.
In jQuery, you don't need to be worried about checking the existence of any element. If element does not exists, jQuery will do nothing. jQuery provides length property for every element which returns 0 if element doesn't exists else length of the element.
To check if an element is hidden or not, jQuery :hidden selector can be used. .toggle() function is used to toggle the visibility of an element.
$('elemId').length
doesn't work for me.
You need to put #
before element id:
$('#elemId').length ---^
With vanilla JavaScript, you don't need the hash (#
) e.g. document.getElementById('id_here')
, however when using jQuery, you do need to put hash to target elements based on id
just like CSS.
Try to check the length of the selector, if it returns you something then the element must exists else not.
if( $('#selector').length ) // use this if you are using id to check { // it exists } if( $('.selector').length ) // use this if you are using class to check { // it exists }
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