Adding and removing elements

given

where subHeading is a h1 element with text.

We now look at how the DOM’s body property deals with moving elements around

appendChild

appends the subHeading element to the body, which puts it in the very last place. In the DOM, you will see the subHeading element right before the closing body tag.

insertBefore

puts the subHeading element in front of the heading element.

Notice the h1 in front of the header element

contains and removeChild

first we check to see if heading element exist, if we do, just remove it

Notice no more header

Swapping out

our subHeading element is the 0th index or first header we see. Let’s say we want to replace that with an italic element.

Thus, we create an italic element first by using createElement and giving it a tag name ‘i’, which stands for italic. We then assign text content of that italic element. Finally we use DOM’s body property and use replaceChild to replace the header element with our italic element.