How often does this operation need to happen? Is it a performance hazard or is it a rare occasion?
If it's not a bottleneck, you can just select all descendants of your div and append them to the div. When you append an existing node, it will be automatically moved to the appropriate position.
const myDiv = document
.querySelector('#my-div')
const allDescendants = Array.from(myDiv.getElementsByTagName('*'))
allDescendants.forEach(d => {
myDiv.appendChild(d);
});
console.log(myDiv.innerHTML);
<div id="my-div">
<p>
some text on here 1
<i>
some italic
<b>text</b>
here
</i> text text text
</p>
<b>
some bold text on here
</b>
</div>
Not sure if this is intentional but based on your example, you only want to move elements and leave other nodes such as text nodes where they were. A specific example is the here text portion in the first <i>.
To achieve this, you can perform a pre-order DFS through all descendants, and build the new flat tree. Once finished, replace the old element with the new one.
const myDiv = document
.querySelector('#my-div')
const flatDiv = document.createElement('div')
function recurseAndFlatten(parent) {
parent.childNodes.forEach(child => {
if (child.nodeType === Node.ELEMENT_NODE) {
flatDiv.appendChild(child);
recurseAndFlatten(child);
}
});
}
recurseAndFlatten(myDiv);
myDiv.replaceWith(flatDiv);
console.log(flatDiv.innerHTML);
<div id="my-div">
<p>
some text on here 1
<i>
some italic
<b>text</b>
here
</i> text text text
</p>
<b>
some bold text on here
</b>
</div>