Borislav Hadzhiev
Mon Jan 10 2022·2 min read
Photo by Eberhard Grossgasteiger
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.
<!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.
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"
.
const box = document.getElementById('box'); console.log(box.tagName); // 👉️ "DIV"
You could use the String.toLowerCase method to convert the tag name to lowercase.
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'); }
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.
const box = null; if (box?.tagName?.toLowerCase() === 'div') { console.log('✅ the element is a div'); } else { console.log('⛔️ the element is not a div'); }
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.