Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
38
rated 0 times [  44] [ 6]  / answers: 1 / hits: 158837  / 11 Years ago, tue, april 30, 2013, 12:00:00

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

More From » html

 Answers
53

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/


[#78503] Monday, April 29, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
joep

Total Points: 32
Total Questions: 97
Total Answers: 104

Location: Wales
Member since Thu, Jul 1, 2021
3 Years ago
;