...

View Full Version : innerHTML help



absolutezero
12-15-2008, 07:54 AM
function GenerateItembarLinks()
{
itembar = document.getElementById('itembar')
items = document.getElementsByTagName('h2')
for (var i=0; i<items.length; i++)
{
itembar.innerHTML = items[i].innerHTML
}
}

Thats my code so far. It's purpose is to get all the links inside h2 headers in the "main content" section of my website and copy them to a bar at the top of my site. Although this code seems to copy only the last link. I'm still sort of new to javascript BTW... Any ideas?

v08i
12-15-2008, 08:13 AM
function GenerateItembarLinks()
{
itembar = document.getElementById('itembar')
items = document.getElementsByTagName('h2')
for (var i=0; i<items.length; i++)
{
itembar.innerHTML = items[i].innerHTML
}
}

Currently itembar.innerHTML gets reset each time the loop executes. You must append the innerhtml of items[i] to previous one. Change the line

itembar.innerHTML= items[i].innerHTML;

with

itembar.innerHTML+= items[i].innerHTML;


thanks
Vijay
http://vijayjoshi.org

absolutezero
12-15-2008, 11:03 PM
Thanks!

it is working so much better now. I had a quick issue with adding the li tags along with it so I just added them manually in the for loop:

itembar.innerHTML += "<li>" + items[i].innerHTML + "</li>";

Just in case anyone is wondering.

Thanks again :)

A1ien51
12-16-2008, 03:19 PM
If you want a lot better performance, do not update the innerHTML each time.

Build up a string and at the end, update the innerHTML.

Eric

v08i
12-18-2008, 07:46 AM
If you want a lot better performance, do not update the innerHTML each time.

Build up a string and at the end, update the innerHTML.

Eric

Yes. accessing the dom each time you are inside the loop will cost some performance. It is a lot better to build a string and then set the innerHTML a single time.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum