[英]LI append SPAN element
I have a small problem with JavaScript/AppendChild. 我对JavaScript / AppendChild有一个小问题。 So i have navigation designed as :
所以我的导航设计为:
<ul class = 'child_ul general_ul'>
<li><a href='#'>Theme 1</a></li>
<li><a href='#'>Theme 2</a></li>
</ul>
And I want to append this one inside all LIs: 我想在所有LI中附加一个:
<span class = 'arrow'><i class = 'fa fa-angle-left'></i></span>
This code did't work: 这段代码不起作用:
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);
Can anyone help me? 谁能帮我? :)
:)
You want querySelectorAll (to get all LIs) and innerHTML or createElement 您需要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 needs a CLONED dom fragment like this: 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.