Home > Software design >  JavaScript - Split HTML Element into Parts
JavaScript - Split HTML Element into Parts

Time:10-17

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>&lt;span class=&quot;wrapper&quot;&gt;Hello &lt;/span&gt;&lt;span class=&quot;splitter&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;wrapper&quot;&gt;orld!&lt;/span&gt;</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>&lt;span class=&quot;wrapper&quot;&gt;Hello &lt;/span&gt;&lt;span class=&quot;splitter&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;wrapper&quot;&gt;orld!&lt;/span&gt;</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>

  • Related