11

How to check if element exists in jQuery and JavaScript

 2 years ago
source link: https://www.laravelcode.com/post/how-to-check-if-element-exists-in-jquery-and-javascript
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How to check if element exists in jQuery and JavaScript

  403 views

  7 months ago

Javascript

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.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK