Reputation: 170
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
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
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
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
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:
If you change document.appendChild(button);
to document.body.appendChild(button);
it will work:
Upvotes: 0