JSFiddle - React, Tailwind, and code Playground
by sperske
HTML
<div contenteditable id="editor">
<h1>
The List of Interesting words
</h1>
<ul>
<li>A Words
<ul>
<li>Apple</li>
<li>Aligator</li>
</ul>
</li>
<li>B Words
<ul>
<li>Brownie</li>
<li>Bear</li>
</ul>
</li>
</ul>
<p>
This is not an exhaustive list but it should help you get started.
</p>
</div>
<button data-analyzer="pug">PUG</button>
<button data-analyzer="blocks">Start/End Blocks</button>
<button data-analyzer="nested">Nested</button>
CSS
#editor {
border: 1px solid #aaa;
border-radius: 8px;
padding: 8px;
}
JavaScript
const editor = document.getElementById('editor')
const analyzers = {
pug(el, depth = {
down: 0,
in: 0
}) {
const res = []
if (el.nodeType === Node.TEXT_NODE) {
const data = el.data.trim()
if (data.length > 0) {
res.push({
depth,
data
})
}
} else {
for (const child of el.childNodes) {
res.push(...analyzers.pug(child, {
...depth,
in: depth.in + 1
}))
}
}
return res
}
}
document.querySelectorAll('[data-analyzer]').forEach((el) => {
el.addEventListener('click', () => {
console.log(analyzers[el.dataset.analyzer](editor))
}, false)
})