-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>

Link for example: http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_document_getelementsbyclassname

This example show us how to change first div to "hello world". I wanna learn how can i change all classes to "Hello world". I tried to change x[0].innerHTML = "Hello World!"; to x[*].innerHTML = "Hello World!"; but nothing happened. Any idea? :/

3 Answers3

0

You have to use a loop in order to affect all of the elements:

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

Use loop as:

<!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>
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
0

You can use querySelectorAll method:

function myFunction() {
    var divs = document.querySelectorAll('.example');
    [].forEach.call(divs, function(div) {
        div.innerHTML = "Hello World!";
    });
}
n-dru
  • 9,285
  • 2
  • 29
  • 42