Search code examples
javascriptarrayscontains

.contains() does not accept as arguments an element of array when looping


I am looping through HTML elements and checking if they contain elements of my month array in italian. Problem is when I try to access the element of the array with month[i] returns nothing, when I write for example month[2], it returns true. I suppose that notation month[i] is not acceptable for contains. Has somebody solution. My code is under. Thanks.

const months = ["Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"];


for(i = 0; i < tdCellBody.length; i++){
        if(tdCellBody[i].classList.contains(months[i])) {
            console.log(true);
        } else {
            console.log(false);
        }
    }

Solution

  • This example uses only one node to check against an array of given values.

    var months = ["Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"],
        node = document.getElementById('div1'),
        j;
    
    for (j = 0; j < months.length; j++) {
        console.log(months[j], node.classList.contains(months[j]));
    }
    <div id="div1" class="Marzo Maggio"></div>