Matt
Matt

Reputation: 1609

Loop through <li> elements with jquery and highlight searched text

I have a page of results from a search. Given a list of results, I need to be able to highlight a given text string from an input. Given the following code, I am able to highlight the term, but I am trying to do so with a list of results. The intended result is to highlight every instance of the search string in the list of returned results.

HTML

<input type="text" id="searchfor" />
<p id="all_text">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua</p>

CSS

#all_text span {
    text-decoration:underline;
    background-color:yellow;
}

JavaScript

$('#searchfor').keyup(function () {

    var page = $('#all_text');
    var pageText = page.text().replace("<span>", "");
    var searchedText = $('#searchfor').val();
    var theRegEx = new RegExp("(" + searchedText + ")", "igm");
    var newHtml = pageText.replace(theRegEx, "<span>$1</span>");
    page.html(newHtml);
});

Upvotes: 2

Views: 918

Answers (1)

Eric J.
Eric J.

Reputation: 150108

You can use the jQuery Highlight plugin

http://bartaz.github.com/sandbox.js/jquery.highlight.html

It does a great job of highlighting search results. There is an option to pass in an array terms to highlight rather than just a single term. That's not obvious from the documentation, but it pointed out in the comments at the top of the code.

UPDATE

Passing multiple search terms at once (from the comments at the top of the source code):

// search for and highlight more terms at once
// so you can save some time on traversing DOM
$('#content').highlight(['lorem', 'ipsum']);

Upvotes: 2

Related Questions