Reputation: 301
I want to check specific attributes of event target during click
event:
$('div').on('click', function(e) {
console.log(e.target.attr('class'));
});
This results in error in browser console:
main.js:47 Uncaught TypeError: e.target.attr is not a function
Isn't event.target
a jQuery object too?
Upvotes: 19
Views: 8091
Reputation: 12452
e.target
is not a jQuery object by default, it is a DOM element. You have to cast it:
$(e.target).attr('class')
Working example:
$('div').on('click', function(e) {
console.log($(e.target).attr('class'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">click me</div>
Upvotes: 28
Reputation: 4584
It is better not to mix with javascript and jquery code ,because it is hard to handle or understand .
$('div').on('click', function(e) {
//console.log(e.target.className); javascript
console.log($(this).attr('class')); //jquery
});
Upvotes: 2