skip to Main Content

I am using JS on a react project to ‘setAttribute’ of a button to set the text of a button but I can’t seem to get the text to appear on the button…

I have tried both ‘value’ and ‘innerHTML’

 var removeBranchBtn = document.createElement('button');
    removeBranchBtn.setAttribute('type','button');
    removeBranchBtn.setAttribute('value','Remove');
    removeBranchBtn.setAttribute('innerHTML','Remove');

but the button only looks like a small grey rectangle

enter image description here

In developer tools I can see they have been added

enter image description here

What am I missing or doing wrong? Thanks

2

Answers


  1. innerHTML is a property, not an attribute. In general, you should prefer using properties over attributes when both exist, too: they’re easier to read and can represent richer types.

    Also, the better property to use here is textContent, since you’re just setting text whose HTML representation is incidentally the same.

    var removeBranchBtn = document.createElement('button');
    removeBranchBtn.type = 'button';
    removeBranchBtn.textContent = 'Remove';
    
    Login or Signup to reply.
  2. If it’s a React project, use JSX: <button>Remove</button> or <input type="button" value="Remove">

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search