Hi there, I'm in need of some assistance with a JavaScript task. Can anyone help?
I'm looking to create a JavaScript function that can take an array and return the corresponding HTML string.
For example: [tagName, child1, child2, ...]
• The tag name will always be the first entry in the array and will be a string.
• The children can be arrays or strings.
• Strings are treated as plain text, not HTML markup.
• Arrays are considered nested elements.
• No support for attributes, comments, etc., only elements and text.
• Empty tags should be self-closing.
• Consecutive text nodes will be merged in the final output.
• No libraries, build processes, or transpilers are permitted.
Examples:
['div'] => '<div/>'
['h1', 'Text'] => '<h1>Text</h1>'
['span', 'More', 'Text'] => '<span>MoreText</span>'
['a', ['b', 'More'], ' Text'] => '<a><b>More</b> Text</a>'
['p', '<b>Text</b>'] => '<p><b>Text</b></p>'
This is my current code using objects instead of arrays. Any suggestions on how to convert it?
var obj = {
"h1": 'text',
"a": {"b": 'more'}, // nested element
"text": '', // empty tag
"p": '<b>text</b>' // with HTML
};
var finalString = '';
function createHTML(obj){
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
if (obj[prop] == '[object Object]') {
finalString += "<" + prop + ">";
createHTML(obj[prop]);
finalString += "</" + prop + ">";
} else {
if (obj[prop] == '') {
finalString += "<" + prop + "/>";
} else {
finalString += "<" + prop + ">" + encodeURI(obj[prop]) + "</" + prop + ">";
}
}
}
}
}
createHTML(obj);
console.log(finalString);
// "<h1>text</h1><a><b>more</b></a><text/><p>%3Cb%3Etext%3C/b%3E</p>"