jquery count li elements inside ul -> length?

 ̄綄美尐妖づ 提交于 2019-12-18 12:03:45

问题


If a ul has more than one li-element inside of it, something should happen, otherwise not!

What am I doing wrong?

if ( $('#menu ul').length > 1 ) {

回答1:


You have to count the li elements not the ul elements:

if ( $('#menu ul li').length > 1 ) {

If you need every UL element containing at least two LI elements, use the filter function:

$('#menu ul').filter(function(){ return $(this).children("li").length > 1 })

You can also use that in your condition:

if ( $('#menu ul').filter(function(){ return $(this).children("li").length > 1 }).length) {



回答2:


The correct syntax is

$('ul#menu li').length



回答3:


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);



回答4:


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 ) {



回答5:


Use $('ul#menu').children('li').length

.size() instead of .length will also work




回答6:


Another approach to count number of list elements:

var num = $("#menu").find("li").length;
if (num > 1) {
  console.log(num);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="menu">
  <li>Element 1</li>
  <li>Element 2</li>
  <li>Element 3</li>
</ul>



回答7:


Make the following change:

console.log($("#menu li").length);



回答8:


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.




回答9:


alert( "Size: " + $("li").size() ); 

or

alert( "Size: " + $("li").length );

You can find some examples of the .size() method here.




回答10:


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>


来源:https://stackoverflow.com/questions/3158649/jquery-count-li-elements-inside-ul-length

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!