Javascript appendChild()不起作用。

时间:2015-11-21 00:38:57

标签: javascript appendchild

我不知道为什么以下不起作用。

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); 
};

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

您的代码正在运行(假设您的JS位于这些元素下方)。您只是没有在元素中设置任何内容。

首先,您应该了解浏览器中的Web开发人员工具。点击&#34; F12&#34;,找到您的父母&#34; &#34;元素中的div&#34;出现的窗口中的选项卡。一旦找到&#34;父母&#34;元素,单击您的按钮。您会看到您的新div显示在&#34; parent&#34;。

但是,它没有呈现任何内容,因为它没有内容。只需做

newGroup.textContent = "Hello, world!";

使用document.createElement创建元素后,您现在可以在您的孩子中拥有内容。

另外,不要将每个孩子的id设置为相同的值。 HTML中的ID应该是唯一的。您也许应该考虑在代码中使用addEventListener而不是onclick。

答案 1 :(得分:0)

你想做什么?您是否尝试访问函数外部的parent和newGroup?如果是这样,您需要在函数外声明变量。

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); 
};

你只是展示一个空div,所以如果你想知道为什么你什么也看不见,那可能就是原因。尝试添加一个简单的字符串或CSS样式来查看您的新div。以下是一个示例:http://jsfiddle.net/inspiredtolive/Lrydh3ar/2/