LI附加SPAN元素

时间:2018-03-14 21:00:45

标签: javascript append

我对JavaScript / AppendChild有一个小问题。 所以我的导航设计为:

 <ul class = 'child_ul general_ul'>
      <li><a href='#'>Theme 1</a></li>
      <li><a href='#'>Theme 2</a></li> 
  </ul>

我想在所有LI中附加这个:

<span class = 'arrow'><i class = 'fa  fa-angle-left'></i></span>

此代码不起作用:

var arrow = "<span class = 'arrow'><i class = 'fa  fa-angle-left'></i></span>";

var li_list = document.querySelector('.child_ul > li');

 li_list.appendChild(arrow);

任何人都可以帮助我吗? :)

1 个答案:

答案 0 :(得分:0)

您需要querySelectorAll(获取所有LI)和innerHTML或createElement

var arrow = "<span class='arrow'><i class='fa fa-angle-left'></i></span>"

var li_list = document.querySelectorAll('.child_ul > li');
for (var i=0;i<li_list.length;i++) {
  li_list[i].innerHTML+=arrow; // += concatenates to the LI
}

// show the html for verification
console.log(document.querySelector(".child_ul").innerHTML)
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />


<ul class='child_ul general_ul'>
  <li><a href='#'>Theme 1</a></li>
  <li><a href='#'>Theme 2</a></li>
</ul>

appendChild需要一个像这样的CLONED dom片段:

var arrowSpan = document.createElement("span");
arrowSpan.className = "arrow"
arrowSpan.innerHTML = "<i class='fa fa-angle-left'></i>" // or more createElements

var li_list = document.querySelectorAll('.child_ul > li');
for (var i = 0; i < li_list.length; i++) {
  li_list[i].appendChild(arrowSpan.cloneNode(true));
}

// show the html for verification
console.log(document.querySelector(".child_ul").innerHTML)
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />


<ul class='child_ul general_ul'>
  <li><a href='#'>Theme 1</a></li>
  <li><a href='#'>Theme 2</a></li>
</ul>