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

120
Vistas
js: how to simplify html string

is there any way to simplify the HTML string? Like removing all redundant tags from the string.

For instance:

Source HTML:

<div><span><span>1</span></span><span>2</span></div>

Expected output:

<div><span>12</span></div>

(or even less)

<div>12</div>

I've known some libs like quilljs can do this, but it's a huge library, kind of overkill for my case.

also, https://github.com/htacg/tidy-html5 is kind of what I want, but it does not have a js release

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can try using the DOMParser:

let s = `<div><span><span>1</span></span><span>2</span></div>`
let d = new DOMParser()
let doc = d.parseFromString(s, 'application/xml')
let tag = doc.children[0].tagName
let text = doc.children[0].textContent

let result = `<${tag}>${text}</${tag}>`
console.log(result)

about 4 years ago · Juan Pablo Isaza Denunciar

0

Please refer to the below code, It may help you to go further.

var childs = document.querySelectorAll("div#parent")
var tmpTexts = []
for (const c of childs) {
    if (tmpTexts.includes(c.innerText)) continue
    tmpTexts.push((c.innerText).trim())
    c.parentNode.removeChild(c)
}
tmpTextArr = tmpTexts[0].split('\n');
console.log(tmpTextArr);
const para = document.createElement("div");
tmpTextArr.forEach(function(text) {
    var node = document.createElement("div");
  var nodeTxt = document.createTextNode(text);
    node.appendChild(nodeTxt);
    para.appendChild(node)
});
  document.body.appendChild(para);

   

https://jsfiddle.net/Frangly/pnLgr8ym/66/

In tmpTexts, for every new line - you should add a div tag.

Create a new Element and iterate the tmpTexts array and a div tag by using innerHTML

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