kritya
kritya

Reputation: 3362

jQuery highlight the characters found by :contains text from an input box

I got this code: Link

I can highlight the chars of static text by this js:

$("li:contains('Content1')").each(function(){
    var content = "Content1";
    this.innerHTML = this.innerHTML.replace(content,"<span>"+content+"</span>")
})

The Content1 by a dynamic value : $("#main").val()

QUESTION: How can i highlight words found with :contains and with the value from the input box

Upvotes: 4

Views: 1316

Answers (1)

hayesgm
hayesgm

Reputation: 9096

This is going to be a little dicey, but check this out.

Your issue was that as you adjusted the content, you'd no longer be able to check what the original content was. The best way around this is, at the beginning, store the original LI text in a data-attribute, and then use that for manipulation later on.

 $("li").each(function() {
   $(this).attr( 'data-original', $(this).text() );
   $(this).attr( 'data-original-l', $(this).text().toLowerCase() );
 });

We then need to adjust your selector to check this attribute (as opposed to the text value):

 $("li[data-original *= \"" + $("#main").val().toLowerCase() + "\"]")

which, e.g. will search li[data-original*="Harry Potter"], which is "any LI with an attribute "data-original" which contains "Harry Potter" (see here).

From there, we just need to tweak your replacement statement as follows:

 $(this).html($(this).data('original').replace(new RegExp(content, "i"), "<span class='highlight'>$&</span>"));

We are doing the same thing you had originally, but now using the $(this).data('original') value instead of $(this).val(). We are also using a Regular Expression so that we can do the replacement case-insensitive. Also, we replace with $& which contains the match from the RegExp test in the original string.

Easy as pie! Hope this works for you and let me know if you run into any snags.

Upvotes: 3

Related Questions