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

432
Vistas
Remove nested, duplicate formatting in HTML (e.g. <b>This is<strong>unnecessary</strong></b>

I am parsing articles that can occasionally have duplicated formatting tags, resulting in bloated HTML, and preventing proper conversion into e.g. Markdown.

Example:

<p>
  This is an article
  <strong>with <a href="#"><b>nested</b></a> <strong>emphasized words</strong></strong>
</p>

The result should, thus, be:

<p>
  This is an article
  <strong>with <a href="#">nested</a> emphasized words</strong>
</p>

(for sake of my cleanup, I treat bold and strong equally, even if they are semantically different)

My intuition was to set up an array with the duplicates

const duplicates = [
    ["strong", "b"],
    ["em", "i"],
  ];

And then finding all elements that are in the list using

let searchTags: string[] = [];
searchTags.concat(...duplicates);

// Search for all formatting tags
const result: NodeList = doc.querySelectorAll(searchTags);

// ... in each result, check for formatting type, and check for children of the same formatting type

However, this looks like a wildly inefficient way to traverse the DOM, and I'd have to run the querySelectorAll to update the NodeList after every iteration to ensure already removed nodes are not being traversed.

It seems there should be an easier way to identify descendants (even if they are deeply nested and not direct child nodes) of the same tag, and remove the tag, but I cannot fathom it.

Thanks :-)

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

0

const duplicates = [
    ["strong", "strong"],
    ["strong", "b"],
    ["em", "i"],
  ]; 
  for(let i =0; i<duplicates.length; i++){
    let sel = [duplicates[i].join` `,duplicates[i].reverse().join` `].join`,`;
     document.querySelectorAll(sel)
       .forEach(tag=>tag.replaceWith(document.createTextNode(tag.innerText)));
  }
  
  console.log(document.querySelector('p').outerHTML);
<p>
  This is an article
  <strong>with <a href="#"><b>nested</b></a> <strong>emphasized words</strong></strong>
</p>

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