views:

14897

answers:

4

I am looking to extend jQuery so I can easily retrieve the tagName of the first element in a jQuery object. This is what I have come up with, but it doesn't seem to work:

$.fn.tagName = function() {
    return this.each(function() {
        return this.tagName;
    });
}
alert($('#testElement').tagName());

Any ideas what's wrong?

BTW, I'm looking to use this more for testing than in production.

+20  A: 

Try this instead:

$.fn.tagName = function() {
    return this.get(0).tagName;
}
alert($('#testElement').tagName());

To explain a little bit more of why your original example didn't work, the each() method will always return the original jQuery object (unless the jQuery object itself was modified). To see what is happening in each with your code, here is some pseudocode that shows how the each() method works:

function each(action) {
    for(var e in jQueryElements) {
        action();
    }
    return jQueryObject;
}

This is not how each() really gets implemented (by a long shot probably), but it is to show that the return value of your action() function is ignored.

Dan Herbert
It might be a good idea to convert the tag to lower case. return this.get(0).tagName.toLowerCase()
David Brockman
+7  A: 

Why create a plugin at all? Seems a bit unnecessary...

alert( $('div')[0].tagName );
J-P
+6  A: 

You may wish to add a toLowerCase() to make it more consistent (and XHTML compliant).

$.fn.tagName = function() {
    return this.get(0).tagName.toLowerCase();
}

alert($('#testElement').tagName());
+1  A: 

This one will return the lower case tagname of the matched element.

for example,

jQuery("#test_div").tagName();

would return div (assuming that element was a div).

If you pass an element collection, it returns an array of all the tagnames, where each array entry corresponds to the matched element.

for example if we run

jQuery(".classname").tagName();

on the following (X)HTML:

<div>
<p class="classname">test text</p>
<div class="anotherClass">
 <ul>
  <li class="classname"><a href="test">Test link</a></li>
 </ul>
 <p class="classname">Some more text</p>
</div>
<div>

would an array of tagnames:

["p", "li", "p"]

This is the function - it's basically the same as above but it supports multiple elements, which may or may not be useful to your project.

jQuery.fn.tagName = function(){
 if(1 === this.length){
  return this[0].tagName.toLowerCase();
 } else{
  var tagNames = [];
  this.each(function(i, el){
   tagNames[i] = el.tagName.toLowerCase();
  });
  return tagNames;
 }
};
adamnfish
may return an array or an item... will throw an exception if one of the selected item doesn't have a tagName...
Frank Schwieterman