Can jQuery provide the tag name?

JavascriptJquery

Javascript Problem Overview


I've got several elements on a HTML page which have the same class - but they're different element types. I want to find out the tag name of the element as I loop over them - but .attr doesn't take "tag" or "tagname".

Here's what I mean. Consider these elements on a page:

<h1 class="rnd">First</h1>
<h2 id="foo" class="rnd">Second</h2>
<h3 class="rnd">Third</h3>
<h4 id="bar" class="rnd">Fourth</h4>

Now I want to run something like this to ensure that my elements all have an id if one wasn't already defined:

$(function() {
  $(".rnd").each(function(i) {
    var id = $(this).attr("id");
    if (id === undefined || id.length === 0) {
      // this is the line that's giving me problems.
      // .attr("tag") returns undefined
      $(this).attr("id", "rnd" + $(this).attr("tag") + "_" + i.toString());
    }
  });
});

The result I would like would be that the H2 and H4 elements would then have an id of

rndh2_1
rndh4_3

respectively.

Any ideas on how I can discover the tag name of the element represented by "this"?

Javascript Solutions


Solution 1 - Javascript

You could try this:

if($(this).is('h1')){
  doStuff();
}

See the http://docs.jquery.com/Traversing/is#expr">docs</a> for more on is().

Solution 2 - Javascript

$(this).attr("id", "rnd" + $(this).attr("tag") + "_" + i.toString());

should be

$(this).attr("id", "rnd" + this.nodeName.toLowerCase() + "_" + i.toString());

Solution 3 - Javascript

Since I've hit this question once before and it didn't help me in my case (I didn't have a this, but instead had a jQuery selector instance). Calling get() will get you the HTML element, by which you can get the nodeName as mentioned above.

this.nodeName; // In a event handler, 'this' is usually the element the event is called on

or

$('.hello:first-child').get(0).nodeName; // Use 'get' or simply access the jQuery Object like an array
$('.hello:first-child')[0].nodeName;     // will get you the original DOM element object

Solution 4 - Javascript

You could also use $(this).prop('tagName'); if you're using jQuery 1.6 or higher.

Solution 5 - Javascript

Yes. You could use the below code:

this.tagName

Solution 6 - Javascript

I think you cannot use the nodeName in jQuery since nodeName is a DOM property and jQuery itself do not have a either a nodeName function or property. But based on the respondent who first mentioned about this nodeName stuff, this is how I was able to resolve the problem:

this.attr("id", "rnd" + this.attr("nodeName") + "_" + i.toString());

NOTE: this here is a jQuery object.

Solution 7 - Javascript

Since this is a question you come along on google using jquery tagname first child as a query I'll post another example:

<div><p>Some text, whatever</p></div>

$('div').children(':first-child').get(0).tagName); // ...and not $('div:first-child')[...]

The jquery result is an (uppercase) tagname: P

Solution 8 - Javascript

Consider the fast FILTER method:

$('.rnd').filter('h2,h4')

returns:

[<h2 id=​"foo" class=​"rnd">​Second​</h2>​, <h4 id=​"bar" class=​"rnd">​Fourth​</h4>​]

so:

$('.rnd').filter('h2,h4').each(function() { /*...$(this)...*/ });

Solution 9 - Javascript

You can get html element tag name on whole page.

You could use:

        $('body').contents().on("click",function () {
          var string = this.tagName;
          alert(string);
         });

Solution 10 - Javascript

you can try:
jQuery(this).get(0).tagName;
or
jQuery(this).get(0).nodeName;

note: replace this with your selector (h1, h3 or ...)

Solution 11 - Javascript

I only just wrote it for another issue and thought it may help either of you as well.

Usage:

  • i.e. onclick="_DOM_Trackr(this);"

Parameters:

  1. DOM-Object to trace
  2. return/alert switch (optional, default=alert)

Source-Code:

function _DOM_Trackr(_elem,retn=false)
{
    var pathTrackr='';
    var $self=$(_elem).get(0);
    while($self && $self.tagName)
    {
        var $id=($($self).attr("id"))?('#'+$($self).attr("id")):'';
        var $nName=$self.tagName;
        pathTrackr=($nName.toLowerCase())+$id+((pathTrackr=='')?'':' > '+(pathTrackr));
        $self=$($self).parent().get(0);
    }
    if (retn)
    {
        return pathTrackr;
    }
    else
    {
        alert(pathTrackr);
    }
}

Solution 12 - Javascript

The best way to fix your problem, is to replace $(this).attr("tag") with either this.nodeName.toLowerCase() or this.tagName.toLowerCase().

Both produce the exact same result!

Solution 13 - Javascript

Instead simply do:

$(function() {
  $(".rnd").each(function(i) {
    var id = $(this).attr("id");
    if (id === undefined || id.length === 0) {
      // this is the line that's giving me problems.
      // .attr("tag") returns undefined
      // change the below line...
      $(this).attr("id", "rnd" + this.tagName.toLowerCase() + "_" + i.toString()); 
  });
});

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
QuestionBigPigVTView Question on Stackoverflow
Solution 1 - JavascriptmiddusView Answer on Stackoverflow
Solution 2 - JavascriptWabbitseasonView Answer on Stackoverflow
Solution 3 - JavascriptScott KirkwoodView Answer on Stackoverflow
Solution 4 - JavascriptBijay RungtaView Answer on Stackoverflow
Solution 5 - JavascriptfernandoView Answer on Stackoverflow
Solution 6 - JavascriptAbetView Answer on Stackoverflow
Solution 7 - JavascriptHeinView Answer on Stackoverflow
Solution 8 - JavascriptFrancesco CasulaView Answer on Stackoverflow
Solution 9 - Javascriptuser2029521View Answer on Stackoverflow
Solution 10 - Javascriptakbar amaniView Answer on Stackoverflow
Solution 11 - JavascriptChris S.View Answer on Stackoverflow
Solution 12 - JavascriptJohn SlegersView Answer on Stackoverflow
Solution 13 - JavascriptAlirezaView Answer on Stackoverflow