Как я могу использовать jquerySelectorAll на основе стиля div - PullRequest
0 голосов
/ 10 ноября 2019

Я пытаюсь изменить все деления одного цвета на другой. Он работает с 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 голосов
/ 10 ноября 2019

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>
0 голосов
/ 10 ноября 2019

Используйте для каждого, потому что 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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...