Add styles with js in the DOM

0

I am trying to add css to all the elements with the class menu-icon and menu-title, but when doing so with js, I only add the css to the first element. I mean, I have about 10 elements with that label but it only adds the style to the first one

var x = document.getElementsByClassName("menu-title")[0];
x.style.marginLeft = "25px";

var y = document.getElementsByClassName("menu-icon")[0];
y.style.backgroundSize = "contain";
    
asked by Tefef 06.11.2018 в 10:02
source

2 answers

5

Of course, you add it to the first element because you have a [0] .

By using getElementsByClassName , you collect a lista of items with that same class. It is not like getElementById because a id is unique.

What you would have to do would be to go through it, and for each round, you add the styles.

It would be as follows:

var x = document.getElementsByClassName("menu-title");
for(var i = 0; i < x.length; i++){
     x[i].style.marginLeft = "25px";
}

var y = document.getElementsByClassName("menu-icon");
for(var i = 0; i < y.length; i++){
     y[i].style.backgroundColor = "yellow";    
}
<div class="menu-title">Clase menu-title</div>
<div class="menu-title">Clase menu-title</div>
<div class="menu-title">Clase menu-title</div>
<div class="menu-icon">Clase menu-icon</div>
<div class="menu-icon">Clase menu-icon</div>
<div class="menu-icon">Clase menu-icon</div>
    
answered by 06.11.2018 / 10:06
source
4

As they indicate, getElementsByClassName returns a list of elements with the indicated class. Just review it with for and you're done.

var x = document.getElementsByClassName("menu-title");

for(elt of x){
  elt.style.marginLeft = "25px";
}

var y = document.getElementsByClassName("menu-icon");
for(elt of y){
  elt.style.backgroundColor = "Red";
}
<html>
<body>
<div class="menu-title">Menu 1</div>
<div class="menu-title">Menu 2</div>
<div class="menu-title">Menu 3</div>
<div class="menu-title">Menu 4</div>

<div class="menu-icon">Icono 1</div>
<div class="menu-icon">Icono 2</div>
<div class="menu-icon">Icono 3</div>
<div class="menu-icon">Icono 4</div>
</body>
</html>
    
answered by 06.11.2018 в 10:08