How To Use Basic jQuery Filters With HTML List
In this post I would like to show you how you can make use of jQuery selectors and filters to manipulate HTML list. Here is the starting HTML to play with:
<h2>
Here is my magic list
</h2>
<p>
<ul class="magicList">
<li>first point</li>
<li>second point</li>
<li>third point</li>
<li>fourth point</li>
<li>fifth point</li>
<li>sixth point</li>
</ul>
</p>
Please note that on ul tag has a CSS class magicList defined. It’s useful to have a unique CSS class or ID defined because it makes writing selectors much easier. Now, having magicList CSS class defiend, you can use following jQuery selector to get list of all elements:
$(document).ready(function () {
$("ul.magicList > li").css("color", "green");
});
A bit of explanation:
- selector $(“ul.magicList”) will return all ul tags where CSS class equals ’magicList’
- selector $(“ul.magicList > li”) will return all li tags within ul tag where CSS class is ‘magicList’
- css(“color”,”green”) – functions css() setts attribute color to provided value, in this case ‘green’
As a a result our HTML will look like this:
Now, let’s try to make it a bit more sophisticated – odd elements can stay green, but even elements should be red
Here is a jQuery code which can do that for you:
$(document).ready(function () {
$("ul.magicList > li:odd").css("color", "green");
$("ul.magicList > li:even").css("color", "red");
});
In the above case I have used jQuery filters to limit set of elements to the one which I need:
- selector $(“ul.magicLIst > li”) will return all li tags and by using filter “:odd” it’s possible to take only odd elements and remove the even ones.
- for even elements filter to use is “:even”
Okey, let’s add another requirement – first and last elemets should be blue. As you can probably guess already there are additional jQuery filters which will return for you first and last element:
$(document).ready(function () {
$("ul.magicList > li:odd").css("color", "green");
$("ul.magicList > li:even").css("color", "red");
$("ul.magicList > li:last").css("color", "blue");
$("ul.magicList > li:first").css("color", "blue");
});
And here is the final result:
In this post I wanted to give you an idea how powerful and useful jQuery is and how easy you can manipulate HTML list with it. Of course ,the same results you can achieved in many different ways within ASP.NET but none of them is not as simple as jQuery one.
In the next posts you will find more advanced filters which means more fun and more options to get exactly what you need!


[...] About « How To Use Basic jQuery Filters With HTML List [...]
How To Use Basic jQuery Filters With HTML List (part 2) « jQuery with ASP.NET
9 Aug 10 at 12:19 pm
[...] How To Use Basic jQuery Filters With HTML List [...]
How To Empower ASP.NET Repeater With jQuery « jQuery with ASP.NET
10 Aug 10 at 4:41 pm