0

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);
}

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.