user163408
user163408

Reputation:

jQuery - onPage search like a browser

I try to make onpage searches like in modern browsers with STRG + F. I tried:

$("#mydiv").find(':contains(\'mySearchString\')').prepend('found you!');

The problem is that jQuery adds found you multiple times, bedause there are multipile elements who has the string. Example:

Found you<div>
   Found you<ul>
      Found you<li>
         Found you<a>mySearchString</a>
      </li>
   </ul>
</div>

Upvotes: 1

Views: 1097

Answers (2)

Dave.Sol
Dave.Sol

Reputation: 251

$('#mydiv').find(':contains(\'mySearchString\')').contents().filter(function(){return this.nodeType == Node.TEXT_NODE}).prepend('found you!');

would only select the last inner text node. If you are using IE, use the constant 3 instead of Node.TEXT_NODE.

Upvotes: 2

David Hedlund
David Hedlund

Reputation: 129832

You could do:

$("#mydiv").find(':contains(\'mySearchString\')').eq(0).prepend('found you!');

to single out the first match.

Otherwise you could just say it works like Google Chrome, which highlights all search matches immediately ;)

Upvotes: 1

Related Questions