1

Could someone show me the most efficient way to convert an html ul/ol list string to a tree liked structure with plain javascript or 3rd libraries?

The html string and data structure may look like below, the property name in data is just for example:

enter image description here

1 Answer 1

1

I search for answers in SO to mark as duplicate. And to my dismay, I couldn't find an answer which will solve your problem.

But the silver lining is, it made me write my own function.

const $List = document.getElementById('list')

const processNode = node => {
  if (node.children.length) {
    const children = Array.from(node.children).map(child => {
      return processNode(child)
    })

    return {
      tag: node.localName,
      id: node.id,
      children
    }
  } else {
    return {
      tag: node.localName,
      id: node.id,
      content: node.innerText
    }
  }
}

const vList = processNode($List);

console.log(vList)
<ul id="list">
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <ol>
    <li>Four</li>
    <li>Five</li>
    <li>Six</li>
  </ol>
</ul>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.