Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create nested elements dynamically?

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.

like image 221
Muyie Avatar asked Mar 23 '19 08:03

Muyie


2 Answers

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>
like image 80
Mark Avatar answered Nov 15 '22 18:11

Mark


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>
like image 12
dangreen Avatar answered Nov 15 '22 17:11

dangreen