Skip to content

Instantly share code, notes, and snippets.

@ncksllvn
Created August 28, 2017 20:51
Show Gist options
  • Save ncksllvn/1b658582420531045270b65e697a26cb to your computer and use it in GitHub Desktop.
Save ncksllvn/1b658582420531045270b65e697a26cb to your computer and use it in GitHub Desktop.
Array to dom
/**
* Nick Sullivan
* [email protected]
* Translates an array into a DOM string.
* Example:
*
* arrayToDom(['a', ['b', 'More'], ' Text']) // => "<a><b>More</b> Text</a>"
*
*/
function arrayToDom(element){
// If the parameter is a string, no further processing is needed.
if (typeof(element) == 'string'){
// Replace < and > to prevent html injection
return element.replace(/</g, '&lt;').replace(/>/g, '&gt;')
}
// If it's not a string, it has to be an array
var tagName = element[0]
// If there are no further arguments, then the tag should be self-closing
if (element.length == 1){
return '<' + tagName + '/>'
}
var tagContent = element.slice(1)
// Any elements after the first may also contain elements,
// so we need to use recursion to process those.
var processedContent = tagContent.map(arrayToDom).join('')
return '<' + tagName + '>' + processedContent + '</' + tagName + '>'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment