Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

dom

People also ask

What is the type of HTML element in JavaScript?

The Element type represents an XML or HTML element, providing access to information such as its tag name, children, and attributes. the element's tag name. may be a Document or Element.

What are the ways to finding HTML elements in JavaScript?

HTML elements can be retrieved using CSS selectors in two ways. The querySelector() method returns the first element that matches the particular CSS selector. The querySelectorAll() method returns all element that matches the particular CSS selector. To use id/class as a parameter users have to add the '#'/'.

Can you get element by type in JavaScript?

Use the querySelectorAll() method to get all elements by type, e.g. document. querySelectorAll('input[type="text"]') . The method returns a NodeList containing the elements that match the provided selector.


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>"

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.


Sometimes you want element.constructor.name

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

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

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