Function for creating buttons that receive "text" and "onclick" by parameter

I want to do what I said in the title. I've tried this:

function createButton(func, text){
    var butt = document.createElement('BUTTON');
    var btTxt = document.createTextNode(text);
    btTxt.style.color = '#006633';
    btTxt.style.fontWeight = 'bold';
    butt.onclick = func;
    butt.appendChild(btTxt);
    butt.style.margin = '5px';
    document.body.appendChild(butt);
}

      

And this:

createButton(doSomething, click to do something);

      

But that doesn't work: /

Anyone?

+3


source to share


1 answer


You need to set the button styles, not the TextNode object:



function createButton(func, text) {
    var butt = document.createElement('BUTTON');
    var btTxt = document.createTextNode(text);
    butt.style.color = '#006633';
    butt.style.fontWeight = 'bold';
    butt.onclick = func;
    butt.appendChild(btTxt);
    butt.style.margin = '5px';
    document.body.appendChild(butt);
}

createButton(doSomething, 'click to do something');

function doSomething() { alert('Hello'); }
      

Run codeHide result


+3


source







All Articles