Skip to content

querySelectorAll selects all similar classes

Calendar is using 3 different classes to style its child elements: “old day”, “day”, “new day”. Trying to querySelectorAll element with class name “day” also captures the other two classes, so when i say something like:

t = document.getElementByTagName('table');
d = t.item(0).querySelectorAll('.day');
/* also selects td.new.day and td.old.day */

for (i = 0; i < d.length: i ++) {
     if(d[i].textContent == 28) {
         d[i].click();
     }
}

I will get click on old 28th instead of current month 28th.

How do i select “day” class of td element without also selecting “old day” and “new day”?

Answer

You can use :not to specify which classes you don’t want to match.

document.querySelectorAll(".red:not(.big):not(.small)").forEach(e => {
  e.style.marginLeft = "100px";
});
.red {color: red;}
.big {font-size: 20px}
.small {font-size: 12px}
<a class="red">red</a><br>
<a class="red big">red big</a><br>
<a class="red small">red small</a>