How can I determine the type of an HTML element in JavaScript?

JavascriptDom

Javascript 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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAdamTheHuttView Question on Stackoverflow
Solution 1 - JavascriptpkaedingView Answer on Stackoverflow
Solution 2 - JavascriptBrian ClineView Answer on Stackoverflow
Solution 3 - JavascriptCode4R7View Answer on Stackoverflow
Solution 4 - JavascriptgolopotView Answer on Stackoverflow