& ldquo; thing.appendChild is not a function & rdquo; for the method of the object

advertisements

Apologies for the horrific title; I'm unsure how to summarise this problem in such few characters.

TL;DR Why doesn't $("#canvas").appendChild() work?

I have a prototype Car which, on instantiation, is supposed to create a div inside a div whose id is "canvas".

$(document).ready(function() {

    var canvas = $("#canvas");

    function Car(speed) {
        ...
        this.domDiv = document.createElement("div");
        $(this.domDiv).addClass("car");
        this.addToCanvas = function() {
            canvas.appendChild(this.domDiv);
        };
        this.addToCanvas();
        ...
    }

    car1 = new Car(0.5);

});

However, I get Uncaught TypeError: canvas.appendChild is not a function, and I don't understand why.


I think the correct function is append, rather than appendChild on a jQuery wrapper

canvas.append(this.domDiv);

You would want to use appendChild if you used a host query selector (document.getElementById('canvas')) rather than a jQuery selector ($('canvas'))