1

I have 2 arrays or more likely NodeLists,

const mainSlides = document.querySelectorAll('.mainSlides')
const thumbSlides = document.querySelectorAll('.thumbSlides')

Currently i am iterating over them like this:


mainSlides.forEach(slide => {
    slide.style.backgroundColor = `red`
})

thumbSlides.forEach(slide => {
    slide.style.backgroundColor = `red`
})

Since they both set the same property ie; background-color:red;, is there a shorthand way to loop through both nodelists at once?

const mainSlides = document.querySelectorAll('.mainSlides')
const thumbSlides = document.querySelectorAll('.thumbSlides')

mainSlides.forEach(slide => {
    slide.style.backgroundColor = `red`
})

thumbSlides.forEach(slide => {
  //  slide.style.backgroundColor = `red`
})
<div class="holder">
  <div class="mainSlides"> some mainSlides </div>
  <div class="mainSlides"> some mainSlides </div>
  <div class="mainSlides"> some mainSlides </div>
  <div class="mainSlides"> some mainSlides </div>
</div>

 <div class="holder">  
  <div class="thumbSlides"> some mainSlides </div>
  <div class="thumbSlides"> some mainSlides </div>
  <div class="thumbSlides"> some mainSlides </div>
  <div class="thumbSlides"> some mainSlides </div>
</div>

2
  • 1
    If you give both .mainSlides and .thumbSlides an additional class such as .slides, then you can select all slides and perform your loop on that one NodeList. Otherwise, if your NodeLists contain the same amount of elements, then you can iterate one and use the index (second argument of forEach callback) to target the other node list's elements Commented Jul 24, 2021 at 9:02
  • This code work fine ! I added your code to code snippet and works nice. I give you possible fix in answer. Commented Jul 24, 2021 at 9:33

2 Answers 2

3

Yes, you can select both in one selector:

const mainAndThumbSlides = document.querySelectorAll('.mainSlides,.thumbSlides')
Sign up to request clarification or add additional context in comments.

Comments

2

You can select both mainSlides and thumbSlides like so:

const allSlides = document.querySelectorAll('.mainSlides, .thumbSlides');

Or, if you don't want to select them together (e.g. if you want to use them further separately) but just want to use them together for this specific action:

const allSlides = [...mainSlides, ...thumbSlides];
allSlides.forEach(slide => {
    slide.style.backgroundColor = 'red';
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.