我正在编写动态创建div
的代码,并且我将此div
添加到现有div
。然后,我创建了一个p
元素,并希望将其添加到动态创建的div
。
这是我的代码:
HTML:
<div class="modal fade" id="destribution-details" role="dialog">
<div class="modal-dialog modal-lg" id="modal-lg">
</div>
</div>
JS:
var modal_lg = document.getElementById("modal-lg");
//modal header
var modal_content = document.createElement("div");
modal_content.className = "modal-content";
modal_lg.appendChild(modal_content);
var modal_header = document.createElement("div");
modal_header.className = "modal_header";
modal_content.appendChild(modal_header);
var closeButton = document.createElement("button");
closeButton.className = "close";
closeButton.setAttribute("data-dismiss", "modal");
var modal_title = document.createElement("h4");
modal_title.className = "modal-title";
modal_title.innerHTML = "Details 1";
modal_header.appendChild(closeButton);
modal_header.appendChild(modal_title);
//modal body
var modal_body = document.createElement("div");
modal_body.className = "modal-body";
modal_content.appendChild(modal_body);
var para = document.createAttribute("p");
modal_body.appendChild(para);
//modal footer
var modal_footer = document.createElement("div");
modal_footer.className = "modal-footer";
modal_lg.appendChild(modal_footer);
var closeButton = document.createElement("button");
closeButton.className = "btn btn-default";
closeButton.setAttribute("data-dismiss", "modal");
closeButton.innerHTML = "Close";
modal_footer.appendChild(closeButton);
当我运行它时,在我的控制台中出现错误Uncaught DOMException: Failed to execute 'appendChild' on 'Node': Nodes of type 'p' may not be inserted inside nodes of type 'DIV'.
请让我知道我哪里出错了,我该怎么办呢。
这是一个工作小提琴https://jsfiddle.net/57yf14o4/
由于
答案 0 :(得分:1)
当我运行它时,在我的控制台中,我收到一条错误消息“Uncaught” DOMException:无法执行&#39; appendChild&#39; on&#39; Node&#39;:类型的节点 &#39; P&#39;可能无法插入类型&#39; DIV&#39;
的节点内
p
也是一个元素,因此将其更正为
var para = document.createElement("p");
检查更新后的fiddle