使用Javascript将HTML的DocType作为字符串

使用Javascript将HTML的DocType作为字符串

本文介绍了使用Javascript将HTML的DocType作为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以通过 document.doctype document.childNodes [0] 访问doctype对象我的问题是将doctype作为一个字符串。我可以通过调用 document.doctype 返回<!DOCTYPE html PUBLIC - // W3C // DTD HTML 4.01 // ENhttp://www.w3.org/TR/html4/strict.dtd> 。但是在Firefox中,调用 document.doctype 返回DocumentType对象。

I know that I can access to doctype object via document.doctype or document.childNodes[0] but my problem is getting doctype as a string. I can do this in chrome and safari by calling document.doctype which returns <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">. However in Firefox, calling document.doctype returns DocumentType object.

有没有办法在chrome和safari中获得所有浏览器中的doctype字符串?

Is there a way to get the the doctype string in all browsers as in chrome and safari?

谢谢

推荐答案

在所有兼容的浏览器(包括Chrome / Safari)中,还返回一个对象,请访问w3.org/TR/DOM-Level-3-Core/core.html#ID-412266927rel =noreferrer> 以下代码可用于生成有效的DOCTYPE字符串。

In all compliant browsers (including Chrome/Safari), document.doctype also returns a DocumentType object. 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 SYSTEMabout:legacy-compat> code>

  • <!DOCTYPE HTML PUBLIC - // W3C // DTD HTML 4.0 // ENhttp://www.w3 .org / TR / REC-html40 / strict.dtd>

  • <!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">

代码说明:

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将HTML的DocType作为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 23:45