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

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

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 Report

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