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

The question was asked: 8 years 6 months ago   views: 27
0

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> </ul> the <script> spis var = document.ul.li.length; document.write('number of elements ul '+spis); </script>

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

0

There are at least two ways

<ul id="mymenu"> the <li>aaaa</li> the <li>bbbb</li> ...... </ul> <script type="text/javascript"> // method 1: alert(document.getElementById('mymenu').childNodes.length); // method 2: alert(document.getElementById('mymenu').getElementsByTagName('li').length); </script>
Answered: 05-03-2011 в 09:43:37
The first method considers all text nodes. - 05-03-2011 в 11:39:15
0
the <script> spis var = document.ul.li.length; document.write('number of elements ul '+spis); </script>

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

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

But it is Your task to solve

<style> ul li { float: left; width: 50px; height: 50px; } </style> 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> </ul>
Answered: 05-03-2011 в 15:41:51
0

or this:

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