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



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: