Skip to content Skip to sidebar Skip to footer

When To Use Jquery's .find()

When would I use jQuery's .find()? For example, $('tr').find('.someClass'); is equivalent to $('tr .someClass') So, when would be a good example of when you would use .find() over

Solution 1:

The answer is whenever possible.

It is always more performant than having children / multi-item / CSS / context selectors, and is the fastest-performing traversing mechanism.

jsPerf to show what I mean.

The only time you may even consider not using it is if you only want to select items that are direct children, and those children happen to have the same class as their children that you don't want to select. This is a job for .children(), but is a very rare case.

Solution 2:

It depends on what you're selecting.

As the number of elements selected by $('tr') goes up, .find will become more expensive.

Generally it's best to do whatever will result in touching the least number of elements. When you're dealing with just 2 elements (a parent and a child), the .find will clearly be faster because it's just one parent getting it's children and filtering to a selector. But when there are, say, 200 parents, it's going to have to iterate over all 200 and search for children within each. By using a selector to begin with, you never touch all of the parents, you just go directly to the child elements. Even then, the performance of one vs the other will differ from browser to browser.

spend less time worrying about these micro optimizations until it's a real problem you are trying to solve, and at that point, solve that one problem rather than trying to figure out a general rule to follow.

Solution 3:

.find() is simply for searching for descendants of a jQuery object that represents a DOM element.

An example use case would be passing a jQuery object that represents a form element into a form parsing function, and then using .find() to grab different values from the form's child inputs.

Instead of converting the form into a jQuery object every time you want to grab an element, it's cheaper to assign the jQuery form object to a variable, and then use .find() to grab the inputs.

In code, this:

var$form = $('#myFormId'),
    firstName = $form.find('input[name="firstName"]').val(),
    lastName = $form.find('input[name="lastName"]').val();

is cheaper then this:

var firstName = $('#myFormId input[name="firstName"]').val(),
    lastName = $('#myFormId input[name="lastName"]').val();

It's also cheaper then using .children(), see this reference, unless the items you are searching for direct children of the jQuery object you are operating on.

Hopefully that makes sense :)

Solution 4:

Great answers above, but just wanted to add .find() is a descendant based search. So it will find all the children of the Dom element being selected.

Post a Comment for "When To Use Jquery's .find()"