简体   繁体   中英

LI append SPAN element

I have a small problem with 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:

<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

 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:

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM