2

I have checked for syntax errors and it does seems like everything is okay, it just does not do anything when loading the body of the page. I know I have linked the script correctly to the html file, because I've already implemented a JS Clock which displays itself in the page as you can see in the pen. Is there anything wrong with my code? Why aren't my 10 buttons displaying? I fear Bootstrap may be preventing me from getting my buttons show up.

My purpose is to create 10 buttons, so that I don't have to write the same code 10 times.

The Codepen is just to check out my code, I work on Atom usually. This is my Codepen!

<div class="container-fluid" id="buttons">

</div>

function createButtons() { 
  for(i = 0; i < 11; i++) {
    var button = document.createElement("<button type=\"button\" class=\"btn btn-outline-success\">Chapter[i]</button>");
    var buttonDiv = document.getElementById("buttons");
    buttonDiv.appendChild(button);
  }
}
document.body.addEventListener("load", createButtons(), false);
3
  • 6
    That's not how you use createElement, view documentation on how to use it correctly. You should have seen errors on the console due to it Commented Apr 25, 2018 at 15:23
  • Please (re)read the documentation on createElement() Commented Apr 25, 2018 at 15:25
  • var buttonDiv = document.getElementById("buttons"); for(var i = 1; i <= 10; i++) { buttonDiv.innerHTML += '<button type="button" class="btn btn-outline-success">Chapter['+i+']</button>'; } Commented Apr 25, 2018 at 15:25

2 Answers 2

5

The function createElement accept a tag name as argument.

var Chapter = [0,1,2,3,4,5,6,7,8,9,10];
for(i = 0; i < 11; i++) {
    var button = document.createElement("button");
    button.innerHTML = Chapter[i];
    button.className = "btn btn-outline-success";
    var buttonDiv = document.getElementById("buttons");
    buttonDiv.appendChild(button);
  }
Sign up to request clarification or add additional context in comments.

Comments

0

Improve your code and add dynamic functions

let buttonDiv = document.getElementById("buttons");

const createButtons = () => {
  for (let i = 1; i <= 20; i++) {
    let button = document.createElement("button");
    button.id = `${i}`;
    button.textContent = `Button #${i}`
    button.click(buttonEvent(i));
    buttonDiv.appendChild(button);
  }
}

const buttonEvent = i => {
  document.body.addEventListener( 'click',  (event)  => {
    if(event.target.id === i.toString()) alert(event.target.id);
    event.preventDefault();

  });
}



document.body.addEventListener("load", createButtons(), false);

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.