Lets say this is my HTML:
<div id="foo"> <input id="goo" value="text" /> <span id="boo"> </span> </div>
I would like to be able to determine what tag belongs to a html element.
Example element with id "foo" = div
, "goo" = input
, "boo" = span
...
So something like this:
function getTag (id) { var element = document.getElementById(id); return element.tag; }
JavaScript – Tag Name of an HTML Element To get the tag name of a specific HTML Element as a string, using JavaScript, get reference to this HTML element, and read the tagName property of this HTML Element. tagName is a read only property that returns the tag name of this HTML Element as a string.
Introduction to JavaScript getElementsByTagName() method The getElementsByTagName() is a method of the document object or a specific DOM element. The getElementsByTagName() method accepts a tag name and returns a live HTMLCollection of elements with the matching tag name in the order which they appear in the document.
If you want to find all HTML elements that match a specified CSS selector (id, class names, types, attributes, values of attributes, etc), use the querySelectorAll() method. This example returns a list of all <p> elements with class="intro" .
HTMLElement.tagName
const element = document.getElementById('myImgElement'); console.log('Tag name: ' + element.tagName); // Tag name: IMG
<img src="http://placekitten.com/200/200" id="myImgElement" alt="">
NOTE: It returns tags in capitals. E.g. <img />
will return IMG
.
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