Watchmaker
Watchmaker

Reputation: 5308

Why creating a jQuery object from another jQuery object?

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');

Upvotes: 0

Views: 37

Answers (1)

eisbehr
eisbehr

Reputation: 12462

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);

Upvotes: 1

Related Questions