如何将 Javascript 的 window.find 限制为特定的 DIV? [英] How to limit Javascript's window.find to a particular DIV?

查看:87
本文介绍了如何将 Javascript 的 window.find 限制为特定的 DIV?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 Safari/Firefox/Chrome 中使用 Javascript 来搜索给定文本字符串的特定 div 容器.我知道您可以使用 window.find(str) 来搜索整个页面,但是否可以将搜索区域限制为仅 div?

Is it possible to use Javascript in Safari/Firefox/Chrome to search a particular div container for a given text string. I know you can use window.find(str) to search the entire page but is it possible to limit the search area to the div only?

谢谢!

推荐答案

一旦你查找你的 div(你可以通过 document.getElementById 或任何其他 DOM 函数,此处有各种规格),您可以使用 textContentinnerText 以查找该 div 的文本.然后你可以使用 indexOf 来查找其中的字符串.

Once you look up your div (which you might do via document.getElementById or any of the other DOM functions, various specs here), you can use either textContent or innerText to find the text of that div. Then you can use indexOf to find the string in that.

或者,在较低级别,您可以使用递归函数搜索窗口中的所有文本节点,这听起来比实际复杂得多.基本上,从您的目标 div(这是一个 Element),你可以遍历它的 childNodes 并搜索它们的 nodeValue 字符串(如果它们是 Texts) 或递归到它们中(如果它们是 Elements).

Alternately, at a lower level, you can use a recursive function to search through all text nodes in the window, which sounds a lot more complicated than it is. Basically, starting from your target div (which is an Element), you can loop through its childNodes and search their nodeValue string (if they're Texts) or recurse into them (if they're Elements).

诀窍是简单版本将无法在此标记中找到 "foo":

The trick is that a naive version would fail to find "foo" in this markup:

<p><span>fo</span>o</p>

...因为两个 Text 节点都没有 nodeValue"foo" (其中一个有 "fo",另一个"o").

...since neither of the two Text nodes there has a nodeValue with "foo" in it (one of them has "fo", the other "o").

这篇关于如何将 Javascript 的 window.find 限制为特定的 DIV?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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