用javascript在html页面中找到单词 [英] find words in html page with javascript

查看:97
本文介绍了用javascript在html页面中找到单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何快速搜索一个html页面?
以及如何获取该单词所在的html标签? (所以我可以使用整个标签)

how can i search an html page for a word fast? and how can i get the html tag that the word is in? (so i can work with the entire tag)

推荐答案

要查找单词存在的元素,您必须遍历整个树只看文本节点,应用与上面相同的测试。在文本节点中找到该单词后,返回该节点的父节点。

To find the element that word exists in, you'd have to traverse the entire tree looking in just the text nodes, applying the same test as above. Once you find the word in a text node, return the parent of that node.

var word = "foo",
    queue = [document.body],
    curr
;
while (curr = queue.pop()) {
    if (!curr.textContent.match(word)) continue;
    for (var i = 0; i < curr.childNodes.length; ++i) {
        switch (curr.childNodes[i].nodeType) {
            case Node.TEXT_NODE : // 3
                if (curr.childNodes[i].textContent.match(word)) {
                    console.log("Found!");
                    console.log(curr);
                    // you might want to end your search here.
                }
                break;
            case Node.ELEMENT_NODE : // 1
                queue.push(curr.childNodes[i]);
                break;
        }
    }
}

承诺为IE。

它所做的是从body元素开始,并检查该元素是否存在于该元素中。如果没有,就是这样,搜索停在那里。如果它在身体元素中,则它遍历身体的所有直接子女。如果它找到一个文本节点,那么看看这个单词是否在该文本节点中。如果它找到一个元素,那么将其推入队列。继续下去,直到您找到该单词或没有更多要搜索的元素。

What it does is start with the body element and check to see if the word exists inside that element. If it doesn't, then that's it, and the search stops there. If it is in the body element, then it loops through all the immediate children of the body. If it finds a text node, then see if the word is in that text node. If it finds an element, then push that into the queue. Keep on going until you've either found the word or there's no more elements to search.

这篇关于用javascript在html页面中找到单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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