JavaScript to get the node Text Value

Source: Internet
Author: User

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/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.