I'm new to JS, but I was hoping there might be a selector like document.getElementsByClassName("div:not(div-1)")
that selects elements by class name, unless they also have another class name, that I can define.
Basically my project is a list of movies and their genres.
Using an onclick
function, if you click on a genre, I'm trying to hide all other movies that don't belong to that genre. Now I'm looking for a way to select the DIVs without having to add a "not-comedy", "not-action", etc… class to every single movie.
So far I got this:
function test() {
var x = document.getElementsByClassName("movie-div");
var i;
for (i=0; i < x.length; i++) {
if (x[i].style.display === "none") {
x[i].style.display = "block";
} else {
x[i].style.display = "none";
}
}
}
Use querySelectorAll with i.e: the :not()
selector
const ELS_x = document.querySelectorAll(".x:not(.zzz)");
ELS_x.forEach(EL => {
// do something with EL
EL.classList.toggle("active");
});
.active {background: gold;}
<div class="x">a</div>
<div class="x zzz">b</div>
<div class="x">a</div>
or if you want to do the class check inside the loop use classList.contains()
const ELS_x = document.querySelectorAll(".x");
ELS_x.forEach(EL => {
if (!EL.classList.contains("zzz")) {
// do something with NON .zzz Elements
EL.classList.toggle("active");
}
});
.active {background: gold;}
<div class="x">a</div>
<div class="x zzz">b</div>
<div class="x">a</div>
if you want to filter out some Elements, use .filter()
const ELS_x = document.querySelectorAll(".x");
const ELS_without_zzz = [...ELS_x].filter(EL => !EL.classList.contains("zzz"));
ELS_without_zzz.forEach(EL => {
// do something with NON .zzz Elements
EL.classList.toggle("active")
});
.active {background: gold;}
<div class="x">a</div>
<div class="x zzz">b</div>
<div class="x">a</div>