Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace text of a class name but within a particular id

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading