How do I create a DIV with javascript?
I want to create a DIV manually with javascript. How is that accomplished?
Status:
Open Sep 11, 2006 - 05:47 PM
Web Design, JavaScript, html, DHTML
4answers
Answers
Sep 12, 2006 - 06:16 AM
I found out myself:
var newdiv = document.createElement('div');
var divIdName = 'testDiv';
newdiv.setAttribute('id',divIdName);
newdiv.style.width = "300px";
newdiv.style.height = "300px";
newdiv.style.left = "300px";
newdiv.style.top = "300px";
newdiv.style.position = "absolute";
newdiv.style.background = "#00C";
newdiv.style.border = "4px solid #000";
newdiv.innerHTML = 'Test Div';
document.body.appendChild(newdiv);
Sep 12, 2006 - 08:58 AM
good work...now give me your points...lol
Sep 13, 2006 - 12:17 PM
Ok, good enough david, but what I usually do is to define the DIV in the html code like this (example with some of your attributes):
Test Div
Note the "display: none" which hides it initially.
When you want to show it, just execute
document.getElementById("divID").style.display = "";
You can also create copies of it in javascript and - of course - hide it again.
I think it makes it simpler to keep layout in the html file and only let javascript handle execution.
Jakob
Sep 20, 2006 - 08:25 AM
Thanks, Jakob, but I needed the complete dynamic approach since it will be used on different html-pages without me being able to alter the html on beforehand.
Answer this question
Share Your Own Experience & Expertise
We look to ensure that every question is answered by the best people with relevant expertise and experience, the best answers include multiple perspectives. Do you have relevant expertise or experience to contribute your answer to any of these commonly asked questions?
Add New Comment