andrej
andrej

Reputation: 255

Jquery: Adding a class to even an odd List-Elements

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

Upvotes: 5

Views: 29735

Answers (5)

qsfsd
qsfsd

Reputation:

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

Upvotes: 4

Elzo Valugi
Elzo Valugi

Reputation: 27856

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.

Upvotes: 0

peirix
peirix

Reputation: 37741

Try removing the space between addClass and (

Same with $ and your selector

Are you using Firebug, if you are, look at the HTML, and see if the class names are being applied or not. If they are, you simply forgot to link your stylesheet. If they're not, then there's something wrong with your javascript.

Upvotes: 0

user142019
user142019

Reputation:

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.

Upvotes: 0

PetersenDidIt
PetersenDidIt

Reputation: 25620

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">
<html>
<head>
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <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>

Upvotes: 10

Related Questions