Lukas Baliƫnas Lukas Baliƫnas - 3 months ago 16
HTML Question

Changing innerHTML when multiple elements have a specific class removed

I have 10 elements with multiple classes. 5 of them have classes

.home
and
.not-added
, 5 of them have
.away
and
.not-added
. With jQuery when an event happens i toggle the class
.not-added
for a specific element. I want to check when these 10 elements don't have the class
.not-added
, so that i can change the innerHTML of an element.

My method for checking this:

$(document).ready(function () {
var ready = false;

$(".home").each(function (i) {
if ($(this).hasClass(".not-added")) {
ready = false;
}
else {
ready = true;
}
});
if (ready) {
document.getElementById("button1").innerHTML = "Points";
}
});


This doesn't work. When the page is loaded,
#button1
has already
Points
inside of it.

Sample of my elements:

before event:

<div class='dropdown-toggle stat-dropdown not-added home' data-toggle='dropdown'>
...
</div>


after event:

<div class='dropdown-toggle stat-dropdown home' data-toggle='dropdown'>
...
</div>


What could be the problem?

Answer

You need to specify the class name in .hasClass(). In your case: use .hasClass('not-added) instead of the wrong .hasClass('.not-added'). Here is a working JSFiddle with your use case.

Note that it would be better to use a for loop instead of .each(), because you can utilize the conditional to check for your flag (ready in your case), to avoid iterating through all of the elements.