<script> const rootElement = el => { if (typeof el === 'string') { returndocument.querySelector(el) } return el }
const AST = root => { const children = (el, lv = 0) => { let color = el.dataset.color || null let text = null let child = el.children if (child.length === 0) text = el.textContent return { color, text, lv: lv, children: Array.prototype.map.call(child, v => children(v, lv + 1)) } } return children(root).children }
const render = list => { const htmlArr = children => { return children.map(child => { let color = child.color let text = child.text let ch = child.children let lv = child.lv if (ch.length > 0) { return`<div class="lv${lv}">${htmlArr(ch)}</div>` } else { return`<div class="lv${lv}" style="color:${color}">${text}</div>` } }).join('') } return htmlArr(list) }
classTest{ constructor (el) { let $el = rootElement(el) let list = AST($el) console.log(list) let html = render(list) console.log(html) $el.innerHTML = html } } </script>
<script> new Test('#nav') </script> </body> </html>