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?
target Property with Example. The event. target is an inbuilt property in jQuery which is used to find which DOM element will start the event.
bind( eventType [, eventData ], handler )Returns: jQueryversion deprecated: 3.0. Description: Attach a handler to an event for the elements.
jQuery's event system normalizes the event object according to W3C standards. The event object is guaranteed to be passed to the event handler. Most properties from the original event are copied over and normalized to the new event object.
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>
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
});
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