Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select all items with class name using document.querySelector

Tags:

javascript

I have 4 images using the class .light-image

I am trying to change them all using js. The code below only grabs the first item, how can I make it grab all 4?

if (window.matchMedia("(max-width: 768px)").matches) {
  document.querySelector('.light-image').src="/app/themes/piranha/assets/public/images/light-open.svg";
}
like image 570
Justin Blayney Avatar asked Dec 30 '25 06:12

Justin Blayney


1 Answers

Instead of querySelector use querySelectorAll that returns a node list of all elements matching the selector (not just the first one).

Then you need to iterate it over the node list.


if (window.matchMedia("(max-width: 768px)").matches) {
  let itemList = [...document.querySelectorAll('.light-image')]
  itemList.forEach(el => el.src="/app/themes/piranha/assets/public/images/light-open.svg";)
}

See this post for more information

like image 52
lior bakalo Avatar answered Dec 31 '25 22:12

lior bakalo