1

I have a for loop that needs to append a list item to two menus sharing the same class name. The problem is it will only append to one or the other if I reference the index of it or if I use index of I it will only append to the 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; i < menu.length; ++i){
    menu[i].appendChild(listItem);
}

Is this another weird quirk of JS or am I just missing something?

NicholasByDesign
  • 781
  • 1
  • 11
  • 33

1 Answers1

4

Should be...

var menu = document.querySelectorAll('.menu');
var listItem = document.createElement('li');

for (var i=0; i < menu.length; ++i) {
    menu[i].appendChild(listItem.cloneNode());
    // or menu[i].appendChild(document.createElement('li'));
    // the point is, you'll have to create a new element and append it
}

As it stands, you just move the same element from one parent .menu item to another. Quoting the docs:

If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position (there is no requirement to remove the node from its parent node before appending it to some other node).

raina77ow
  • 103,633
  • 15
  • 192
  • 229