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.
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.
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.