Search

How to check if element exists in jQuery and JavaScript

post-title

When you do some change in elements, sometimes you need to make sure that the required element exists, or need to create.

In this short article, i will show you few ways to check if the element exist. You can check it with jQuery or pure Javascript.

Using jQuery

if ($("#myElem").length > 0) {
    // do something awesome...
}

If the element with selector not exists, the element length property will return 0.

Or you even don't need to compare with zero. Same way you can set class selector instead of id.

if ($(".myElem").length) {
    // do something awesome...
}

If element length property is 0, it will return false, anything more than that true.

Using Javascript

Same way, you can also find it with pure Javascript code. 

if(document.querySelectorAll("#myElem").length) {
    // do something awesome...
}

Or Something like this:

if(document.getElementById('myElem')) {
    // do something awesome...
}

Hope you will like it.