0

Trying to change the text of all points having a class name as child.

Tried the below code but it is not changing.

function myFunction() {

  document.getElementsByClassName("child").innerHTML = "Milk";
}
<!DOCTYPE html>
<html>

<body>

  <ul class="example">
    <li class="child">Coffee</li>
    <li class="child">Tea</li>
  </ul>


  <button onclick="myFunction()">Click here!</button>

</body>

</html>
user9836106
  • 105
  • 1
  • 2
  • 8

2 Answers2

2

To get all the elements with specific selector you can use Document.querySelectorAll(). Then loop through all the element to set the content.

Please Note: If the value to be set is text then it is better to use textContent instead of innerHTML:

function myFunction() {
  document.querySelectorAll(".child").forEach(function(li){
    li.textContent = "Milk";
  });
}
<!DOCTYPE html>
<html>

<body>

  <ul class="example">
    <li class="child">Coffee</li>
    <li class="child">Tea</li>
  </ul>

  <button onclick="myFunction()">Click here!</button>

</body>

</html>
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

document.getElementsByClassName() returns an array of HTMLElements. So you can not use innerHTML instantly.

You need to iterate over the array, for example like so:

var eles = document.getElementsByClassName('child');
for (var i = 0; i < eles.length; i++) {
    eles[i].innerHTML = 'Milk';
}
Stephan Strate
  • 1,401
  • 1
  • 12
  • 15