Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Children length of an ol

I am trying to count the child elements of an OL

jQuery :

$(document).ready(function(){

$("#my_select").change(function(){
    alert($("#ol3").children.length);
                                     });});

HTML:

<ol id="ol1">
    <li class="2">Location 1-1</li>
</ol>

<ol id="ol2">
    <li class="15">Location 2-1</li>
    <li class="20">Location 2-2</li>
</ol>

<ol id="ol3">
    <li class="17">Location 3-1</li>
    <li class="16">Location 3-2</li>
    <li class="14">Location 3-3</li>
</ol>

I always get the number 2 no matter how many li are there under the ol.

Know what's going on..?

like image 337
DMin Avatar asked May 31 '10 02:05

DMin


People also ask

How do you get children of children in jQuery?

jQuery children() MethodThe children() method returns all direct children of the selected element. The DOM tree: This method only traverse a single level down the DOM tree. To traverse down multiple levels (to return grandchildren or other descendants), use the find() method.

What is jQuery length?

The length property in jQuery is used to count the number of elements in the jQuery object. The size() function also returns the number of elements in the jQuery object.

What is $() in jQuery?

The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s). Basic syntax is: $(selector).action() A $ sign to define/access jQuery. A (selector) to "query (or find)" HTML elements. A jQuery action() to be performed on the element(s)

What does the length property for a jQuery object return?

lengthReturns: Integer Description: The number of elements in the jQuery object.


2 Answers

try

$("#ol3").children().length \\ you missed () in children...

when you do $("#ol3").children.length it returns the number of arguments in the .children() function...

try alerting $("#ol3").children and you will get this...

function (d,f){var e=c.map(this,b,d);eb.test(a)||(f=d);if(f&&typeof f==="string")e=c.filter(f,e);e=this.length>1?c.unique(e):e;if((this.length>1||gb.test(f))&&fb.test(a))e=e.reverse();return this.pushStack(e,a,R.call(arguments).join(","))}

where d and f are the two arguments... that's why you are always getting 2 in your code when you alert..

like image 100
Reigel Avatar answered Nov 02 '22 06:11

Reigel


Try children() instead of children.

For a belt-and-suspenders approach, try children('li').

like image 30
Ken Redler Avatar answered Nov 02 '22 08:11

Ken Redler