Reputation: 13
I am trying to create a new div element with the attribute "id" with the value of "Block1". My plan is, when the element is created and it gets the id "Block1" and my CSS will be able to position the elements. I call the function like so: <body onload="falling()">
but for some reason I can't get it to create the div element. Any advice or help?
function falling()
{
var div1 = document.createElement("div");
var att=document.createAttribute("id");
att.value="Block1";
div1.setAttribute(att);
var newElement = document.getElementById("board");
newElement.appendChild(div1);
}
Upvotes: 0
Views: 68
Reputation: 388316
To set the id of an element, just set the id property of the dom element like
function falling() {
var div1 = document.createElement("div");
div1.id = "Block1";
var newElement = document.getElementById("board");
newElement.appendChild(div1);
}
falling()
#board {
padding: 5px;
border: 1px solid red;
}
#Block1 {
padding: 5px;
border: 1px solid blue;
}
<div id="board"></div>
If you want to create a attribute node then you need to use setAttributeNode()
function falling() {
var div1 = document.createElement("div");
var att = document.createAttribute("id");
att.value = "Block1";
div1.setAttributeNode(att);
var newElement = document.getElementById("board");
newElement.appendChild(div1);
}
falling()
#board {
padding: 5px;
border: 1px solid red;
}
#Block1 {
padding: 5px;
border: 1px solid blue;
}
<div id="board"></div>
Upvotes: 2