How to restrict Javascript window.find to a specific DIV?

Is it possible to use Javascript in Safari / Firefox / Chrome to find a specific div container for a given text string. I know that you can use window.find(str) to search the entire page, but is it possible to limit the search to only divs?

Thanks!

+9
source share
8 answers

Once you look through your div (which you can do with document.getElementById or any of the other DOM functions, various specifications here ), you can use textContent or innerText to find the text of this div . Then you can use indexOf to find the string in it.

Alternatively, at a lower level, you can use the recursive function to search all the text nodes in a window, which sounds a lot more complicated than it is. Basically, starting with your target div (which is an Element ), you can skip its childNodes and search in the nodeValue line (if they are Text s) or write in them (if they are Element s).

The trick is that the naive version will not be able to find "foo" in this markup:

 <p><span>fo</span>o</p> 

... since neither of the two Text nodes has a nodeValue with "foo" (one of them has "fo" , the other has "o" ).

+7
source

Depending on what you are trying to do, there is an interesting way to do this, which works (some work is required).

First, the search starts from the place where the last click of the user. So, to get to the right context, you can force click on the div. This will put the internal pointer at the beginning of the div.

Then you can use window.find, as usual, to find the item. It will highlight and move to the next item found. You can create your own dialog and handle the truth or false returned by find, and also check the position. For example, you can save the current scroll position, and if the next returned result is outside the div, you will restore the scroll. Also, if it returns false, you can say that no results were found.

You can also show the default search box. In this case, you can specify the starting position, but not the ending position, because you lose control.

Sample code to get you started. I could also try expanding jsfiddle if there is enough interest.

Syntax:

 window.find(aStringToFind, bCaseSensitive, bBackwards, bWrapAround, bWholeWord, bSearchInFrames, bShowDialog); 

For example, to start a search inside myDiv, try

 document.getElementById("myDiv").click(); //Place cursor at the beginning window.find("t", 0, 0, 0, 0, 0, 0); //Go to the next location, no wrap around 

You can set the blur event handler (lose focus) so that you know when you leave the div to stop the search.

To save the current scroll position, use document.body.scrollTop. Then you can set it back if it tries to go beyond the div.

Hope this helps! ~ Techdude

+1
source

According to another answer, you cannot use window.find functions for this. The good news is that you don’t have to program it completely on your own, as there is currently a library called rangy that helps a lot with this. Thus, since the code itself is too much to copy the paste into this answer, I will simply refer to the rangy library code example, which can be found here . After reviewing the code, you will find

  searchScopeRange.selectNodeContents(document.body); 

which you can replace with

  searchScopeRange.selectNodeContents(document.getElementById("content")); 

Search only in content div.

0
source
 var elements = []; $(document).find("*").filter(function () { if($(this).text().contains(yourText)) elements.push($(this)); }); console.log(elements); 

I have not tried, but according to the jQuery documentation, it should work.

0
source

Here is how I do with jquery:

 var result = $('#elementid').text().indexOf('yourtext') > -1 

it will return true or false

0
source

If you are still looking for something, I think I found a pretty good solution;

Here it is: https://www.aspforums.net/Threads/211834/How-to-search-text-on-web-page-similar-to-CTRL-F-using-jQuery/

And I'm working on removing jQuery (wip): codepen.io/eloiletagant/pen/MBgOPB I hope it's not too late :)

0
source

You can use Window.find() to search for all occurrences on the page and Node.contains() to filter inappropriate search results.
Here is an example of how to find and select all occurrences of a string in a specific element:

 var searchText = "something" var container = document.getElementById("specificContainer"); // selection object var sel = window.getSelection() sel.collapse(document.body, 0) // array to store ranges found var ranges = [] // find all occurrences in a page while (window.find(searchText)) { // filter out search results outside of a specific element if (container.contains(sel.anchorNode)){ ranges.push(sel.getRangeAt(sel.rangeCount - 1)) } } // remove selection sel.collapseToEnd() // Handle ranges outside of the while loop above. // Otherwise Safari freezes for some reason (Chrome does not). if (ranges.length == 0){ alert("No results for '" + searchText + "'") } else { for (var i = 0; i < ranges.length; i++){ var range = ranges[i] if (range.startContainer == range.endContainer){ // Range includes just one node highlight(i, range) } else { // More complex case: range includes multiple nodes // Get all the text nodes in the range var textNodes = getTextNodesInRange( range.commonAncestorContainer, range.startContainer, range.endContainer) var startOffset = range.startOffset var endOffset = range.endOffset for (var j = 0; j < textNodes.length; j++){ var node = textNodes[j] range.setStart(node, j==0? startOffset : 0) range.setEnd(node, j==textNodes.length-1? endOffset : node.nodeValue.length) highlight(i, range) } } } } function highlight(index, range){ var newNode = document.createElement("span") // TODO: define CSS class "highlight" // or use <code>newNode.style.backgroundColor = "yellow"</code> instead newNode.className = "highlight" range.surroundContents(newNode) // scroll to the first match found if (index == 0){ newNode.scrollIntoView() } } function getTextNodesInRange(rootNode, firstNode, lastNode){ var nodes = [] var startNode = null, endNode = lastNode var walker = document.createTreeWalker( rootNode, // search for text nodes NodeFilter.SHOW_TEXT, // Logic to determine whether to accept, reject or skip node. // In this case, only accept nodes that are between // <code>firstNode</code> and <code>lastNode</code> { acceptNode: function(node) { if (!startNode) { if (firstNode == node){ startNode = node return NodeFilter.FILTER_ACCEPT } return NodeFilter.FILTER_REJECT } if (endNode) { if (lastNode == node){ endNode = null } return NodeFilter.FILTER_ACCEPT } return NodeFilter.FILTER_REJECT } }, false ) while(walker.nextNode()){ nodes.push(walker.currentNode); } return nodes; } 

For the Range object, see https://developer.mozilla.org/en-US/docs/Web/API/Range .
For the TreeWalker object TreeWalker see https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker

0
source

Maybe you are trying not to use jquery ... but if not, you can use this $('div:contains(whatyouarelookingfor)') , the only way is to return the parent elements that also contain a child div that matches.

-2
source

All Articles