How can I determine the element type of a matched element in jQuery?

I’m matching ASP.Net generated elements by ID name, but I have some elements which may render as text boxes or labels depending on the page context. I need to figure out whether the match is to a textbox or label in order to know whether to get the contents by val() or by html().

$("[id$=" + endOfIdToMatch + "]").each(function () {
    //determine whether $(this) is a textbox or label
    //do stuff
});

I found a solution that doesn’t work, it just returns “undefined”:

$("[id$=" + endOfIdToMatch + "]").each(function () {
    alert($(this).tagName);
});

What am I missing?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Just one jQuery too much:

$("[id$=" + endOfIdToMatch + "]").each(function () {
    alert(this.tagName);
});

Method 2

Consider this solution without using each():

var elements = $("[id$=" + endOfIdToMatch + "]");
var vals = elements.is("input").val();
var htmls = elements.is("label").html();
var contents = vals.concat(htmls);

Have a look at the documentation for is.

Method 3

you could also use something like this:

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

replace “this” with whatever instance you need and ‘checkbox’ with whatever input type you need.

Method 4

First time I’ve answered my own question. After a little more experimentation:

$("[id$=" + endOfIdToMatch + "]").each(function () {
   alert($(this).attr(tagName));
});

works!

Method 5

tagName what a nice tip. I would like to suggest also to use tagName.toLowerCase() since the value returned depends on the document type (HTML or XML/XHTML).

See: http://reference.sitepoint.com/javascript/Element/tagName

Method 6

in jquery 1.6 use prop()

Example

var el = $('body');

if (el.prop('tagName') === 'BODY') {
    console.log('found body')
}

Method 7

This the best way to Get the element type

function tgetelementType( elmentid )
{

    var TypeName = $('#' + elmentid).get(0).tagName;
    var TypeName2 = $('#' + elmentid).get(0).type;


    if($('#' + elmentid).get(0).tagName== "INPUT")
    {
       return $('#' + elmentid).get(0).type.toUpperCase()
    }
    else 
    {
        return $('#' + elmentid).get(0).tagName.toUpperCase() ; 
    }
}

Method 8

$("[id$=" + endOfIdToMatch + "]").each(function(){
    var $this=jQuery(this),ri='';
    switch (this.tagName.toLowerCase()){
        case 'label':
            ri=$this.html();
            break;
        case 'input':
            if($this.attr('type')==='text'){ri=$this.val();}
            break;
        default:
            break;
    }
    return ri;
})

The question is, what do you intend to do after you’ve determined the tag name? You could just as easily filter the jquery list using an additional selector combined with .end() to do the same thing:

$("[id$=" + endOfIdToMatch + "]")
    .find("input:text")
    .each(function(){
         /* do something with all input:text elements */
    })
    .end()
    .find("label")
    .each(function(){
        /* do something with label elements */
    })
    .end()

This could still be chained if you needed to do further things with this particular collection of elements…just like the example above.

In either case, you’d have to do something with the values while inside the each() statements

Method 9

Yet another solution, arguably more elegant, is to write two separate functions for each element type:

$("input#" + id).each(function() { alert(this + " is an input"); });
$("label#" + id).each(function() { alert(this + " is a label"); });


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x