accessing TagName of jquery object

烈酒焚心 提交于 2019-12-10 16:33:39

问题


I want to know the tagName of the jquery object , i tried :

   var obj = $("<div></div>");
   alert($(obj).attr("tagName"));

This alert shows me undefined. Whats wrong i am doing?


回答1:


tagName is a property of the underlying DOM element, not an attribute, so you can use prop, which is the jQuery method for accessing/modifying properties:

alert($(obj).prop('tagName'));

Better, however, is to directly access the DOM property:

alert(obj[0].tagName);



回答2:


You need to access the underlying DOM node, as jQuery objects don't have a tagName property, and tagName is not a property, not an attribute:

var obj = $("<div></div>");
alert(obj[0].tagName);

Notice that I've also removed the call to jQuery on the 2nd line, since obj is already a jQuery object.




回答3:


tagName is a native DOM element property, it isn't part of jQuery itself. With that in mind, use $()[0] to get the DOM element from a jQuery selector, like this:

var obj = $("<div></div>");
alert(obj[0].tagName);

Example fiddle



来源:https://stackoverflow.com/questions/10781593/accessing-tagname-of-jquery-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!