I have a page structured like this:
<body>
<div class="one">
<div class="two">
<p class="three">Some text</p>
</div>
</div>
<div class="four">
<div class="five">
<p class="six">Some other text</p>
</div>
</div>
</body>
Given a selector, such as .five, I want to remove all elements from the DOM while preserving the hierarchy of .four > .five > .six. In other words, after deleting all the elements, I should be left with:
<body>
<div class="four">
<div class="five">
<p class="six">Some other text</p>
</div>
</div>
</body>
I came up with the following solution to this problem:
function removeElementsExcept(selector) {
let currentElement = document.querySelector(selector)
while (currentElement !== document.body) {
const parent = currentElement.parentNode
for (const element of parent.children) {
if (currentElement !== element) {
parent.removeChild(element)
}
}
currentElement = parent
}
}
This works well enough for the above case, for which I've created a JSfiddle.
However, when I try run it on a more complex web page such as on https://developer.mozilla.org/en-US/docs/Web/API/Node/removeChild with a call such as removeElementsExcept('#sect1'), I'd expect only the blue div containing the text "Note: As long as a reference ..." and its inner contents to be kept on the page. However, if you try to run this, lots of other elements are kept on the page along with the blue div as well.
What am I doing incorrectly in my function?