0

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?

4
  • Just change the starting value to 1 instead of 0 and use <= instead of <. And use string concatenation (as indicated by Teemu below). And don't forget to use var i. Commented Nov 20, 2017 at 11:16
  • Where is the foreach? Commented Nov 20, 2017 at 11:17
  • 3
    + operator has used to be a string concatenation operator in JS ... Commented Nov 20, 2017 at 11:17
  • Most jQuery methods implicitly iterate over the collection, so I'd rather try to narrow down the matches, then call addClass once on the right set of elements, e.g. $(this).find('.placeholder-style td').filter( function(idx){ return idx < 5 }).addClass('hidden-td') Commented Nov 20, 2017 at 11:21

3 Answers 3

3
  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')
Sign up to request clarification or add additional context in comments.

5 Comments

@LluísPuigFerrer — The loop should be exactly as it is in the question. jsbin.com/masuvuluvi/1/edit?html,css,js,output
Thanks @Quentin for you answer and explanation. Your jsbin works, I'm checking in my real code and is not working. I will put here a link to my other question and maybe you can help me.
With your second answer works, but not with for. Can check it?
I know why is not working. I'm using in for a variable which I get like this: ` var numcells = $('.hidden-td').length ` but in blade I have a foreach so I get all the .hidden-td of blade not in the row. Know how can I do it?
1
  • 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')
}

Comments

0

I think u can do this in easier way

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.