If a ul
has more than one li
-element inside of it, something should happen, otherwise not!
What am I doing wrong?
if ( $(\'
Working jsFiddle
Please use .size() function instead of .length and also specify li tag in selector.
Change your code like.
if ( $('#menu ul li').size() > 1 ) {
Use $('ul#menu').children('li').length
.size() instead of .length will also work
Warning: Answers above only work most of the time!
In jQuery version 3.3.1 (haven't tested other versions)
$("#myList li").length;
works only if your list items don't wrap. If your items wrap in the list then this code counts the number of lines occupied not the number of <li> elements.
$("#myList").children().length;
gets the actual number of <li> elements in your list not the number of lines that are occupied.
alert( "Size: " + $( "li" ).size() );
alert( "Size: " + $( "li" ).length );
Both .size() and .length return number of item. but size() method is deprecated (JQ 1.8). .length property can use for instead of size().
also you can use
alert($("ul").children().length);
The correct syntax is
$('ul#menu li').length
If you have a dom object of the ul, use the following.
$('#my_ul').children().length;
A simple example
window.setInterval(function() {
let ul = $('#ul'); // Get the ul
let length = ul.children().length; // Count of the child nodes.
// The show!
ul.append('<li>Item ' + (length + 1) + '</li>');
if (5 <= length) {
ul.empty();
length = -1;
}
$('#ul_length').text(length + 1);
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h4>Count of the child nodes: <span id='ul_length'>0</span></h4>
<ul id="ul"></ul>