Search code examples
javascripthtmlinnerhtml

Change the value of an label using innerText Javascript


I am trying to change the text value of an label inside an li inside an ul.

So:

HTML and JS

document.getElementsByClassName("hs-error-msgs inputs-list").innerText = "Bitte füllen Sie dieses Pflichtfeld aus!";
<ul class="hs-error-msgs inputs-list" style="display:block;" role="alert" data-reactid=".hbspt-forms-0.0:$0.3">
  <li data-reactid=".hbspt-forms-0.0:$0.3.$0"> <label data-reactid=".hbspt-forms-0.0:$0.3.$0.0">Please complete this required field. </label> </li>
</ul>


Solution

  • getElementsByClassName returns a collection. You could take the first element of this collection and then select label within it with for example another collection method getElementsByTagName.

    var ul = document.getElementsByClassName("hs-error-msgs inputs-list")[0]
    var label = ul.getElementsByTagName('label')[0]
    
    label.innerText = "Bitte füllen Sie dieses Pflichtfeld aus!";
    <ul class="hs-error-msgs inputs-list" style="display:block;" role="alert" data-reactid=".hbspt-forms-0.0:$0.3">
      <li data-reactid=".hbspt-forms-0.0:$0.3.$0"> <label data-reactid=".hbspt-forms-0.0:$0.3.$0.0">Please complete this required field. </label> </li>
    </ul>

    However way more convenient method for this is querySelector:

    var label = document.querySelector(".hs-error-msgs.inputs-list label")
    
    label.innerText = "Bitte füllen Sie dieses Pflichtfeld aus!";
    <ul class="hs-error-msgs inputs-list" style="display:block;" role="alert" data-reactid=".hbspt-forms-0.0:$0.3">
      <li data-reactid=".hbspt-forms-0.0:$0.3.$0"> <label data-reactid=".hbspt-forms-0.0:$0.3.$0.0">Please complete this required field. </label> </li>
    </ul>