Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

javascript - JS DOM: Get elements by text content

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...