jQuery add() function and the context of jQuery objects

Posted by patrick on Stack Overflow See other posts from Stack Overflow or by patrick
Published on 2010-04-13T01:47:49Z Indexed on 2010/04/13 1:52 UTC
Read the original article Hit count: 321

Filed under:
|
|

Given the following HTML example...

<div id='div1'>div one</div>
<div id='div2'>div two</div>

...I found that the following jQuery code...

$('#div1').click(function() {

    var $d = $(this);    // Using 'this' instead of '#div1'

    $d.add('#div2').remove();
});

...would not add #div2 to the set referenced by $d, but this code...

$('#div1').click(function() {

    var $d = $('#div1');    // Using '#div1' instead of 'this'

    $d.add('#div2').remove();
});

...successfully added #div2.

Upon consulting firebug, I found that using $(this) gave the jQuery object a context of #div1, but doing $('#div1') gave the object a context of document.

Given this information I tried...

var $d = $(this, document);

...and the add() function worked as expected.

So here's the question. Could someone please explain to my why a different context is assigned when using $(this) vs $('#div1')?

Thanks much!

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about object