1

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);
    }
}
1
  • That's because className gets the class attribute value. So it would be "answer correct" rather than just "correct". Instead you will want to see if it's in the classList or split by space the className property (since this is better supported). Commented Feb 14, 2018 at 21:47

2 Answers 2

3

You need to use the method contains from classList.

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.classList.contains("correct")) {
    console.log(correctMsg);
  } else {
    console.log(wrongMsg);
  }
}
<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>

Resource

Sign up to request clarification or add additional context in comments.

Comments

0

I believe correct approach would you to look for correct classname in element's classList property

like so: this.classList.contains("correct");

more information: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.