10.02.2014 Views

Beginning Ajax With ASP.NET (2006).pdf

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

JavaScript and the Document Object Model<br />

<br />

<br />

<br />

DOM Tree 2<br />

<br />

<br />

This is the Header<br />

This is a paragraph of text.<br />

<br />

List Item 1<br />

List Item 2<br />

<br />

<br />

alert(“About to change the document.”);<br />

// ... script code goes here ...<br />

<br />

<br />

<br />

This document is almost identical to the previous example except for the addition of id attributes to each<br />

of the elements you want to manipulate. The JavaScript code can then be simplified a little to make use<br />

of the getElementById() method, as shown in the following:<br />

// Get a node reference to the header element<br />

var hdr = document.getElementById(“hdr1”);<br />

// Use that reference to change the text/data.<br />

hdr.firstChild.data = “My Dynamically written Header Text”;<br />

// Get a node reference to the paragraph element<br />

var paragraph = document.getElementById(“p1”);<br />

// Use that reference to change the text/data.<br />

paragraph.firstChild.data = “This represents the new text of the first paragraph.”;<br />

// Get a node reference to the ul element<br />

var ul = document.getElementById(“ul1”);<br />

// Using the parentNode (in this case the ‘body’ element), remove that child<br />

element<br />

paragraph.parentNode.removeChild(ul);<br />

// create a new Text node for the second paragraph<br />

var newTextNode = document.createTextNode(“This text is the second set of paragraph<br />

text”);<br />

// create a new Element to be the second paragraph<br />

var newElementNode = document.createElement(“p”);<br />

// put the text in the paragraph<br />

newElementNode.appendChild(newTextNode);<br />

// and put the paragraph on the end of the document by appending it to<br />

// the BODY (which is the parent of para)<br />

paragraph.parentNode.appendChild(newElementNode);<br />

61

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!