Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if element exists in jQuery [duplicate]

How do I check if an element exists if the element is created by .append() method? $('elemId').length doesn't work for me.

like image 369
Nick Avatar asked Jan 04 '11 10:01

Nick


People also ask

How do you check if an element exists or not in jQuery?

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.

Does not exist in 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.

How do you check a hidden field exists in jQuery?

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.


2 Answers

$('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.

like image 91
Sarfraz Avatar answered Oct 20 '22 23:10

Sarfraz


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 } 
like image 25
Tapan kumar Avatar answered Oct 20 '22 23:10

Tapan kumar