-1

I can't figure out I want when I press button and selected all paragraphs and changing font-color but I cant I was trying

<script>
var colorChanger = document.getElementsByTagName("button")[0];
colorChanger.addEventListener("click",function() {
  document.querySelector('p').style.color = "blue";  
});
</script>

working code but only 1 paragraph so after I was trying

<script>
var colorChanger = document.getElementsByTagName("button")[0];
colorChanger.addEventListener("click",function() {
  document.querySelectorAll('p').style.color = "blue";  
});
</script>

doesn't work ...
I tried giving the same id tag to all the paragraphs, but again only 1 of them worked.

Rana
  • 2,500
  • 2
  • 7
  • 28
  • `document.querySelectorAll()` returns a `NodeList` iterable, you can't just assign values to `style` (NodeList does not have any such attribute). Loop the members of the returned `NodeList` and apply the style to each. – esqew Oct 27 '21 at 16:09
  • 1
    Duplicate of [What do querySelectorAll and getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return) – esqew Oct 27 '21 at 16:10

1 Answers1

0

Since document.querySelectorAll('p') returns an array, you need to loop and set the color.

var colorChanger = document.getElementsByTagName("button")[0];
colorChanger.addEventListener("click",function() {
  let allP = document.querySelectorAll('p');
  for(let i=0; i<allP.length; i++)
  {
    allP[i].style.color = "blue"; 
  }
});
<button>Click</button>
<p>para1</p>
<p>para2</p>
<p>para3</p>
Ayaz
  • 2,111
  • 4
  • 13
  • 16