1

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 douments. Obviously I can't use innerHTML because of the img and a href tags.

1
  • just join array elements together as a string like this: new DOMParser().parseFromString(youArray.join(','), "text/xml") Commented May 3, 2020 at 7:48

2 Answers 2

3

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>

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

Comments

0

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)

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.