344

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 5

502

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>"
Sign up to request clarification or add additional context in comments.

3 Comments

I recommend doing it like this: if(elt.nodeName.toLowerCase() === "div") { ... } This way, if for some reason it is no longer returned in uppercase letters (lowercase or mixed), you won't have to change it and this code will still work fine.
In response to @TheCuBeMan, using toLowerCase() means you also need to make sure nodeName exists (if it's at all possible elt is not, in fact, an element): if (elt.nodeName && elt.nodeName.toLowerCase() === 'div') { ... }
what about localName?
76

What about element.tagName?

See also tagName docs on MDN.

4 Comments

According to timestamps you beat me by less than 1 second!
From QuirksMode: My advice is not to use tagName at all. nodeName contains all functionalities of tagName, plus a few more. Therefore nodeName is always the better choice.
@bdukes Are you still here? You say you quote QuirksMode, but I can't find the original text there, and I'm curious what the differences are. As well as localName.
quirksmode.org/dom/core/#t23 looks like 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.
56

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

Is elseif some kind of legacy syntax?
It is not really relevant for the example which is about 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.
24

Sometimes you want element.constructor.name

document.createElement('div').constructor.name
// HTMLDivElement

document.createElement('a').constructor.name
// HTMLAnchorElement

document.createElement('foo').constructor.name
// HTMLUnknownElement

Comments

0

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.