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

Adding the content

Adding the content of the div presents a bit of a problem. I could use the innerHTML property:




newNote.innerHTML = "<a href=\"javascript:editNote('note"  
                     +getCurrentNumber()+")\">edit</a><br />New note";

but how could I do it using straight DOM methods? The first thought would be to simply set the value of the text node child of the div element:



noteText = document.createTextNode(
          "<a href=\"javascript:editNote('note"+getCurrentNumber()+")\">"+
          "edit</a><br />New note");
newNote.appendChild(noteText);

The text does indeed get added, but the results might not quite be what you expect, as shown in Figure 4.

Figure 4. The text in the box
The text in the box

The problem is that you're not really adding text, but rather mixed content, consisting of text and elements. The browser assumes that you mean this as CDATA, which is taken literally, and the elements are not created. Rather than simply adding all of the content in one block, you need to actually add each element:

Listing 6. Adding the content



...
  function makeNewNote(){
    mainDivElement = document.getElementById("mainDiv");

    newNote = document.createElement("div");
    newNote.setAttribute("id", "note"+getCurrentNumber());
...

      editLink = getEditLink("note"+getCurrentNumber());
      newNote.appendChild(editLink);
      newNote.appendChild(document.createElement("br"));
 
      noteText = document.createTextNode("New Form");
      newNote.appendChild(noteText);

    mainDivElement.appendChild(newNote);

    incrementCurrent();

  }

    function getEditLink(thisId){
      editLink = document.createElement("a");
      linkText = document.createTextNode("edit");

      editLink.setAttribute("href", "javascript:editNote('"+thisId+"')");
        
      editLink.appendChild(linkText);
      return editLink;
    }
...

First, you've created a new function, getEditLink, which returns an object. That object is the a element, which you created using standard DOM methods. Next, you add a standard break tag, br, and finally, the node that contains the actual note text.

The result is the completed note, with elements intact and ready for use.



View JavaScript and the Document Object Model Discussion

Page:  1 2 3 4 5 6 7 8 Next Page: Changing existing nodes

First published by IBM developerWorks


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