2

I tried to add "1fr " to a DOM element’s style many times using a for loop and the "+=" operator, but it only applied once, no matter how many times I ran the loop. So, I would like to know why it behaves this way. Here’s a little bit of my code.

for (i = 1; i <= number; i++){
  sketchPadElement.style.gridTemplateColumns += "1fr ";
}

Since, I couldn’t get it to work, I wrote a function to repeat the string and used that to generate as many "1fr "s as I needed in one string like so.

function makeGrid(number) {
  sketchPadElement.style.gridTemplateColumns = repeatString("1fr ", number);
}

And that works fine, but I’d still love to know why my previous attempt failed.

3

1 Answer 1

3

When assigning the string, any trailing space is automatically removed. So instead of using trailing space, use leading space:

for (let i = 1; i <= number; i++){
  sketchPadElement.style.gridTemplateColumns += " 1fr";
}

But instead of looping, it's better to outright use the repeat() CSS function:

sketchPadElement.style.gridTemplateColumns = `repeat(${number}, 1fr)`;
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the detailed answer. It solves my problem perfectly. I'll read on the repeat function. Oh, I'd like to ask tho, is the trailing space removal a JavaScript thing?
Not in general, it's just how the setter for style properties works.

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.