JavaScript: for loop append element in several places -


i have loop needs append list item 2 menus sharing same class name. problem append 1 or other if reference index of or if use index of append last item.

html

<ul class="menu"> <li>list one</li> </ul>  <ul class="menu"> <li>list two</li> </ul> 

js

var menu    = document.queryselectorall('.menu'); var listitem    = document.createelement('li');  for(i=0; < menu.length; ++i){     menu[i].appendchild(listitem); } 

is weird quirk of js or missing something?

should be...

var menu = document.queryselectorall('.menu'); var listitem = document.createelement('li');  (var i=0; < menu.length; ++i) {     menu[i].appendchild(listitem.clonenode());     // or menu[i].appendchild(document.createelement('li'));     // point is, you'll have create new element , append } 

as stands, move same element 1 parent .menu item another. quoting the docs:

if given child reference existing node in document, appendchild() moves current position new position (there no requirement remove node parent node before appending other node).


Comments

Popular posts from this blog

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

html - Outlook 2010 Anchor (url/address/link) -

android - How to create dynamically Fragment pager adapter -