JSDOM:删除 once-nested 块引号但保留 2+ 嵌套块引号

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

我正在尝试在 Node.JS 中使用 JSDOM 编辑一些 HTML。我想要删除任何 <blockquote>,即 至多 的 child 周围的 <div>。但我希望保留两个或更多 <div> 内的任何 <blockquote> 标记。我已阅读this question but I am still confused. You can see what I have tried in this JSFiddle。这里是原文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>

应该变成

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

这是我到目前为止尝试过的功能,但它不起作用(none 块引用正在更改):

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);
    };
});
}

只需将两个 .closest 调用链接到每个 blockquote 上,看看周围是否有多个 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>

(您需要一个 .parentElement,因为 .closest 将 return 调用它的元素 如果匹配)