如何动态创建嵌套元素?

时间:2019-03-23 08:16:36

标签: javascript html dom

我有这个字符串数组var arr = ["ul", "li", "strong", "em", "u"]

如何将这些元素从左到右在另一个内部变成DOM元素,第一个元素作为根元素。由于某些原因而不使用ID。

也许可以通过使用循环使其灵活地适应任意数量的元素。

var new_element = document.createElement(arr[0]);

我期望这样的事情:

<ul>
    <li><strong><em><u>Text Here</u></em></strong></li>
</ul>

谢谢。

3 个答案:

答案 0 :(得分:12)

您可以使用Array.prototype.reduceNode.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>

答案 1 :(得分:9)

您可以使用reduceRight()来执行此操作,这避免了查询结果来获取最深的值,因为它从最深的元素开始并计算出来。返回值将是最上面的元素:

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>

它也会因空数组而正常失败:

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>

答案 2 :(得分:0)

createDocumentFragment()并通过循环运行阵列。在每次迭代createElement()appendChild()

const frag = document.createDocumentFragment();
const useless = ["ul", "li", "strong", "em", "u"];

let previous;
for (let u = 0; u < useless.length; u++) {
  const current = document.createElement(useless[u]);
  if (u === 0) {
    frag.appendChild(current);
  } else {
    previous.appendChild(current);
  }
  previous = current;
}

document.body.appendChild(frag);
ul {
  outline: 5px dashed green;
  padding: 15px;
}

li {
  outline: 5px solid blue;
  padding: 12px;
}

strong {
  outline: 5px dashed red;
  padding: 9px
}

em {
  outline: 5px dashed grey;
  padding: 6px
}

u {
  outline: 5px solid black;
  padding: 3px;
}

u::before {
  content: 'THIS TEXT SHOULD BE UNDERLINED'
}