我知道如何使用querySelector、id等获取元素。但是如何遍历多个元素,然后选择一个元素。下面的片段将说明我愿意实现的目标。
在这里,我希望通过类p
遍历example
并应用一些css。
function myFunction() {
//document.querySelector(".example").style.backgroundColor = "red";
document.querySelector(".example p").style.backgroundColor = "red";
}
<!DOCTYPE html>
<html>
<body>
<div class="example">
<p>Hello lovely people</p>
<p>Hello lovely people</p>
<p>Hello lovely people</p>
</div>
<button onclick="myFunction()">Try it</button>
</body>
</html>
发布于 2017-04-18 23:13:33
关于你在评论中的问题:
如果您的p
在一个.example
中,并且您希望所有这些都在按钮单击时被更改,您可以将您的函数更改为:
function myFunction() {
var element = document.querySelectorAll('.example p');
for(i = 0; i <= element.length; i++) {
element[i].style.backgroundColor = 'red';
}
}
“老”问题
您可以在您的+
中使用querySelector
CSS选择器。
使它
document.querySelector(".example + p").style.backgroundColor = "red";
function myFunction() {
document.querySelector(".example + p").style.backgroundColor = "red";
}
<!DOCTYPE html>
<html>
<body>
<h2 class="example">Dont be a racist hate everyone.</h2>
<p>Hello lovely people</p> <!-- This element I wish to make red -->
<button onclick="myFunction()">Try it</button>
</body>
</html>
发布于 2017-04-18 23:23:19
你可以用“TreeWalker”。它基于提供的过滤器遍历所有节点。
<script type="text/javascript">
var walker = document.createTreeWalker(
document.body, window.NodeFilter.SHOW_ELEMENT, null, false
),currentNode;
currentNode = walker.nextNode();
while (currentNode !== null) {
currentNode.style.backgroundColor = 'red';
currentNode = walker.nextNode();
}
</script>
上面的示例只需遍历document.body
中的所有ode并应用背景颜色红色。但是要确保从父节点遍历。在您的例子中,您可以将'.example‘和'p’放在'div‘和遍历中。
<div class="container>
<h2 class="example">Dont be a racist hate everyone.</h2>
<p>Hello lovely people</p>
</div>
并将walker设置为此容器节点。
var walker = document.createTreeWalker(
document.querySelector('.container'), window.NodeFilter.SHOW_ELEMENT, null, false
)
发布于 2017-04-18 23:19:08
如果您希望元素后面的p带有“示例”类,那么在类和p之间使用"+“。
function myFunction() {
document.querySelector(".example+p").style.backgroundColor = "red";
}
<!DOCTYPE html>
<html>
<body>
<h2 class="example">Dont be a racist hate everyone.</h2>
<p>Hello lovely people</p> <!-- This element I wish to make red -->
<button onclick="myFunction()">Try it</button>
</body>
</html>
https://stackoverflow.com/questions/43488872
复制相似问题