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

192
Views
JSDOM: removing once-nested blockquotes but leave 2+-nested blockquotes

I'm trying to edit some HTML using JSDOM within Node.JS. I want any <blockquote> that is the child of at most one surrounding <div> to be removed. But I want any <blockquote> tag that is inside two or more <div>s to remain. I have read this question but I am still confused. You can see what I have tried in this JSFiddle. Here is the original HTML:

<html>
    <div id="div1">
        <blockquote>Text 1</blockquote>
    </div>
    <div id="div2"> 
        <div id="div3"> 
            <blockquote>Text 2</blockquote>
            <div id="div4">
                <blockquote>Text 3</blockquote>
            </div>
        </div>
    </div>
<span onclick="removeblockquotes(this)">Change</span>
</html>

Should turn into

<html>
    <div id="div1">
        Text 1
    </div>
    <div id="div2"> 
        <div id="div3"> 
            <blockquote>Text 2</blockquote>
            <div id="div4">
                <blockquote>Text 3</blockquote>
            </div>
        </div>
    </div>
</html>

Here is the function I have tried so far, but it isn't working (none of the blockquotes are changing):

function removeblockquotes(e)
{
var x = document.querySelectorAll("blockquote"); 
x.forEach(y=>{
    if (y.parentNode.parentNode==null){
        y.parentNode.appendChild(x.innerHTML);
        y.parentNode.removeChild(x);
    };
});
}
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Just chain two .closest calls onto each blockquote to see if there's more than one surrounding div:

for (const b of document.querySelectorAll('blockquote')) {
  if (!b.closest('div')?.parentElement.closest('div')) {
    b.replaceWith(b.textContent);
  }
}
console.log(document.body.innerHTML);
<div id="div1">
    <blockquote>Text 1</blockquote>
</div>
<div id="div2"> 
    <div id="div3"> 
        <blockquote>Text 2</blockquote>
        <div id="div4">
            <blockquote>Text 3</blockquote>
        </div>
    </div>
</div>

(you need a single .parentElement because .closest will return the element it's called on if it matches)

over 4 years ago · Santiago Trujillo 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!