JavaScript By Example
We do not need to step forward though the nodes in our web page, we can also start at the end and work backwards using the previousSibling property.
With a very minor change to the code from our last example we can have the substitutions start in exactly the same place but instead of working forward through the document from that point we can instead have it work backwards through the document until it reaches the first node that is at the same level in the document as the one we started from.
While we do not have any script tag above the point we are processing from in this example we still leave the test for it there just in case someone decides to add such a tag in the future.
With a very minor change to the code from our last example we can have the substitutions start in exactly the same place but instead of working forward through the document from that point we can instead have it work backwards through the document until it reaches the first node that is at the same level in the document as the one we started from.
While we do not have any script tag above the point we are processing from in this example we still leave the test for it there just in case someone decides to add such a tag in the future.
HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<head>
<title>Example D06</title>
</head>
<body>
<div>x</div>
<div>x</div>
<div id="last">x</div>
<div>x</div>
<div>x</div>
<div>x</div>
<script type="text/javascript" src="exampleD06.js"></script>
</body>
</html>
JavaScript
var node;
node = document.getElementById('last');
while (node) {
if (3 !== node.nodeType && 'SCRIPT' !== node.nodeName)
node.innerHTML = 'y';
node = node.previousSibling;
}