Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

76
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda