Setting button text via javascript [duplicate]

2019-02-08 00:01发布

This question already has an answer here:

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!

4条回答
一夜七次
2楼-- · 2019-02-08 00:20

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

查看更多
神经病院院长
3楼-- · 2019-02-08 00:22

Basically, use innerHTML instead of value, because the 'button' type you are appending sets it's value in its innerHTML.

JS:

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

Looks like this in the DOM:

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

Demo: http://jsfiddle.net/CuXHm/

查看更多
老娘就宠你
4楼-- · 2019-02-08 00:25

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/

查看更多
时光不老,我们不散
5楼-- · 2019-02-08 00:38

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

var t = document.createTextNode("test content");
b.appendChild(t);
查看更多
登录 后发表回答