- How to Check if Element Exists Using jQuery
- Checking the Existence of an HTML Element Using jQuery With a Click
- How to Check if An Element Doesn’t Exist with jQuery
- Other Articles You’ll Also Like:
- About The Programming Expert
- How to Check if a DOM element exists using JavaScript
- How to check if an element exists in the DOM using JavaScript
- Conclusion
- How to check if an element exists in JavaScript (with examples)
- Psssst! Do you want to learn web development in 2023?
- Check if an element exists in NodeList objects
- Final notes
- ❤️ You might be also interested in:
- JavaScript: How to check if an element exists in the DOM
- Learn JavaScript for Beginners 🔥
- About
- Search
- Tags
How to Check if Element Exists Using jQuery
To check if an element exists using jQuery, the simplest way is to use the length property.
Let’s say I have the following HTML:
To check if the div with id “div” exists, we can use the jQuery length method to do this with the following Javascript code:
If $(“#div”).length is 0, then #div does not exist – and we shouldn’t try to do anything with it. If $(“#div”).length is not 0, then #div exists and we can perform other operations on the element.
If you are using WordPress, don’t forget to change the $ to jQuery as below:
Checking the Existence of an HTML Element Using jQuery With a Click
Many times when creating a web page and the user experience, we want to check the existence of various html elements based on an interaction with another element on the web page.
We can check using jQuery very easily by combining the length property with a click event.
Let’s say we have the following HTML code and we want to check to see if there is a paragraph with id “check-me”.
We can utilize both the jQuery click() method
and jQuery length property to check if the paragraph exists.
Below is the Javascript code which will allow the user to be check if the element exists:
The final code and output for this example of how to check if an element exists on click using jQuery and Javascript is below. In the example below, after clicking, you will see that the span updates because “check-me” exists.
Click me to check if the paragraphs “check-me” exists
This is the paragraph “check-me”.
How to Check if An Element Doesn’t Exist with jQuery
Many times when designing a web page, we also need to add elements which don’t exist. If an element doesn’t exist, then we need to add it to the DOM before trying to do anything with it.
Let’s take the same example from above and add a little more to it.
First, if “check-me” exists, let’s change the background color of the parent div.
Let’s also check if an element with id “check-me-too” exists. If “check-me-too” doesn’t exist, let’s add the element after the last “check-me” paragraph.
To check if an element doesn’t exist, we can check if the jQuery length property is equal to 0.
The resulting Javascript code to do both checks would be:
$("#click-me").click(function() < if($("#check-me").length) < $("#div").css("background-color","green") // change background color >if($(#check-me-too").length === 0) < // if this does NOT exist $("p").add("Check me too now exists!
").insertAfter("#check-me"); > >);
The final code and output for this example of how to check if an element doesn’t exist on click using jQuery and Javascript is below:
Click me to check if the paragraphs “check-me” and “check-me-too” exist
This is the paragraph “check-me”
Hopefully this article has been useful for you to understand how to use jQuery to check if an element exists.
Other Articles You’ll Also Like:
- 1. Using jQuery to Add CSS Important Style
- 2. Using jQuery to Count Children of an Element
- 3. jQuery Random Number Generator Between Two Numbers
- 4. onclick this jQuery
- 5. Using jQuery to Remove Class from an HTML Element
- 6. Using jQuery to Change Image src
- 7. How to Set Checkbox Checked With jQuery
- 8. jQuery rotate – How to Rotate an Image using jQuery
- 9. jQuery text – Set the text of an HTML Element
- 10. Using jQuery to Set the Width of a Div
About The Programming Expert
The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.
Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.
At the end of the day, we want to be able to just push a button and let the code do it’s magic.
You can read more about us on our about page.
How to Check if a DOM element exists using JavaScript
The DOM, standing for Document Object Model, is a tree-like structure that represents the HTML document.
With the rise of front-end libraries like React, Vue, and Angular, it can sometimes be difficult to determine if a DOM element exists.
In this post, we’ll look at all the ways to check if an element exists in the DOM using JavaScript.
How to check if an element exists in the DOM using JavaScript
There are a few ways to check if an element exists in the DOM using JavaScript.
The first one is maybe the most common one, document.getElementById() .
This method takes an id and returns the element with that id, or null if it doesn’t exist.
If you want to use the name of the tag, you can use document.getElementsByTagName() , which returns a list of elements with that tag name.
If you want to get elements by a class, you can use document.getElementsByClassName() , which returns a list of elements with that class name.
Finally, you can alternatively use the versatile document.querySelector() method, which returns the first element that matches the selector.
In this method, you can pass in an ID, class, tag, or any combination.
Conclusion
In this post, we learned how to check if an element exists in the DOM using JavaScript.
We looked at the document.getElementById() , document.getElementsByTagName() , document.getElementsByClassName() , and document.querySelector() methods, all with different valid use cases.
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
Give feedback on this page , tweet at us, or join our Discord !
How to check if an element exists in JavaScript (with examples)
In JavaScript, to check if an element exists or not, you need to access it first. You can use one the following methods to access DOM elements:
- document.getElementById()
- document.getElementByClassName()
- document.querySelector()
- document.querySelectorAll()
Whenever you access a web page, the web browser parses the HTML code and populates a DOM tree of all the elements on the page. It also makes the DOM available to your JavaScript code via the DOM API.
And the document object is the entry to the DOM API.
Psssst! Do you want to learn web development in 2023?
In these four methods, the first two methods return a single DOM element (Element) if the element exists. Otherwise, they return null .
So to check if the element exists in the DOM, you need to check the returned value.
The method document.getElementById() takes a case-sensitive string argument and returns the element whose id property matches the specified string.
If the element doesn’t exist, we’ll get a null value.
html> body> div id="main"> . div> script> let element = document.getElementById('main') if (element !== null) // Do something with the element > script> body> html>
Please note the argument you pass to getElementById() is case-sensitive, meaning main is different from Main .
The document.querySelector() method takes a CSS selector (or selectors) and returns the first element that matches the selector.
This method returns null if no element matches the specified selector.
html> body> div id="main"> article class="post"> span class="post__title"> . span> article> div> script> let element = document.querySelector('#main .post .post__title') if (element != null) // Do something with the element > script> body> html>
Check if an element exists in NodeList objects
Unlike the first two methods, the document.querySelectorAll() method returns a NodeList object.
This NodeList collection can contain zero or multiple elements that match the specified selectors. You can check the number of elements of a NodeList object via its length property.
If the length is zero, it means no elements matches the selector.
html> body> div id="main"> article class="post"> span class="post__title"> . span> article> div> script> let postTitles = document.querySelectorAll('#main .post .post__title') if (postTitles.length) // Do something with the elements > script> body> html>
The document.getElementByClassName() method also returns an array-like object called an HTMLCollection. The HTMLCollection interface has a length property too.
You can convert both NodeList and HTMLCollection objects into arrays with Array.from() methods:
let postTitles = document.querySelectorAll('#main .post .post__title') postTitles = Array.from(postTitles) if (postTitles.length) // Do something with the elements >
Final notes
Always access DOM when the initial HTML document has been completely loaded and parsed. You might get unexpected results if you place your JavaScript code inside the section.
The reason is the browser parses the document from top to bottom, and it might evaluate your JavaScript code before the elements are inserted into the DOM tree.
Additionally, it’s a good practice to place your JavaScript code before the closing body tag (just like the above example).
If you have to place your code before the body tag, you can use the DOMContentLoaded event to ensure your code only runs after the DOM content is loaded:
html> head> script> window.addEventListener('DOMContentLoaded', function () let postTitles = document.querySelectorAll('#main .post .post__title') if (postTitles.length) console.log('found!') // Do something with the elements > >) script> head> body> div id="main"> article class="post"> span class="post__title"> . span> article> div> body> html>
If you get a ReferenceError when accessing the document, check this quick guide on fixing document is not defined error.
I hope these examples simplified the «javascript check if the element exists» problem for you.
Reza Lavarian Hey 👋 I’m a software engineer, an author, and an open-source contributor. I enjoy helping people (including myself) decode the complex side of technology. I share my findings on Twitter: @rlavarian
If you read this far, you can tweet to the author to show them you care.
❤️ You might be also interested in:
JavaScript: How to check if an element exists in the DOM
After you tried to retrieve the element using the selectors above, you can check if the specified element exists or not by checking the value returned by the methods.
Both querySelector() and getElementById() returns null when the element doesn’t exist, so you can check the result as follows:
On the other hand, both getElementsByName() and getElementsByClassName() methods return an array, so you need to check the .length property and see if its value is greater than 0 .
And that’s how you can check whether an element exists in the DOM or not.
Learn JavaScript for Beginners 🔥
Get the JS Basics Handbook, understand how JavaScript works and be a confident software developer.
A practical and fun way to learn JavaScript and build an application using Node.js.
About
Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.
Search
Type the keyword below and hit enter
Tags
Click to see all tutorials tagged with: