why isn't it working?
$('.cupsGame-level').each((i, item) => {
if (item.hasClass(`cupsGame-level-${this.gameCupsStats.level}`)) {
item.addClass('passedLevel');
}
})
im pretty sure i have jquery object instead of basic DOM el
CodePudding user response:
item
in your code is a basic DOM element, not the DOM object.
So you need to put it inside $()
to make it DOM object and to make your code work:
$('.cupsGame-level').each((i, item) => {
if ($(item).hasClass(`cupsGame-level-${this.gameCupsStats.level}`)) {
$(item).addClass('passedLevel');
}
})
Sample example:
$('.cupsGame-level').each((i, item) => {
/*for understanding purpose
if (i == 0) {
console.log(item); //check output
console.log($(item)); //check output
}*/
if ($(item).hasClass(`cupsGame-level-${i}`)) {
$(item).addClass('passedLevel');
}
});
.passedLevel {
background: darkgrey;
height: 30px;
}
.passedLevel p {
padding: 5px 5px 5px 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<p>This is first text</p>
</div>
<div >
<p>This is second text</p>
</div>
<div >
<p>This is third text</p>
</div>
<div >
<p>This is fourth text</p>
</div>
<div >
<p>This is fifth text</p>
</div>
Note: do console.log(item);console.log($(item));
to see the difference. Added in my code snippet too.