PDA

View Full Version : Dynamically adding a div.



Bob90
04-11-2007, 08:33 PM
How do I add a div dynamically That i can alter afterwards.


function addElement(parent, id, style, inner) {
var parentElement = document.getElementById(parent);
var newdiv = document.createElement('div');
newdiv.setAttribute('id',id);
newdiv.innerHTML = inner;
parentElement.appendChild(newdiv);
return true;
}

this adds it but I can't alter the style. Any ideas what I'm doing wrong?

:)

Twey
04-11-2007, 08:44 PM
function addDiv(parent, id, style, children) {
var r = document.createElement("div");
if(id)
r.id = id;
if(style)
for(var x in style)
r.style[x] = style[x];
if(children)
for(var i = 0; i < children.length; ++i)
r.appendChild(children);
parent.appendChild(r);
return r;
}Stay away from innerHTML.

Bob90
04-11-2007, 09:15 PM
in the function addDiv
parent = object?
id = string
style = string?
children = object?

I'm confused. Mostly about the children thing as I got a huge error.

Using Firebug output was:

uncaught exception: [Exception... "Could not convert JavaScript argument" nsresult: "0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)" location: "JS frame :: file:///D:/robgar%20webmania/test%20pages/Grapher/TMPr65eqgcqx9.htm :: addDiv :: line 23" data: no]

Bob90
04-11-2007, 09:17 PM
Global Moderator...
Well done. Nice fancy title

:D

Twey
04-11-2007, 09:33 PM
Yeah, depressing, isn't it? :p

Anyway... parent is a DOM node, id is a string, style is an object containing key:value pairs of styles, and children is an array or collection of elements.
var myDiv = addElement(
document.body,
"myDivID",
{
'background-color' : "red",
'position' : "absolute",
'left', "0"
},
document.getElementsByTagName("span")
);

Bob90
04-11-2007, 10:07 PM
Thanks Twey,

I think you just bumped my knowledge of JS up a lot!
I don't usually use objects like that.
nice one
:)

mburt
04-12-2007, 12:31 AM
Twey, so you can use the for in loop for objects that aren't html elements? Neat... I'm going to play for an hour with this one. :)