Search code examples
javascripthtmlinputlabelinnertext

Javascript - how to change innerText of label while not wiping out the input


I would like to ask how - by Javascript - to change the label innerText of radio buttons (see code below) while not wiping out the input tag inside. Label innerText here means "Button-Label-X".

I've tried to diagnose the label style via elements of document.getElementsByClassName("radio-label"), including

  • textContent: "Button-Label-X"
  • innerText :"Button-Label-X"
  • outerText :"Button-Label-X"

then assigned new string value (ex. "Button-Label-Y") to them. However, all those ways lead to the same result: the input disappeared, only new value left. Anyone has any idea here?

<div class="radio">
  <label class="radio-label"><input type="radio" name="optradio"> Button-Label-X </label>
</div>

Of course, I could do the way around by putting input tag outside of label, then everything is solved. But, for that case, I must set id for input and "for:id" for label. And it becomes tedious work for the case of 05 buttons instead of 01 one.


Solution

  • If I understand you correctly, you can access to the text part from childNodes. Once you have it, you can change the text by set the property textContent to the wanted text.

    Like this:

    function changeLabelText(label, text) {
      var children = label.childNodes;
      [].forEach.call(children, function(child) {
        if (child.nodeType == 3) {
          child.textContent = text;
        }
      });
    }
    
    var label = document.querySelector('label');
    changeLabelText(label, 'blabla');
    <div class="radio">
      <label class="radio-label"><input type="radio" name="optradio"> Button-Label-X </label>
    </div>