当我这样做时:
col = document.createElement("div");
col.setAttribute("id", "col" + ii);
alert(document.getElementById("col" + ii));
警报显示空。如何让setAttribute生效?
最佳答案
当您使用 document.createElement
创建元素时,它会创建该元素,但不会将其添加到 DOM。要将其添加到 DOM,您必须在您希望新元素位于其中的元素上使用 appendChild
方法。
假设您想要在 body
末尾添加新的 div
。尝试以下代码。
col = document.createElement("div");
col.setAttribute("id", "col" + ii);
document.body.appendChild(col)
alert(document.getElementById("col" + ii));
关于javascript - setAttribute 和 getElementById,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25586547/