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?
>Solution :
The DOMParser
method you are using parses the HTML string into an HTML document, which includes a DOCTYPE
declaration, html
element, head
element, and body
element. The firstElementChild property returns the first child of the body element, which in the case of your thead
example is null, because thead is not a valid child of body.
To parse the thead element and return it as a valid DOM element, you can wrap the thead element inside a table element (which in your case you don’t want to do, so you achieve this by creating a template
element ) and then parse the whole string as follows:
function parseMarkupToDOM(markup) {
const template = document.createElement('template');
template.innerHTML = markup.trim();
return template.content.firstChild;
}
const theadElement = parseMarkupToDOM(`
<thead>
<tr></tr>
<tr></tr>
</thead>
`);
console.log(theadElement);