appendChild

J

jacster

Hi,
I'm using the following code in a Greasemonkey script.

var start, newElement;
start = document.body;
newElement = document.createElement('b');
newText = document.createTextNode("The Greasemonkey salutes you!");
newElement.appendChild(newText);
start.appendChild(newElement);

Can anyone tell me: 1) why my string appears twice; 2) how to make it
appear just once?

I'm trying to insert code at the top of every viewed page. Obviously,
document.body appends the string to the closing body tag which is not
what I want. What could I use to insert my code as the first childnode
under 'body'?

Thanks.
 
M

Michael Winter

On 18/06/2005 19:09, jacster wrote:

[snip]
var start, newElement;
start = document.body;
newElement = document.createElement('b');
newText = document.createTextNode("The Greasemonkey salutes you!");
newElement.appendChild(newText);
start.appendChild(newElement);

Can anyone tell me: 1) why my string appears twice

It shouldn't, and it doesn't (not here, anyway).

[snip]
I'm trying to insert code at the top of every viewed page.

Server-side includes would seem to be a better solution.
Obviously, document.body appends the string to the closing body tag

The appendChild method appends the B element as the last child node of
the BODY element.

<!-- content --> <- new element inserted after this point.
What could I use to insert my code as the first childnode under
'body'?

The insertBefore method.

var body = document.body,
element, text;

if(body && body.insertBefore && document.createTextNode
&& document.createElement)
{
element = document.createElement('b');
text = document.createTextNode('The Greasemonkey salutes you!');

if(element && text && element.appendChild) {
element.appendChild(text);
body.insertBefore(element, body.firstChild);
}
}

Mike
 
J

jacster

Hi Mike,
Thanks for the appendBefore and body.firstChild tips. Changed my script
and now the double-string problem is gone and text at page top.
Server side includes aren't that suitable because my code is for giving
the browsing user expanded parse/report/log options on remote pages.
Did consdier filtering/changing remote pages through a local server
with PHP for extended language functions but want to get js working
first.
Cheers.
 

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

No members online now.

Forum statistics

Threads
473,786
Messages
2,569,626
Members
45,328
Latest member
66Teonna9

Latest Threads

Top