Học JavaScript qua ví dụ part 71 doc

8 211 0
Học JavaScript qua ví dụ part 71 doc

Đang tải... (xem toàn văn)

Thông tin tài liệu

ptg 15.7 Modifying the DOM (Appending, Copying, and Removing Nodes) 629 15.7 Modifying the DOM (Appending, Copying, and Removing Nodes) You can create new nodes, make a clone of an existing node, insert a new node before an existing node, remove a node, or replace a node. All of this is possible because the W3C DOM introduced methods to modify the DOM. Table 15.6 lists the DOM methods. For a complete list of DOM methods and an excellent resource, go to the JavaScript Kit page at http://www.JavaScriptkit.com/domref/elementmethods.shtml. For another great resource on how to modify the DOM, go to http://www.howtocreate.co.uk/tutorials/Java- Script/dombasics. 3 This p element is also assigned attributes. The dir attribute with rtl means the text will be displayed from the right side of the screen to the left, as would be used with Arabic or Hebrew. 4 The getElementById() method uses the id of the first paragraph and returns a ref- erence to it. 5 The first paragraph has a dir and style attribute. Using dir and style.fontSize, Java- Script can get access to these attributes. 6 The second paragraph has also been assigned attributes. Using the dir and class- Name properties, JavaScript can find the direction of the text, right to left, and the name of the class that is used to style this paragraph. The className property can also be assigned the name of a different class to change the style of the object. The output is shown in Figure 15.11. Figure 15.11 Displaying HTML attributes with JavaScript properties. EXPLANATION ( CONTINUED) From the Library of WoweBook.Com ptg 630 Chapter 15 • The W3C DOM and JavaScript 15.7.1 The innerHTML Property and the Element’s Content The easiest way to get or modify the content of an element is by using the innerHTML property. Although the innerHTML is not a part of the W3C DOM specification, it is sup- ported by all major browsers. The innerHTML property is useful for inserting or replacing the content of HTML elements; that is, the code and text between the element’s opening and closing tag. It can also be used to view the source of a page that has been dynamically modified (including <html> and <body>). Interactive pages are created by simply changing the value of the element’s innerHTML property. Because it is a property, not a method, innerHTML doesn’t return a reference to the content it inserts. If you need to do more than simply get or set content, then you can use specific DOM methods instead. In Example 15.5 the innerHTML property is used to retrieve the contents of two para- graphs. First we will give the paragraphs an id so that we can easily identify a particular paragraph. Next, with the id of the element, the getElementById method returns a Java- Script reference to the specified paragraph, and finally the innerHTML property contains the text between the <p></p> tags. With this property we can easily modify the para- graph’s text and style on the fly. Table 15.6 The DOM Methods Method What It Does appendChild(new node) Appends a new node onto the end of the list of child nodes. cloneNode(child option) Makes a clone of a node. hasChildNodes() Returns true if the node has children. getAttribute(attributeName) Returns the value of the attribute of the current node. hasAtrributes() Returns a Boolean value if the node has defined attributes. hasChildNodes() Returns a Boolean value if the node has defined child nodes. insertBefore(new node, current node) Inserts a new node in the list of children. removeChild(child node) Removes a child node from a list of children. setAttributeNode(attributereference) Sets or creates an attribute for the current node. replaceChild(new child, old child) Replaces an old child node with a new one. EXAMPLE 15.5 <html> <head> <title>innerHTML</title> From the Library of WoweBook.Com ptg 15.7 Modifying the DOM (Appending, Copying, and Removing Nodes) 631 <style type="text/css"> body{ background-color:blue;} 1 p { background: white; font-style: bold; font-family: courier,arial; text-indent: 5%; margin-left:20%; margin-right:20% } </style> </head <body> 2 <p id="para1">Today is Sunday and there is a sailing festival going on in the Ferry Park. The tall ships are docked in the bay for tourists to visit. The fog is rolling in.</p> 3 <p id="para2">I'm trying to figure out how to grab the text from this paragraph with JavaScript using the innerHTML property. I may take a break now and go to the park.</p> <script type="text/javascript"> document.write("<p>JavaScript's innerHTML property</p>"); 4 ptxt1=document.getElementById("para1").innerHTML; 5 ptxt2=document.getElementById("para2").innerHTML; document.write("<p style='background:yellow'>"+ 6 ptxt1.toUpperCase()+ "</p>"); document.write("<p style='background:yellow'>" + 7 ptxt2.toUpperCase()+ "</p>"); </script> </body> </html> EXPLANATION 1 This is the CSS code to style paragraphs in this document. 2 The first HTML paragraph element is given an id with the id attribute. 3 The second HTML paragraph element is also given an id. 4 The getElementById() uses the id of the paragraph to get a reference to the para- graph. By applying the innerHTML property to this reference, all the text between <p></p> tags is assigned to the variable, ptext1. 5 By applying the innerHTML property to this reference, all the text between <p></p> tags is assigned to the variable, ptext2. 6, 7 The text in both paragraphs is displayed in uppercase letters by applying the toUp- perCase() method to the variables, ptxt1 and ptxt2. Figure 15.12 shows the result. EXAMPLE 15.5 (CONTINUED) From the Library of WoweBook.Com ptg 632 Chapter 15 • The W3C DOM and JavaScript 15.7.2 Modifying the Content of an Element By changing an element’s innerHTML property, after some user interaction, you can change the text that occurs between that element’s opening and closing tag. Figure 15.12 JavaScript grabs the two paragraphs at the top of the page and displays them at the bottom. EXAMPLE 15.6 <html> <head><title>Modify Text</title> <style type="text/css"> body{background-color:aliceblue;} .divStyle { background-color:green; margin-left:20% margin-right:20% border-style:solid; color:white; font-size:150% } </style> From the Library of WoweBook.Com ptg 15.7 Modifying the DOM (Appending, Copying, and Removing Nodes) 633 <script type="text/javascript"> 1 window.onload=function(){ 2 var divObj = document.getElementById("divtest"); 3 alert(divObj); 4 divObj.innerHTML="Inserting new text in the div container."; } </script> </head> <body> 5 <div id="divtest" class="divStyle"> 6 Original text in div container. </div> </body> </html> EXPLANATION 1 When the page has finished loading the statements in the anonymous function are executed. 2 The variable, divObj, is assigned a reference to the div element identified by its id, divtest. 3 By adding this alert, you will be able to see what was in the original div container be- fore it is overwritten by the new text. After the user clicks the alert’s OK button, the new text will be displayed. If the alert box is removed, the original text will be over- written before you can see it. The only output will be what you see in Figure 15.13. 4 The innerHTML property is used to change the text within the <div></div> tags. 5 The id and class attributes are assigned to the <div> tag. 6 This is the original text that is modified by JavaScript on line 4. See Figure 15.14. Figure 15.13 The original text before it is modified. EXAMPLE 15.6 (CONTINUED) From the Library of WoweBook.Com ptg 634 Chapter 15 • The W3C DOM and JavaScript 15.7.3 Creating New Elements with the DOM To create new elements on the fly, the DOM provides the createElement() method, and for new text, the createTextNode() method. Once you get a reference to the new element, you must insert or append it to the document. If, for example, you have created a p ele- ment as follows: var pref = document.body.createElement("p"); you can now append the new element to the body as follows: document.body.appendChild(pref); Now we can add text to the new paragraph by using the createTextNode() method and the appendChild() method as follows: txt = document.createTextNode("Hello, new paragraph!"); And finally, we will append this text to the new paragraph as: new_pref.appendChild(txt); Figure 15.14 Original text is modified using the innerHTML property. EXAMPLE 15.7 <html> <head><title>Creating a New Element</title> <style type="text/css"> .divStyle { background-color:blue; border-style:solid; color:white; } p{ color:yellow; font-size:150%;} </style> <script type="text/javascript"> // Create a new p element and append it to a div 1 window.onload=function(){ 2 var para = document.createElement("p"); 3 var divObj = document.getElementById("divtest"); From the Library of WoweBook.Com ptg 15.7 Modifying the DOM (Appending, Copying, and Removing Nodes) 635 4 divObj.appendChild(para); 5 var txt = document.createTextNode("Wow! Hope this works!"); 6 para.appendChild(txt); } </script> </head> <body> 7 <div id="divtest" class="divStyle"> <p>Original text in div container.</p> </div> </body> </html> EXPLANATION 1 After the page has completely loaded this anonymous function will be called. 2 A new paragraph is created with the DOM’s createElement() method. 3 Now we get a reference to the div element defined on line 7. 4 The paragraph is appended to the div element with the DOM’s appendChild() method (see Figure 15.15). 5 The DOM’s createTextNode() method will return a reference to the text that will be placed within the new paragraph node. 6 The text created on line 5 is appended to the paragraph. 7 A div container is created with an id attribute, divtest, to be used on line 3 to get a reference to the div element. Figure 15.15 Creating a new p element with the DOM and appending it to a div container. EXAMPLE 15.7 From the Library of WoweBook.Com ptg 636 Chapter 15 • The W3C DOM and JavaScript 15.7.4 Inserting Before a Node The insertBefore() method allows you to insert a child node before the specified node, called the reference node, and if the reference node is null, this will insert the node at the end of a list of child nodes. Example 15.8 demonstrates how to insert a new paragraph node into a DOM before another node. FORMAT insertBefore(newElement, targetElement) EXAMPLE document.body.insertBefore(newPara, firstPara); EXAMPLE 15.8 <html> <head><title>Inserting Before</title> <style type="text/css"> p { font-style:arial; color:darkblue; font-size:18; } </style> <script type="text/javascript"> 1 function insertMessage() { 2 var newPara = document.createElement("p"); 3 var newText = document.createTextNode("I am inserting myself above you!"); // If you copy this, don’t break the lines. 4 newPara.appendChild(newText); 5 var firstPara = document.getElementById("firstp"); 6 document.body.insertBefore(newPara, firstPara); } </script> </head> 7 <body onload="insertMessage()"> <p id=”firstp”>I was supposed to be first.</p> </body> </html> EXPLANATION 1 Once the page has loaded, this function will be called. 2 With the createElement() method, a new paragraph is created. A reference to it is assigned to a variable, newPara. From the Library of WoweBook.Com . type="text /javascript& quot;> document.write("<p> ;JavaScript& apos;s innerHTML property</p>"); 4 ptxt1=document.getElementById("para1").innerHTML; 5 ptxt2=document.getElementById("para2").innerHTML; document.write("<p. the document. If, for example, you have created a p ele- ment as follows: var pref = document.body.createElement("p"); you can now append the new element to the body as follows: document.body.appendChild(pref); Now. type="text /javascript& quot;> // Create a new p element and append it to a div 1 window.onload=function(){ 2 var para = document.createElement("p"); 3 var divObj = document.getElementById("divtest");

Ngày đăng: 04/07/2014, 02:20

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan