Setting button text via JavaScript

JavascriptHtmlWindows Store-Apps

Javascript Problem Overview


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);

Javascript Solutions


Solution 1 - Javascript

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/

Solution 2 - Javascript

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

Solution 3 - Javascript

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

var t = document.createTextNode("test content");
b.appendChild(t);

Solution 4 - Javascript

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/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondinnoutiView Question on Stackoverflow
Solution 1 - JavascriptStevieView Answer on Stackoverflow
Solution 2 - JavascriptDenys SéguretView Answer on Stackoverflow
Solution 3 - JavascriptRick ViscomiView Answer on Stackoverflow
Solution 4 - JavascriptcgatianView Answer on Stackoverflow