Style dynamically imported list tags with jQuery

I thought this would be a cool quick tip as I just started using this myself.

Sometimes you want to style <li> tags in tables and lists to make them more visible, like alternating background colors. This is normally quite easy, by adding a normal class to the tag like

<li class="even"> or <li class="odd">

you can style the rows appropriately. However, what if you want to style <li> tags that don’t yet exist?

Well if you want to style <li> tags that are being imported dynamically (like with Twitter), you’ll need some jQuery!

First you’ll need to call two scripts in your head section, first the jQuery library, and then the script that will insert itself in your code. Note, in order for this to work, your <li> tags need to be inside <ul> tags, which is standard practice anyway.

Before your </head> tag, insert these lines:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$ ('ul.classhere li:even').addClass('even');
$ ('ul.classhere li:odd').addClass('odd');
});
</script>

This is now going to look for a <ul class=”classhere”> (you can name it whatever) to style its internal <li> tags, therefore automatically adding classes “even” and “odd” to the <li> tags:

<ul class="classhere">
<li class="even">first element</li>
<li class="odd">second element</li>
<li class="even">third element</li>
<li class="odd">fourth element</li>
<li class="even">fifth element</li>
<li class="odd">last element</li>
</ul>

So for that example right there, I had the <ul> tag with the class, “classhere” and no <li> tags because Twitter lets say is importing them live. So my written code would look like:

<ul class="classhere">
</ul>

But then Twitter starts to populate the <ul> tag with <li> tags dynamically (which are the tweets). All this script does is find the <li> tags within the specified <ul> tag, and then adds a class. Now I can style them in my CSS to change their background colors, making them a little more visible.

You can see an example here.

Obviously this script has a number of uses, it can add classes to any dynamically imported <li> tag, and you can tweak it to add classes to almost anything. Have fun!

Recent comments

Blog comments powered by Disqus