Question

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?

Was it helpful?

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.

OTHER TIPS

Append the title element, then append the text to the appended object. Note parentheses-

warning- The title element is a special case, only one title element is valid in a document

document.head.appendChild(document.createElement("title")).appendChild(document.createTextNode("Test Title"));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top