0

I have the following function:

function parseMarkupToDOM(markup) {
    return new DOMParser().parseFromString(markup, "text/html").body.firstElementChild;
}

When passing most elements, it works just fine. For instance:

parseMarkupToDOM(`<button>myButton</button>`); // returns a proper DOM element
parseMarkupToDOM(`<h1>myHeading</h1>`); // returns a proper DOM element

However, when I try to parse a thead into a DOM element, I get null:

parseMarkupToDOM(`
    <thead>
        <tr></tr>
        <tr></tr>
    </thead>
`); // returns null

I thought that maybe thead cannot be the child of body, but I am not sure how to get around it, and was not able to find any useful information about this issue. Any idea?

Michael Haddad
  • 4,085
  • 7
  • 42
  • 82
  • 1
    That's invalid HTML, `` can only be used inside ``.
    – Barmar May 10 '23 at 17:12
  • 2
    Because that's invalid HTML. It needs to be in a `table`. Some browsers will enter quirks mode and try to fix it by automatically adding a table in the DOM for you but regular HTML parsers normally won't do that. – slebetman May 10 '23 at 17:12
  • @Barmar So how would you do that? How to change the function so it could parse all HTML elements? – Michael Haddad May 10 '23 at 17:15
  • 1
    See https://stackoverflow.com/questions/75652465/parse-html-fragment-that-contains-a-table-row – Barmar May 10 '23 at 17:20
  • @Barmar - well, I read the answers there and they focus on a solution specifically for `tr` -- namely, they suggest wrapping it with a table. This is not quite what I am looking for. I need a function that can parse *any* HTML, and wrapping a `button` with a `table` will be meaningless. – Michael Haddad May 10 '23 at 17:28
  • I'm not sure there's a general purpose solution. DOMParser requires the HTML to be valid. If it's not, you have to wrap it in whatever it takes to make it valid. – Barmar May 10 '23 at 17:32
  • @slebetman agree. – Vivek K. May 10 '23 at 17:33
  • This may be an XY problem. What are you doing that requires parsing arbitrary fragments of HTML? – Barmar May 10 '23 at 17:34
  • @Barmar - Maybe... I am creating some [custom elements](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements), but it is extremely exhausting to build their inner HTML using DOM functions. Parsing HTML will be much easier. – Michael Haddad May 10 '23 at 17:37

0 Answers0