javascript get element's tag

Patrick Lorio picture Patrick Lorio · May 10, 2012 · Viewed 66.6k times · Source

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;
}

Answer

Joe picture Joe · May 10, 2012

HTMLElement.tagName

var element = document.getElementById('myImgElement');
console.log('Tag name: ' + element.tagName);
// Tag name: IMG

NOTE: It returns tags in capitals. E.g. <img /> will return IMG.