Search code examples
javascriptoopdomappendchild

document.createElement() getting ignored


I've built a simple program to learn OOP in Javascript. It merely outputs predefined string statements. The problem here is that the program is binding text nodes directly to the "output div", while ignoring the previous command to append them to respective "p" elements.

Student.prototype.sayHello = function()
{
    var responseString = document.createTextNode("Hello, I've been waiting here for you. Student.");
    return document.createElement("p").appendChild(responseString);
}
Student.prototype.sayGoodBye = function()
{
    var responseString = document.createTextNode("tchau");
    return document.createElement("p").appendChild(responseString);
}

var student = new Student();
document.getElementById("output").appendChild(student.sayHello());
document.getElementById("output").appendChild(student.walk());
document.getElementById("output").appendChild(student.sayGoodBye());

Solution

  • Your problem is that appendChild(child) returns child but it seems you're expecting to return the added p element.

    Try doing

    var p = document.createElement("p");
    p.appendChild(responseString);
    return p;