简体   繁体   中英

Turn array of HTML Strings into an array of HTML tags

I have an array of HTML strings:

["<h1>this is a title</h1>", "<a href=#>link</a>", "<img src="#" />","<p>a long paragraph</p>"]

How would I convert these into an array of HTML tags, I'm ultimately trying to return the array to render in React.

I've tried using:

new DOMParser().parseFromString(string, "text/xml");

but that creates an array of doument s. Obviously I can't use innerHTML because of the img and a href tags.

You can just use createContextualFragment() method to parse XML/HTML string, here is a working snippet:

 let elements = ["<h1>this is a title</h1>", "<a href=#>link</a>", "<img src='#' />","<p>a long paragraph</p>"]; let container = document.getElementById('container'); elements.forEach((el, i) => { const fragment = document.createRange().createContextualFragment(el); console.log(fragment.children[0]); container.appendChild(fragment.children[0]); })
 <div id="container"></div>

You can use array map() method and use DOMParser() on each element to get the tags like:

 const data = ["<h1>this is a title</h1>", "<a href=#>link</a>", "<img src='#' />", "<p>a long paragraph</p>"] const res = data.map(tag => new DOMParser().parseFromString(tag, "text/html").querySelectorAll("*:not(html):not(head):not(body)")[0]) console.log(res)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM