1

Does anybody know why this code does not create as many elements as I enter in the
repeat variable?

It creates only 1 element and not 5, why?

function create(el, w, h, bg, repeat){
    for(let i=0; i<repeat; i++){
      el = document.createElement(el);
      el.style.width = w;
      el.style.height = h;
      el.style.background = bg;

      document.body.appendChild(el);
    }
  }

  create("div","100px", "100px", "black", 5);
1
  • 10
    You're using el twice with two different meanings. The second iteration of the loop doesn't like it. Commented Nov 14, 2019 at 13:09

2 Answers 2

3

It's because you're overriding the variable el that holds the tag. After the first element gets inserted, el won't be "div" it will be the DOM element that just got inserted. Use different variables:

// notice the parameter is renamed from 'el' to 'elTag'

function create(elTag, w, h, bg, repeat) {
    for(let i=0; i<repeat; i++){
      let el = document.createElement(elTag);
      el.style.width = w;
      el.style.height = h;
      el.style.background = bg;

      document.body.appendChild(el);
   }
}
Sign up to request clarification or add additional context in comments.

5 Comments

This is a mistake by the OP. It wont help anyone in the future. If you answer, the question can not be deleted anymore. Still i dont understand why they need to downvote.
@PatrickLüthi There are plenty of these questions these days.
I know but it is not what stackoverflow is there for. It should be a question a lot of users can get a solution from and not just the OP.
@PatrickLüthi then should we vote to close as typo, in your opinion? I mean, closing is for avoiding people answering less than useful question, but none of the reasons in the close popup seem to match this one.
@FedericoklezCulloca you probalby know more about this than I do. It is just what i picked up from helping here. Most important thing is OP has his solution. But i dont think that there will be a lot or anyone that can solve a problem in the future cause of this answer.
0

You are using el to createElement every time which is global variable in this case. in the next calls, el won't be a 'div' any more. can be solved by declaring local variables with different name than the parameter.

function create(tagName, w, h, bg, repeat){
    for(let i=0; i<repeat; i++){
      const text = document.createTextNode('Node number ' + i);
      const el = document.createElement(tagName);
      el.style.width = w;
      el.style.height = h;
      el.style.background = bg;
      el.style.color = 'white';
      el.appendChild(text);

      document.body.appendChild(el);
    }
  }

  create("div","100px", "100px", "black", 5);

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.