JS: Appending elements to head - how to chain the methods?

append, appendchild, createelement, dom, javascript

Solution

Method chaining works off the return value of the previous method.

var chain = {
    example: function (val) {
        alert(val);
        return this;
    }
};
chain.example('this').example('works');

`example` can be chained off of `example` because `return this` returns an object which has an `example` method.

In the case of `parent.appendChild(child)` the return value is `child`, which means that chaining will not add elements to `parent` further, instead subsequent elements will be nested.

Problem

I am a bit confused here. I was trying to do some basic DOM manipulation - testing it with appending a title to the `<head>` tag. This is what I wrote: ``` document.head.appendChild(document.createElement("title").appendChild(document.createTextNode("Test Title"))); ``` However, the above doesn't work. If I split it up, it works: ``` var node = document.createElement("title"); var text = document.createTextNode("Test title"); node.appendChild(text); document.head.appendChild(node); ``` Why is that, what am I missing?

Original source