JSFiddle - React, Tailwind, and code Playground

by zakariamouhid

HTML

<div id="div1">

before
↚
this content will be contained inside #hide div
↚
after

</div>

<hr>

<div id="div2">

before
↚
this content will be contained inside <i>#hide</i> div
↚
after

</div>

<hr>

<div id="div3">

before
↚
this content will be contained inside <i>#hide</i> div
after

</div>

CSS

#hide {
  color: #f00;
}

JavaScript

function getAllTextNodes(el, out = [], ignore = ['script', 'style']) {
  for (let node of el.childNodes) {
    if (node.nodeType === node.TEXT_NODE) {
      out.push(node);
    } else if (node.nodeType === node.ELEMENT_NODE)  {
    	if (!ignore.includes(node.tagName.toLowerCase())) {
      	getAllTextNodes(node, out, ignore);
      }
    }
  }
  return out;
}

function getAllParents(el) {
  let parents = [];
  while ((el = el.parentNode)) {
    parents.push(el);
  }
  return parents;
}

function replaceContent1(el, isTextNodes = false) {
	let textNodes = isTextNodes ? el : getAllTextNodes(el);
	let found = false;
	textNodes.forEach(text => {
    // '↚' === '\u219a'
    // '↚'.charCodeAt(0).toString(16) === '219a'
    let match = text.data.match(/^([\s\S]*?)\u219a([\s\S]*)\u219a([\s\S]*?)$/);
    if (!match) return;
    let [, before, content, after] = match;
    let div = document.createElement('div');
    div.append(document.createTextNode(content));
    div.id = "hide";
    text.replaceWith(
      before,
      div,
      after
    );
    found = true;
  });
  return found;
}

function replaceContent2(el, isTextNodes = false) {
	let textNodes = isTextNodes ? el : getAllTextNodes(el);
  let [textNodeStart, textNodeEnd] = textNodes.filter(text => {
    return text.data.includes('\u219a');
  });
  if (!textNodeStart || !textNodeEnd) return false;
  let parentsStart = getAllParents(textNodeStart);
  let parentsEnd = getAllParents(textNodeEnd);
  let neerCommonParent = parentsStart.find(parent => parentsEnd.includes(parent));
  let match = neerCommonParent.innerHTML.match(/^([\s\S]*?)\u219a([\s\S]*?)\u219a([\s\S]*?)$/);
  if (!match) return false;
  let [, before, content, after] = match;
  neerCommonParent.innerHTML = `${before}<div id="hide">${content}</div>${after}`;
  return true;
}

function replaceContent3(el, isTextNodes = false) {
	let textNodes = isTextNodes ? el : getAllTextNodes(el);
	let found = false;
	textNodes.forEach(text => {
    let match =...