如何基于div的样式使用jquerySelectorAll

时间:2019-11-10 10:10:58

标签: javascript jquery html

我正在尝试将一种颜色的所有div更改为另一种颜色。它适用于document.querySelector(),但不适用于querySelectorAll。我想更改所有这些。这是我的代码:

<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>

关于我该怎么办的任何想法?谢谢!

2 个答案:

答案 0 :(得分:0)

用于“每个”,因为querySelectorAll不会返回一个元素

<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>

答案 1 :(得分: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>