Developer Forums | About Us | Site Map
Search  
HOME > TUTORIALS > CLIENT SIDE CODING > JAVASCRIPT TUTORIALS > JAVASCRIPT AND THE DOCUMENT OBJECT MODEL


Sponsors





Useful Lists

Web Host
site hosted by netplex

Online Manuals

JavaScript and the Document Object Model
By Nicholas Chase - 2004-03-10 Page:  1 2 3 4 5 6 7 8

Changing existing nodes

Now you have the content, but how can you change it? Because you added elements separately, you can just edit the single text node that represents the text of the note. You can do this three ways. First, you can remove the offending node and add a new one:

Listing 7. Removing the node and adding a replacement


...
      function editNote(editLink){
        theDiv = document.getElementById(editLink);
        newText = prompt("What should the note say?");

        oldNode = theDiv.firstChild.nextSibling.nextSibling;
        theDiv.removeChild(oldNode);

        newNode = document.createTextNode(newText);
        theDiv.appendChild(newNode);

      }
...

Another option is to simply replace the existing node:

Listing 8. Replacing a node


...
      function editNote(editLink){
        theDiv = document.getElementById(editLink);
        newText = prompt("What should the note say?");

        oldNode = theDiv.firstChild.nextSibling.nextSibling;
        newNode = document.createTextNode(newText);
        theDiv.replaceChild(newNode, oldNode);
      }
...

In this case, the oldNode is replaced with the newNode, and the document changes accordingly.

Finally, you could simply change the text of the existing node:

Listing 9. Changing the existing node



...
      function editNote(editLink){
        theDiv = document.getElementById(editLink);
        newText = prompt("What should the note say?");

        theDiv.firstChild.nextSibling.nextSibling.nodeValue=newText;
      }
...

Because editNote takes the id value of the appropriate div, the same function can be used for any note, as seen in Figure 5.

Figure 5. The final page
The final page



View JavaScript and the Document Object Model Discussion

Page:  1 2 3 4 5 6 7 8 Next Page: Summary and Resources

First published by IBM developerWorks


Copyright 2004-2024 GrindingGears.com. All rights reserved.
Article copyright and all rights retained by the author.