How to Check if an Element is a Div using JavaScript

avatar

Borislav Hadzhiev

Mon Jan 10 20222 min read

Check if an Element is a Div using JavaScript #

Use the tagName property to check if an element is a div, e.g. if (div.tagName === 'DIV') {}. The tagName property returns the tag name of the element on which it was accessed. Note that the property returns tag names of DOM elements in uppercase.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box">Box content</div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const box = document.getElementById('box'); if (box.tagName === 'DIV') { console.log('โœ… the element is a div'); } else { console.log('โ›”๏ธ the element is not a div'); }

The tagName property returns the tag name of the element on which it was accessed.

It should be noted that DOM element names are upper-cased. For example, if accessed on an img element, the tagName property would return "IMG".

index.js
const box = document.getElementById('box'); console.log(box.tagName); // ๐Ÿ‘‰๏ธ "DIV"

You could use the String.toLowerCase method to convert the tag name to lowercase.

index.js
const box = document.getElementById('box'); if (box.tagName.toLowerCase() === 'div') { console.log('โœ… the element is a div'); } else { console.log('โ›”๏ธ the element is not a div'); }
This can be a bit more intuitive as readers of your code might get confused by the capitalized DIV string.

If you need to make sure that the value stored in the box variable is not null or undefined before accessing the tagName property, use optional chaining.

index.js
const box = null; if (box?.tagName?.toLowerCase() === 'div') { console.log('โœ… the element is a div'); } else { console.log('โ›”๏ธ the element is not a div'); }
You could get a null value back if you provide a non-existent id to the getElementById method or a non-existent selector to the querySelector method.

The optional chaining (?.) operator allows us to short-circuit if the reference points to a null or undefined value.

Instead of throwing an error, the operator short-circuits returning undefined.

In the example above, the else block would run.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee