Simple jQuery function to check the div ClassName

Viewed 104

I have written a very simple function for checking the tag class name. I attached it to the div(s) by using .attr() and it seems no problem to alert.

However, $(this).attr('class') cannot show the correct class name and just display

"undefined"

. Actually, I have more things want to do with $(this), so it is really bad that i stop at the very beginning.

Would anyone tell me why this happened and how to fix it?

<div class="testing class1" >Something here</div>
<div class="testing class2" >Something here</div>    
<script>

$("div.testing").attr('onclick', 'checkClass()');

function checkClass(){
  alert( $(this).attr('class'));
  // what do something more with "$(this)"
}
3 Answers

Try implementing it the following way, your code will output undefined inside alert because this references checkClass() function and not the element you are trying to target, see the demo below, you should learn how to make a simple plugin

$.fn.checkClass = function() {
  $(this).on('click', function() {
    console.log($(this).attr('class'));
  });
}
$("div.testing").checkClass();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="testing class1">Something here</div>
<div class="testing class2">Something here</div>

Although jQuery have own methods for adding / removing classes from / to elements, for enumeration have nothing. So you should use native js method.

var checkClass = e => {
  alert(e.target.classList)
}

$("div.testing").click(checkClass)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="testing class1" >Something here</div>
<div class="testing class2" >Something here</div>

You have to pass this to the function because $(this) = window;

please try this :

$("div.testing").attr('onclick', 'checkClass(this)');
function checkClass(e){
  alert( e.className);
  // what do something more with e, this is you clicked element
}
Related