jQuery可以提供标签名称吗?


115

我在HTML页面上有几个具有相同类的元素-但是它们是不同的元素类型。我想在遍历元素时找出元素的标签名称-但.attr不会使用“标签”或“标签名称”。

这就是我的意思。考虑页面上的以下元素:

<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(如果尚未定义):

$(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”表示的元素的标签名称的任何想法?


Answers:


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

应该

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

18
您将需要使用this.nodeName.toLowerCase(),因为HTML文档的大多数DOM表示都会自动将nodeName大写。
NickFitz

this.nodeName和this.tagName似乎都对我有用。谢谢大家!
09年

5
+1表示nodeName。有时,jQuery太过分了:-)
Serge Wautier

2
+1 jQuery is()无法完成工作,因为在h1,h2等情况下,如果使用is(),则必须处理6种不同的情况。
康斯坦丁·迪涅夫

166

您可以尝试以下方法:

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

有关is()的更多信息,请参见文档


12
可能会涉及到谁:如果您对我的答案不满意,请告诉我原因,以便我改善它并学习将来的SO答案。谢谢。
middus 2011年

3
我也讨厌 无论如何我都赞成,因为nodeName返回的字符串取决于浏览器,是否为大写。
Marcel Falliere 2011年

2
假设以下内容:您不仅会选择少量可能的标签,而且可能是100多个html标签中的任何一个。然后,您需要编写:$(this).is('sometag')超过100次。我认为这就是为什么有人拒绝您的回答的原因。
ximi 2012年

哇...好is('*')几年没见过了 它可能不会回答OP,但对我有用,谢谢@middus!
Alastair

53

由于我之前曾经遇到过这个问题,并且对我的情况没有帮助(我没有this,但是有一个jQuery选择器实例)。调用get()将获得HTML元素,您可以通过该元素获得nodeName上述内容。

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

要么

$('.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

1
此页面上的第一个有用帮助
Rooster



1

我认为您不能nodeName在jQuery中使用,因为nodeName是DOM属性,而jQuery本身没有nodeName函数或属性。但是基于首先提到此问题的受访者nodeName,这就是我能够解决问题的方式:

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

注意:this这是一个jQuery对象。


0

由于这是一个问题,您在Google上使用jquery标记名的第一个孩子作为查询,因此我将发布另一个示例:

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

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

jQuery结果是一个(大写的)标记名:P


0

您可以在整个页面上获取html元素标签名称。

您可以使用:

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

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

注意:用您的选择器(h1,h3或...)替换


0

我只是为另一个问题写了它,并认为它也可能对你们两个都有帮助。

用法:

  • onclick="_DOM_Trackr(this);"

参数:

  1. 跟踪的DOM对象
  2. 返回/警报开关(可选,默认为警报)

源代码:

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);
    }
}

示例输出:html > body > div#coreApp > div#productpage > div#productpage-wrapper > div > div > div > div > div#pthumb12 > form#thumb_uploader_src > input
Chris S.

另一个用法示例: $('*').each(function(_i,_e){$(_e).attr('title',_DOM_Trackr(_e,true));});
Chris S.

0

解决问题的最佳方法是$(this).attr("tag")this.nodeName.toLowerCase()或替换this.tagName.toLowerCase()

两者都产生完全相同的结果!


0

考虑快速的FILTER方法:

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

返回:

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

所以:

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

0

而是简单地做:

$(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()); 
  });
});
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.