首页 文章

jQuery:获取选定的元素标记名称

提问于
浏览
574

有没有简单的方法来获取标签名称?

例如,如果我被赋予 $('a') 函数,我想得到 'a' .

6 回答

  • 91

    jQuery 1.6+

    jQuery('selector').prop("tagName").toLowerCase()
    

    Older versions

    jQuery('selector').attr("tagName").toLowerCase()
    

    toLowerCase()不是必需的 .

  • 55

    从jQuery 1.6开始,你现在应该调用prop:

    $target.prop("tagName")
    

    http://api.jquery.com/prop/

  • 10

    你可以拨打 .prop("tagName") . 例子:

    jQuery("<a>").prop("tagName"); //==> "A"
    jQuery("<h1>").prop("tagName"); //==> "H1"
    jQuery("<coolTagName999>").prop("tagName"); //==> "COOLTAGNAME999"
    

    如果写出 .prop("tagName") 很乏味,你可以像这样创建一个自定义函数:

    jQuery.fn.tagName = function() {
      return this.prop("tagName");
    };
    

    例子:

    jQuery("<a>").tagName(); //==> "A"
    jQuery("<h1>").tagName(); //==> "H1"
    jQuery("<coolTagName999>").tagName(); //==> "COOLTAGNAME999"
    

    请注意,按照惯例,标记名称返回 CAPITALIZED . 如果希望返回的标记名全部为小写,则可以编辑自定义函数,如下所示:

    jQuery.fn.tagNameLowerCase = function() {
      return this.prop("tagName").toLowerCase();
    };
    

    例子:

    jQuery("<a>").tagNameLowerCase(); //==> "a"
    jQuery("<h1>").tagNameLowerCase(); //==> "h1"
    jQuery("<coolTagName999>").tagNameLowerCase(); //==> "cooltagname999"
    
  • 930

    您可以使用DOM的nodeName property

    $(...)[0].nodeName
    
  • 43

    你应该 NOT 使用 jQuery('selector').attr("tagName").toLowerCase() ,因为它只适用于旧版本的Jquery .

    如果're certain that you'使用的jQuery版本> = 1.6版,则 could 使用 $('selector').prop("tagName").toLowerCase() .


    注意:

    您可能认为现在每个人都在使用jQuery 1.10或其他东西(2016年1月),但遗憾的是并非如此 . 例如,今天很多人仍在使用Drupal 7,到今天Drupal 7的每个正式版本都默认包含jQuery 1.4.4 .

    因此,如果您不确定您的项目是否将使用jQuery 1.6,请考虑使用适用于所有jQuery版本的选项之一:

    Option 1 :

    jQuery('selector')[0].tagName.toLowerCase()
    

    Option 2

    jQuery('selector')[0].nodeName.toLowerCase()
    
  • 21

    这是另一种方式:

    $('selector')[0].tagName
    

相关问题