.find() vs. .children(): which one should you use?

jQuery offers two functions to find children in an element: .find() and .children(). .find() will look through all children of an element while .children() will only look at immediate children.

<ul>
    <li>
        <p></p>
    </li>
    <li>
        <p></p>
    </li>
    <li>
        <p></p>
    </li>
</ul>

In the snippet above, $('ul').children('p') wouldn’t return anything, while $('ul').find('p') would return all three paragraph blocks.

In terms of performance, .find() is faster than .children() in most cases, since it uses native browser methods instead of JavaScript.

Here is a performance test that compares .find() and .children().

That was it! If you want to learn jQuery properly, I highly recommend Mark Myers’ “A Smarter Way to Learn jQuery“. Mark Myers tends to write very high quality programming books with a focus on good practices.

One comment on “.find() vs. .children(): which one should you use?

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax