JSFiddle - React, Tailwind, and code Playground
by moshfeu
HTML
<div class="app">
<div class="main">
<p>Some text</p>
<iframe></iframe>
<p>Other text1</p>
<p>Other text2</p>
text without parent
<iframe></iframe>
<p>Other text3</p>
<iframe></iframe>
</div>
<div class="main">
<p>Some text4</p>
<iframe></iframe>
<p>Other text5</p>
<p>Other text6</p>
</div>
</div>
JavaScript
const app = document.querySelector('.app');
document.querySelectorAll('.main').forEach(manipulate)
function manipulate(main) {
const wrapper = wrap(main);
let lastMain;
let isLastNodeIframe = false;
Array.from(main.childNodes).forEach(child => {
if (isIframe(child)) {
isLastNodeIframe = true;
main.parentNode.appendChild(child);
} else if (isEmptyText(child)) {
return;
} else {
if (isLastNodeIframe) {
isLastNodeIframe = false;
lastMain = main.cloneNode(false);
main.parentNode.appendChild(lastMain);
}
if (lastMain) {
lastMain.appendChild(child);
}
}
});
unwrap(wrapper);
}
function wrap(el) {
const wrapper = document.createElement('div');
el.parentNode.insertBefore(wrapper, el);
wrapper.appendChild(el);
return wrapper;
}
function unwrap(element) {
element.outerHTML = element.innerHTML;
}
function isIframe(element) {
return element.tagName === 'IFRAME';
}
function isEmptyText(element) {
return !element.tagName && !element.textContent.trim();
}
console.log(app.innerHTML)