Duplo W
Duplo W

Reputation: 623

How to simplify this Jquery solution?

This is my Jquery at the moment:

$("button").click(function() {
  var counter = 1
  $("tr td:nth-child(2)").text(counter);
  click ++;

});

Instead of using;

$"(tr td:nth-child(2)").text(counter); 

I would like to use .slice() in order to avoid having to do this:

$("tr td:nth-child(2)").text(counter);
$("tr td:nth-child(4)").text(counter);
$("tr td:nth-child(6)").text(counter);
$("tr td:nth-child(8)").text(counter);

Alternatively if there is a better solution I would appreciate that too. Thanks.

Upvotes: -1

Views: 51

Answers (2)

tewathia
tewathia

Reputation: 7328

Try the jQuery :even selector:

$('tr td:even').text(counter);

If you want to start from index 2(and not 0), use:

$('tr td:even:not(:first)').text(counter);

DEMO

Upvotes: 1

Tilman Schweitzer
Tilman Schweitzer

Reputation: 1487

Just iterate over the elements.

$("tr td").each(function (index, element) {
    if (index % 2 === 0) { // if you want to check for evens
        element.text(index);
    }
})

Upvotes: 0

Related Questions