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.
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 '#'/'.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With