JSFiddle - React, Tailwind, and code Playground
by zakariamouhid
HTML
<div>
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 replaceContent(el) {
let textNodes = getAllTextNodes(el);
return replaceContent1(textNodes, true) || replaceContent2(textNodes, true);
}
replaceContent(document.body);