Search code examples
javascriptstenciljs

How do I convert an HTML string into a Vnode or a JS object?


I need to convert this HTML string: '<path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="M19.5 13.5v-5a7 7 0 1 0-14 0v5c-.03 2.47-.72 4.887-2 7h18a13.833 13.833 0 0 1-2-7Z"/>'

into a Vnode or, if that is not possible, a JS object so I can then loop through it, get its properties, and construct a Vnode.

This is what I need to get:

{$attrs$: {d: "M19.5 13.5v-5a7 7 0 1 0-14 0v5c-.03 2.47-.72 4.887-2 7h18a13.833 13.833 0 0 1-2-7Z"
stroke: "currentColor"
stroke-linecap: "round"
stroke-linejoin: "round" }
$children$: null
$elm$: path
$flags$: 0
$tag$: "path"
$text$: null
}

SVG structure when is nested inside before rendering.

SVG that works

SVG structure when is referenced from inside the .

SVG not working


Solution

  • If you need to get dom node from string you can do something like that

    function getNodeFromString (htmlString) {
        const div = document.createElement('div')
        div.innerHTML = htmlString
        return div.firstElementChild
    }
    

    Then you can get attributes from node like that

    const node = getNodeFromString('<path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="M19.5 13.5v-5a7 7 0 1 0-14 0v5c-.03 2.47-.72 4.887-2 7h18a13.833 13.833 0 0 1-2-7Z"/>')
    
    const result = Array
      .from(node.attributes, ({ name, value }) => ({ name, value }))
      .reduce((acc, current) => {
        acc[current.name] = current.value
        return acc
      }, {})
    
    console.log(result)