0
var wrapper = document.getElementsByClassName('.wrapper');

for(var i =0; i < 10; i++){  //create grid of buttons

    var num = document.createElement("div");
    var node = document.createTextNode(i);
    num.appendChild(node);
    wrapper.appendChild(num);
    num.className = "number";

}

It throws an error that wrapper is not defined, it only worked when I used document.body instead of wrapper, but I want to append them divs to the wrapper div any suggestions ?

2
  • Is there only one element with class wrapper? If so, replace getElementsByClassName with querySelector (Element.querySelector()) Commented Jun 10, 2017 at 10:40
  • it is the only element with that class in the whole document Commented Jun 10, 2017 at 10:43

1 Answer 1

1
var wrapper = document.getElementsByClassName('wrapper');

instead of

var wrapper = document.getElementsByClassName('.wrapper');

EDIT:

var addButtons = function() {
 var wrapper = document.getElementsByClassName("wrapper")[0];
var num, node;
  for (var i = 0; i < 10; i++) { 
    console.info("Button"+i);
    num = document.createElement("div");
    num.className = "number";
    node = document.createTextNode(i);
    num.appendChild(node);

    wrapper.appendChild(num);

  }
}

addButtons();

https://jsfiddle.net/tonysamperi/7jzdsk08/

Sign up to request clarification or add additional context in comments.

4 Comments

it throws another error TypeError: wrapper.appendChild is not a function
That's because wrapper is null. I'll add a fiddle to the answer. Wait a sec.
document.getElementsByClassName() will always return a HTMLCollection (<- hint) hence wrapper won't ever be null...
Yes you're right, you missed a "[0]" after the "wrapper" selector

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.