firstChild - lastChild Properties

calendar November 13, 2009

Value: Node object reference

Compatibility: winIE5+, macIE5+, moz1+, safari1+

W3C DOM-based document object models are built around an architecture known as a node map. Each object defined by HTML is a node in the map. A  node has relationships with other nodes in the document. A child node is an element that is contained by another element. The container is the parent of such a child. A parent object have zero or more children.

var nodeArray = document.getElementById(”elementID”).childNodes;

While you can use this array to get a reference to the first or last child node, the firstChild and lastChild properties offers shortcuts to those positions.

Code:

<html>
<head>
<title>firstChild - lastChild properties</title>
<script type="text/javascript">
function makeNewLi(txt)
{
  var newItem = document.createElement("li");
  newItem.innerHTML = txt;
  return newItem;
}
function prepend(form)
{
  var newItem = makeNewLi(form.input.value);
  var firstLi = document.getElementById("mylist").firstChild;
  document.getElementById("mylist").insertBefore(newItem, firstLi);
}    
function append(form)
{
  var newItem = makeNewLi(form.input.value);
  var lastLi = document.getElementById("mylist").lastChild;
  document.getElementById("mylist").appendChild(newItem);
}
function replaceFirst(form)
{
  var newItem = makeNewLi(form.input.value);
  var firstLi = document.getElementById("mylist").firstChild;
  document.getElementById("mylist").replaceChild(newItem, firstLi);
}
function replaceLast(form)
{
  var newItem = makeNewLi(form.input.value);
  var lastLi = document.getElementById("mylist").lastChild;
  document.getElementById("mylist").replaceChild(newItem, lastLi); 
}
</script>
</head>
<body>
<h1>firstChild and lastChild properties</h1>
<hr />
<form>
<input type="text" name="input" /><br />
<input type="button" value="Insert at top" onClick="prepend(this.form)" />
<input type="button" value="Insert at bottom" onClick="append(this.form)" />
<input type="button" value="Replace at top" onClick="replaceFirst(this.form)" />
<input type="button" value="Replace at bottom" onClick="replaceLast(this.form)" />
</form>
<ol id="mylist">
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
<li>item 4</li>
</ol>
</body>
</html>  

Related items: nextSibling, parentElement, parentNode, previousSibling properties, appendChild( ), hasChildNodes( ), removeChild( ), removeNode( ), replaceChild( ), replaceNode( ) methods.

admin

Leave a Reply

You must be logged in to post a comment.