查找所有文本节点 [英] Find all text nodes

查看:176
本文介绍了查找所有文本节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个书签,在文档上所有可见文本的实例上调用函数doSomething(textNode).

I'm trying to write a bookmarklet that calls the function doSomething(textNode) on all instances of visible text on the document.

doSomething()仅出于娱乐目的,通过替换传递给它的textNode的textContent,将每个单词替换为"derp".但是,这使一些textNodes空了,在其中包含单词,因此破坏了网页.

doSomething(), just for fun, replaces every word with "derp" by replacing the textContent of the textNode passed into it. However, this makes some textNodes that are empty to have words in them, so it breaks the web page.

是否可以仅在每个包含单词的textNode上调用doSomething()?

Is there a way to call doSomething() on only every textNode that has words in it?

function recurse(element)
{
    if (element.childNodes.length > 0) 
        for (var i = 0; i < element.childNodes.length; i++) 
            recurse(element.childNodes[i]);

    if (element.nodeType == Node.TEXT_NODE && element.nodeValue != '') 
        doSomething(element);
}
var html = document.getElementsByTagName('html')[0];
recurse(html);

推荐答案

更改此...

element.nodeValue != ''

对此...

/\S/.test(element.nodeValue)

这使用/\S/正则表达式,该表达式搜索至少一个非空格字符.

This uses the /\S/ regex, which searches for at least one non-space character.

您可能需要进一步定义单词"的含义.我认为这意味着您仅排除仅空白节点.

You may need to define further what you mean by "words". I took it to mean that you're only excluding whitespace-only nodes.

在支持String.prototype.trim的浏览器中,这是替代方法...

In browsers that support String.prototype.trim, this would be an alternative...

element.nodeValue.trim() != ''

这篇关于查找所有文本节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆