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:
Facing issues? Have Questions? Post them here! I am happy to answer!
Author Info:
Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.
Follow him on: X
You can also reach out to him via e-mail: rakesh@code2care.org
More Posts related to jQuery,
- jQuery: Check if an element exists or not
- [jQuery] Uncaught ReferenceError: $ is not defined at index.html:5
- Make div element draggable using jQuery
- jQuery : Move to top of the page
- Dynamically Obtaining Browser Screen Width and Height with jQuery [Updated 2023]
- How to check if an element is hidden using jQuery code?
- Redirect page using jQuery
- Disable jQuery button after being click
More Posts:
- Elegant CSS Box Shadows Ideas - CSS
- Outlook - The mailbox isn't available. This may have occurred because the license for the mailbox has expired. - Microsoft
- How to change the tab color on Microsoft Excel on Mac - MacOS
- Understanding and Handling NullPointerException in Java: Tips and Tricks for Effective Debugging - Java
- How to create a dictionary comprehension in Python - Python
- Spring 5 IoC Example with application Context XML (ClassPathXmlApplicationContext) and Gradle. - Java
- How to Unzip a file using Python - Python
- How to find the Battery Cycle Count on macOS Ventura - MacOS