0

I'm trying to change all divs of one color to another one. It works with document.querySelector() but not with querySelectorAll. I would like to change all of them. Here's my code:

<html>
<head>
<script >
var v;
var v1;
function link(){
 v1=document.querySelector('[style*="background:black;"]');
 v1.style.backgroundColor = "red";
    v=document.querySelectorAll('[style*="background:black;"]');
 v.style.backgroundColor = "red";
}
</script>
</head>
<body>
<div style="background:black; height:100px; width:100px;"></div>
<div style="background:blue; height:100px; width:100px;"></div>
<div style="background:black; height:100px; width:100px;"></div>
<div style="background:black; height:100px; width:100px;"></div>
<div style="background:blue; height:100px; width:100px;"></div>
<button onclick="link()" style="height:20px; width:50px;">Click </button>

</body>
</html>

Any ideas on what could I do? Thanks!

Tamir Abutbul
  • 7,301
  • 7
  • 25
  • 53
Matus86309
  • 41
  • 1
  • 8
  • Does this answer your question? [What do querySelectorAll and getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return) – Titus Nov 10 '19 at 10:16

2 Answers2

0

Use for Each, because querySelectorAll will not return you one element

<html>
<head>
<script >
var v;
var v1;
function link(){
 v1=document.querySelector('[style*="background:black;"]');
 v1.style.backgroundColor = "red";
    v=document.querySelectorAll('[style*="background:black;"]');
  v.forEach(function(value){
   value.style.backgroundColor = "red";
  })
}
</script>
</head>
<body>
<div style="background:black; height:100px; width:100px;"></div>
<div style="background:blue; height:100px; width:100px;"></div>
<div style="background:black; height:100px; width:100px;"></div>
<div style="background:black; height:100px; width:100px;"></div>
<div style="background:blue; height:100px; width:100px;"></div>
<button onclick="link()" style="height:20px; width:50px;">Click </button>

</body>
</html>
Ace
  • 1,398
  • 13
  • 24
0

var v;
var v1;
function link(){

    v=document.querySelectorAll('[style*="background:black;"]');
    for(var j in v){
        if(v[j].style){
            v[j].style.backgroundColor = "red";
        }
    }
  
}
<html>
<head>
</head>
<body>
<div style="background:black; height:100px; width:100px;"></div>
<div style="background:blue; height:100px; width:100px;"></div>
<div style="background:black; height:100px; width:100px;"></div>
<div style="background:black; height:100px; width:100px;"></div>
<div style="background:blue; height:100px; width:100px;"></div>
<button onclick="link()" style="height:20px; width:50px;">Click </button>

</body>
</html>
François Huppé
  • 2,006
  • 1
  • 6
  • 15