Sl4rtib4rtf4st Sl4rtib4rtf4st - 1 month ago 7
Javascript Question

Why can you chain some JavaScript methods but not others?

I'm relatively new to JavaScript and I would like to know when it is okay to chain JavaScript methods and when not, and what is the reason when you can't....

I'm creating an element and want to assign a class-name and then put some text inside the element. But for some reason you can't chain these methods.
Ideally I would do something like this:

var li = document.createElement("li").classList.add("className").innerHTML = "Some string";


I kind of understand why you can't chain the final part, because you can't assign twice. But I can't even chain the second method, instead I have to do this:

var li = document.createElement("li");
li.classList.add("className");
li.innerHTML = "Some string";


Why is that?

Answer

Chaining isn't anything special. It's just using the return value of a function. If a function returns an object that has a method on it, then you can use that method by calling it directly on the result of calling the function. That is,

foo().bar();

...works if foo returns an object that has a method called bar.

You can't do what you've shown in your first code block because:

  • add doesn't return anything, so the result of calling it is undefined.
  • If add did return something, it almost certainly wouldn't be the element createElement created. (It probably should return a reference to the DOMTokenList you called it on, but it doesn't.)
  • And even if it did, the result of an assignment operation (innerHTML = ...) is the value that was assigned, not a reference to the element.

Side note: If you like chaining APIs, look at using jQuery. It lets you do this:

var li = $("<li>").addClass("className").html("Some string");

...because most of its API methods return the jQuery instance that they were called on or another useful jQuery instance if not (and $() returns the set containing the single element outermost element it creates in the $("<li>") example). The API is specifically designed with chaining in mind. The DOM API is not.

Comments