我在一个HTML页面上有几个元素,它们具有相同的类-但它们是不同的元素类型。我想在遍历元素时找出元素的标记名--但是.attr不接受" tag“或"tagname”。
这就是我的意思。考虑页面上的这些元素:
<h1 class="rnd">First</h1>
<h2 id="foo" class="rnd">Second</h2>
<h3 class="rnd">Third</h3>
<h4 id="bar" class="rnd">Fourth</h4>
现在,我想运行类似这样的命令,以确保我的元素都有一个id (如果没有定义id的话):
$(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());
}
});
});
我希望得到的结果是H2和H4元素的id为
rndh2_1
rndh4_3
分别使用。
关于如何发现由"this“表示的元素的标记名,有什么想法吗?
https://stackoverflow.com/questions/1532331
复制相似问题