The Basics of jQuery

The nuts and bolts of jQuery syntax and usage.

Scroll down...




Now that you've had a taste of what jQuery can do, let's start really getting into it. This lesson will cover the full basic usage of jQuery, including:

  1. Basic Selectors
  2. Inspecting jQuery objects
  3. Implicit and explicit iteration
  4. Chaining methods
  5. Refreshing jQuery objects and collections
  6. Creating elements

Our goal is to show you how to create and work with jQuery objects. Future lessons will focus more on what methods are available to you and what you can actually do with them.

The Basic Process

Using jQuery is almost always a 2-step process:

  1. Locate the element(s) you want to modify by using the top-level $ function, which will return them as a jQuery Object which acts like an "array" of DOM objects. This jQuery Object is commonly called the "selection".
  2. Use any of the many methods available on the jQuery object to modify the returned DOM object(s) it contains. We'll cover these specific methods more in later lessons.

To do these steps yourself, you will need to know how to locate elements and then what you can do with them. We'll cover the first part and some of the second in this lesson.

Basic Selectors

To locate elements on the page, you pass a selector or series of selectors to the $ function. These selectors look just like CSS ones, so the syntax should come naturally:

// find the element with this ID

// find all elements with these classes

// find all div elements

// find list items nested under elements with class
$(".articles li");

Just remember that the selection returned is a jQuery Object which you will probably save to a variable. If you later add elements to the page, this variable will NOT be updated unless you re-run the query!

Variable Naming Convention

When you're working with a selection of DOM objects returned by a query, you'll frequently save that jQuery selection to a variable for later use.

Because jQuery objects have super powers when compared to normal objects, it's conventional to differentiate the variables you've stored them in by prepending the jQuery ones with the $ sign. There's no special functionality granted by this symbol -- it's just another valid variable name that people decided to use with variables storing jQuery objects.

We'll use it from now on:

// save the jQuery object aka Selection to a variable
var $headers = $(".header");

Alternate jQuery Object Inputs

If you want to create a jQuery object without explicitly querying the DOM using a string like $("#some-id"), the $ function also handles a comma-separated list of selectors or even plain-old-JavaScript (POJ?) selectors:

// create a jQuery object from a normal JS
// DOM traversal
$( document.body.children[0] );

// combine selectors with normal JavaScript DOM traversal
// Note that it will look for the LEFT element WITHIN
// the right element
$( 'li', document.body.children[0] );

// make a selection within a previous selection
// Again, now looking for `a` tags inside `p`
$( 'a', 'p' );

// create a jQuery object from a list of DOM elements
// (not terribly common)
$( [ window, document ] );

Inspecting jQuery Objects

How do you know if your query returned anything? You'll frequently want to check that before doing anything that might otherwise cause problems.

The easiest thing to do is treat your jQuery "array" as a normal array and check its length:

// if length is 0... remember that 0 is falsey!
if ( $('#not-finding-this').length ){
  // will not run

Make sure you do not rely on the return value of the method itself. That's because a jQuery query will return an empty jQuery Object even if nothing is found and that is TRUTHY:

if ( $('#not-finding-this') ){
  // This will always run because
  // an empty jQuery object is TRUTHY

Grabbing Elements in a jQuery Selection

The jQuery Object (aka the Selection) is an array-like object that contains a collection of normal DOM objects. If you want to access one of those DOM objects directly, you can dig into the "array" to grab it, either using the standard JavaScript bracket notation or a special jQuery function called get which accomplishes the same thing.

If you want to pull one of the DOM elements out of your jQuery Object but as another jQuery object, use the eq method instead. This saves you from having to "jQuery-ify" the basic DOM object by running another $ function yourself:

// Grab all the paragraphs into a jQuery Object
var $manyObjects = $("p");

// Normal JavaScript array getter
// Note the lack of $ before the variable
// because the object returned is a normal
// DOM element
var firstP = $manyObjects[0];

// And the same, using the special jQuery array
// getter.
// Note the lack of $ before the variable
var firstP = $manyObjects.get(0);

// Now let's use the `eq` method, which
// returns the jQuery-object-version instead
// of the boring DOM version like `get` does
// Note that we now use the `$` variable
var $firstP = $('p').eq(0);

// `eq` is really just doing this behind the scenes
// (which we'll cover in a minute)
var $firstP = $($('p').get(0));

As we covered in the example, the object returned by get or the bracket notation (e.g. $manyObjects[0]) is just a plain old DOM object (PODO? ...Hodor?) and not a jQuery object. That's why we named our variables the old fashioned way (someVar) instead of the jQuery way ($someVar). They have no jQuery superpowers... unless you supercharge them by making them into jQuery objects:

// Fill up our jQuery selection with paragraphs
var $manyObjects = $("p");
//=> [ <p>​…​</p>​, <p>​…​</p>​, <p>​…​</p>​, <p>​…​</p>​, <p>​…​</p>​, <p>​…​</p>​, <p>​…​</p>​, <p>​…​</p>​, <p>​…​</p>​, <p>​…​</p>​, <p>​…​</p>​, <p>​…​</p>​, <p>​…​</p>​, <p>​…​</p>​, <p>​…​</p>​, <p>​…​</p>​, <p>​…​</p>​, <p>​…​</p>​, <p>​…​</p>​, <p>​…​</p>​, <p>​…​</p>​, <p>​…​</p>​, <p>​…​</p>​, <p>​…​</p>​, <p>​…​</p>​, <p>​…​</p>​, <p>​…​</p>​, <p>​…​</p>​, <p>​…​</p>​, <p>​…​</p>​, <p>​…​</p>​]

// Grab just the first paragraph, which will
// be a plain-old-DOM-element (note the lack
// of brackets around it in the console output)
var oneObject = $manyObjects.get(0);
//=> <p>​…​</p>​

// Now turn that paragraph into a jQuery object
// Note the brackets are now around it
var $jQueryObject = $(oneObject);
//=> [<p>​…​</p>​]

// As we saw above, you can just use `eq`
var $firstObject = $manyObjects.eq(0);
//=> [<p>...</p>]

// Or use a shortcut method we'll see later
$firstObject = $manyObjects.first();
//=> [<p>...</p>]

Basically, we extract a naked DOM element from the jQuery object and then wrap it in the gentle embrace of jQuery, turning it into a jQuery object in its own right. Now we can run all the usual batch of jQuery methods on it.

In the examples above, we just plucked a single DOM element from within a collection of them provided by our jQuery object. You might be wondering -- If a jQuery object can contain either a single DOM element OR a collection of DOM elements, what's the difference between these two?

The answer is: Not much. jQuery will implicitly iterate through the collection anyway, as discussed below.

Implicit and Explicit Iteration

You'll often work with single elements inside a jQuery object, for instance, if you've searched for just one object (like an ID) or plucked a specific DOM element from within a previous jQuery object like we just saw.

In this case, you can immediately start executing jQuery methods on that object:

// let's add a class with jQuery's `addClass` method

Just to make things easy for you, you can do this same exact thing even on a collection of objects returned by your jQuery selection, and it will perform the action on EACH element inside:

//=> [  <p class=​"paragraph">​…​</p>​,
        <p class=​"paragraph">​…​</p>​,
        <p class=​"paragraph">​…​</p>​ ]

This is known as Implicit Iteration and it makes your life a lot easier.

What happened above is the same thing as Explicitly Iterating, just with a lot less work. The Explicit format takes advantage of jQuery's each method (it's back!), and would look something like:

// Note that the index is passed in FIRST!
// This is guaranteed to cause you grief until
// you get it in your head
$( 'p' ).each(function( index, element ) {

  // element is the naked DOM element
  // so we need to manually turn it into
  // a jQuery object by passing it into the
  // `$` function
  $( element ).addClass("lets-boogie");


Note: Don't get confused between the normal-JavaScript forEach and jQuery's each -- they're similar and accomplish similar goals but are not actually identical!

Obviously, that seems like a lot of work, so we take advantage of the implicit iteration wherever possible.

"This" in jQuery

Inside the each method, this is set to the naked DOM element which is being passed in (element in the example above). In fact, you can count on pretty much any iteration function or callback function in jQuery passing in the "current object" as this.

In plain JavaScript, this is just the global window inside an iteration. jQuery setting it to the current element is another way it's trying to help you out:

// Output our `this`
function foo(){
  console.log( this );

// JavaScript iteration over an array
// ... `this` is the global window
[1,2,3].forEach( foo );
// Window {top: Window, window: Window, location: Location, external: Object, chrome: Object…}
// Window {top: Window, window: Window, location: Location, external: Object, chrome: Object…}
// Window {top: Window, window: Window, location: Location, external: Object, chrome: Object…}

// jQuery iteration through the page's paragraphs
// ... `this` is the passed object (paragraph)
$( 'p' ).each( foo );
<p class="scroll-prompt" style="display: block;">Scroll Down...</p>

Each and Map

jQuery provides more than just the jQuery-object's each method -- it also provides a top-level utility method of the same name as well as two similar implementations of the familiar map method. Don't be confused by seeing two versions of each and map in the documentation -- one runs directly on the jQuery object (like an instance method) and the other is a top-level utility method where you need to pass the collection in (like a class method).

The top-level utility methods are designed to be used with any sort of collection (not just a jQuery object). You can use them with standard arrays.

// Iterate through a jQuery object by using
// its `each` method
$("li").each(function(index, obj, array){
  console.log("LI contents are " + $(obj).html());

// Or map the result to an array using the jQuery
// Object's `map` method instead.
// Note that this returns a jQuery-wrapped collection
// and if you just want a plain object, call `get` on
// it with no arguments
var listIds = $( "li" ).map( function(index, element) {

// Now use the top-level jQuery `each` on any
// collection (an Array for example)
$.each([1,2,3], function(index, element){
  console.log("Element is " + element);
Element is 1
Element is 2
Element is 3
//=> [1,2,3]        // Returns original collection

// Same works with `map`
// because it's dumb and wanted to comply with
// ECMAScript 5.  And just to confuse you.
// Note that this returns a boring old array
// so you don't need to call `get` to de-jQuery it
$.map([10,20,30], function(element, index){
  return "el" + index + " is " + element;
//=> ["el0 is 10", "el1 is 20", "el2 is 30"]

For greater clarity on either each or map, see this article on

Chaining Methods

You can chain jQuery methods together because most of jQuery's methods return another jQuery object. It's conventional to list additional methods on multiple lines:


    // Note that, as explained above, `this`
    // is the current element
    // We have to turn it into a jQuery object
    // to actually use jQuery methods on it
    $( this ).addClass("clicked")


Refreshing jQuery Objects (and Collections)

Let's take a minute and think about the order of operations that are occurring with jQuery. We said above that the jQuery Object returned by a selection is static, meaning that if you later add new DOM elements which the query would otherwise catch, the now-stale query will not contain them.

Despite not "refreshing" when the DOM refreshes, jQuery selection objects aren't really static -- they have a direct link to the DOM element(s) they represent. Whenever you execute a "getter" method (to return a value) or a "setter" method (to set a value), the real element on the page is queried first. In the case of a "setter", the change is made to the actual element on the page immediately.

For example:

// Grab the first paragraph element on the page
// Recall that `eq` pulls it out as a jQuery Object
$firstP = $("p").eq(0)
//=> [<p>​…​</p>​]

// "get" its class to verify none exist yet:
//=> undefined

// ASSUME: we manually went into the DOM and
// added a class called "fluffy-bunny".
// Now, even though we haven't manually re-queried,
// the class shows up when we ask for it.
// This shows that specific jQuery objects refresh
// themselves when necessary
//=> "fluffy-bunny"

// ASSUME: we manually went into the DOM and
// added a new class called "fluffier-bunnies"
// Here, we'll remove that class without manually
// re-querying for that object.
// Again, jQuery first refreshes the object, sees
// that there is, in fact, a "fluffier-bunnies"
// class there, and removes it for us
//=> [<p class=​"fluffy-bunny">​…​</p>​]

So, to sum that up:

  1. jQuery objects containing collections will not update that collection unless manually re-querying for it. But...
  2. When running any getter or setter methods on individual jQuery objects, they will be refreshed to reflect the current state of the DOM prior to running those operations.

Creating DOM Elements

jQuery doesn't just grab existing elements, it can also create them. In jQuery, if you pass an element (eg <p>) into the $ function, it will create a DOM element in memory which is contained inside a jQuery Object. This hasn't been placed on the page yet, but you can do that later:

// Creates a jQuery-wrapped `<p>` element for
// later placement onto the page
$myNewP = $( '<p>' );
//=> [<p>...</p>]

// Creates a full-featured element for later placement
// onto the page
$myNewerP = $( '<p class="howdy">Howdy!</p>' );
//=> [<p class=​"howdy">​Howdy!​</p>​]

You might be wondering how jQuery can sometimes view its input as a search query and other times as instructions to create a new element. Good question. Magic!!!

...Actually, it will look at the query string you've passed it and, if that query string is wrapped in tags, jQuery will create the new element instead of searching for an existing one. So versatile!

This isn't some esoteric feature either -- it's used fairly often to create elements for the page. Sometimes, you might construct the entire web page just using jQuery.

A more explicit way to create an element is to pass it an object with attributes:

$( '<p>', {
  html: 'Howdy!',
  'class': 'howdy'  // << class is a string because it's a reserved word

Note: that is generally preferred to create elements by chaining jQuery calls rather than string concatenation.

For example:

// bad
var $h1 = $(
  '<h1 id="my-heading" class="bar" data-cool="whoa">' +
    '<a href="#" title="Awesome" data-sweet="dude">Awesome</a>' +

// good
var $a = $('<a></a>')
  .attr('href', '#')
  .attr('title', 'Awesome')
  .attr('data-sweet', 'dude')

var $h1 = $('<h1></h1>')
  .attr('id', 'my-heading')
  .attr('data-cool', 'whoa')

Learn More

To learn more about the jQuery object, see the article on it. See the Resources tab for lots more information.

To look through the jQuery source code in an easily searchable fashion (totally recommended for a Saturday night!), check out this source code displayer from James Padolsey.

Code Review

The important bits of code from this lesson

// find the element with this ID

// find all elements with these classes

// find all elements

// find list items inside class
$(".articles li");

// look for `<a>` inside `<p>`
$( 'a', 'p' );

// Name jQuery object variables with `$`
var $headers = $(".header");

// jQuery-ify the first element returned
var $firstLi = $($('li').get(0));

// ...or just use the `eq` method, which
// does that for you:
var $firstLi = $('li').eq(0);

// Implicitly iterate and run function on them all

// Explicitly do the same thing
$( 'p' ).each(function( index, element ) {
  $( element ).addClass("paragraph");

// Chain methods on multiple lines
    $( this ).addClass("clicked")

// Create a DOM element for later placement
$( '<p>' );

var $a = $('<a></a>')
  .attr('href', '#')
  .attr('title', 'Awesome')
  .attr('data-sweet', 'dude')

var $h1 = $('<h1></h1>')
  .attr('id', 'my-heading')
  .attr('data-cool', 'whoa')

Wrapping Up

As a quick review of what we just covered:

  1. The primary responsibility of the $ function is to query the DOM and return a selection of DOM elements wrapped in a jQuery object. It can do so by accepting a CSS-like selector syntax or even JavaScript.
  2. $ can also construct a DOM element for you if you pass it a valid element string.
  3. Elements inside the jQuery Object will be iterated over implicitly if you run a jQuery method on the whole collection.
  4. If you choose to explicitly iterate, remember that each element will be a plain DOM object until you turbocharge it by turning it into a jQuery element with $(...) or pull it out using eq.

As usual, there's nothing magical about all this except a bunch of clever JavaScript on the back end, and you'll get used to its conventions as soon as you start using it.

In this lesson, you primarily learned how jQuery works and how it treats the objects you return. In the next few lessons, we'll begin looking more at the specific things you can do with jQuery and the methods it provides.

Sign up to track your progress for free

There are ( ) additional resources for this lesson. Check them out!

Sorry, comments aren't active just yet!

Next Lesson: DOM Traversal and Modifcation