jQuery: Check if an element exists or not


















We can make use of the .length property in jQuery to know if an element exists or not in the HTML page DOM.

The .lenght property returns a count of the number of elements that are present on the page. If there is no match then the count is zero.


Example:

<div id="welcome">
Welcome to Code2care.org
</div>

<div id="tagline">
Code2dcare - Lines of code for a change!
</div>

<script>
if ($('#welcome').length > 0) {
    console.log("Element exists.");
} else {
    console.log("Element doesn't exist.");
}
</script>
Output:

Element exists.

jQuery - Check if an element exists or not
-

Facing issues? Have Questions? Post them here! I am happy to answer!


Author: Rakesh
Author Info:

Rakesh is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X





























Copyright © Code2care 2023 | Privacy Policy | About Us | Contact Us | Sitemap