views:

33

answers:

3

Right, idiot moment coming up. I've done a search, but can't find the right solution.

I've got a jQuery selector selecting a class, maybe an ID, in fact it could be anything, this selector is fed into a function I'm programming.

I need to be able to figure out the type of each matched element, for example:

<div class="target"></div>

Would return div, and

<input class="target" />

Would return input, simple right?

Well you'd have thought so, but I cannot seem to find the solution.

Any help would be greatly appreciated :-)

+2  A: 

You need to get the underlying DOM element and access the tagName property. For example,

alert($("#target").get(0).tagName);
// -> DIV

Be aware that browsers will return the tag name in uppercase, so something like this would cause you a bit of grief:

if ($("#target").get(0).tagName == "div") { alert("DIV!"); }
Andy E
That's the one, I was trying to use `tagName` directly on the selector, without using `.get(0)`. Thank you very much! :D
ILMV
A: 

try:

$("yourelement").is("input")

or:

if ($(this).is('input:checkbox'))

etc.... where appropriate

jim
Thanks for your answer, I'd prefer to get the element type back as the others have shown, and run it through a condition from there :-)
ILMV
no worries - just another of the many ways to skin the jquery cat :)
jim
+1  A: 
$.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.

Thank you for your answer! +1
ILMV