Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding onClick function with Javascript doesn't go through

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>
like image 663
David Grabon Avatar asked Oct 27 '25 13:10

David Grabon


1 Answers

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').

like image 183
Scimonster Avatar answered Oct 30 '25 05:10

Scimonster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!