Setting button text via javascript

dinnouti picture dinnouti · Apr 30, 2013 · Viewed 116.8k times · Source

I am setting up a button via javascript, but the button shows not the text.

Any recommendation on how to fix it?

var b = document.createElement('button');
b.setAttribute('content', 'test content');
b.setAttribute('class', 'btn');
b.value = 'test value';

var wrapper = document.getElementById(divWrapper);
wrapper.appendChild(b);

Thanks!

Answer

Stevie picture Stevie · Apr 30, 2013

Use textContent instead of value to set the button text.

Typically the value attribute is used to associate a value with the button when it's submitted as form data.

Note that while it's possible to set the button text with innerHTML, using textContext should be preferred because it's more performant and it can prevent cross-site scripting attacks as its value is not parsed as HTML.

JS:

var b = document.createElement('button');
b.setAttribute('content', 'test content');
b.setAttribute('class', 'btn');  
b.textContent = 'test value';

var wrapper = document.getElementById("divWrapper");
wrapper.appendChild(b);

Produces this in the DOM:

<div id="divWrapper">
    <button content="test content" class="btn">test value</button>
</div>

Demo: https://jsfiddle.net/13ucp6ob/