accessing TagName of jquery object

7.1k Views Asked by At

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?

3

There are 3 best solutions below

0
On BEST ANSWER

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);
0
On

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.

0
On

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