For something like that to work, you're going to have to have some sort of object to be the focal point of the chained calls. The object would be the value of this
, in other words, in your "_append" function. An alternative would be to have your functions extend the native DOM object prototypes, but that won't work in older IE versions (and maybe not even newer ones; I'm not sure).
You could perhaps root everything in a wrapper around document.getElementById()
. You'd set up a "class" object for all your append()
and appendChild
and whatever other functions you'd like to gather up for this facility. Those functions would all go on the prototype for that:
function chainingWrapper(elem) {
this.targetElement = elem;
}
chainingWrapper.prototype = {
append: function(arg) {
// do the append operation
return this;
},
appendChild: function(arg) {
// do the appendChild operation
return this;
},
// ...
};
Now you'll have a utility to start things off:
function forElement(id) {
return new chainingWrapper(document.getElementById(id));
}
So then you could do:
var div = forElement("myDiv");
div.appendChild(xyz).append(abc);
Inside the functions like "append" you'll be able to refer to that <div>
as this.targetElement
. There are a zillion other interesting things you could do with this sort of structure, of course.