MDuB
MDuB

Reputation: 371

Jquery nth-child selector in an array

I want to use the nth-child selector to return the even values of the array. This is what I have:

Javascript Code

var blog = Note01,Date01, Username01,Note02,Date02, Username02,
for(var i=0; i<blog.length-1; i++){
    alert(blog + " :nth-child(even)").html();
}

This is the array

[0]Note01
[1]Date01
[2]Username01
[3]Note02
[4]Date02
[5]Username02

This is what I think should return:

Username01, Date02

How can I accomplish this using the nth-child selector?

Upvotes: 2

Views: 1550

Answers (1)

martynas
martynas

Reputation: 12300

You shouldn't use nth-child for this. You could make use of the modulo operator:

Given:

var A = ['Item 1', 'Item 2', 'Item 3'];

Use $.each() to iterate over the array:

$.each(A, function(k, v) {
    if (k % 2 == 0) console.log(v);
});

Demo

Or you can do it with a simple for loop:

for (var i = 0; i < A.length; i++) {
    if (i % 2 == 0) console.log(A[i]);
}

Upvotes: 3

Related Questions