views:

15

answers:

2

Is this selector valid? and what $(this) refer to?

$('div', $(this).parents('div'))

i just learn javascript and jquery, thanks

A: 

It's valid. It's taking all of the parent divs of this and then finding all of the divs underneath them. Breaking it down:

var jq = $(this);                // Get a jQuery object for `this`
var parents = jq.parents('div'); // Find all of its parents that are divs
var divs = $('div', parents);    // Find all divs under those parent divs

The result is a jQuery object with matches for all of the divs that are descendants of the divs that are parents of this. More here and here.

Example: Let's assume that this initially refers to the input element foo below:

<div id='d1'>
    <div id='d2'>
        <input id='foo' type='button'>
        <div id='d3'>
        ...
        </div>
    </div>
    <div id='d4'>
        <div id='d5'>
        ...
        </div>
    </div>
</div>

$(this).parents('div') will match d1 and d2. Then $('div', parents) will match:

  • d3
  • d2 (beacuse in addition to being one of the parents, it's a child of d1)
  • d4
  • d5
T.J. Crowder
A: 

Actually:

$('div', $(this).parents('div'))

The jQuery function (jquery() or $()) needs at least one parameter of selector and second optional one is for a context, in your example $(this).parents('div').

So, above code is going to perform on $(div) which is inside the context $(this).parents('div'). However, this is not that much usual, it most cases, it looks like:

$('#element').click(function(){
    $('div', this).addClass('some class');
});

In the above case, this refers to #element and then adds class to div inside that.

Sarfraz