I have this array of strings var arr = ["ul", "li", "strong", "em", "u"]
.
How can I make these into DOM Elements one inside another from left to right, first element as the root element. Without using ID because of some reason.
And maybe by using loop for it to be flexible to any number of elements.
var new_element = document.createElement(arr[0]);
I'm expecting something like this:
<ul>
<li><strong><em><u>Text Here</u></em></strong></li>
</ul>
Thank you.
You can do this with reduceRight()
which avoids needing to query the result to get the deepest value because it starts with the deepest element and works out. The return value will be the topmost element:
var arr = ["ul", "li", "strong", "em", "u"]
let el = arr.reduceRight((el, n) => {
let d = document.createElement(n)
d.appendChild(el)
return d
}, document.createTextNode("Text Here"))
document.getElementById('container').appendChild(el)
<div id = "container"></div>
It also fails gracefully with an empty array:
var arr = []
let el = arr.reduceRight((el, n) => {
let d = document.createElement(n)
d.appendChild(el)
return d
}, document.createTextNode("Text Here"))
document.getElementById('container').appendChild(el)
<div id = "container"></div>
You can use Array.prototype.reduce
and Node.prototype.appendChild
.
https://jsbin.com/hizetekato/edit?html,js,output
var arr = ["ul", "li", "strong", "em", "u"];
function createChildren(mount, arr) {
return arr.reduce((parent, elementName, i) => {
const element = document.createElement(elementName);
parent.appendChild(element);
return element;
}, mount);
}
const deepest = createChildren(document.querySelector('#root'), arr);
deepest.innerText = 'WebDevNSK'
<div id="root"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With