使用JavaScript创建HTML Div出现异常,求问题排查与修复方案
Issue Analysis & Solution
Great question! The problem you're seeing ([object HTMLDivElement]) happens because you're using innerHTML to assign DOM element objects directly. innerHTML expects an HTML string, not an element object—when you pass an element, it gets converted to its string representation instead of being inserted into the DOM properly. Let's break down the fixes step by step.
Key Mistakes in Your Code:
- Using
innerHTMLto add DOM elements (instead of appending them) - Repeatedly overwriting
alcohol.innerHTML(each call replaces content instead of adding to it) - Overwriting
row.innerHTMLin each loop iteration (so only the last element would be kept even if fixed)
Corrected JavaScript Function
function addDivs() { var jsonInput = { 'a': '1', 'b': '2' }; var colDiv = document.getElementById("col-md-12"); // Clear existing content to avoid duplicates on multiple button clicks colDiv.innerHTML = ''; var row = document.createElement("div"); row.className = "row"; Object.keys(jsonInput).forEach(function(k) { var string = k; var range = jsonInput[k]; var col4Div = document.createElement("div"); col4Div.className = "col-md-4 icon-plus"; var alcohol = document.createElement("span"); alcohol.className = string; // Create and append <strong> element var strong = document.createElement("strong"); strong.textContent = string; alcohol.appendChild(strong); // Create and append dropdown arrow var dropDownArrow = document.createElement("span"); dropDownArrow.className = "down-arrow"; alcohol.appendChild(dropDownArrow); // Add line break alcohol.appendChild(document.createElement("br")); // Add the range text alcohol.appendChild(document.createTextNode(range)); col4Div.appendChild(alcohol); row.appendChild(col4Div); }); colDiv.appendChild(row); }
Explanation of Changes:
- Use
appendChild()instead ofinnerHTML: This properly inserts DOM elements into their parent containers without converting them to strings. - Avoid overwriting content: Instead of setting
alcohol.innerHTMLmultiple times (which replaces content each time), we append each element and text node sequentially. - Clear existing content: Added
colDiv.innerHTML = ''to ensure clicking the button multiple times doesn't create duplicate rows. - Use
textContentfor plain text: For elements like<strong>that only contain plain text,textContentis safer and more efficient thaninnerHTML.
Resulting HTML Structure
After clicking the button, the DOM will match your expected output exactly:
<div id="col-md-12"> <div class="row"> <div class="col-md-4 icon-plus"> <span class="a"> <strong>a</strong> <span class="down-arrow"></span> <br> 1 </span> </div> <div class="col-md-4 icon-plus"> <span class="b"> <strong>b</strong> <span class="down-arrow"></span> <br> 2 </span> </div> </div> </div>
内容的提问来源于stack exchange,提问作者user3872094
相关产品推荐
相关产品推荐

