Lluís Puig Ferrer
Lluís Puig Ferrer

Reputation: 1146

Javascript: Correct syntax in for

I have this code:

$(this).find('.placeholder-style td:nth-child(1)').addClass('hidden-td')
$(this).find('.placeholder-style td:nth-child(2)').addClass('hidden-td')
$(this).find('.placeholder-style td:nth-child(3)').addClass('hidden-td')
$(this).find('.placeholder-style td:nth-child(4)').addClass('hidden-td')
$(this).find('.placeholder-style td:nth-child(5)').addClass('hidden-td')

And I want to do it dynamic like this:

for (i = 0; i < 5; i++){
   $(this).find('.placeholder-style td:nth-child'.(i)).addClass('hidden-td')
}

Which is the correct syntax to this code?

Upvotes: 0

Views: 38

Answers (3)

Ramesh Rajendran
Ramesh Rajendran

Reputation: 38683

  • Should define i variable like var i
  • The i value should be start with 1
  • use + instead of . for concatenate string

just like,

for ( var i = 1; i <= 5; i++){
   $(this).find('.placeholder-style td:nth-child'+i).addClass('hidden-td')
}

Upvotes: 1

Ivan Karaman
Ivan Karaman

Reputation: 1234

I think u can do this in easier way

.placeholder-style td:nth-child(-n+5){display: none;}

Upvotes: 0

Quentin
Quentin

Reputation: 943751

  1. In JavaScript, the concatenation operator is + not .
  2. The ( and ) are part of the selector syntax, not JavaScript syntax, they need to be strings.

Such

$(this).find(
    '.placeholder-style td:nth-child(' + i + ')' 
).addClass('hidden-td')

This would probably be easier to do without the for loop.

$(this).find(
    '.placeholder-style td:not(:nth-child(6) ~ td)' 
).addClass('hidden-td')

Upvotes: 3

Related Questions