Pergunta

I have a piece of code that works to add a class to menu items:

$(document).ready(function() {
    $('#submenu ul li ul li').addClass("top4");
});

This works fine. However I just want to apply the class to the first 4 of each block of menu items.

I assumed that I could use slice:

.slice(0,3)

However the following code:

$(document).ready(function() {
    $('#submenu ul li ul li').slice(0,3).addClass("top4");
});

doesn't seem to work.

Any ideas?

Foi útil?

Solução

You can use the :lt-selector as below

$(document).ready(function () {
    $('#submenu ul li ul').find('li:lt(4)').addClass("top4");
});

Demo: Fiddle

Outras dicas

You can use :lt() selector instead:

Select all elements at an index less than index within the matched set.

$(document).ready(function() {
    $('#submenu ul li ul').find('li:lt(4)').addClass("top4");
});
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top