Reputation: 498
How to set a CSS property to multiple elements having the same class?
As for my situation: I would like to know how to set the background-image
for multiple elements which has the same class using vanilla JavaScript.
Let's say I have 5 div
's, each having a class .panel
<div class="container">
<div class="panel">
<h3>Mesmerizing Mountains</h3>
</div>
<div class="panel">
<h3>The connecticut</h3>
</div>
<div class="panel">
<h3>Spooky forest</h3>
</div>
<div class="panel">
<h3>Wheat fields</h3>
</div>
<div class="panel">
<h3>Alpha Hills</h3>
</div>
</div>
If i have the links to the images as an array, like this:
const imgLinks = ["https://example.com/panel_1img", "https://example.com/panel_2img", "https://example.com/panel_3img", "https://example.com/panel_4img", "https://example.com/panel_5img"]
How can i set the background-image
for each of the .panel
from the imgLinks
array.
quick note: The first element in the array should be the background-image
of the first .panel
The second element in the array should be the background-image
of the second .panel
and so on.
Upvotes: 2
Views: 618
Reputation: 31992
We can use querySelectorAll
to get an array of all elements with the class panel
and forEach
to loop through each.
const imgLinks = ["https://www.w3schools.com/cssref/paper.gif",
"https://www.w3schools.com/cssref/img_tree.gif",
"https://www.w3schools.com/cssref/img_tree.gif",
"https://www.w3schools.com/cssref/paper.gif",
"https://www.w3schools.com/cssref/img_tree.gif"];
/* images coutesy of w3schools.com */
document.querySelectorAll('.panel').forEach((e, i) => {
e.style.backgroundImage = `url('${imgLinks[i]}')`;
})
<div class="container">
<div class="panel">
<h3>Mesmerizing Mountains</h3>
</div>
<div class="panel">
<h3>The connecticut</h3>
</div>
<div class="panel">
<h3>Spooky forest</h3>
</div>
<div class="panel">
<h3>Wheat fields</h3>
</div>
<div class="panel">
<h3>Alpha Hills</h3>
</div>
</div>
Upvotes: 3