JavaScript: The Definitive Guide, Sixth Editio javaScript权威指南(第6版) pdf 文字版-文字版, javascript电子书, 和javascript 有关的电子书:

15.5.3 Element Content As Text Nodes

15.5.3 Element Content As Text Nodes


Another way to work with the content of an element is as a list of child nodes, each of which may have its own set of children. When thinking about element content, it is usually the Text nodes that are of interest. In XML documents, you must also be prepared to handle CDATASection nodes—they are a subtype of Text and represent the content of CDATA sections.

Example 15-3 shows a textContent() function that recursively traverses the children of an element and concatenates the text of all the Text node descendants. In order to understand the code, recall that the nodeValue property (defined by the Node type) holds the content of a Text node.

Example 15-3. Finding all Text node descendants of an element

// Return the plain-text content of element e, recursing into child elements. // This method works like the textContent property function textContent(e) {

var child, type, s = ""; // s holds the text of all children

for(child = e.firstChild; child != null; child = child.nextSibling) { type = child.nodeType; if (type === 3 || type === 4) // Text and CDATASection nodes

s += child.nodeValue; else if (type === 1) // Recurse for Element nodes

s += textContent(child); } return s;

}

The nodeValueproperty is read/write and you can set it to change the content displayed by a Text or CDATASection node. Both Text and CDATASection are subtypes of CharacterData, which you can look up in Part IV . CharacterData defines a data property, which is the same text as nodeValue. The following function converts the content of Text nodes to uppercase by setting the data property:

// Recursively convert all Text node descendants of n to uppercase. function upcase(n) { if (n.nodeType == 3 || n.nodeTyep == 4) // If n is Text or CDATA n.data = n.data.toUpperCase(); // ...convert content to uppercase. else // Otherwise, recurse on child nodes for(var i = 0; i < n.childNodes.length; i++) upcase(n.childNodes[i]); }

CharacterData also defines infrequently used methods for appending, deleting, inserting, and replacing text within a Text or CDATASection node. Instead of altering the content of existing Text nodes, it is also possible to insert brand-new Text nodes into

15.5 Element Content | 381

an Element or to replace existing nodes with new Text nodes. Creating, inserting, and deleting nodes is the topic of the next section.

欢迎转载,转载请注明来自一手册:http://yishouce.com/book/1/31428.html
友情链接It题库(ittiku.com)| 版权归yishouce.com所有| 友链等可联系 admin#yishouce.com|粤ICP备16001685号-1