tags:

views:

798

answers:

5

I have the following jquery-code:

<script type="text/javascript">
    $(document).ready(function() {
        $ ('ul.image-list li:even').addClass ('even');
        $ ('ul.image-list li:odd').addClass ('odd');
    });
</script>

and the following html:

<ul class="image-list">
<li>first element</li>
<li>second element</li>
...
<li>last element</li>
</ul>

However the jquery does not seem to be applied, because the li-tags don't get the proper classes (even or odd). What am I doing wrong? thanks

A: 
peirix
A space between the function name and parenthesis is perfectly acceptable.
Kane Wallmann
so it seems...hmm...
peirix
style-sheet is being applied, but no classes are being applied
andrej
Which means there's a problem with your javascript. Did you remember to reference the jQuery library? Have a look at line 5 in petersendidit's answer.
peirix
do I have to reference it in the <head> section? Or can I put in anywhere in the html?
andrej
the problem might occur because the list is generated by an asp:repeater?
andrej
you need to reference the jquery library before you use `$(document).ready()`. And it should have anything to do with asp:repeater, as that would output the html before jQuery fires.
peirix
+1  A: 

This works just fine for me. Why do you think its not working in your code?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt;
<html>
<head>
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"&gt;&lt;/script&gt;
    <script type="text/javascript">
        $(document).ready(function() {
            $ ('ul.image-list li:even').addClass('even');
            $ ('ul.image-list li:odd').addClass('odd');
        });
    </script>
    <style>
     .even{
      background: gray;
     }
     .odd{
      color:red;
     }
    </style>
</head>
<body>

<ul class="image-list">
    <li>first element</li>
    <li>second element</li>
    <li>third element</li>
    <li>fourth element</li>
    <li>fifth  element</li>
    <li>last element</li>
</ul>

</body>
</html>
PetersenDidIt
A: 

First of all, are you sure you inserted your style sheet into your page? I often forget this. Second, have you inserted the jquery js file into your page? I forget this very often. Third, do what peirix says and it should work. I don't see whats wrong with it.

Time Machine
A: 

Is it possible that you create the li dynamically? In that case the call to add the class should not be on ready() but on a callback after the insertion of the li.

Elzo Valugi
and how do I add the class on callback?
andrej
and the list is populated with a asp:repeater. However I thought, this would be called "dynamically", or am I wrong?
andrej
A: 

you can alternatively use: .filter(":odd").addClass("odd")