Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - how to check if an element exists?

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?

like image 815
A-OK Avatar asked Mar 13 '11 22:03

A-OK


People also ask

How do you check if an element exists or not in 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. To check if an element which has an id of “div1” exists.

How do I check if an element is available?

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.

Does not exist jQuery?

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.


1 Answers

You can use length to see if your selector matched anything.

if ($('#MyId').length) {     // do your stuff } 
like image 103
Bjarki Heiðar Avatar answered Oct 23 '22 19:10

Bjarki Heiðar