Jump to content

Element.id: Can I Use It This Way?


tinfanide

Recommended Posts

  var div = document.createElement("div");  div.setAttribute("id","div1");// div.id = "div1"  document.getElementById("div1").setAttribute("style","background-color: white; position: absolute; left: 100px; top: 100px; width: 500px; height: 500px;");  document.body.appendChild(div); 

Can I refer to the element id within JS in this way?

Link to comment
Share on other sites

Yep, you can, but you need to insert (append) the newly created div, into the body, before you get the element with:
document.getElementById()

.

Thanks for the reminder.I reverse the order of those lines:
var div = document.createElement("div");  div.setAttribute("id","div1");// div.id = "div1"  document.body.appendChild(div);  document.getElementById("div1").setAttribute("style","background-color: white; position: absolute; left: 100px; top: 100px; width: 500px; height: 500px;");

And in this order it works.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...