Categories
JavaScript Answers

How to Check if an Element is a Div with JavaScript?

Spread the love

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

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

Check if an Element is a Div with JavaScript

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

For instance, if we have the following HTML:

<div>
  foo
</div>
<p>
  bar
</p>

Then we can write:

for (const el of document.querySelectorAll('*')) {
  if (el.tagName.toLowerCase() === "div") {
    //it's a div
    console.log(el)
  } else {
    //it's not a div
  }
}

to select all the elements in the HTML with document.querySelectorAll and loop through the selected elements with the for-of loop.

Then in the loop body, we get the tag name of each element with the tagName property.

We call toLowerCase to convert the tag name to lower case.

Then we can check if el is a div by comparing it against 'div' .

If it’s a div, then we log it.

And we should see the div in the console log.

Conclusion

To check if an element is a div with JavaScript, we can get the tagName property of an 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 *