I have the following html:
<h2 id="program-selector-modal_heading">
<span class="modal-heading-before-text"></span>
<span>Start your application to </span>
<span class="modal-heading-after-text"></span>
</h2>
and I’m trying to update the text shown in the class modal-heading-text-after for this particular id heading:
const programSelectorModalHeadingOuter = document.getElementById("program-selector-modal_heading");
programSelectorModalHeadingOuter.getElementsByClassName("modal-heading-after-text").innerHTML = "test";
But it’s not working. Any ideas? My environment setup is strange and I can’t see errors.
>Solution :
Your issue here is that getElementsByClassName returns an array of matches.
So when you try and set the text attribute you’re actually setting it against the matching set of HTML elements – not a HTML element within that array.
There may only be 1 element in that set, but it will always return an array, not a single element.
If you change the second line to address the [0] index element within that array it should work.
The final code for your JS would look like this:
const programSelectorModalHeadingOuter = document.getElementById("program-selector-modal_heading");
programSelectorModalHeadingOuter.getElementsByClassName("modal-heading-after-text")[0].innerHTML = "test";
That should then work.