javascript get element's tag

JavascriptHtmlTags

Javascript Problem Overview


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 Solutions


Solution 1 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPatrick LorioView Question on Stackoverflow
Solution 1 - JavascriptJoeView Answer on Stackoverflow