-2

What is the proper way to add a text to a button?

Here are 3 different ways and all of them works. But I suspect there should be only a single the most correct one. Which one of them?

const button1 = document.createElement('button');
const textForButton1 = 'btn1';
button1.append(textForButton1);
document.querySelector('div').append(button1);

const button2 = document.createElement('button');
const textForButton2 = document.createTextNode('btn2');
button2.append(textForButton2);
document.querySelector('div').append(button2);

const button3 = document.createElement('button');
button3.innerText = 'btn3';
document.querySelector('div').append(button3);
<div></div>
user90726
  • 939
  • 1
  • 8
  • 28

1 Answers1

1

See comments inline:

const button1 = document.createElement('button');
// Not really necessary to set up a variable here
// you could just pass the string as the value for 
// .appendChild()
const textForButton1 = 'btn1';
// This may "work", but by passing a string, you are 
// implicitly creating a text node and passing that 
// to the append method, which isn't intuitive.
button1.append(textForButton1);
document.querySelector('div').append(button1);

// This is the most "correct" IF your intention is
// to use the DOM API to do 100% of the job.
const button2 = document.createElement('button');
const textForButton2 = document.createTextNode('btn2');
button2.append(textForButton2);
document.querySelector('div').append(button2);


const button3 = document.createElement('button');
// .innerText works everywhere for legacy reasons
// and is part of the WHATWG HTML Living Standard,
// but it's not part of the W3C HTML standard, which
// is considered the most authoritative standard
button3.innerText = 'btn3';
document.querySelector('div').append(button3);

// This is probably the most common approach:
const btn4 = document.createElement("button");
btn4.textContent = "btn4"; // .textContent is W3C standard
document.querySelector("div").appendChild(btn4);
<div></div>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71