1. Tech

Your suggestion is on its way!

An email with a link to:


was emailed to:

Thanks for sharing About.com with others!

The Javascript DOM

11. appendChild

clr gif

Having created a container and the text that it is to contain we next need to add the text into the container. This is done using the appendChild method. To continue on from the example in our last tutorial we add one extra line to the end of our existing code to do this.

var newP = document.createElement("p");
var txt = 'Kilroy was here.';
var newT = document.createTextNode(txt);

One way of adding this container complete with content to our web page is to use one of the methods that we have already learned to locate the container we want to add the new one into and then again use appendChild to add our new container into the end of that one.

Here's the extra code to add our new paragraph to the end of the page.

var theBody = document.getElementsByTagName('body')[0];

After running all of the above code our new paragraph complete with its short sentence has now been added to the end of the web page after all of the other content.

©2017 About.com. All rights reserved.