62

I am setting up a button via JavaScript, but the button doesn't show the text.

Any recommendations 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);
Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
dinnouti
  • 1,707
  • 2
  • 15
  • 21

4 Answers4

102

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/

Stevie
  • 2,000
  • 1
  • 18
  • 28
  • I saw what went wrong I try innerHtml as a method,not as property. Thanks for your help. – dinnouti Apr 30 '13 at 16:42
  • 4
    According to the [MDN website](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML), when inserting plain text, it is recommended to use [textContent](https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent), because `innerHTML` has a security risk and does an unnecessary parse of the content to HTML. – Rosberg Linhares Dec 09 '19 at 22:13
14

The value of a button element isn't the displayed text, contrary to what happens to input elements of type button.

You can do this :

 b.appendChild(document.createTextNode('test value'));

Demonstration

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
6

Create a text node and append it to the button element:

var t = document.createTextNode("test content");
b.appendChild(t);
Rick Viscomi
  • 8,180
  • 4
  • 35
  • 50
5

Set the text of the button by setting the innerHTML

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

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

http://jsfiddle.net/jUVpE/

cgatian
  • 22,047
  • 9
  • 56
  • 76