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

352
Views
¿Hay alguna alternativa a innerHTML con el método .replace()?

Conozco las desventajas de usar innerHTML . Pero en mi situación, innerHTML parece inevitable. O es innecesariamente complejo o no es posible (que no lo creo...)

Aquí está mi código:

 function identifier(reg, className) { const regex = new RegExp(reg, "gi"); const p2 = document.querySelectorAll("p"); p2.forEach((ps) => { ps.innerHTML = ps.innerHTML.replace( regex, (match) => `<span class="${className}">${match}</span>` ); }); } identifier("[^<>]+?:", "identifier");

¿Hay alguna forma alternativa más segura de hacer esto sin usar innerHTML ?

¡Gracias por adelantado!

Editar: el elemento p al principio no contiene ninguna otra etiqueta. Solo contiene texto. Pero quiero agregarle spans con la función anterior.lo que estoy tratando de hacer.

En esto, estoy usando RegExp con el método replace() para hacer que todos los identificadores (por ejemplo: Nombre, Correo electrónico) sean un span para diseñar por separado. Los valores como John Doe no tienen estilo.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Con su información adicional es relativamente fácil:

 p2.forEach((ps) => { // Get text of paragraph removing any HTML const text = ps.textContent; // Look for colon const colon = text.indexOf(':'); // Skip if there is no colon if (colon === -1) { return; } // Delete content of paragraph while (ps.lastChild) { ps.removeChild(ps.lastChild); } // Extract texts before (and including) colon and after colon const labelText = text.substring(0, colon + 1); const otherText = text.substring(colon + 1); // Create span with text before colon const label = document.createElement('span'); label.className = className; label.appendChild(document.createTextNode(labelText)); // Create new text node with text after colon const otherTextNode = document.createTextNode(otherText); // Add both as new children of the paragraph ps.appendChild(label); ps.appendChild(otherTextNode); });

Por supuesto, es más largo que usar innerHTML , porque básicamente estamos reescribiendo lo que está haciendo la expresión regular y el analizador HTML para el navegador.

about 4 years ago · Juan Pablo Isaza 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!