繁体   English   中英

如何在正文标签中使用document.getElementByTagName()

[英]How to use document.getElementByTagName() with body tag

我尝试将body标记与document.getElementsByTagName()方法一起使用,但无法正常工作。

var p = document.createElement("p");
var node = document.createTextNode("This is new");
p.appendChild(node);
var parent = document.getElementByTagName("body");
parent.appendChild(p);

为什么它不返回结果,我在哪里出错了?

document.body将返回单个元素,而getElementsByTagName()将返回一个HTMLCollection

var p = document.createElement("p");
var node = document.createTextNode("This is new");
p.appendChild(node);
var parent = document.body;
parent.appendChild(p);

命令是getElementsByTagName ,注意Elements上的复数。

var parent = document.getElementsByTagName("body");

尝试(但是通过document.body更轻松地访问body,詹姆斯·艾伦答案中提到的内容)

 let body = document.getElementsByTagName("body")[0]; body.innerHTML += "<p>This is new</p>"; 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM