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?
Asked
Active
Viewed 2.5e+01k times
270
AdamTheHutt
- 7,707
- 8
- 31
- 33
4 Answers
405
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>"
Michał Perłakowski
- 80,501
- 25
- 149
- 167
pkaeding
- 34,628
- 30
- 98
- 139
-
42I 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. – TheCuBeMan Oct 20 '14 at 15:39
-
13In 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') { ... }` – Erik Koopmans Nov 06 '17 at 07:10
-
what about `localName`? – bomba Sep 13 '18 at 09:03
59
What about element.tagName?
See also tagName docs on MDN.
Michał Perłakowski
- 80,501
- 25
- 149
- 167
Brian Cline
- 19,664
- 6
- 25
- 25
-
6
-
32From 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 Oct 31 '08 at 17:38
27
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.
Code4R7
- 2,306
- 1
- 16
- 39
13
Sometimes you want element.constructor.name
document.createElement('div').constructor.name
// HTMLDivElement
document.createElement('a').constructor.name
// HTMLAnchorElement
document.createElement('foo').constructor.name
// HTMLUnknownElement
golopot
- 8,948
- 5
- 32
- 44