JS DOM:通过文本内容获取元素

发布于 2024-08-31 04:12:39 字数 402 浏览 3 评论 0原文

我正在寻找一种用 JS 在 DOM 树上执行全文搜索的方法。简而言之,我想检索包含给定字符串的文本节点列表。

我尝试过 mootools' Element.getElements ( ':contains[string]' ) 但我无法让它处理包含空格的字符串。

编辑:jQuery 和 mootools 似乎有他们的 :contains 运算符通过树遍历工作。这意味着没有本地搜索页面的方式,这是正确的吗?如果页面很大并且您拥有的有关元素的唯一信息是正在搜索的字符串,则似乎效率非常低。我错了吗?

我正在考虑对所有文本节点建立索引并检查正在搜索的每个字符串的索引,但是,在我的项目中,没有办法告诉 DOM 何时更新以维护这样的索引是最新的。

还有更好的想法吗?

I am looking for a way to perform fulltext search on the DOM tree with JS. In two words, I would like to retrieve the list of text nodes which contain a given string.

I've tried mootools' Element.getElements ( ':contains[string]' ) but I can't get it to work with strings containing whitespace.

EDIT: jQuery and mootools seem to have their :contains operators work through tree traversal. This would mean that there is no native way for searching the page, is this correct? Seems very inefficient if the page is huge and the only info you have about your element is the string being searched for. Am I wrong?

I'm thinking about indexing all text nodes and checking against the index for each string being searched for, but, in my project, there's no way of telling when the DOM updates in order to maintain such an index up-to-date.

Any better ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

醉南桥 2024-09-07 04:12:39

如果您有现代浏览器,则始终可以使用 XPATH,因为它具有基于内容的搜索。

这是一个示例:

document.evaluate('//*[text()="' + string + '"]', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE).snapshotItem(0);

对于较旧的浏览器,您可以使用 http://llamalab.com/ 之类的内容填充 XPATH js/xpath/

If you have a modern browser, you can always use XPATH, since it has content-based search.

This is an example:

document.evaluate('//*[text()="' + string + '"]', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE).snapshotItem(0);

And with older browsers, you can shim XPATH in with something like http://llamalab.com/js/xpath/

山人契 2024-09-07 04:12:39

jquery 中的“包含”选择器能解决问题吗?

http://api.jquery.com/contains-selector/

Will 'contains' selector from jquery solve the problem?

http://api.jquery.com/contains-selector/

蓝天 2024-09-07 04:12:39

一般 DOM:用于通过 DOM 中的文本获取元素

//*[text()='anytext']

//*[.='anytext']

In general DOM: For getting element by text in DOM

//*[text()='anytext']

or

//*[.='anytext']
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文