I want to make a menu in two lines, for this I need to count the number of ul elements, which function in javascript is responsible for this? I tried something like this:

<ul> <li>Главная</li> <li>Контакты</li> <li>Резюме</li> <li>Портфолио</li> <li>Услуги</li> <li>Стихи</li> <li>Программы</li> <li>Статьи</li> </ul> <script> var spis = document.ul.li.length; document.write('Кол-во элементов ul '+spis); </script> 

The script should count the number of li and after every 4th, transfer the rest to the next line.

  • Thanks for answers! I understand javascript do not care where to stand: before the ul elements or after them? - chuikoff
  • Of course not. Either after, or you need to call the code on the onload event (or its more advanced versions). - Artem Sapegin

3 answers 3

At least there are two ways.

 <ul id="mymenu"> <li>aaaa</li> <li>bbbb</li> ...... </ul> <script type="text/javascript"> // способ 1: alert(document.getElementById('mymenu').childNodes.length); // способ 2: alert(document.getElementById('mymenu').getElementsByTagName('li').length); </script> 
  • one
    The first way will count also all text nodes. - Artem Sapegin
 <script> var spis = document.ul.li.length; document.write('Кол-во элементов ul '+spis); </script> 

This code is not a valid DOM, you need to use dom-functions:

 document.getElementsByTagName('ul')[0].getElementsByTagName('li'); 

But it is your problem that is solved like this:

 <style> ul li { float: left; width: 50px; height: 50px; } </style> <ul> <li>element 1</li> <li>element 2</li> <li>element 3</li> <li>element 4</li> <li>element 5</li> <li>element 6</li> </ul> 

    or so:

     var len = document.querySelector('ul').children.length;