Categories
jQuery

jQuery 1.12 Context and prevObject Properties

I was recently stumbled upon issues that made me realize that context object was deprecated in jQuery 3.0. As I figured it out, I also figured what prevObject actually is.

NOTE: selector property is also deprecated in jQuery 3.0. That’s why WordPress stuck in jQuery 1.12 for backward compatibility reason. Bunch of things are deprecated in jQuery 2+ one simply doesn’t know when things will break if jQuery, which is highly used as dependency, gets updated.

context Property

Here’s an easy way to understand what context property is. Let’s say you have this:

console.log($('div'));

The returned jQuery object instance:

{
  0: div,
  context: document,
  length: 1,
  selector: 'div',
}

Most of the time, context will be current document unless you’re in event callback attached to other element like this:

$('div').on('click', 'h2', () => {
  console.log($(this));	
});

If this is the case, the returned jQuery object instance will be:

{
  0: h2,
  context: div, // the context property
  length: 1,
  selector: '',
}

Notice that the context is now element where the event callback is attached to.

prevObject Property

prevObject property is basically the jQuery object instance before the current selector object. Let’s say you do this:

console.log($('div').find('h2'));

The returned jQuery object instance will be:

{
  0: 'h2',
  context: document,
  length: 1,
  prevObject: a.fn.init [h2],
  selector: 'div h2',
}

References


Photo by Greg Rakozy on Unsplash

Leave a Reply

Your email address will not be published. Required fields are marked *