appendChild( )

The most common means of making one node a child of another is to use the appendChild( ) method.

new_div.appendChild( text );

appendChild( ) is a method available to any element node, and it takes only a single argument: the node you want to insert. With appendChild( ), you can also skip the intermediate step of assigning the text node to a variable, and directly append the new text node to the div:

new_div.appendChild( document.createTextNode( 'This is a new div' ) );

Of course, this only puts those two nodes together, so we still need to put our div into the body of the document to have it show up in the browser. Using appendChild( ), we can add the div to the body of the page, but appendChild( ) simply does what it says: appends the argument to the target element. The div would become the last element in the body. What if we wanted our new div to be the first element in the body?

Get Web Design in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.