Using jQuery methods on event.target

I want to check specific attributes of the target during the click event:

 $('div').on('click', function(e) { console.log(e.target.attr('class')); }); 

This results in an error in the browser console:

main.js: 47 Uncaught TypeError: e.target.attr is not a function

Is event.target a jQuery object also?

+7
javascript jquery
source share
2 answers

e.target is not a jQuery object by default, it is a DOM element. You have to drop it:

 console.log($(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> 
+6
source share

It is better not to mix with javascript and jquery code, because it is difficult to process or understand.

 $('div').on('click', function(e) { //console.log(e.target.className); javascript console.log($(this).attr('class')); //jquery }); 
0
source share

All Articles