given
1 2 3 4 |
<header> <h1 class="heading" id="mainHeading"><p>JavaScript Fundamentals</p></h1> <h2 class="heading subHeading">Part of the Front End Development learning path by Tuts+</h2> </header> |
1 |
var subHeading = document.getElementsByClassName('heading')[0]; |
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.
1 |
document.body.appendChild(subHeading); |
insertBefore
puts the subHeading element in front of the heading element.
1 |
document.body.insertBefore(subHeading, heading); |
Notice the h1 in front of the header element
1 2 3 4 5 6 7 |
<body> <h1 class="heading" id="mainHeading" contenteditable="true">I love Envato!</h1> <header> <h2 class="heading subHeading">Part of the Front End Development learning path by Tuts+</h2> </header> |
contains and removeChild
first we check to see if heading element exist, if we do, just remove it
1 2 3 4 |
if (document.body.contains(heading)) { console.log('heading exists, lets remove it'); document.body.removeChild(heading); } |
Notice no more header
1 2 3 4 5 6 |
<body> <h1 class="heading" id="mainHeading" contenteditable="true">I love Envato!</h1> <a name="historyLink" href="history.html">History</a> <a href="#">empty</a> <script src="js/elements.js"></script> </body> |
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.
1 2 3 |
var substitute = document.createElement('i'); substitute.textContent = 'I have been swapped in'; document.body.replaceChild(substitute, subHeading); |