Site LogoReverie

Convert String To Html

Web/HTML

To convert an HTML string into real HTML or DOM, we can use the DOMParser Web API using JavaScript. The DOMParser helps us to parse HTML or XML string into real Document or DOM nodes.

const convertStringToHTML = (htmlString: string): Element | null => {
  try {
    const parser = new DOMParser()
    const doc = parser.parseFromString(htmlString, "text/html")
 
    const parseError = doc.querySelector("parsererror")
    if (parseError) {
      throw new Error("HTML parsing failed")
    }
 
    const element = doc.body.firstElementChild
    return element
  } catch (error) {
    throw new Error(`Failed to convert HTML string: ${error.message}`)
  }
}

There are other mime types we can use such as:

  • text/html
  • text/xml
  • application/xml
  • application/xhtml+xml
  • image/svg+xml

Ref: