JS DOM:通过文本内容获取元素
我正在寻找一种用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您有现代浏览器,则始终可以使用 XPATH,因为它具有基于内容的搜索。
这是一个示例:
对于较旧的浏览器,您可以使用 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:
And with older browsers, you can shim XPATH in with something like http://llamalab.com/js/xpath/
jquery 中的“包含”选择器能解决问题吗?
http://api.jquery.com/contains-selector/
Will 'contains' selector from jquery solve the problem?
http://api.jquery.com/contains-selector/
一般 DOM:用于通过 DOM 中的文本获取元素
或
In general DOM: For getting element by text in DOM
or