Find all text nodes

浪尽此生 提交于 2019-12-18 04:37:07

问题


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

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.

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);

回答1:


Change this...

element.nodeValue != ''

to this...

/\S/.test(element.nodeValue)

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.


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

element.nodeValue.trim() != ''


来源:https://stackoverflow.com/questions/9178174/find-all-text-nodes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!