jQuery: Find Text and Highlight Elements

Let us see how to use jQuery to find/search a piece of text and highlight elements if that text is present in them.

I am a big fan of jQuery’s terse syntax and we will see an example here which searches a text as well as highlights elements, using just a single line of jQuery code.

<html xmlns="http://www.w3.org/1999/xhtml" >
<
head>
<
title>Search Text in jQuery from DevCurry.com</title>
<
style type="text/css">
div { height: 50px; width: 150px; border: 1px solid blue; }
</style>
<
script type="text/javascript"
src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.min.js">
</
script>

<
script type="text/javascript">
$(function () {
$("#btnSearch").click(function () {
$("div:contains('simple')").css("border", "4px solid blue");
});
});
</script>
</
head>
<
body>
<
div id="divOne">DivOne. This is a simple looking DIV</div><br />
<
div id="divTwo">DivTwo. This is another simple looking DIV</div><br />
<
div id="divThree">DivThree. This is just a DIV</div><br />
<
div id="divFour">DivFour. This is again a DIV</div><br />
<
div id="divFive">DivFive. Yet another simple looking DIV</div><br />

<
input id="btnSearch" type="button" value="Search" />
</
body>
</
html>

What we are doing here is use the jQuery contains selector which looks for a string of text within the selected element and any of that element's descendants. Once the divs containing the text ‘simple’ are found, they are all highlighted by giving them a 4px border – all of this using just one line of code

Note: contains() is case-sensitive

jquery search text

OUTPUT

jquery search text

See a Live Demo

Liked this tip? Check plenty of jQuery tips here






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: