lastChild and firstChild
The firstChild and lastChild properties point to the first and last node in the childNodes list. someNode.firstChild is equal to someNode.childNodes[0].
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<div id="div1">
<p>Hello <b>World!</b></p>
<ul>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ul>
</div>
<p>Hello <b>World!</b></p>
<script type="text/javascript">
var div = document.getElementById("div1");
var node = div.firstChild;
var sameNode = div.childNodes[0];
if (node === sameNode){
document.writeln("same.");
} else {
document.writeln("not");
}
</script>
</body>
</html>
someNode.lastChild is equal to someNode.childNodes[someNode.childNodes.length-1].
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<div id="div1">
<p>Hello <b>World!</b></p>
<ul>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ul>
</div>
<p>Hello <b>World!</b></p>
<script type="text/javascript">
var div = document.getElementById("div1");
var node = div.lastChild;
var sameNode = div.childNodes[div.childNodes.length-1];
if (node === sameNode){
document.writeln("same.");
} else {
document.writeln("not");
}
</script>
</body>
</html>
If there is only one child node, firstChild and lastChild point to the same node. If there are no children, then firstChild and lastChild are both null. hasChildNodes() returns true if the node has one or more child nodes.
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<div id="div1">
<p>Hello <b>World!</b></p>
<ul>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ul>
</div>
<p>Hello <b>World!</b></p>
<script type="text/javascript">
var div = document.getElementById("div1");
var node = div.lastChild;
document.writeln(div.hasChildNodes());
</script>
</body>
</html>
Home
JavaScript Book
DOM
JavaScript Book
DOM
DOM Model:
- Document Object Model
- nodeName and nodeValue Properties
- Node Relationships:childNodes
- parentNode
- previousSibling and nextSibling properties
- lastChild and firstChild
- appendChild() adds a node to the end of the childNodes list
- insertBefore()
- ownerDocument property
- removeChild
- replaceChild()
- Working with Text
- Check the length of NodeList
- Convert NodeList to an Array
- html tag and its cooresponding JavaScript class