For chaining to work, a method has to return the object that you want to chain with. Because .classList methods do not return either the classList object or the DOM object, you can't natively do chaining with them.
You could, of course write your own methods and have them return the appropriate object and thus re-implement the functionality in a chainable way, but you'd have to put them on a system prototype in order to be able to use them as easily.
Without reimplementing chainable methods, you could shorten your code a bit:
var sidebarList = document.querySelector("#sidebar").classList;
sidebarList.toggle("active");
sidebarList.remove("hover");
If you want to add chainable methods on the actual HTML5 objects, you could do this:
(function() {
var p = HTMLElement.prototype;
p.clAdd = function(cls) {
this.classList.add(cls);
return this;
};
p.clRemove = function(cls) {
this.classList.remove(cls);
return this;
};
p.clToggle = function(cls) {
this.classList.toggle(cls);
return this;
}
})();
// sample use
document.querySelector("#sidebar").clAdd("active").clRemove("inactive");
Working demo: http://jsfiddle.net/jfriend00/t6w4aj0w/
Or, if you want a .classList type interface, you could do this:
Object.defineProperty(HTMLElement.prototype, "classListChain", {
get: function() {
var self = this;
return {
add: function(cls) {
self.classList.add(cls);
return self;
},
remove: function(cls) {
self.classList.remove(cls);
return self;
},
toggle: function(cls) {
self.classList.toggle(cls);
return self;
}
}
}
});
// sample use
document.querySelector("#sidebar").classListChain.add("active").classListChain.remove("inactive");
Working demo: http://jsfiddle.net/jfriend00/pxm11vcq/
FYI, because both of these options chain the actual DOM element (unlike torazaburo's method which chains a custom object), you can add a DOM element method/property at the end as in:
el.classListChain.add("active").style.visibility = "visible";
Or, you can do something like this:
var el = document.querySelector("#sidebar").classListChain.add("active");
with(sidebar.classList){ toggle("active"); remove("hover"); }Use of the with statement is not recommended,