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

Changing Paragraph Text to Stylized Span

I’m trying to change paragraph text in a for each loop. This seems like a simple issue (specific to JS?). I’m new to this language, coming from Matlab and Java. Fiddle attached. Any help is appreciated.

https://jsfiddle.net/npkx3of4/1/

function myFunction() {
    var ps = document.getElementsByClassName('.test');
    for (var p of ps) {
        p = p.replace('a', '<span style="color:blue;">b</span>');
    }
    alert("Working?");
    return null;
}

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 :

  1. getElementsByClassName('.test') should be getElementsByClassName('test').

  2. You should be assigning the result of replacing the innerHTML of the paragraph back to the innerHTML of the paragraph.

function myFunction() {
  var ps = document.getElementsByClassName('test');
  for (var p of ps) {
    p.innerHTML = p.innerHTML.replace('a', '<span style="color:blue;">b</span>');
  }
  alert("Working?");
  return null;
}
<h1>Test</h1>
<hr>
<p class="test">a</p>
<button type="button" onclick='myFunction();'>Click Me!</button>
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