I would like to "split" an HTML element into three parts using outerHTML. Unfortunately closing tags with outerHTML doesn't work as expected (see example below). If anyone knows how I can achieve the desired effect it would be very much appreciated.
var content = document.querySelector('.content');
var splitter = document.querySelector('.splitter');
var result = document.querySelector('.result');
splitter.outerHTML = '</span>' splitter.outerHTML '<span >';
result.innerText = content.innerHTML;
<div >
<span >Hello <span >w</span>orld!</span>
</div>
<hr>
Result: <div ></div>
<hr>
Expected: <div><span class="wrapper">Hello </span><span class="splitter">w</span><span class="wrapper">orld!</span></div>
CodePudding user response:
var content = document.querySelector('.content');
var splitter = document.querySelector('.splitter');
var result = document.querySelector('.result');
var chuncks = content.innerHTML.split(`${splitter.outerHTML}`);
content.innerHTML = chuncks[0] '</span>' splitter.outerHTML '<span >' chuncks[1];
result.innerText = content.innerHTML;
<div >
<span >Hello <span >w</span>orld!</span>
</div>
<hr>
Result: <div ></div>
<hr>
Expected: <div><span class="wrapper">Hello </span><span class="splitter">w</span><span class="wrapper">orld!</span></div>
CodePudding user response:
Here is a solution that creates elements with DOM methods, instead of playing with innerHTML
:
const content = document.querySelector('.content');
const wrapper = document.querySelector('.wrapper');
for (const node of [...wrapper.childNodes]) {
if (node.classList?.contains("splitter")) {
content.appendChild(node);
} else if (node.textContent.trim()) {
const span = wrapper.cloneNode();
span.appendChild(node);
content.appendChild(span);
}
}
wrapper.remove();
// Verification
console.log(content.innerHTML);
<div >
<span >Hello <span >w</span>orld!</span>
</div>