Skip to content

Instantly share code, notes, and snippets.

@simondell
Created October 26, 2012 14:24
Show Gist options
  • Save simondell/3959121 to your computer and use it in GitHub Desktop.
Save simondell/3959121 to your computer and use it in GitHub Desktop.
Tinkering with dynamically creating HTML from JS/JSON
/* ====================
Render
String builders for
- elements
- their attributes
======================*/
Render = function () {
/*
* Returns: string representation of HTML element and its content
* @type: String, should be an HTML element name (img, article, hr etc. Defaults to div
* @attrs: Object, {name:value} pairs
* @content: String, equiv of return value of HTMLelement.innerHTML
*/
var renderElementString = function ( type, attrs, content ) {
var type = type? type: 'div',
attrs = attrs? attrs: {},
content = content ? content: '',
html = '<' + type + ' ';
html += (attrs === {} )? '': renderAttributeString( attrs );
html += (content === '' )? '/>': '>' + content + '</' + type + '>';
return html;
}
/*
* Returns: string representation of HTML element attributes
* @attrs: Object, {name:value} pairs
*/
, renderAttributeString = function ( attrs ) {
var attString = '';
for ( attName in attrs ) {
attString += attName + '="' + attrs[ attName ] + '" ';
}
return attString;
}
;return {
elementString: renderElementString,
attributeString: renderAttributeString
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment