I am looking to check if a element has a class name on click. I have the click event calling the function but nothing logs to the console. Interestingly, document.write works but no matter what I click, it logs the else even if the HTML element has the class name.
HTML
<p>What is 2+2?</p>
<a href="#" class="answer wrong">5</a>
<a href="#" class="answer correct">4</a>
<a href="#" class="answer wrong">7</div>
<a href="#" class="answer wrong">2</div>
CSS
var wrongMsg = "Sorry, that's not the answer"
var correctMsg = "Correct!"
var answers = document.getElementsByClassName("answer");
for (var i=answers.length; i--;){
answers[i].addEventListener('click', checkMulti);
};
function checkMulti(){
if ( this.className == "correct" ){
console.log(correctMsg);
}else{
console.log(wrongMsg);
}
}
classNamegets theclassattribute value. So it would be"answer correct"rather than just"correct". Instead you will want to see if it's in theclassListor split by space theclassNameproperty (since this is better supported).