[英]how to use document.getElementByTagName and target specific class name
[英]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.