We know that the innerHTML attribute provided by the browser can be used to obtain the value of the string contained in the node. For example, there are the following nodes:
Copy to ClipboardReference: [www.bkjia.com] <div id = "test"> <strong> I'm strong </strong> </div>
Pass
Copy to ClipboardReference: [www.bkjia.com] var obj = document. getElementById ("test ");
Alert (obj. innerHTML); // The returned value is <strong> I'm strong </strong>
What should I do if I want to get the text value of the node and do not include the string that the label thinks. The text value here is: I'm strong
Copy to ClipboardReference: [www.bkjia.com] // non-Mozilla Browser:
Obj. innerText;
// Other browsers
Obj. firstChild. nodeValue;
First, a general method is provided to solve the compatibility problem:
The complete code is as follows:
Copy to ClipboardReference: [www.bkjia.com] <Head>
<Title> JavaScript obtains the node text value -bkjia.com </title>
</Head>
<Body>
<Div id = "test"> <strong> I'm strong </strong> </div>
<Script type = "text/javascript"> var obj = document. getElementById ("test ");
// Compatible with the browser's method for obtaining node text
Function text (e) {var t = "";
// If the input element is an element, the child element will be traversed.
// Otherwise, assume it is an array.
E = e. childNodes | e;
// Traverse all subnodes
For (var j = 0; j <e. length; j ++ ){
// If it is not an element, append its text value
// Otherwise, recursively traverse the subnodes of all elements
T + = e [j]. nodeType! = 1? E [j]. nodeValue: text (e [j]. childNodes );}
// Return the text of the partition.
Return t;} alert (text (obj ))
</Script>
</Body>
</Html>
From: http://www.cnblogs.com/wbkt2t/