-1

Bit of a JS novice so excuse the question, but I have two menu lists in which I want the images to change. It works with just one menu using the below JS

function changeImage(anything) {
        document.getElementById('slider').src = anything;
      }

But if I try to target two IDs using document.querySelectorAll("slider, slider 2"); it still only works with one IDs. Is there any way to target both IDs as I don't think

https://jsfiddle.net/hyt1xLkz/

Thanks!

daniel.b
  • 27
  • 4
  • use classes instead of id. `class='slider'` and then `document.getElementsByClassName('slider)` – pilchard Mar 16 '22 at 09:32
  • querySelectorAll uses css selectors not id names, so you'd have to add hashes in front of the id name – Krzysztof Krzeszewski Mar 16 '22 at 09:32
  • To get all the elements in the querySelectorAll you can: 1. Add *#* before the names 2. Switch the ids from images to classes If you decide to add classes to your images, remember that in your changeImage function you need to use getElementsByClassName method which (in this case) return array. So you'll need to go through each element of this array to update the src attribute. Demo: https://jsfiddle.net/a0g3srLh/ – Dominik Chudy Mar 16 '22 at 09:43

2 Answers2

0

it shouldn't be much more then adding a "#" infront of the id's in the querySelector as so

document.querySelectorAll("#slider, #slider2")
Daniel707
  • 15
  • 2
0

You can do it like this:

document.querySelectorAll("#slider, #slider2");
Nikhil
  • 60
  • 8