javascripthtmldomdomparser

Make DOMParser use Standard mode instead of Quirks mode


Just realized that by default, DOMParser.parseFromString() creates documents in Quirks mode. Is there a way to make it Standard mode?

console.log(document.compatMode) // 'CSS1Compat'

const doc = new DOMParser().parseFromString('<div>Hello World</div>', 'text/html');
console.log(doc.compatMode) // 'BackCompat'


Solution

  • All you need to do is prepend <!DOCTYPE html> to the HTML your parsing

    DOMParser will result in the following "document"

    <html>
      <head>
      </head>
      <body>
        <div>Hello World</div>
      </body>
    </html>
    

    console.log(document.compatMode) // 'CSS1Compat'
    
    const doc = new DOMParser().parseFromString('<!DOCTYPE html><div>Hello World</div>', 'text/html');
    console.log(doc.compatMode) // 'BackCompat'
    console.log(doc.documentElement.outerHTML)