Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Thead parsing returns null

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading