Categories
JavaScript Answers

How to check if element is a div with JavaScript?

Spread the love

Sometimes, we want to check if element is a div with JavaScript.

In this article, we’ll look at how to check if element is a div with JavaScript.

How to check if element is a div with JavaScript?

To check if element is a div with JavaScript, we can check the tagName property of the element.

For instance, we write

const myElement = document.getElementById("myElementId");

if (myElement.tagName === "DIV") {
  alert("is a div");
} else {
  alert("is not a div");
}

to select the element with getElementById.

Then we check if the myElement.tagName property returns 'DIV'.

If it is, then myElement is a div.

Conclusion

To check if element is a div with JavaScript, we can check the tagName property of the element.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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