views:

18718

answers:

5

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?

+5  A: 

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

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

works!

CMPalmer
Still one jQuery too much. :-) You have the DOM element already with "this", no need to wrap it again!
Tomalak
+31  A: 

Just one jQuery too much:

$("[id$=" + endOfIdToMatch + "]").each(function () {
    alert(this.tagName);
});
Tomalak
Ohhhhh. I get it now. Good answer!
CMPalmer
Or `$(this).get(0).tagName`
Znarkus
@Znarkus: True, but makes no sense. ;)
Tomalak
No, not in this case. But if you have a variable with a jQuery object, this would be how you'd have to do it :)
Znarkus
+1  A: 

tagName what a nice tip. I would like to suggest also to use tagName.toLowerCase() so values in the actual XHTML or HTML standard are returned

+17  A: 

I think you should do it like this:

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

(Or whichever element you're looking for.) Then you don't need each.

Have a look at the documentation for is.

Christian Davén
+4  A: 

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.

Jelgab