您可以浏览文档或某些父元素,并检查每个文本节点,
返回具有与您的搜索文本匹配的数据的节点数组。
如果您想以某种方式操作它们,这将为您提供匹配的实际节点数组。
或者,如果您只想读取每个匹配项的路径,则可以返回路径而不是节点。
这个例子需要三个函数——一个递归树,寻找文本节点,
一个跟踪从根节点下降的节点,
和一个匹配文本并将其节点的路径作为字符串返回。
前两个是可重复使用的,第三个是一次性的。
document.deepText= function(node, fun){
var A= [], tem;
fun= fun || function(n){
return n
};
if(node){
node= node.firstChild;
while(node!= null){
if(node.nodeType== 3){
tem= fun(node);
if(tem!= undefined) A[A.length]= tem;
}
else A= A.concat(document.deepText(node, fun));
node= node.nextSibling;
}
}
return A;
}
//返回一个父元素数组
document.descent= function(node, pa){
var A= [];
pa= pa || document.documentElement;
while(node){
A[A.length]= node;
if(node== pa) return A.reverse();
node= node.parentNode;
}
}
//这个返回一个数组,其中包含每个匹配节点的“路径”
// 几乎所有的时间都花在为路径制作字符串上
//传递一个正则表达式或一个字符串
function pathstoText(rx, pa){
pa= pa || document.body;
if(!(rx instanceof RegExp)) rx= RegExp('\\b'+rx+'\\b', 'g');
var matches= document.deepText(pa, function(itm){
if(rx.test(itm.data)){
return document.descent(itm).map(function(who){
if(who.nodeType== 3) return '="'+who.data.match(rx)+'"';
var n= 1, sib= who.previousSibling, tag= who.tagName;
if(who.id) return tag+'#'+who.id;
else{
while(sib){
if(sib.tagName=== tag)++n;
sib= sib.previousSibling;
}
if(n== 1) n= '';
else n= '#'+n;
return who.tagName+n;
}
}).join('> ');
}
});
return matches.join('\n');
}
//几个例子
pathstoText('Help') //finds 'Help' on a button
HTML> BODY> DIV#evalBlock> DIV#evalBar> BUTTON#button_009> ="Help"
pathstoText(/\bcamp[\w]*/ig)
finds 'Camp,camping,etc on a page
found in 2nd paragraph of div #page3,
found 2 instances in fifth paragraph on div#page6,
and so on.
HTML> BODY> DIV#bookview> DIV#pagespread> DIV#page3> P#2>= "Camp"
HTML> BODY> DIV#bookview> DIV#pagespread> DIV#page3> P#4>= "camp"
HTML> BODY> DIV#bookview> DIV#pagespread> DIV#page3> P#12>= "camping"
HTML> BODY> DIV#bookview> DIV#pagespread> DIV#page4> P#3>= "camp"
HTML> BODY> DIV#bookview> DIV#pagespread> DIV#page4> P#7>= "camp"
HTML> BODY> DIV#bookview> DIV#pagespread> DIV#page5> P#3>= "Camp"
HTML> BODY> DIV#bookview> DIV#pagespread> DIV#page5> P#5>= "camp"
HTML> BODY> DIV#bookview> DIV#pagespread> DIV#page5> P#7>= "camp"
HTML> BODY> DIV#bookview> DIV#pagespread> DIV#page6> P#5>= "camp,camp"
//哦,是的-
if(!Array.prototype.map){
Array.prototype.map= function(fun, scope){
var T= this, L= T.length, A= Array(L), i= 0;
if(typeof fun== 'function'){
while(i< L){
if(i in T){
A[i]= fun.call(scope, T[i], i, T);
}
++i;
}
return A;
}
}
}