Get DocType of an HTML as string with Javascript

matte提出了一个问题:Get DocType of an HTML as string with Javascript,或许与您遇到的问题类似。

回答者ChristophRob W给出了该问题的处理方式:

In all compliant browsers (including Chrome/Safari), document.doctypealso returns a DocumentTypeobject. The following code can be used to generate a valid DOCTYPE string.

var node = document.doctype;
var html = "<!DOCTYPE "
         + node.name
         + (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '')
         + (!node.publicId && node.systemId ? ' SYSTEM' : '') 
         + (node.systemId ? ' "' + node.systemId + '"' : '')
         + '>';

This method returns the correct string for valid (HTML5) doctypes, eg:

  • <!DOCTYPE html>
  • <!DOCTYPE html SYSTEM "about:legacy-compat">
  • <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">

Explanation of the code:

node.name      # Holds the name of the root element, eg: HTML / html
node.publicId  # If this property is present, then it's a public document type.
               #>Prefix PUBLIC
!node.publicId && node.systemId
               # If there's no publicId, but a systemId, prefix SYSTEM
node.systemId  # Append this if present

希望本文对你有帮助,欢迎支持JavaScript中文网

原文链接:stackoverflow.com

上一篇:default array values
下一篇:Node.js request CERT_HAS_EXPIRED

相关推荐

官方社区

扫码加入 JavaScript 社区