0

I tried to use querySelector All. I added onclick to button. And I made a function and wanted to change divs background. but i does not work even if i clicked the button. I want to know what i am doing wrong

<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="jquery-3.5.1.min.js"></script>
<link rel="stylesheet" href="stil.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>

    <button type="button" onclick="basla()">TIKLA</button> I ADDED ONCLİCK TO START FUNCTION
    
<div id="kutu1" class="kutu"></div>
<div id="kutu2" class="kutu"></div>
<div id="kutu3" class="kutu"></div>


<script>

function basla () {                          

var kutular = document.querySelectorAll(".kutu");                 

kutular.style.background = "white";      

}



</script>

</body>
</html>
Vedat
  • 15
  • 4
  • What **exactly** does "it does not work" mean? Does *anything* happen? Are errors reported? – Pointy Feb 16 '22 at 20:49

1 Answers1

2

document.querySelectorAll returns a NodeList. You cannot access .style on the NodeList directly.

var kutular = document.querySelectorAll(".kutu");
kutular.style.background = "white"; // ❌

You must iterate over the resulting NodeList using for..of

var kutular = document.querySelectorAll(".kutu");
for (const elem of kutular) {
  elem.style.background = "white"; // ✅
}
よつば
  • 467
  • 1
  • 8
  • I would favour using a class instead of updating the style directly: `elem.classList.add('white)`. `forEach` also works well. – Andy Feb 16 '22 at 20:54
  • The question asks to edit `style` directly so that is the answer I provide. Thanks for comment. – よつば Feb 16 '22 at 20:55
  • And that's why I upvoted you :) – Andy Feb 16 '22 at 20:56
  • 1
    Do try to avoid answering questions [that have been asked many times before](https://stackoverflow.com/questions/linked/10693845?lq=1) (as advised in [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer)). Questions like this are closed [as a duplicate](https://stackoverflow.com/help/duplicates) so we can keep all the good/up-to-date content in one place. – Ivar Feb 16 '22 at 21:12
  • @Ivar the question was open when I submitted my answer. I did not know sorry. – よつば Feb 16 '22 at 21:14
  • @よつば I don't blame you for not knowing. You just recently created your Stack Overflow account. :) It was just a hint for future reference. – Ivar Feb 16 '22 at 22:11