0

Once you have a jQuery object like the one you get by doing:

var car = $('li .car');

I saw code doing the following:

var carChildren = $(car).children('span');

What is the point of it? Why not just use the .children method on the already jQuery var car like so?

var carChildren = car.children('span');
3
  • 6
    The point is wrong usage. Don't do this. Commented Sep 28, 2016 at 9:34
  • 1
    there is no point in recreating jquery object of existing object. Use second approach. Commented Sep 28, 2016 at 9:34
  • 1
    When one is making a polymorphic function that accepts string selectors, jquery objects, dom nodes etc he/she might need it function doSmthToCar(car) { $(car).children(...)} even if you are passing jquery object var car = $(); doSmthToCar(car). Otherwise it is just a wrong usage. Commented Sep 28, 2016 at 9:40

1 Answer 1

1

In short:
There is no reason for doing this. But it makes no difference in result too. It's basically just bad practice. So don't do it.


TL;DR
As said before, it makes no sense and it makes no difference. Let's think about what the lines do. To be clear we write it in one line:

var car = $('li .car');
var carChildren = $(car).children('span');

Is the same as:

var carChildren = $($('li .car')).children('span');

Nobody would ever do it this way! The reason someone would write $(car) is that they meight be confused by things like $(this), what often is write many times right after.

Why does it work anyway?

If you write $(car) jQuery will notice that car is already a jQuery object and replace it as it's context. But that is a unnecessary task what can be saved.

This said, you can directly use car as context too.

var carChildren = $('span', car);
Sign up to request clarification or add additional context in comments.

1 Comment

The flexibility is probably seen as a bonus, but it really lets you do some crazily stupid things also.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.