Javascript 创建包含Doctype的新HTML文档
如果我这样做:Javascript 创建包含Doctype的新HTML文档,javascript,html,dom,innerhtml,outerhtml,Javascript,Html,Dom,Innerhtml,Outerhtml,如果我这样做: let html = `<!DOCTYPE html> <html> <head> <title>Hello, world!</title> </head> <body> <p>Hello, world!</p> </body> </html>`; let newHTMLDocumen
let html = `<!DOCTYPE html>
<html>
<head>
<title>Hello, world!</title>
</head>
<body>
<p>Hello, world!</p>
</body>
</html>`;
let newHTMLDocument = document.implementation.createHTMLDocument().documentElement;
newHTMLDocument.innerHTML = html;
console.log( newHTMLDocument );
let html=`
你好,世界!
你好,世界
`;
让newHTMLDocument=document.implementation.createHTMLDocument().documentElement;
newHTMLDocument.innerHTML=html;
console.log(newHTMLDocument);
输出为:
<html>
<head>
<title>Hello, world!</title>
</head>
<body>
<p>Hello, world!</p>
</body>
</html>
你好,世界!
你好,世界
为什么不包括doctype标记?我需要做什么才能在输出新HTMLDocument时包含doctype标记?返回
元素(文档根目录下的元素--
不是元素,它是一个声明节点),因此您将自己排除doctype
如果去掉.documentElement
,则doctype
仍保留
let html=`
你好,世界!
你好,世界
`;
让newHTMLDocument=document.implementation.createHTMLDocument();
newHTMLDocument.innerHTML=html;
//您可以作为对象访问doctype:
log(“是节点类型:”+newHTMLDocument.doctype.nodeType,
“\n当documentElement是节点类型时:”+newHTMLDocument.documentElement.nodeType);
log(newHTMLDocument.doctype);
警报(newHTMLDocument.innerHTML)
返回
元素(文档根目录下的元素--
不是元素,它是声明节点),因此您将自己排除在doctype
之外
如果去掉.documentElement
,则doctype
仍保留
let html=`
你好,世界!
你好,世界
`;
让newHTMLDocument=document.implementation.createHTMLDocument();
newHTMLDocument.innerHTML=html;
//您可以作为对象访问doctype:
log(“是节点类型:”+newHTMLDocument.doctype.nodeType,
“\n当documentElement是节点类型时:”+newHTMLDocument.documentElement.nodeType);
log(newHTMLDocument.doctype);
警报(newHTMLDocument.innerHTML)代码>您也可以与或一起使用:
const doc=document.implementation.createHTMLDocument('title');
log('before',new XMLSerializer().serializeToString(doc));
const docType=document.implementation.createDocumentType('qualifiedNameStr','publicId','systemId');
doc.doctype.replacetwith(doctype);
log('after',new XMLSerializer().serializeToString(doc))代码>您也可以与或一起使用:
const doc=document.implementation.createHTMLDocument('title');
log('before',new XMLSerializer().serializeToString(doc));
const docType=document.implementation.createDocumentType('qualifiedNameStr','publicId','systemId');
doc.doctype.replacetwith(doctype);
log('after',new XMLSerializer().serializeToString(doc))代码>我尝试了你的代码,但如果我使用console.log(newHTMLDocument);它不包含我的元素、title标签和p标签。我需要一个对象中的所有元素,因为我将在该对象上使用一些JS DOM函数。@GTSJoe newhtmldocument是一个对象,您不能直接记录它。我的代码记录为.innerHTML。例如,您可以使用newHTMLDocument.querySelector()获取其任何内容;doc.write(html);doc.close();为了创建一个HTML对象,我尝试了你的代码,但如果我使用console.log(newHTMLDocument);它不包含我的元素、title标签和p标签。我需要一个对象中的所有元素,因为我将在该对象上使用一些JS DOM函数。@GTSJoe newhtmldocument是一个对象,您不能直接记录它。我的代码记录为.innerHTML。例如,您可以使用newHTMLDocument.querySelector()获取其任何内容;doc.write(html);doc.close();创建HTML对象的步骤