2017-02-06 40 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> 
相關問題