Created
August 28, 2017 20:51
-
-
Save ncksllvn/1b658582420531045270b65e697a26cb to your computer and use it in GitHub Desktop.
Array to dom
This file contains hidden or 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
/** | |
* 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, '<').replace(/>/g, '>') | |
} | |
// 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