DOM - Manipulation
by Shane Porter
HTML
<div id="container">
<h1>Hello, DOM!</h1>
<p>This is some fine fruit:</p>
<ul class="listy">
<li>Apples</li>
<li class="second">Pears</li>
<li>Cherries</li>
</ul>
</div>
JavaScript
/**
* We can drop in straight html by using innerHTML property
*/
var htmlFragment = "<a href='http://www.google.com'>Search</a>";
var pEl = document.getElementsByTagName("p")[0];
pEl.innerHTML += " " + htmlFragment;
/**
* We can create elements through the DOM
*/
// create the element
var newLi1 = document.createElement('li');
// give it some text
var newLiText = document.createTextNode('Watermelon');
newLi1.appendChild(newLiText);
// determine position for insertion
var ulElement = document.querySelector(".listy");
// insert it
ulElement.appendChild(newLi1);
/**
* More insertion
*/
var newLi2 = document.createElement('li');
newLi2.innerHTML = "Grapes";
ulElement.insertBefore(newLi2, newLi1);
/**
* Warning: These will MOVE elements that already exist
*/
/*
var h1El = document.getElementsByTagName('h1')[0];
ulElement.appendChild(h1El);
*/
/**
* Replacing
*/
var newLi3 = document.createElement('li');
newLi3.innerHTML = "Peaches";
ulElement.replaceChild(newLi3, newLi1);
/**
* Removing elements
*/
// get a reference node-to-be-removed
var liToRemove = document.querySelector(".second");
// and remove it through the parent
liToRemove.parentNode.removeChild(liToRemove);