Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

appendChild is not a function error (JAVASCRIPT)

I have this piece

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();

When I run this chrome console it says 'Uncaught TypeError: inviteSection.appendChild is not a function' Is there any fix for this please help me guys!

like image 590
Abhinav Singh Avatar asked Jul 23 '26 13:07

Abhinav Singh


1 Answers

The problem is that, as 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 meant by NodeList.)

If you're absolutely sure that there will only ever be the one element with that class name, then you just need to change the first line to

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

If there is ever more than one element with this class name, this will just give you the first element.

like image 181
Scott Schupbach Avatar answered Jul 25 '26 04:07

Scott Schupbach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!