Technology Programming

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.


<title>Example D06</title>
<div id="last">x</div>
<script type="text/javascript" src="exampleD06.js"></script>


var node;
node = document.getElementById('last');
while (node) {
  if (3 !== node.nodeType && 'SCRIPT' !== node.nodeName)
    node.innerHTML = 'y';
  node = node.previousSibling;

Leave a reply