var tree = document.getElementsByTagName('ul')[0]; var treeLis = tree.getElementsByTagName('li'); /* wrap all textNodes into spans */ for (var i = 0; i < treeLis.length; i++) { var li = treeLis[i]; var span = document.createElement('span'); li.insertBefore(span, li.firstChild); span.appendChild(span.nextSibling); } /* catch clicks on whole tree */ tree.onclick = function(event) { var target = event.target; if (target.tagName != 'SPAN') { return; } /* now we know the SPAN is clicked */ var childrenContainer = target.parentNode.getElementsByTagName('ul')[0]; if (!childrenContainer) return; // no children childrenContainer.hidden = !childrenContainer.hidden; } 
 .tree span:hover { font-weight: bold; } .tree span { cursor: pointer; } 
 <ul class="tree"> <li>Животные <ul> <li>Млекопитающие <ul> <li>Коровы</li> <li>Ослы</li> <li>Собаки</li> <li>Тигры</li> </ul> </li> <li>Другие <ul> <li>Змеи</li> <li>Птицы</li> <li>Ящерицы</li> </ul> </li> </ul> </li> <li>Рыбы <ul> <li>Аквариумные <ul> <li>Гуппи</li> <li>Скалярии</li> </ul> </li> <li>Морские <ul> <li>Морская форель</li> </ul> </li> </ul> </li> </ul> 

Very interested in the line:

 var childrenContainer = target.parentNode.getElementsByTagName('ul')[0]; 

What <ul> does it apply to?

    1 answer 1

     target.parentNode.getElementsByTagName('ul')[0]; 

    getElementsByTagName returns an object (like an array) of elements (in the order mentioned in the document). [0] - means the first element, i.e. first ul in this case.

    • ie the first parent ul on top? - aleksei
    • @aleksei Yes, that's right. - user208916 pm
    • @aleksei for <span>"Животные"</span> , for example, is followed by <ul> about mammals and others. - Regent
    • for <span> "Sea" </ span> what ul it will be? then down below? - aleksei
    • @aleksei for any text will be <ul> , immediately following it. - Regent