adding DOM elements on the fly

L

laredotornado

Hi,

I have a DIV, with ID = "sidebarItems". Is it possible, and how would
I use JS to add an item to the end of the DIV on-the-fly, that is,
after the page has already loaded and is running? The item in
question would be a simple table

<table><tr><td><img src="src.gif"></td></tr></table>

Thanks, - Dave
 
M

Martin Honnen

I have a DIV, with ID = "sidebarItems". Is it possible, and how would
I use JS to add an item to the end of the DIV on-the-fly, that is,
after the page has already loaded and is running? The item in
question would be a simple table

<table><tr><td><img src="src.gif"></td></tr></table>


var div = document.getElementById("sidebarItems");

var table = document.createElement("table");
var tbody = document.createElement("tbody");
var row = document.createElement("tr");
var cell = document.createElement("td");
var img = document.createElement("img");
img.src = "src.gif";
cell.appendChild(img);
row.appendChild(cell);
tbody.appendChild(row);
table.appendChild(tbody);

div.appendChild(table);
 
W

Walton

var div = document.getElementById("sidebarItems");
var table = document.createElement("table");
var tbody = document.createElement("tbody");
var row = document.createElement("tr");
var cell = document.createElement("td");
var img = document.createElement("img");
img.src = "src.gif";
cell.appendChild(img);
row.appendChild(cell);
tbody.appendChild(row);
table.appendChild(tbody);

div.appendChild(table);

someone correct me if i'm wrong, but i believe the order you append
these elements is important in preventing a memory leak (in IE
specifically). it's called a cross-page leak. you can read about it
here:

http://msdn.microsoft.com/library/d...en-us/IETechCol/dnwebgen/ie_leak_patterns.asp
(near the bottom of the page)


the way to prevent a memory leak here would be to reverse the order
you append elements. see the link for more info as to why. anyway- i
can't see it being a big problem if you're only running this code
once, but if you do it many many times, the memory then becomes an
issue.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top