JS DOM:通过文本内容获取元素 [英] JS DOM: Get elements by text content

查看:304
本文介绍了JS DOM:通过文本内容获取元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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



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



我正在考虑索引所有文本节点,并检查每个正在搜索的字符串的索引,但在我的项目中,没有办法告诉DOM什么时候更新以保持这样的索引是最新的。



任何更好的想法?



谢谢

解决方案

如果你有一个现代浏览器,你可以随时使用XPATH,



这是一个例子:

  document.eval ('// * [text()='+ string +']',document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE).snapshotItem(0);对于旧版浏览器,您可以使用 http://llamalab.com/js/xpath/  


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?

Thanks

解决方案

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/

这篇关于JS DOM:通过文本内容获取元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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