Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery methods on event.target

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?

like image 789
Filip Bartnicki Avatar asked Aug 29 '16 08:08

Filip Bartnicki


People also ask

Is jQuery a target event?

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.

Which jQuery method is used to attach an event handler function to an HTML element on mouse click?

bind( eventType [, eventData ], handler )Returns: jQueryversion deprecated: 3.0. Description: Attach a handler to an event for the elements.

Does jQuery have an event object?

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.


2 Answers

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>
like image 107
eisbehr Avatar answered Oct 17 '22 23:10

eisbehr


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
});
like image 29
David Jaw Hpan Avatar answered Oct 18 '22 00:10

David Jaw Hpan