You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript获取同class名元素的全部innerHTML内容?

Fix: Get innerHTML of All Elements with the Same Class

Hey there, let's break down why your code isn't working as expected and fix it up step by step!

First, let's spot the issues in your code:

  1. Duplicate variable declaration: You first assign var child = document.querySelectorAll(".child"); to get all your .child elements, but then immediately re-declare var child, i;—this overwrites the child variable with undefined, so your loop can't run properly. That's a big reason you're not getting all the content.
  2. Overwriting the result variable: Even if you had the correct list of elements, your loop keeps reassigning childall = child[i].innerHTML, which means only the last element's content gets stored (not all of them).
  3. Invalid duplicate IDs: While this doesn't break the class selection, having two elements with id="child" is against HTML rules—IDs must be unique. It's a good practice to remove those duplicate IDs or rename them.

Here's the fixed code:

JavaScript (using forEach for cleaner syntax):

function myFunction() {
  // Grab all elements with class "child"
  const children = document.querySelectorAll(".child");
  // Store all innerHTML values in an array
  const allInnerHTML = [];

  // Loop through each child element and collect its innerHTML
  children.forEach(child => {
    allInnerHTML.push(child.innerHTML);
  });

  // Display the results in the demo div (using <br> to separate each entry)
  document.getElementById("demo").innerHTML = allInnerHTML.join("<br>");
}

Or if you prefer a traditional for loop:

function myFunction() {
  const children = document.querySelectorAll(".child");
  let allInnerHTML = "";

  for (let i = 0; i < children.length; i++) {
    // Append each innerHTML to the string, with a line break
    allInnerHTML += children[i].innerHTML + "<br>";
  }

  document.getElementById("demo").innerHTML = allInnerHTML;
}

Fixed HTML (removed duplicate IDs):

<div class="parent" id="parent">
  <div class="child">Hello</div>
  <div class="child">World!</div>
</div>
<button onclick="myFunction()">click</button>
<div class="demo" id="demo"></div>

What changed?

  • We use const (instead of var) for variables that don't need reassigning—this avoids accidental overwrites and makes the code clearer.
  • We collect all innerHTML values either in an array (then join them with line breaks) or build a string incrementally, so we keep all content instead of just the last one.
  • We fixed the duplicate ID issue to follow HTML standards.

Now when you click the button, you'll see both "Hello" and "World!" (and any additional .child elements you add later) displayed in the demo div.

内容的提问来源于stack exchange,提问作者maja

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:19:53