What’s $(this)??

I am far from being a javascript Ninja. But I do try to catch up.
The first JS library I used to work with was Prototype + Scriptaculous. Unfortunately These are not maintained anymore. So I moved on to the next Buzz – Mootools.

I really like Mootools. It’s a great powerful library. Unfortunately, Mootools’ golden days seem to be over. The new king is now Jquery. The fact that all the big players – Yahoo, Google, Microsoft implement this library for all their projects makes it a safe bet and the immediate choice for any developer. So although Mootools is great and my own choice, me too, I should move on.

At start I found Jquery rather annoying. On one hand it’s easy enough to point to a DOM element using the same notation as being used on your stylesheet. On the other hand I now need to learn new references to all its attributes and remember to pass them as arguments in a function, instead of the original and intuitive assignment. Html(‘bla’) instead of innerHTML = ‘bla’, css() instead of style, etc.. On top of everything – what’s with the $(this)? How does it relates to ‘this’? This is mind boggling.

So here’s the deal, in a nutshell:

Whenever we call the Jquery function, or its alias $, with a jquery DOM selector as a parameter, we get in return an array of elements.

For instance, if we point to ‘.my_class’, i.e. pass it as a parameter to Jquery (), we get back an array that contains all the elements in the page that have the ‘my_class’ class.

And here’s the big thing: we can refer to the first member of this array as ‘this’.
$(this)[0] == this
That means, that if we point only to a unique element:
$(‘#my_unique_element’)[0] == this;
$(‘#my_unique_element’).html(‘new content!’);
Is as good as
$(‘#my_unique_element’)[0].innerHTML = ‘new content!’;

As this is a reference to an element within its own context, $(this) means we pass it as a parameter to the Jquery function.

When we are within the context of $(‘.my_elements’), ‘this’ is any element that has a ‘my_elements’ class, and $(this), is that same element being passed to the $(Jquery) function. That way we can apply all the Jquery magic on it.

Keeping this in mind may also help us making our code more efficient: As Jquery almost never throws error at selecting a none-existance dom element, we now have a way to manually test that it indeed exists before we go on trying to manipulate it, simply by checking the returned array length:

if ($(‘div.my_elements’).length) { … }
When it equals 0 – i.e – jQuery returned an empty array – no such element on the DOM, let’s move on!