Can jQuery provide the tag name?
Asked Answered
O

13

117

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

Offensive answered 7/10, 2009 at 15:24 Comment(1)
Maybe answer is here: https://mcmap.net/q/63472/-jquery-get-selected-element-tag-nameIndigestive
L
110
$(this).attr("id", "rnd" + $(this).attr("tag") + "_" + i.toString());

should be

$(this).attr("id", "rnd" + this.nodeName.toLowerCase() + "_" + i.toString());
Longevity answered 7/10, 2009 at 15:25 Comment(4)
You'll need to use this.nodeName.toLowerCase(), as most DOM representations of HTML documents automatically uppercase the nodeName.Metz
both this.nodeName and this.tagName seem to work for me. Thanks all!Offensive
+1 for mentioning nodeName. Sometimes, jQuery is one step too far :-)Edin
+1 jQuery is() doesn't do the job because in the case of h1, h2, etc there are 6 different cases you have to handle if using is().Vacua
B
167

You could try this:

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

See the docs for more on is().

Brendon answered 7/10, 2009 at 15:27 Comment(4)
To whom it may concern: if you downvote my answer, please tell me why so I can improve it and learn for future SO-answers. Thanks.Brendon
I hate it too. Anyway I upvoted because nodeName returns a string that, depending browser, is upper cased or not.Randall
Assume the following: You don't just have a small selection of possible tags, but it could be any of 100+ html tags. Then you'd need to write: $(this).is('sometag') a 100+ times. I assume this is why some people downvoted your answer.Taiwan
Wow...never seen is('*') in years. It probably won't answer the OP but it worked for me, thanks, @middus!Stockdale
L
110
$(this).attr("id", "rnd" + $(this).attr("tag") + "_" + i.toString());

should be

$(this).attr("id", "rnd" + this.nodeName.toLowerCase() + "_" + i.toString());
Longevity answered 7/10, 2009 at 15:25 Comment(4)
You'll need to use this.nodeName.toLowerCase(), as most DOM representations of HTML documents automatically uppercase the nodeName.Metz
both this.nodeName and this.tagName seem to work for me. Thanks all!Offensive
+1 for mentioning nodeName. Sometimes, jQuery is one step too far :-)Edin
+1 jQuery is() doesn't do the job because in the case of h1, h2, etc there are 6 different cases you have to handle if using is().Vacua
F
53

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
Faradize answered 17/11, 2010 at 1:23 Comment(1)
first helpful one on the pageAbiotic
B
46

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

Bancroft answered 11/5, 2011 at 7:23 Comment(2)
This is exactly what I needed. In my design, I had the jquery element handy, but not the original HTML DOM element. This works for me.Hydrothorax
I think this is the exact answer that answers the subject of this question.Gwendagwendolen
E
4

Yes. You could use the below code:

this.tagName
Epilogue answered 7/10, 2009 at 15:39 Comment(0)
R
1

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.

Regine answered 13/9, 2011 at 10:20 Comment(0)
G
0

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);
    }
}
Genetic answered 7/10, 2009 at 15:24 Comment(2)
Example Output: html > body > div#coreApp > div#productpage > div#productpage-wrapper > div > div > div > div > div#pthumb12 > form#thumb_uploader_src > inputGenetic
Another usage example: $('*').each(function(_i,_e){$(_e).attr('title',_DOM_Trackr(_e,true));});Genetic
L
0

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

Lewls answered 20/10, 2011 at 17:27 Comment(0)
E
0

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)...*/ });
Engobe answered 23/2, 2012 at 16:15 Comment(0)
L
0

You can get html element tag name on whole page.

You could use:

        $('body').contents().on("click",function () {
          var string = this.tagName;
          alert(string);
         });
Ligroin answered 2/2, 2013 at 7:31 Comment(0)
S
0
you can try:
jQuery(this).get(0).tagName;
or
jQuery(this).get(0).nodeName;

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

Selry answered 11/2, 2013 at 11:1 Comment(0)
W
0

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!

Wernsman answered 20/1, 2016 at 23:8 Comment(0)
M
0

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()); 
  });
});
Mythological answered 17/6, 2017 at 10:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.