binaryfunt
binaryfunt

Reputation: 7127

"thing.appendChild is not a function" for object method

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.

Upvotes: 2

Views: 102

Answers (2)

Scott Schwalbe
Scott Schwalbe

Reputation: 430

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'))

Upvotes: 1

Sterling Archer
Sterling Archer

Reputation: 22405

appendChild is a DOM function. append is a jQuery function (canvas is a jQuery object).

Upvotes: 2

Related Questions