Cant Add Attributes To Buttons
Solution 1:
I believe that your confusion is due to the fact that your dynamically adding elements (in this case, buttons) and then wanting to access said elements (buttons).
The easiest way to name these new elements is to first assign the statement that creates them,
document.createElement("BUTTON");
to a variable, which you actually did do!
btn = document.createElement("BUTTON");
So, keep in mind that you can do stuff with that variable you created, like giving it a class or ID name to access.
btn.setAttribute('class', 'btn-class');
Now you can assign any styling elements from your CSS with class name btn-class
or whatever else you may desire to choose.
Here's a JSFiddle that shows that: https://jsfiddle.net/dg1amubr/4/
Solution 2:
add an onclick function to the button
e.g
function myFunction() {
// onclick stuff
}
element.onclick = myFunction; // Assigned
[UPDATE]
to make it easier I've created a fiddle
Solution 3:
Use addEventListener
to attach an event with new button. Hope this snippet will be useful
function test(){
var btn = document.createElement("BUTTON");
var name = document.createTextNode("Button");
btn.id = "newButton"
btn.appendChild(name);
document.body.appendChild(btn);
var _getNewButton = document.getElementById('newButton');
_getNewButton.addEventListener('click',function(){
alert('New Button');
})
}
// You can also directly attach addEventListener without going via id.
// btn.addEventListener('click',function(){ ..})
Solution 4:
You need to assign an event handler to that button.
btn.addEventListener('click', function(event) {
console.log('I was clicked');
});
function test() {
var btn = document.createElement("BUTTON")
var name = document.createTextNode("Button")
btn.appendChild(name);
btn.addEventListener('click', function(event) {
alert('I was clicked');
});
document.body.appendChild(btn);
}
<button onclick="test()">
Click Me!
</button>
Solution 5:
May be you need to use something like
btn.addEventListener('click',callback_function)
?
Post a Comment for "Cant Add Attributes To Buttons"