Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript get element's tag

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; } 
like image 322
Patrick Lorio Avatar asked May 10 '12 17:05

Patrick Lorio


People also ask

How do I find an 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.

How do I get a tag name?

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.

How do I get the HTML element?

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


1 Answers

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.

like image 177
Joe Avatar answered Sep 17 '22 03:09

Joe