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 wh
$("[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
Just one jQuery too much:
$("[id$=" + endOfIdToMatch + "]").each(function () {
alert(this.tagName);
});
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.
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"); });
in jquery 1.6 use prop()
var el = $('body');
if (el.prop('tagName') === 'BODY') {
console.log('found body')
}
First time I've answered my own question. After a little more experimentation:
$("[id$=" + endOfIdToMatch + "]").each(function () {
alert($(this).attr(tagName));
});
works!