html - If all elements don't have a particular class, then apply styles -
i have list of elements class name of .box
. sometimes, element have class, not know element has it.
is there way check if elements of .box
don't have .extraclass
, apply styles .box
, if elements of .box
has class .extraclass
, don't apply css style?
i want using css only.
var toggleclass = document.getelementbyid('toggleclass'), box = document.getelementsbyclassname('box'), randomnumber = -1; toggleclass.addeventlistener('click', function() { if (randomnumber !== -1) box[randomnumber].classlist.remove('extraclass'); randomnumber = math.floor(math.random() * 9); box[randomnumber].classlist.toggle('extraclass'); }); removeclass.addeventlistener('click', function() { if (randomnumber !== -1) box[randomnumber].classlist.remove('extraclass'); });
#wrapper { padding: 0; margin: 0; display: flex; justify-content: center; flex-wrap: wrap; } .box { background-color: yellow; width: 100px; height: 100px; border: 1px solid; list-style-type: none; } /*if of '.box' does't have class '.extraclass`; make background of '.box' pink*/ .box { background-color: pink; } .extraclass { background-color: red; }
<ul id="wrapper"> <li class="box"></li> <li class="box"></li> <li class="box"></li> <li class="box"></li> <li class="box"></li> <li class="box"></li> <li class="box"></li> <li class="box"></li> <li class="box"></li> <li class="box"></li> </ul> <button id="toggleclass">toggle class</button> <button id="removeclass">remove class</button>
sounds should use third css class add parent when add .extraclass
-- using 2 cumbersome. example, here's sample styling use:
#wrapper:not(.disablestyling) .box { background: red; }
this way, whenever add .extraclass
box, add .disablestyling
class wrapper. might make bit easier follow
edit:
here's js segment need change:
var toggleclass = document.getelementbyid('toggleclass'), box = document.getelementsbyclassname('box'), wrapper = document.getelementbyid('wrapper'), randomnumber = -1; toggleclass.addeventlistener('click', function() { if (randomnumber !== -1) box[randomnumber].classlist.remove('extraclass'); randomnumber = math.floor(math.random() * 9); box[randomnumber].classlist.toggle('extraclass'); var boxes = document.getelementsbyclassname("box"); var disabled = false; (var = 0; < boxes.length; i++) if (boxes[i].classlist.contains("extraclass")) disabled = true; if (disabled) wrapper.classlist.add("disablestyling"); else wrapper.classlist.remove("disablestyling"); }); removeclass.addeventlistener('click', function() { if (randomnumber !== -1) { box[randomnumber].classlist.remove('extraclass'); wrapper.classlist.toggle('disablestyling'); } });
Comments
Post a Comment