appendChild 不是函数错误 (JAVASCRIPT)

appendChild is not a function error (JAVASCRIPT)

我有这个

var inviteSection = document.getElementByClassName("invitedFriends");
var friend = document.createElement("div").class = "friend";

var mail = document.createElement("p").class = "mail";
var span = document.createElement("span").class = "status accepted";

function main() {
    inviteSection.appendChild(friend);

    friend.appendChild(mail);
    friend.appendChild(span);
}

main();

当我 运行 这个 chrome 控制台时它说 'Uncaught TypeError: inviteSection.appendChild is not a function' 有什么解决方法请帮帮我!

问题是,Akshay Arora points out, the method for getting elements by class name has to be plural. The implication is that it will always return an array-like collection of elements, even if it only finds one element with that class name. (This is what Arun P Johny NodeList 的意思。)

如果您绝对确定永远只有一个元素具有 class 名称,那么您只需将第一行更改为

var inviteSection = document.getElementsByClassName("invitedFriends")[0];

如果有不止一个元素具有此 class 名称,这只会给您第一个元素。