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";
var li = document.createElement("li");
li.innerHTML = "Some string";
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 returns an object that has a method called
You can't do what you've shown in your first code block because:
adddoesn't return anything, so the result of calling it is
adddid return something, it almost certainly wouldn't be the element
createElementcreated. (It probably should return a reference to the
DOMTokenListyou called it on, but it doesn't.)
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.