2016-04-16 25 views
-1
<!DOCTYPE html> 
<html> 
<body> 

<div class="example">First div element with class="example".</div> 

<div class="example">Second div element with class="example".</div> 

<p>Click the button to change the text of the first div element with class="example" (index 0).</p> 

<button onclick="myFunction()">Try it</button> 

<p><strong>Note:</strong> The getElementsByClassName() method is not supported in Internet Explorer 8 and earlier versions.</p> 

<script> 
function myFunction() { 
    var x = document.getElementsByClassName("example"); 
    x[0].innerHTML = "Hello World!"; 
} 
</script> 

</body> 
</html> 

鏈接,例如:http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_document_getelementsbyclassname如何返回2個值與getElementsByClassName()?

這個例子告訴我們如何改變第一個div來的 「Hello World」。我想學習我如何將所有課程改爲「Hello world」。我試圖將x[0].innerHTML = "Hello World!";更改爲x[*].innerHTML = "Hello World!";,但沒有發生任何事情。任何想法? :/

+0

它可能是重複的,但提問者似乎並不明白他需要循環... –

回答

0

使用循環爲:

<!DOCTYPE html> 
 
<html> 
 
<body> 
 

 
<div class="example">First div element with class="example".</div> 
 

 
<div class="example">Second div element with class="example".</div> 
 

 
<p>Click the button to change the text of the first div element with class="example" (index 0).</p> 
 

 
<button onclick="myFunction()">Try it</button> 
 

 
<p><strong>Note:</strong> The getElementsByClassName() method is not supported in Internet Explorer 8 and earlier versions.</p> 
 

 
<script> 
 
function myFunction() { 
 
    var x = document.getElementsByClassName("example"); 
 
    for(var i = 0; i < x.length; i++) 
 
    x[i].innerHTML = "Hello World!"; 
 
} 
 
</script> 
 

 
</body> 
 
</html>

0

你必須使用一個循環,以影響所有的元素:

function myFunction() { 
    var x = document.getElementsByClassName("example"); 
    for (var i = 0; i < x.length; i++) 
     x[i].innerHTML = "Hello World!"; 
} 
0

您可以使用querySelectorAll方法:

function myFunction() { 
    var divs = document.querySelectorAll('.example'); 
    [].forEach.call(divs, function(div) { 
     div.innerHTML = "Hello World!"; 
    }); 
}