Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 879
Hristo Avatar asked May 01 '10 18:05

Hristo


People also ask

What is textContent in JavaScript?

The textContent is the DOM property that is used to set text content for the HTML element or get the text content written inside that element. If you set the text using textContent for an element, then the other child elements will be removed and only this text will be added in that element.

How do I get div text?

Use the textContent property to get the text of a div element, e.g. const result = element. textContent . The textContent property will return the text content of the div and its descendants. If the element is empty, an empty string is returned.


2 Answers

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/

like image 187
blerik Avatar answered Sep 26 '22 08:09

blerik


Will 'contains' selector from jquery solve the problem?

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

like image 34
Nikita Rybak Avatar answered Sep 23 '22 08:09

Nikita Rybak