tags:

views:

40

answers:

2

Let's say I do something stupid like this:

<div class="my_class">fun wee!!</div>
<span class="my_class"><b class="my_class">Title</b></span>
<p class="my_class">Client</p>

<Script>
$('.my_class').click(function() {
    alert('You clicked a ??????? Tag!!');
});
</script>

Where I have selected lots of different tags with the same selector. How do i figure out what tag was selected?

Seems like something simple but I haven't yet found an answer...

+4  A: 

In jQuery event handlers, 'this' is set to the DOM node on which the event was triggered. So you'd want:

$('.my_class').click(function() {
    alert('You clicked a ' + this.nodeName + ' Tag!!');
});

The W3C DOM spec has more info: http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247

Matt
+1 on nodeName (vs tagName), due to IE issues.
Marc
it's sad when I know jquery better than I know plain javascript, so I can't do something as simple as this!
SeanDowney
A: 

If you want to do something different with various HTML tags that have the same class, you are almost always better off using the tag in the selector and only getting the ones you want than getting all by class and using some sort of logic (short of selecting by tag) to sort them out.

$('div.my_class').click( function() { alert("hey, I'm a div"); } );

I suppose the exception would be if you only wanted to alert the tag name.

tvanfosson
I agree this would be ideal, but I've painted myself into a corner
SeanDowney