Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Adding html to DOM 1

Status
Not open for further replies.

rctek

Programmer
May 8, 2009
4
Hi all,

I'd like to add some html to the top of the body tag. I was thinking something like this snippet below.

However, the commented out line adds it to the html tag inbetween the head and body and the next line doesn't work

Code:
	var bnrContent = "";
	var bnrLink = "";
	var bnrContentHTML = "";
	var bnr = document.createElement('div');

	    bnr.setAttribute('id', 'openPropBnr');
	    //document.childNodes[1].appendChild(bnr);	

	    document.getElementsByTagName('body').appendChild(bnr);

Any ideas what I need to do to make it work?
Thanks in advance.
Regards,


Richard
 
Hi

The [tt]getElementsByTagName()[/tt] method returns a list oof elements.
Code:
document.getElementsByTagName('body')[red][0][/red].appendChild(bnr);
But of course is pointless to get the reference to [tt]body[/tt] that way.
Code:
document[red].body[/red].appendChild(bnr);

Feherke.
 
Thanks - I totally forgot that method.

I do however have an issue, both methods cause an error?

Code:
document.getElementsByTagName("body")[0] is undefined
document.getElementsByTagName('body')[0].appendChild(bnr);

Is that because the script is in the head and the body has yet to load?
 
Hi

rctek said:
Is that because the script is in the head and the body has yet to load?
Certainly. I would put that code to be executed [tt]onload[/tt]. Or :
YSlow said:
Put JavaScript at bottom
( YSlow's suggestion actually is for optimization, but will solve your problem too. )

Feherke.
 
I wanted to make the script very reusable and be able to just drop it into the head. At the bottom of my javascript file I had this

Code:
window.onload = OPbannerToDOM('somevalue');

I was thining this would run once everything in the page had loaded? Was this the right way to do this?
 
Hi

rctek said:
I was thining this would run once everything in the page had loaded?
No. That will run immediately.
rctek said:
Was this the right way to do this?
No. You should assign the [tt]function[/tt] itself to the [tt]onload[/tt] event, not the [tt]function[/tt]'s return value. As you are passing parameter, you have to wrap it in an anonymous [tt]function[/tt] :
Code:
window.onload = [red]function() {[/red] OPbannerToDOM('somevalue'); [red]}[/red]

Feherke.
 
Brillant! Thanks for you help.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top