Search code examples
javascriptjquerytypeerrorappendchild

How to properly use appendChild


$(document).ready(function() {
    $("a:last").on("click", function(event) {
        event.preventDefault();
        var url = $("a:last").attr("href");
        var page = url.slice(-2).trim();
        var newDiv = document.createElement("div");
        $(newDiv).addClass("content");
        $(newDiv).addClass(page);
        $(newDiv).load(url);
        document.getElementById("main").appendChild($(newDiv)); 
    });
});

I want to create a new div and load some content into it, then append it to the "main" div, but I get a TypeError:

Argument 1 of Node.appendChild does not implement interface Node.

I already have a div with id="main", why can't I append my new div to it?


Solution

  • Basically appendChild() expects a node object as its parameter, but here you are passing a jquery object. You can fix it by passing a node object,

    document.getElementById("main").appendChild(newDiv);
    

    And since you are using jquery, you can use its own append() function,

    $(document).ready(function() {
        $("a:last").on("click", function(event) {
            event.preventDefault();
            var url = $("a:last").attr("href");
            var page = url.slice(-2).trim();
            var newDiv = $("<div>");
            newDiv.addClass("content");
            newDiv.addClass(page);
            newDiv.load(url);
            $("#main").append(newDiv); 
        });
    });