为什么appendChild不起作用?

时间:2017-05-13 11:17:04

标签: javascript html css css3

我正在尝试创建三个元素(父元素和一个子元素),但第三个元素<a>标记不会附加到modalChild事件,因为它认为它正确创建它。

modal = document.createElement("div");
    modal.className = "parent";
	modalChild = document.createElement("div");
	modalChild.className = "child";
    btnClose = document.createElement("a");
	btnClose.className = "btnClose";
	btnClose.textContent = "X";

	modal.appendChild(modalChild);
	modalChild.appendChild(btnClose);

	document.body.appendChild(modal);
	modal.style.display = "flex";

正确地将

modalChild附加到模态,但btnClose不会附加到modalChild。有没有人看到代码的问题?

1 个答案:

答案 0 :(得分:0)

代码可以正常工作。您可以按任何顺序附加到modalChild

modal = document.createElement("div");
modal.className = "parent";
modalChild = document.createElement("div");
modalChild.className = "child";
btnClose = document.createElement("a");
btnClose.className = "btnClose";
btnClose.textContent = "X";

modalChild.appendChild(btnClose);
modal.appendChild(modalChild);

document.body.appendChild(modal);
modal.style.display = "flex";