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?
This question is related to
javascript
dom
What about element.tagName
?
See also tagName
docs on MDN.
Sometimes you want element.constructor.name
document.createElement('div').constructor.name
// HTMLDivElement
document.createElement('a').constructor.name
// HTMLAnchorElement
document.createElement('foo').constructor.name
// HTMLUnknownElement
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.
What about element.tagName
?
See also tagName
docs on MDN.
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.
What about element.tagName
?
See also tagName
docs on MDN.
Source: Stackoverflow.com