How can I determine the type of an HTML element in JavaScript?
JavascriptDomJavascript Problem Overview
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?
Javascript Solutions
Solution 1 - Javascript
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>"
Solution 2 - Javascript
What about element.tagName
?
See also tagName
docs on MDN.
Solution 3 - Javascript
You can use generic code inspection via instanceof
:
var e = document.getElementById('#my-element');
if (e instanceof HTMLInputElement) {} // <input>
elseif (e instanceof HTMLSelectElement) {} // <select>
elseif (e instanceof HTMLTextAreaElement) {} // <textarea>
elseif ( ... ) {} // any interface
Look here for a complete list of interfaces.
Solution 4 - Javascript
Sometimes you want element.constructor.name
document.createElement('div').constructor.name
// HTMLDivElement
document.createElement('a').constructor.name
// HTMLAnchorElement
document.createElement('foo').constructor.name
// HTMLUnknownElement