hkguile
hkguile

Reputation: 4359

Select every element of a ul li using jquery

I have a menu in form of ul li, and I want to a add different css class to every child of the li.

Here is the javascript code:

$("#menu").ready(function () {
  $("#menu ul li").addClass("menu_background1");
});

css:

.menu_background1 {
    background:#FF0;
}

.menu_background2 {
    background:#66C;
}

How should I select every child using jQuery? Every child should have different css class..

Upvotes: 1

Views: 222

Answers (3)

Dipak
Dipak

Reputation: 12190

try with :eq() selector -

$("#menu ul li:eq(0)").addClass("menu_background1");
$("#menu ul li:eq(1)").addClass("menu_background2");

Upvotes: 0

Ram
Ram

Reputation: 144659

You can use addClass's function:

$(document).ready(function () {
    $("#menu ul li").addClass(function(i){
       return 'menu_background' + (i+1)
    });
});

http://jsfiddle.net/5Buh9/

Upvotes: 4

Pragnesh Chauhan
Pragnesh Chauhan

Reputation: 8476

use each for that

$("#menu ul li").each(function(i){
   $(this).addClass("menu_background"+(i+1));
});

Upvotes: 0

Related Questions