Search code examples
javascriptfunctionclassgetinnerhtml

How get content of all element with same class name?


Get content of all elements with the same class name using javascript. How can I get all innerHTML-content from elements with the same class? I tried the code described below but it doesn't work I only get the first "Hello" from element but I don't get "World! from the second element" Of course there will be many more elements with the same class, not just two.

function myFunction() {
  var child = document.querySelectorAll(".child");
  var child, i;
  for (i = 0; i < child.length; i++) {
    var childall = child[i].innerHTML;
  }

  document.getElementById("demo").innerHTML = childall;
}
<div class="parent" id="parent">
  <div class="child" id="child">Hello</div>
  <div class="child" id="child">World!</div>
</div>
<button onclick="myFunction()">click</button>
<div class="demo" id="demo">


Solution

  • Move childall out of the loop, and assign an array to it. Now push all innerHTML values into it. After the loop ends join the array to a string, and assign to demo.

    function myFunction() {
      var child = document.querySelectorAll(".child");
      var child, i;
      var childall = [];
      for (i = 0; i < child.length; i++) {
        childall.push(child[i].innerHTML);
      }
    
      document.getElementById("demo").innerHTML = childall.join('<br>');
    }
    <div class="parent" id="parent">
      <div class="child" id="child">Hello</div>
      <div class="child" id="child">World!</div>
    </div>
    <button onclick="myFunction()">click</button>
    <div class="demo" id="demo">

    Instead of a for loop, you can use Array.from() to get an array of children's innerHTML.

    function myFunction() {
      const childall = Array.from(document.querySelectorAll(".child"), el => el.innerHTML);
    
      document.getElementById("demo").innerHTML = childall.join('<br>');
    }
    <div class="parent" id="parent">
      <div class="child" id="child">Hello</div>
      <div class="child" id="child">World!</div>
    </div>
    <button onclick="myFunction()">click</button>
    <div class="demo" id="demo">