✋ Update: This post was originally published on my blog decodingweb.dev, where you can read the latest version for a 💯 user experience. ~reza
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.
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.
Here's an example:
<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 <head>
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.
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.
Thanks for reading!
❤️ You might like:
- Cannot find module error in Node.js (Fixed)
- TypeError: map is not a function in JavaScript in JavaScript (Fixed)
- Add commas to numbers in JavaScript (Explained with examples)
- SyntaxError: Unexpected end of JSON input in JavaScript (Fixed)
- How to fix "ReferenceError: document is not defined" in JavaScript
Top comments (1)
Good article!
These are common ways to select DOM nodes in JS.
Thank you