javascript - DOMParser: Getting the real root element from an XML or HTML DOM segment

Mgen

2018-03-31T14:56:46Z||2018-03-31T14:56:46Z

For XML segment, use Document.documentElement:

(new DOMParser()).parseFromString('<haha></haha>', 'text/xml').documentElement
// Prints: 

For HTML segment, use Document.documentElement.firstElementChild. Be aware this only retrieves the first element of a segment, it may contain multiple elements.

(new DOMParser()).parseFromString('<haha></haha>', 'text/html').body
// Prints: <body>…</body>
(new DOMParser()).parseFromString('<haha></haha>', 'text/html').body.firstElementChild
// Prints: <haha></haha>