Question

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>
Was it helpful?

Solution

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

OTHER TIPS

Nvm, the problem was that by setting the onClick through element.onClick I was setting the property without the attribute, and the properties don't show up when inspecting the element on the webpage, so I had to set the attribute for it to show up

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top