Gregor Gregor - 6 months ago 10
Javascript Question

Why is the checking for Class not Working?

When i check for the class name with .hasClass its not working.

function changeClass(){
var elBox = document.getElementById('box');

if(elBox.hasClass('blue')){
elBox.className = 'red';
}
}

var trigger = document.getElementById('trigger');

trigger.onmouseover = changeClass;


But generally its working when i check for attribute for example

if(elBox.hasAttribute('class') ....


I just don't get why the checking for class fails, maybe someone can help.

Answer

elBox is just a DOM object, wrap it with jQuery wrapper in order to use jQuery methods like .hasClass().

Instead of

if(elBox.hasClass('blue')){

Use

if($(elBox).hasClass('blue')){