问题
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