Find an Element based on its Style using jQuery

Here’s how to use jQuery filter to find an element based on its style

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Find Elements based on its style</title>
<
script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js">
</
script>
<
style type="text/css">
.p1
{background-color:red; height:50px; width:50px; }
.p2
{background-color:blue; height:50px; width:50px; }
.p3
{ background-color:red; height:100px; width:50px; }
</style>
<
script type="text/javascript">
$(function () {
$('p').filter(function () {
return $(this).css('background-color') == 'red'
&& $(this).css('height') == '100px';
}).css('border', '2px solid black');
});
</script>
</
head>
<
body>
<
div>
<
p class="p1"></p>
<
p class="p2"></p>
<
p class="p3"></p>
</
div>
</
body>
</
html>


In the code above, we select all the paragraphs and then apply a filter based on the CSS properties set. The code adds a black border around a paragraph whose background color is red and height is 100px

image






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: