21.5. Changing Nodes

As previously mentioned, you can manipulate document nodes on the fly, adding, removing, and changing them as needed. The following sections show examples of changing nodes.

Example: Changing a Node's Value

This example shows how a text node's value can be changed.

Source

This example uses previously discussed methods to find and change the text of an OL node.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>DOM Find Node</title>

<style type="text/css">

  div.div1 { background-color: #999999; }
  div.div2 { background-color: #BBBBBB; }

  table, table * { border: thin solid black; }
  table { border-collapse: collapse; }
  td { padding: 5px; }

</style>

<script type="text/JavaScript">

function findNode(startnode,nodename,nodeid) {

  var foundNode = false;

  // Check our starting node for what we are looking for
  if ( startnode.nodeName == nodename &&
       startnode.id == nodeid ) {
    foundNode = startnode;
  } else {
    // If not found, look through children
    look_thru_children:
    if ( startnode.hasChildNodes() ) {
      var children = startnode.childNodes;
      for (var i = 0; i < children.length; i++) {
        foundNode = findNode(children[i],nodename,nodeid);
         // Return when found
         if (foundNode) { break look_thru_children; }
      }
    }
  }
  return foundNode;
}

function dofindNchange() {
  alert("Click OK to change 'sortme' node's text");
  var node = document.getElementById("sortme");
if (node.firstChild.nodeType == 3) { node.firstChild.nodeValue ...

Get Web Standards Programmer's Reference: HTML, CSS, JavaScript®, Perl, Python®, and PHP now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.