0

I'm trying change CSS class property value. I'm using this soluction:

let pizzas = document.querySelectorAll('.pizza');
pizzas.forEach( pizzaElement => pizzaElement.style.display = 'none' );

Anyone has a solution without use iteration?

  • Does this answer your question? [How can I change an element's class with JavaScript?](https://stackoverflow.com/questions/195951/how-can-i-change-an-elements-class-with-javascript) – aekit Dec 02 '21 at 07:52

3 Answers3

0

It's better to use classList API with possibility to add, remove or toggle CSS classes: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

aleks korovin
  • 724
  • 4
  • 6
0
let pizzas = document.querySelectorAll('.pizza');
 
pizzas.forEach( pizzaElement => pizzaElement.classList.add('d-none') );

jsfiddle

EDIT: Please describe exactly where you want to use it. If you do not want to change the property of any event it is unnecessary to do with JS. You can overwrite css or add a new class ..

Todor Markov
  • 507
  • 5
  • 12
0

if your using pure JavaScript You can use this code:

let pizzas = document.querySelectorAll('.pizza');
pizzas[0].style.display = 'none';
pizzas[1].style.display = 'none';
pizzas[2].style.display = 'none';

or if you are using JQuery you can use this:

$(document).ready(function(){

   $('.pizza').css('display','none');

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<DOCTYPE html>

  <head>
  </head>

  <body>
    <div class="pizza">Some Text</div>
    <div class="pizza">Some Other Text</div>
    <div class="pizza">Text</div>
  </body>

  </html>
  • I'm using pure javascript and looking for a solution without use iteration – Christian Eduardo Dec 02 '21 at 17:44
  • @ChristianEduardo The solution is: make a class in your CSS file that implements your desired style. then use this JS code to implement it on your page:`elementName.classList.add("THE CLASS NAME")` – Anas Hassan Dec 03 '21 at 12:09