September 4, 2012

How to search and highlight the string using jQuery?

Question by Rajasekhar K

How to search the word and highlighting using jquery, can you please help,
here is my code

$("div:icontains('look')").css("background-color", "yellow");

I need to search and highlight the only ‘look’ in the div.

<div>
     On the Insert tab, the galleries include items that are designed to coordinate with the overall look of your document. 
</div>

Thanks, Rajasekhar.

Answer by Starx

Your selector is wrong, it should be :contains rather than :icontains, with that correction, you code works and here is a demo of that.

Or, you can try using the highlight plugin its quite easy.

A simple example:

$("div:contains('look')").highlight('look').show();
March 5, 2012

Custom Highlight Failing on Website

Question by Matt

I’ve noticed on a lot of sites with custom highlight colors, if you press CTRL + A, the default highlight color, blue, always manages to creep through. Why is that? In making my own site, I have my own custom color too, but I also have the same problem. Does anyone know how to keep this from happening?

http://www.smashingmagazine.com/, http://www.admixweb.com/ are both examples of the CTRL + A problem.

Answer by Starx

Selection styles are mostly browser dependant, and might not be customisable in all browsers. Here is an example of how to configure such styles.

p.normal::selection {
    background:#cc0000;
    color:#fff;
}

p.moz::-moz-selection {
    background:#cc0000;
    color:#fff;
}

p.webkit::-webkit-selection {
    background:#cc0000;
    color:#fff;
}

Such styling are very risky to use and should not be depended upon.

...

Please fill the form - I will response as fast as I can!