user3760964
user3760964

Reputation:

jquery select several elements with a short code

i want to select several elements with jquery like this:

$('p:nth-child(1),p:nth-child(4),p:nth-child(7),p:nth-child(10)')
//nth-child is : 1,4,7,10,13,16,19,22 and etc

I have to select 1 item every 3 items. How can do this with dynamic code?

Upvotes: 2

Views: 100

Answers (2)

Nicolas R
Nicolas R

Reputation: 14619

If you want to select 1 item every 3, you can do the following:

$("p:nth-child(3n+1)")

For example, here I will set the background color of your "p" items, but only for the 1st, 4th, 7th...:

$("p:nth-child(3n+1)").css("background-color", "red");

See jsfiddle update: http://jsfiddle.net/TjLdy/1/

Upvotes: 1

James Donnelly
James Donnelly

Reputation: 128856

You can store the children you want to select in an array and use a loop to generate your selector:

var children = [1,4,7,10,13,17,21,24],
    selector = "";

// Loop through each value in your array, populating your selector string
// Each loop will add "p:nth-child(n)," to your selector string
for (var i=0; i<children.length; i++)
    selector += "p:nth-child(" + children[i] + "),";

// Remove trailing comma
selector = selector.slice(0, -1);

This will generate the following selector string:

"p:nth-child(1),p:nth-child(4),p:nth-child(7),p:nth-child(10),p:nth-child(13),p:nth-child(17),p:nth-child(21),p:nth-child(24)"

We can now put this into the jQuery selector simply by using:

$(selector)

Upvotes: 0

Related Questions