I need help understanding how this jQuery filter function works, line-by-line, if possible

Posted by user717236 on Stack Overflow See other posts from Stack Overflow or by user717236
Published on 2012-06-07T16:38:02Z Indexed on 2012/06/07 16:40 UTC
Read the original article Hit count: 213

Filed under:
|
|
|
|

Here is the HTML:

<div>
    <h3>text</h3>
</div>
<div>
    <h3>moretext</h3>
</div>
<div>
    <h3>123</h3>
</div>??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????

Here is the JS:

var rv1_wlength = $("div").filter(function() {
    return $(this).find("h3").filter(function () {
        return $(this).text() != "123";
    }).length;
});

var rv1_wolength = $("div").filter(function() {
    return $(this).find("h3").filter(function () {
        return $(this).text() != "123";
    });
});

var rv2 = $("div").find("h3").filter(function() {
    return $(this).text() != "123";
});

alert(rv1_wlength.text());   // text
                             // moretext

alert(rv1_wolength.text());  // text
                             // moretext
                             // 123

alert(rv2.text());?           // textmoretext

I don't understand why the first two methods print the elements on each line, whereas the second method concatenates them. "rv2" is a jQuery object. Then, what are the first two (rv1_wlength and rv1_wolength)?

Furthermore, I don't understand why the inclusion of the length property makes all the difference in filtering the elements. The second method does nothing, since it returns all the elements. The first method, with the only change being the addition of the length property, correctly filters the elements. I would very much like a line-by-line explanation.

I would sincerely appreciate any feedback. Thank you.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery