So I am trying to add an onClick attribute to a button created with Javascript. Obviously I am using Javascript to add it, however it won't go through because when I inspect the element on the web page it doesn't show an onClick attribute there. This is the code I have to create the button
var buttonExponent = document.createElement('button');
buttonExponent.innerHTML = '^';
buttonExponent.onclick = function(){appendExpr(this.className);}; <---This is my problem
buttonExponent.className = 'button operator ' + expression.id + ' top';
buttonExponent.style.marginTop = '0px';
buttonExponent.style.marginLeft = '-6px';
container.appendChild(buttonExponent);
The rest of the functions work fine and everything, however the onClick attribute simply won't get added on. I have tried doing it multiple ways, but none of them work
EDIT: Figured I should add what the output is on the webpage, the element has this HTML
<button class="button operator expr1 top" style="margin-top: 0px; margin-left: -6px;">^</button>
When it should be looking like this
<button onClick="appendExpr(this.className);" class="button operator expr1 top" style="margin-top: 0px; margin-left: -6px;">^</button>
Modifying the element.onclick DOM property doesn't modify the element's onclick attribute. They are two separate pieces of data, confusingly.
To set the attribute, use element.setAttribute('onclick','code here').
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With