How to check if an html element exists or not using jQuery?
We can check an html element’s existence through checking its length. If length is greater than 0 that means element exist and if 0 that means does not exist.
Let’s see with an example:
<span id="testId">Let's learn together.</span>
Let’s see the jQuery code :
// Checking for an element which exist.
if( $( "#testId" ).length() > 0 ){
console.log("testId Exists")
} else {
console.log("testId does not Exists").
}
// Checking for another element which does not exist. (Just for better understanding)
if( $( "#testCheckId" ).length() > 0 ){
console.log("testCheckId Exists")
} else {
console.log("testCheckId does not Exists").
}
Output:testId Exists
testCheckId does not Exists
Here we checked through id
but we can also use others like class
.