2016-04-16 10 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_getelementsbyclassnamegetElementsByClassName()で2つの値を返すにはどうすればよいですか?例えば

この例では、 "Hello World" のへの最初のdivを変更する方法を私たちに示しています。 私はすべてのクラスを "Hello world"に変更する方法を知りたいです。 x[0].innerHTML = "Hello World!";x[*].innerHTML = "Hello World!";に変更しようとしましたが、何も起こりませんでした。何か案が? :

function myFunction() { 
    var x = document.getElementsByClassName("example"); 
    for (var i = 0; i < x.length; i++) 
     x[i].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 divs = document.querySelectorAll('.example'); 
    [].forEach.call(divs, function(div) { 
     div.innerHTML = "Hello World!"; 
    }); 
} 
0

あなたはquerySelectorAllメソッドを使用することができます/

関連する問題