要选择div中的所有p标记 - 它适用于document.getElementById()
,但不适用于document.getElementsByTagName()
。那是为什么?
<div id="myDIV">
<h2 class="example">A heading with class="example" in div</h2>
<p>Para 1 first</p>
<p>Para 2</p>
<p>Para 3</p>
<p>Para 4</p>
</div>
<button onclick="myFunction()">Submit</button>
这有效
function myFunction() {
var x = document.getElementById("myDIV").querySelectorAll("p");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.backgroundColor = "red";
}
}
这不是
function myFunction() {
var x = document.getElementsByTagName("div").querySelectorAll("p");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.backgroundColor = "red";
}
}
答案 0 :(得分:1)
我建议使用直接选择器,如:
document.querySelectorAll("#myDIV p");
//Or
document.querySelectorAll("div p");
希望这有帮助。
var x = document.querySelectorAll("div p");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.backgroundColor = "red";
}
<div id="myDIV">
<h2 class="example">A heading with class="example" in div</h2>
<p>Para 1 first</p>
<p>Para 2</p>
<p>Para 3</p>
<p>Para 4</p>
</div>
答案 1 :(得分:0)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div id="myDIV">
<h2 class="example">A heading with class="example" in div</h2>
<p>Para 1 first</p>
<p>Para 2</p>
<p>Para 3</p>
<p>Para 4</p>
</div>
<button onclick="myFunction()">Submit</button>
<script>
function myFunction() {
var x = document.querySelectorAll("p");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.backgroundColor = "red";
}
}
</script>
</body>
</html>