getElementsByTagName() equivalent for textNodes

前端 未结 7 926
日久生厌
日久生厌 2020-11-22 06:33

Is there any way to get the collection of all textNode objects within a document?

getElementsByTagName() works great for Elements, but

7条回答
  •  天涯浪人
    2020-11-22 07:13

     document.deepText= function(hoo, fun){
            var A= [], tem;
            if(hoo){
                hoo= hoo.firstChild;
                while(hoo!= null){
                    if(hoo.nodeType== 3){
                        if(typeof fun== 'function'){
                            tem= fun(hoo);
                            if(tem!= undefined) A[A.length]= tem;
                        }
                        else A[A.length]= hoo;
                    }
                    else A= A.concat(document.deepText(hoo, fun));
                    hoo= hoo.nextSibling;
                }
            }
            return A;
        }
    

    /* You can return an array of all the descendant text nodes of some parent element, or you can pass it some function and do something (find or replace or whatever) to the text in place.

    This example returns the text of the non-whitespace textnodes in the body:

    var A= document.deepText(document.body, function(t){
        var tem= t.data;
        return /\S/.test(tem)? tem: undefined;
    });
    alert(A.join('\n'))
    

    */

    Handy for search and replace, highlighting and so on

提交回复
热议问题