Home > Software engineering >  Changing Paragraph Text to Stylized Span
Changing Paragraph Text to Stylized Span

Time:12-27

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;
}

CodePudding user response:

  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 >a</p>
<button type="button" onclick='myFunction();'>Click Me!</button>

CodePudding user response:

There isn't any need to add a period before the class name when using getElementsByClassName.

var ps = document.getElementsByClassName('test');

Select only the plain text content inside the element, then replace all the specified characters before rewriting the inner HTML.

...  
    for (var p of ps) {
        p.innerHTML = p.textContent.replaceAll('a', '<span style="color:blue;">b</span>');
    }
...
  • Related