How to select children and self with jQuery?


I’m wondering what the best way is to find children of an element in jQuery, but also include the parent in the ‘find’.

Here’s my simplified basic HTML setup:

<div id="container">
    <form id="form1"> <!-- form 1 content --> </form>
    <form id="form2"> <!-- form 2 content --> </form>

And I want a function like this…

function getForms ($container) 
    // Option 1
    var $allForms = $container.find('form').andSelf().filter('form');

    // Option 2
    var $allForms = $container.find('form');
    if ($'form')) $allForms.add($container);

    // Should return all the forms in the container if passed $('#container')
    // Or return just one form if passed $('#form1')
    return $allForms;

I’m fairly certain that both option 1 or 2 will work. Does anyone know which option above is more efficient? Are there other options which are more elegant or more efficient?

I wasn’t happy with the .is() in option 2 because it didn’t work when the container had multiple jQuery objects in it. So I came up with something like this:

// Option 3
function getContainerElements ($container, selector) {
    return $container.find(selector).add($container.filter(selector));

I haven’t tested it too much, but I think it’ll work for all general cases.


Option 2 is better according to JSPerf tests (Tested in Chrome on linux)

You can see the results here and the tests if you want to try it in different browsers:

Note: I’ve updated this test to use divs instead of forms (because forms inside other forms don’t work: Form inside a form, is that alright?) and we want to test the case where the parent should be added to get the real performance impact as per comment below

enter image description here


Added third option performance as requested in comment

Answered By – Craig MacGregor

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published