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

427
Views
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 answers
Answer question

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