Java Reference
In-Depth Information
So far we've looked at how to gain access to different elements of a web page and find out
information about them. We've also looked at how to change the attributes of elements. In
this section, we're going to learn how to create new elements and add them to the page, as
well as edit elements that already exist and remove any unwanted elements from the page.
Creating an Element
The document object has a createElement() method that takes a tag name as a para-
meter and returns that element. For example, we could create a new paragraph as a DOM
fragment in memory by writing the following in the console:
var newPara = document.createElement('p');
At the moment, this paragraph element is empty. To add some content, we'll need to create
a text node.
Creating a Text Node
A text node can be created using the document.createTextNode() method. It takes
a parameter, which is a string containing the text that goes in the node. Let's create the text
to go in our new paragraph:
var text = document.createTextNode('Transition 1');
Now we have an element node and a text node, but they are not linked together―we need to
append the text node to the paragraph node.
Appending Nodes
Every node object has an appendChild() method that will add another node (given as
an argument) as a child node. We want our newly created text node to be a child node of
Search WWH ::

Custom Search