Javascript appendChild() not working.

僤鯓⒐⒋嵵緔 提交于 2019-12-08 06:07:13

问题


I am at a loss as to why the following is not working.

HTML:

    ...    
        <div class="col2">
            <h2>Your Groups</h2>
            <input type="submit" id="addnew" class="btn btn-primary" value="Create New Group"/> 
            <div id="parent">
                <!--new div here-->
            </div>
        </div> 
    ...

Javascript:

document.getElementById('addnew').onclick = function(){

    var parent = document.getElementById('parent'); 
    var newGroup = document.createElement("div"); 
    newGroup.setAttribute("id", "newGroup"); 
    newGroup.setAttribute("class", "inner");
    parent.appendChild(newGroup); 
};

Thank you in advance for your help.


回答1:


Your code is working (assuming your JS is located below those elements). You're just not setting any content in the element.

First, you should learn about the web developer tools in your browser. Hit "F12", and locate your "parent" div in the "elements" tab in the window that appears. Once you locate the "parent" element, click on your button. You'll see your new div appear under "parent".

However, it's not rendering anything because it has no content. Simply do

newGroup.textContent = "Hello, world!";

After creating the element with document.createElement, and you'll now have content in your child.

Also, don't set the id of each child to the same value. Id's in HTML are meant to be unique. You perhaps should also consider using addEventListener instead of onclick in your code.




回答2:


What are you trying to do? Are you trying to access the parent and newGroup outside of the function? If so, you need to declare the variables outside the function.

var parent;
var newGroup;

document.getElementById('addnew').onclick = function(){

var parent = document.getElementById('parent'); 
var newGroup = document.createElement("div"); 
newGroup.setAttribute("id", "newGroup"); 
newGroup.setAttribute("class", "inner");
parent.appendChild(newGroup); 
};

You are just displaying an empty div so if you were wondering why you don't see anything, that is probably why. Try adding a simple string or CSS styling to see your new div. Here is an example: http://jsfiddle.net/inspiredtolive/Lrydh3ar/2/



来源:https://stackoverflow.com/questions/33838339/javascript-appendchild-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!