Skip to content Skip to sidebar Skip to footer

Check If Element Has Class

Trying to find a way to display a console.log when a div is clicked. I am trying do do a simple game, if you click on the right box, you will get a message that you won. as of now

Solution 1:

You can use Element.classList.contains function to check if specified class value exists in class attribute of the element.

So assertion should look like:

if (boxes.classList.contains('winning')) {

UPD As Karl Wilbur noticed in the comments to my answer, boxes is a NodeList instance.

So, you have to convert it into array:

var boxes = Array.prototype.slice.apply(document.getElementsByTagName('li'));

and you will be able to iterate over it:

boxes.some(function(el) {
    return el.classList.contains('winning');
});

this should return true if at least one of the boxes contains a class name 'winning'.

Solution 2:

I suggest to check each container (not an array as in previous answer):

functioncheckawinner(box) {
  box.addEventListener("click", function(){
   if (box.classList.contains('winning')) {
        console.log('you win');
    } else {
        console.log('you lose');
   }
  }, false);
}

for (index = 0; index < boxes.length; ++index) {
  checkawinner(boxes[index]);  
}

A pen with "alerts": http://codepen.io/VsevolodTS/pen/BKBjpP

Solution 3:

I think what you are trying to do is:

//user can click on a cup to see if correctfunctionwinningBox(){
    // ensure that we are not working against a cached list of elementsvar boxes = document.getElementsByTagName('li');
    for(i=0,len=boxes.length;i<len;i++) {
        var box = boxes[i];
        if (box.classList.contains('winning')){
            console.log('you win');
        } else {
            console.log('you lose');
        }
    );
}

Post a Comment for "Check If Element Has Class"