Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
144
rated 0 times [  147] [ 3]  / answers: 1 / hits: 132801  / 15 Years ago, wed, october 7, 2009, 12:00:00

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?


More From » jquery

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


should be



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

[#98560] Wednesday, September 30, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
donovanjasek

Total Points: 465
Total Questions: 103
Total Answers: 113

Location: Saint Vincent and the Grenadines
Member since Thu, Oct 15, 2020
4 Years ago
donovanjasek questions
Wed, Jun 23, 21, 00:00, 3 Years ago
Fri, Jun 12, 20, 00:00, 4 Years ago
Mon, Nov 25, 19, 00:00, 5 Years ago
Mon, Oct 15, 18, 00:00, 6 Years ago
;