2
 // Run loop through choices array
  for(let i = 0; i < choices.length; i++) {
    // Populate buttons to screen
    let choiceBtn = document.createElement("BUTTON");
    choiceBtn.classList.add("btn", "throws");
    choiceBtn.setAttribute("data-choice", choices[i]);
    infoScreen.appendChild(choiceBtn);

I thought i could add text from the choiceBtn variable by using

choiceBtn.innerHTML(choices[i]);

but it doesn't seem to work along with .innerText or appendChild, but I may just be doing something incorrectly. Just thought I'd ask you all.

slevy1
  • 3,797
  • 2
  • 27
  • 33
  • 1
    [`var button = document.createElement("button"); button.appendChild(document.createTextNode("text")); document.body.appendChild(button);`](https://www.w3schools.com/jsref/met_document_createelement.asp) – user7393973 Mar 09 '18 at 22:58
  • innerHTML is a property not a function, otherwise innerHTML would work just fine. `.innerHTML = "some HTML"` – Lee Kowalkowski Mar 10 '18 at 00:39

1 Answers1

0

While you may use a button's .textContent or .innerText property (.innerText has the advantage of recognizing newlines), it is better form to explicitly create a new element's text node per this respondent as the following code incorporates the suggestion of user7393973:

var d = document;
var choices = ["alpha", "beta", "gamma"];

for (let i = 0; i < choices.length; i++) {
  let choiceBtn = d.createElement("BUTTON");
  choiceBtn.setAttribute("data-choice", choices[i]);

  /* recommended way: */
  choiceBtn.appendChild(d.createTextNode("Your\nChoice\nButton " + i));
  
  /* another way:
   choiceBtn.textContent = "Your\nChoice\nButton "+i;
  */
  /* and one more way:
   choiceBtn.innerText = "Your\nChoice\nButton "+i;
  */

  d.body.appendChild( choiceBtn );
}
button {
  width: 150px;
  height: 150px;
  color: #f00;
}

Note; this resource argues that either creating a text node explicitly or using the .textContent property are equally legitimate in terms of setting an empty element's text node value. Also, .innerText was originally a MS extension to the DOM which in IE can set as well as get a text value for a text node. Google Chrome supports this feature the same way. So, in sum the OP may set the text node using one of the three indicated ways.

Final point, there is:

... a security risk whenever you use innerHTML to set strings over which you have no control.

That security risk is the threat of a XSS attack; read more here.

slevy1
  • 3,797
  • 2
  • 27
  • 33