May 5, 2012

Jquery: why my 'find()' method not updating?

Question by 3gwebtrain

i have a function to find the length of finding class, but it not working always return the length is ‘0’;

some thing is wrong with my code: can any one advice me the proper way. but i need to use the same structure of the code style to achieve this.

look on to my code :

<div id='list'>
  <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>      
  </ul>
    <p></p>
</div>​

function callMe(params){
    $(params.list).click(function(){
       $(this).addClass('c_on');
        var length = $(params.list).find('.c_on').length;
        $('p').text(length)// return always 0, even i clicked no.of list.        
    })
}

$(document).ready(function(){
    var obj = {
        list : $('ul').find('li')      
    }
   callMe(obj);
})

style :

li.c_on{
border:1px solid green;
}


​Here is the fiddle : http://jsfiddle.net/AeGvf/1/

Answer by mu is too short

You’re using find:

Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

when you should be using filter:

Reduce the set of matched elements to those that match the selector or pass the function’s test.

Note that find works on the descendants whereas filter works on the elements themselves. You have a list of <li>s that don’t have any descendants so find is searching an empty set. You should do this:

var length = $(params.list).filter('.c_on').length;

Also, your params.list is already a jQuery object so you don’t need to $(params.list), you can use params.list directly:

function callMe(params){
    params.list.click(function(){
        $(this).addClass('c_on');
        var length = params.list.filter('.c_on').length;
        $('p').text(length);
    });
}

Demo: http://jsfiddle.net/ambiguous/uCGaY/

Answer by Starx

Your selection method is bit flawed. Use this one instead:

function callMe(params){
    params.list.click(function(){
       $(this).addClass('c_on');
        var length = $(this).parent().find('.c_on').length;
        $('p').text(length)        
    })
}

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!