I know that you can test for width()
or height()
but what if the element's display property is set to none? What other value is there to check to make sure the element exists?
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. To check if an element which has an id of “div1” exists.
Answer: Use the jQuery . length Propertylength property to determine whether an element exists or not in case if you want to fire some event only if a particular element exists in DOM.
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.
You can use length to see if your selector matched anything.
if ($('#MyId').length) { // do your stuff }
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