I need a way to determine the type of an HTML element in JavaScript. It has the ID, but the element itself could be a <div>, a <form> field, a <fieldset>, etc. How can I achieve this?
5 Answers
nodeName is the attribute you are looking for. For example:
var elt = document.getElementById('foo');
console.log(elt.nodeName);
Note that nodeName returns the element name capitalized and without the angle brackets, which means that if you want to check if an element is an <div> element you could do it as follows:
elt.nodeName == "DIV"
While this would not give you the expected results:
elt.nodeName == "<div>"
3 Comments
if (elt.nodeName && elt.nodeName.toLowerCase() === 'div') { ... }localName?What about element.tagName?
See also tagName docs on MDN.
4 Comments
localName.nodeName also provides the name of attribute, text, and comment nodes, in addition to tags/elements. I believe localName is from the XML APIs. If you know you're always dealing with an element there's probably not a lot of difference, but nodeName is the more versatile option.You can use generic code inspection via instanceof:
var e = document.getElementById('#my-element');
if (e instanceof HTMLInputElement) {} // <input>
else if (e instanceof HTMLSelectElement) {} // <select>
else if (e instanceof HTMLTextAreaElement) {} // <textarea>
else if ( ... ) {} // any interface
Look here for a complete list of interfaces.
2 Comments
elseif some kind of legacy syntax?instanceof, but you might want to check out this SO thread about elseif. I've changed my answer and added spaces between else and if.You can query the constructor of an element. See snippet for an idea.
See also: a handy library to determine the type of nearly anything in ES.
console.log(
[
`document.querySelector("#root") is a => ${
getElementType(document.querySelector("#root"))}`,
`document.querySelector("#span") is a => ${
getElementType(document.querySelector("#span"))}`,
`document.querySelector("#ul") is a => ${
getElementType(document.querySelector("#ul"))}`,
`document.querySelector("#ul li") is a => ${
getElementType(document.querySelector("#ul li"))}`,
`document.querySelector("br") is a => ${
getElementType(document.querySelector("br"))}`
].join(`\n`)
);
function getElementType(element) {
switch(true) {
case !!element?.constructor:
const elemType = String(element?.constructor)
.split(/function|\(/)[1].trim();
return `${elemType} (<${
elemType.replace(/(^HTML)(.+)(Element$)/, "$2")
.replace(/list/i, `L`).toUpperCase()}>)`;
default: return "Unknown";
}
}
<div id="root">
ROOT
<br>
<span id="span">span#span</span>
<ul id="ul">
<li>ul#ul first li</li>
<li>ul#ul second li</li>
</ul>
</div>