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

2

5

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?

Bernt answered 27/11, 2013 at 17:36 Comment(0)
W
10

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.

Wivern answered 27/11, 2013 at 17:40 Comment(0)
S
1

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"));
Soulsearching answered 27/11, 2013 at 17:59 Comment(1)
Yep, this is exactly what I was trying to achieve but I messed up the brackets. Thx! +1Bernt

© 2022 - 2024 — McMap. All rights reserved.