簡體   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