Search code examples
jqueryclassname

Simple jQuery function to check the div ClassName


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)"
}

Solution

  • 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
    }