Pete
Pete

Reputation: 170

Making a function that creates a button HTML/JS

I am trying to make a function which takes a characters and makes a button with the character inside it. Here's what I have so far:

function keyButton(char) {
  var btn = document.createElement("button"); //create button
  btn.innerText = char; //fill it with char
  return btn;
    }

  var button = keyButton("a"); //use keyButton to fill buttons with characters
  document.appendChild(button);

This however doesn't seem to work, any help would be appreciated.

Upvotes: 0

Views: 102

Answers (4)

Nina Scholz
Nina Scholz

Reputation: 386522

I think you could use document.createTextNode for making a text node and append the button to document.body.

function keyButton(char) {
    var btn = document.createElement("button");
    btn.appendChild(document.createTextNode(char));
    return btn;
}

var button = keyButton("a");
document.body.appendChild(button);

Upvotes: 1

Hamza Abbad
Hamza Abbad

Reputation: 666

You can not insert a button to the document, if you do that, you will get HierarchyRequestError: Node cannot be inserted at the specified point in the hierarchy (At least in Firefox), so you have to add it to a visible element in your page, such as document.body.

Upvotes: 0

Rajesh Patel
Rajesh Patel

Reputation: 2036

Use body to append child in dom

document.body.appendChild(); 

if you do console.log(btn); it returns button with char which you have passed in function that means your code is correct.Your only mistake is you have forgottend body with document
Here is working code

function keyButton(char) {
  var btn = document.createElement("button"); //create button
  btn.innerText = char; //fill it with char
  return btn;
    }

  var button = keyButton("a"); //use keyButton to fill buttons with characters
console.log(button);
 document.body.appendChild(button);

Upvotes: 0

user5393970
user5393970

Reputation:

It's exactly as @Pointy said, you can't append the button to the document. If you try this out in the console, you should get this error: screenshot

If you change document.appendChild(button); to document.body.appendChild(button); it will work:enter image description here

Upvotes: 0

Related Questions