What are jQuery objects?

Whenever a jQuery programmer sees code like this:

he/she knows a jQuery object is created.

Having some understanding of what objects are (in programming) is important if you want to understand jQuery scripts.

You already understand what objects are in everyday life. A table is an object; a car is an object, etc.

Objects can have properties: a table has legs; a car has wheels and an engine, etc.

Think of jQuery objects in the same way: as soon as an element on a web page becomes a jQuery object you can make use of its properties.

Authors of books and tutorials about jQuery have used various means to give readers an understanding of what it means when something becomes a jQuery object.

I think of changing elements on a web page into objects as a means to give them more power. They can then do things they couldn’t do before.

I am going to use a metaphor to explain objects. When you put a box into a car it can be driven somewhere else.  When you put it in the cargo hold of a plane it can fly. If you leave the box alone it just sits there and does nothing. You give the box extra mobility when you put it into a car or a plane. When you put it in a car it can move but only on the ground. In a plane it can also move but it can leave the ground as well.

When you change an element on a web page into a jQuery object you can attach methods to it. The keywords “tooltip” and “popover” are in fact two different methods. So the same element has different capabilities when you link it to the method “tooltip” compared to when you link it to the method “popover”. The same way the box could move differently in the car compared to in the plane.

Objects hold collections. When we look at the code examples at the start of this post we see 3 different collections:

  • the first collection consists of only one item: an element with the ID ‘element’.
  • the second collection consists of all the paragraphs on the web page.
  • the third object holds all the elements on the web page with the class ‘class’.

When a method is attached to the jQuery object it will only affect that particular collection.

With jQuery you do not have to write a programming script telling it to look for the next element and the next etc. It will automatically look for every element on the page that fit your selection (e.g. all the elements with p tags; all the elements with .class labels). In programming speak: it automatically iterates over all the elements.

But it only iterates over elements that are present in the web page at the time the script was invoked(= run). If you write a program with jQuery that adds an element to the page after the a script was invoked that element will not be part of the object’s collection. And the method attached to the object will then affect all the elements already in the collection but not the element added later on. There are solutions for this but that’s something for another post.

Add your comment