2

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 :-)

3 Answers 3

4

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!"); }
Sign up to request clarification or add additional context in comments.

1 Comment

That's the one, I was trying to use tagName directly on the selector, without using .get(0). Thank you very much! :D
1
$.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.

Comments

0

try:

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

or:

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

etc.... where appropriate

2 Comments

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 :-)
no worries - just another of the many ways to skin the jquery cat :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.