javascript - JS chaining pattern to insert elements into the DOM -
i struggling make pattern below work. i'm not interested in using library.
function _createelement(tagnm, attr){ var el = document.createelement(tagnm); for(var @ in attr){ el.setattribute(at, attr[at]); } } //below function not correct giving idea function _append(ele){ this.appendchild(ele) return this; } // able achive following chaining patter this. var div = document.getelementbyid('div'); div._append( _createelement('div', { id : 'parent', classname: 'parent' })).appendchile( _createelement('div', { id : 'child', classname: 'child' }));
for work, you're going have have sort of object focal point of chained calls. object value of this, in other words, in "_append" function. alternative have functions extend native dom object prototypes, won't work in older ie versions (and maybe not newer ones; i'm not sure).
you perhaps root in wrapper around document.getelementbyid(). you'd set "class" object append() , appendchild , whatever other functions you'd gather facility. functions go on prototype that:
function chainingwrapper(elem) { this.targetelement = elem; } chainingwrapper.prototype = { append: function(arg) { // append operation return this; }, appendchild: function(arg) { // appendchild operation return this; }, // ... }; now you'll have utility start things off:
function forelement(id) { return new chainingwrapper(document.getelementbyid(id)); } so do:
var div = forelement("mydiv"); div.appendchild(xyz).append(abc); inside functions "append" you'll able refer <div> this.targetelement. there zillion other interesting things sort of structure, of course.
Comments
Post a Comment