Skip to content

Instantly share code, notes, and snippets.

@nfeldman
Created June 18, 2012 16:35
Show Gist options
  • Save nfeldman/2949291 to your computer and use it in GitHub Desktop.
Save nfeldman/2949291 to your computer and use it in GitHub Desktop.
constructor for building xml like strings
// extracted from an earlier gist that had a more comprehensive DOM-like implementation
// in this case, I didn't care about namespaces and I didn't require any operation but
// append. This is too basic to be useful for most things, but good enough for what I've
// used it for. Note that the use of ES5 accessors makes this incompatible with IE < 9.
function Tag (name) {
this.name = name;
this.attrs = Object.create(null);
this.children = [];
return this;
}
Tag.prototype = {
get first () {
return this.children[0];
},
get last () {
return this.children[this.children.length - 1];
},
getAttrs: function () {
var a = this.attrs, p, r = [];
for (p in a) r.push(' ', p, '="', a[p], '"');
return r.join('');
},
append: function (node) {
if (node instanceof Tag) {
if (this.children.length > 1) {
node.prev = this.last;
this.last.next = node;
}
node.parent = this;
}
this.children.push(node);
},
toString: function () {
var open = this.name == 'text' ? [''] : ['<', this.name, this.getAttrs(), '>'],
close = this.name != 'text' ? this.children.length ? ['</', this.name, '>'] : [' /' + open.pop()] : [''];
this.children.forEach(function (child) {
open.push(child.toString());
});
return (open.join('') + close.join(''));
}
};
Tag.prototype.constructor = Tag;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment