Coder Perfect

Check if the element [duplicate] exists in jQuery.

Problem

If an element is created using the.append() method, how can I check if it exists? $(‘elemId’). I’m not a fan of length.

Asked by Nick

Solution #1

You must include a # before the element id:

$('#elemId').length
---^

You don’t require the hash (#) e.g. document in vanilla JavaScript. When using jQuery, though, you must use hash to target components based on id, exactly like you would with CSS.

Answered by Sarfraz

Solution #2

Check the selector’s length; if it returns something, the element must exist; else, it does 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
}

Answered by Tapan kumar

Solution #3

Try this:

if ($("#mydiv").length > 0){
  // do something here
}

If the element does not exist, the length attribute will return zero.

Answered by Gaurav123

Solution #4

if ($("#mydiv").length){  }

If it’s 0, it’ll evaluate to false; if it’s greater than that, it’ll evaluate to true.

There is no need to compare bigger than and less than.

Answered by lfender6445

Solution #5

Because your elemId is an Id attribute, there are just a few things you can perform to see if it exists:

If you’re using vanilla JavaScript, you can use the following selectors:

//you can use it for more advanced selectors
if(document.querySelectorAll("#elemId").length){}

if(document.querySelector("#elemId")){}

//you can use it if your selector has only an Id attribute
if(document.getElementById("elemId")){}

jQuery:

if(jQuery("#elemId").length){}

Answered by Mehran Hatami

Post is based on https://stackoverflow.com/questions/4592493/check-if-element-exists-in-jquery