2017-02-06 48 views
1

要选择div内的所有p标记 - 它与document.getElementById()一起使用,但不与document.getElementsByTagName()一起使用。这是为什么?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"; 
    } 
} 
+2

'document.getElementsByTagName(“div”)'返回集合但不是单个Node,因此您不能在其上使用'querySelector'。 –

+0

你在混淆解决方案,这是一种不公平的比较。 'document.getElementById(“myDiv”)。getElementsByTagName(“p”);'应该工作。 –

+0

这很有道理。谢谢。函数myFunction(){ var x = document.getElementsByTagName(“div”)[0] .querySelectorAll(“p”); var i;对于(i = 0; i

回答

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>

+0

它说 - 不能设置backgroundColor的undefined –

+0

在哪里?你有没有试过我的代码片段? –

+0

我的意思是如果你使用document.querySelectorAll(“div p”);它会给出未定义的错误 –

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> 
相关问题