Check if div element with class name exists in JavaScript

In this tutorial, we are going to check if div element with a specific class name exists or not in JavaScript. The JavaScript program we are going to write for the browser will able to detect if one or more div element with the class name exists or not.

To do the task, here we are going to use the getElementsByClassName method of Document interface. The method will be able to return an array-like object of all child elements which have all of the given class names.

JavaScript code to check if the element with class name exists

Below is our JavaScript code where we have used the getElementsByClassName of DOM:

const classList = document.getElementsByClassName("className");

const classLength = classList.length;

if (classLength != 0) {
  console.log("Element found with the specified class name");
} else {
  console.log("No element found with the specified class name");

In the above code, we have passed the class name “className”. If there will be any div element with this specific class name, then we will see “Element found with the specified class name” in the console. Otherwise, it will show the message “No element found with the specified class name”.

Also, read: How we can generate QR code in JavaScript for the web quickly

So what we did actually in our code?

Here we are actually checking the length that is in the array-like object. If there will know element found with the class “className”, it will return 0. If one or more elements found with that class name, then it will return the number of elements with that class.

Just by checking, if the returned length is 0 or not using JavaScript if-else statement, we can easily detect if the element exists or not having the specific class name.

I hope, you understood the procedure that we did. Happy coding…

Leave a Reply

Your email address will not be published. Required fields are marked *