views:

141

answers:

2

Im trying to use jQuery to add a different class for each Span element, using .next() This is the javascript:

<script type="text/javascript">

    $(function() {
        $("a", "div.top_menu").addClass("ui-icons-custom");

        $("span.ui-icon:first", "ul.top_menu_list").addClass("ui-icon-pencil")
            .next().addClass("ui-icon-comment")
            .next().addClass("ui-icon-key");
    });

</script>

And this is the HTML Im trying to make it work:

<div class="top_menu ui-state-default-custom">
                <ul class="ui-widget top_menu_list">

                    <li>
                        <span style="float: left;" class="ui-icon-text-custom"><span style="float: left;" class="ui-icon"></span>
                            <a href="test">Registrarse</a>
                        </span>
                    </li>
                    <li>
                        <span style="float: left;" class="ui-icon-text-custom"><span style="float: left;" class="ui-icon"></span>
                            <a href="test1">Agregar un anuncio</a>
                        </span>
                    </li>
                    <li>
                        <span style="float: left;" class="ui-icon-text-custom"><span style="float: left;" class="ui-icon"></span>
                            <a href="test2">Ingresar (Login)</a>
                        </span>
                    </li>
                </ul>
            </div>

So it should take the first 'span' element with .ui-icon class and add a class, then the next from the list and add other class.

+2  A: 

Take a look at CSS3 psuedo classes.

$('li:odd span.ui-icon')

jQuery supports them: http://api.jquery.com/nth-child-selector/

Jason McCreary
+3  A: 

.next() finds the next immediate sibling to the element that you selected. In your case, the span you selected has an anchor as its next sibling, and then nothing. You'd have to go back up to the parent li using parent("li"), use next() to get to the next li in the list, then use find("span span") to get to the span in question.

It's probably easier and a lot more readable to select all the spans and then edit each individually, e.g.:

$(function() {
    $("a", "div.top_menu").addClass("ui-icons-custom");

    var $spans = $("span.ui-icon", "ul.top_menu_list");

    // end() reverts us back to the selector before each eq()
    // you can just make this three separate statements if you like
    $spans.eq(0).addClass("ui-icon-pencil").end()
          .eq(1).addClass("ui-icon-comment").end()
          .eq(2).addClass("ui-icon-key");
});

Er, and out of curiosity, what's stopping you from adding the classes to the elements directly rather than using jQuery to do it?

Faisal