如何使用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:
- Duplicate variable declaration: You first assign
var child = document.querySelectorAll(".child");to get all your.childelements, but then immediately re-declarevar child, i;—this overwrites thechildvariable withundefined, so your loop can't run properly. That's a big reason you're not getting all the content. - 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). - 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 ofvar) 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
相关产品推荐
相关产品推荐

