简体   繁体   中英

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?

Just one jQuery too much:

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

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 .

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.

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

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

works!

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

in jquery 1.6 use prop()

Example

var el = $('body');

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

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() ; 
    }
}
$("[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

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"); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM