
Converting a string which includes HTML tags to an array.
Javascript trick
What I want to do
There is a string like this.
"<div>ab cdef ghi</div><div>zxy12345</div>"
I want to convert this string to an array like this.
[<div>ab cdef ghi</div>, <div>zxy12345</div>]
Code
const str = `<div>ab cdef ghi</div><div>zxy12345</div>`const tmp = Object.assign(document.createElement('div'),{innerHTML:str})const divs = [...tmp.querySelectorAll('div')].map(x=>x.outerHTML); return divs //=>[<div>ab cdef ghi</div>, <div>zxy12345</div>]
Firstly, div tags are necessary to insert string into them. In this case, tmp has codes like this.
<div>
<div>ab cdef ghi</div>
<div>zxy12345</div>
</div>
Secondly, it is possible to get a node list of “div” by querySelectorAll(‘div’).
Finally, we can change node into html, using outerHTML.