exchez
exchez

Reputation: 503

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?

Upvotes: 1

Views: 357

Answers (3)

Kelvin A.
Kelvin A.

Reputation: 16

$(newDiv) is a jquery object, not the node. You need to pass the node in. This will work

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

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

The issue is because you're mixing up jQuery and plain old JS. The error itself is because you're proving a jQuery object to appendChild() when it's expecting a DOMElement. As you're using jQuery anyway you may as well use that to create your elements. Try this:

$("a:last").on("click", function(e) {
    e.preventDefault();
    var url = $("a:last").attr("href");
    var page = url.slice(-2).trim();
    $('<div />').addClass('content ' + page).appendTo('#main').load(url);
});

Upvotes: 3

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

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

Upvotes: 3

Related Questions