How to count the number of elements of the ul in JavaScript?

The question was asked: 8 years 3 months ago   views: 20

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

the <ul>
the <li>Home</li>
the <li>Contacts</li>
the <li>Summary</li>
the <li>Portfolio</li>
the <li>Services</li>
the <li>Element</li>
the <li>Programs</li>
the <li>Articles</li>

the <script>
 spis var =;
 document.write('number of elements ul '+spis);

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

Asked: 05-03-2011 в 08:30:35
Thanks for the replies! I understand javascript don't care where stand up to the elements ul or after them? - 06-03-2011 в 03:22:15
No, of course. Either after or you need to call code on the onload event (or its more advanced variants). - 06-03-2011 в 08:48:07

Answers   3


There are at least two ways

<ul id="mymenu">
the <li>aaaa</li>
the <li>bbbb</li>

<script type="text/javascript">
 // method 1:

 // method 2:
Answered: 05-03-2011 в 09:43:37
The first method considers all text nodes. - 05-03-2011 в 11:39:15
the <script>
 spis var =;
 document.write('number of elements ul '+spis);

This code is not valid DOM, use the dom functions:


But it is Your task to solve

 ul li {
 float: left;
 width: 50px;
 height: 50px;
the <ul>
 the <li>element 1</li>
 the <li>element 2</li>
 the <li>element 3</li>
 the <li>element 4</li>
 the <li>element 5</li>
 the <li>element 6</li>
Answered: 05-03-2011 в 15:41:51

or this:

var len = document.querySelector('ul').children.length;
Answered: 04-03-2017 в 02:35:25