I have the following code:
<script type="text/javascript">
$("*").click(function(event){
var x = event.target;
if (x.nodeName == "DIV"){
alert(x.attr("class"));
}
})
</script>
This throws an 'undefined' exception... Is there any other way to get the class of an element which triggered the 'click' event? Thank you in advance!
event.target
is a DOM object. So to use jQuery methods you have to convert it to jQuery object:
alert($(x).attr("class"));
Otherwise, you may use property className
to get the class of the element:
alert(x.className);
BTW, in your example you may simply use this
keyword instead of event.target
.
jQuery offers some syntactic sugar to help with your check - .is()
allows you to validate an element against any other valid selector:
var $target = event.target;
if ($target.is('div')){
alert($target.attr('class'));
}
There are some further changes to consider:
.click(handler)
is explicitly assigned to the matching elements (every single element in your case). This adds overhead; also the handler will not apply to any element added dynamically after the handler assignment is executed. Instead, delegate the handler by using on()
$('div')
this
which is pretty much the conventionAfter all these changes the code becomes smaller and more readable:
$('div').on('click', function() {
alert($(this).attr('class'));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With