Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

html - I need the solution to a Javascript DOM textnode selection using javascript?

How would I get all the text nodes in this using javascript? I've tried so many things but them seam not to be working?

 <td bgcolor="#f2f2f2" id='product-1'>
<img src="images/icon.png" width="37" height="30" align="left" style="margin: 8px 10px 25px 0">
<h4 style="font-size:12px; font-weight:bold">Heading</h4>
<p>TEXT</p>
 </td>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This example returns an Array of the text nodes contained by node and its descendents. It skips nodes containing only white space

function deepText(node){
    var A= [], tem;
    if(node){
        node= node.firstChild;
        while(node!= null){
            if(node.nodeType== 3){
                if(/S/.test(node.data)) A[A.length]= node;
            }
            else A= A.concat(deepText(node));
            node= node.nextSibling;
        }
    }
    return A;
}
//test
var text= [], nodes= deepText(document.getElementById('product-1'));

for(var i= 0, L= nodes.length; i<L; i++){
    // do whatever you want to the node
    var pa= nodes[i].parentNode;
    if(pa.nodeName== 'H4') pa.style.color= 'blue';
    text.push(nodes[i].data);
}
alert(text.join(' '))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...