Created
June 18, 2012 16:35
-
-
Save nfeldman/2949291 to your computer and use it in GitHub Desktop.
constructor for building xml like strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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