Reputation: 459
When I do this:
col = document.createElement("div");
col.setAttribute("id", "col" + ii);
alert(document.getElementById("col" + ii));
alert displays null. How can I get setAttribute to have an effect?
Upvotes: 0
Views: 292
Reputation: 1509
When you create an element with document.createElement
, it creates the element but does not add it to the DOM. To add it to DOM you have to use appendChild
method on the element inside which you want your new element to be.
Let us assume that you want to add your new div
at end of the body
. Try the following code.
col = document.createElement("div");
col.setAttribute("id", "col" + ii);
document.body.appendChild(col)
alert(document.getElementById("col" + ii));
Upvotes: 1