3

I am trying to change the colors of each element(button) within a node list with one line of code. First, I made the node list:

var buttons = document.querySelectorAll('button');

Now what I would like to do is change the color of each of the buttons, with one line of code. I tried

buttons.style.color = "green";

This returns an error saying that buttons is undefined. I assume that it's not possible to change all elements with that line of code, and I have been unable to find another way to do so. So if anyone knows, help would be appreciated.

MartyMcFarty
  • 339
  • 1
  • 3
  • 8
  • Since the marked duplicate doesn't really answer the question ... You must iterate over the elements, either using a loop or something like `forEach`. You should check your browser compatibility restrictions, but a "modern" solution would be `document.querySelectorAll('button').forEach(el => el.style.color = 'green')`. – Damon Jun 19 '18 at 23:33
  • @Damon the duplicate questions answer perfectly this question [if of course we take the time to read them] ... as a side note the code you shared is already in those duplicate : https://stackoverflow.com/a/44874457/8620333 which confirm it's a perfect duplicate – Temani Afif Jun 19 '18 at 23:36
  • @TemaniAfif the second link only showed up after I made that comment, I was referring to https://stackoverflow.com/questions/14377590/queryselector-and-queryselectorall-vs-getelementsbyclassname-and-getelementbyid which is not relevant – Damon Jun 19 '18 at 23:43
  • but yes this has been answered many times elsewhere: https://stackoverflow.com/questions/12330086/how-to-loop-through-selected-elements-with-document-queryselectorall – Damon Jun 19 '18 at 23:44

1 Answers1

0

with [].slice.call(document.querySelectorAll('button')); you get an Array and its more easy to work with arrays than nodelist

Sidy Mbengue
  • 19
  • 1
  • 5