jQuery: Get selected element tag name

Is there an easy way to get a tag name?

For example, if I am given $('a') into a function, I want to get 'a' .


You can call .prop("tagName") . Examples:

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


If writing out .prop("tagName") is tedious, you can create a custom function like so:

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

Examples:

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


Note that tag names are, by convention, returned CAPITALIZED. If you want the returned tag name to be all lowercase, you can edit the custom function like so:

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

Examples:

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

您可以使用DOM的nodeName属性:

$(...)[0].nodeName

As of jQuery 1.6 you should now call prop:

$target.prop("tagName")

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

链接地址: http://www.djcxy.com/p/83052.html

上一篇: jQuery获取选择onChange的值

下一篇: jQuery:获取选定的元素标签名称