Dynamically change the button name

Viewed 1081

I have a button, it consists of a name and an icon. I want to dynamically change the name of the button, but do not touch the icon. How can I do it? innerHTML innerText change completely, they don’t fit

<button>
   NameButton
    <svg>
    </svg>
</button>
6 Answers

Wrap the name in span or div element then try to change the name ..

HTML

<button id="buttonid">
   <span>NameButton<span>
    <svg>
    </svg>
</button>

Javascript

function changeName(btnid, value){
    var btn = document.querySelctor("#"+btnid+" span");
    btn.innerHTML = value;
}

You can wrap text into span tag and use childNode to change

document.querySelector("button").childNodes[1].textContent="Something"
<button>
   <span>NameButton</span>
    <svg>
    
    </svg>
</button>

or Without Wrapping into span

document.querySelector("button").childNodes[0].textContent="Something2"
<button>
   NameButton
    <svg>
    
    </svg>
</button>

The best way would be to just leave:

<button>NameButton</button>

which is the most semantic way, and add the svg icon in CSS

button:after {
    background-image: url('my-file.svg');
}

The best solution would be to simply wrap the text in a span, as mentioned in other answers. However, if for whatever reason, you insist on not doing that, then you need to dig into the button's childNodes, and change the textContent of the first one (which is the text node).

document.querySelector('button').childNodes[0].textContent = "Hellow";
<button>
   NameButton
    <svg>
    </svg>
</button>

First extract the svg, then change the text, then add the svg back in.

let btn = document.getElementById('b');
let svg = btn.children[0]
btn.textContent = "changed";
btn.appendChild(svg);
<button id="b">
   NameButton
    <svg>
    <circle cx="50" cy="50" r="50"/>
    </svg>
</button>

Here's how you do it correctly using TextNode.prototype.wholeText:

const button = document.querySelector('button');
const buttonTextNode = button.childNodes[0];
button.removeChild(button.childNodes[0]);
button.insertBefore(new Text(buttonTextNode.wholeText.replace(buttonTextNode.wholeText, 'NewNameForTheButton')), button.firstElementChild);
<button>
   NameButton
  <br /><span>untouched</span>
</button>

This will not affect the other child elements of the button at all.

Related