Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

81
Views
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;
}
about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

  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>

about 4 years ago · Santiago Trujillo Report

0

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>');
    }
...
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!