tags:

views:

8579

answers:

4

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

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

should be

$(this).attr("id", "rnd" + this.nodeName + "_" + i.toString());
Wabbitseason
You'll need to use this.nodeName.toLowerCase(), as most DOM representations of HTML documents automatically uppercase the nodeName.
NickFitz
That's probably a better idea than mine.
middus
both this.nodeName and this.tagName seem to work for me. Thanks all!
BigPigVT
+6  A: 

You could try this:

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

See the docs for more on is().

middus
+1  A: 

It doesn't work because the tag name is not an attribute - it's the name!

To get the tag name, just use this.tagName. I'm pretty sure it's just a DOM method, not a jQuery one.

Matt Ball
A: 

You could use:

this.tagName

fernando