jQuery Tutorial by Example

By Xah Lee. Date: . Last updated: .

To use JQuery, you should know the basics of the JavaScript language.

[see JavaScript Basics Tutorial by Examples]

And, you should know the basic of using JavaScript on DOM. For example, how to select a element, how to change its CSS property. See:

jQuery is the most popular JavaScript library. It makes coding JavaScript very convenient, and you don't have to worry about different browser compatibility, because jQuery does that for you.

Adding the jQuery Lib

Add the following to your pages:

<!-- Google hosting -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>


<!-- Microsoft hosting -->
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.0.min.js"></script>

Be sure the version number is latest. Go to jQuery site http://jquery.com/, download section to see what versions are available.

Because jQuery is very popular, so Google and Microsoft both host it. You don't need to place the jQuery lib on your site. Using hosted code is actually better because users probably already have it cached in browser.

Add the following to your HTML pages, after the line that loads jQuery:

<script src="http://example.com/my_js_code.js"></script>

The my_js_code.js is your JavaScript code.

$() and jQuery() Equivalence

The function jQuery is the only function/name exported by jQuery. $ is a name alias to jQuery. Calling $(…) is equivalent to jQuery(…).

Note: JavaScript identifier allow the dollar sign $. There's nothing special about it. [see JS: Dollar Sign in JavaScript]

To stop $ as alias to jQuery, call:

jQuery.noConflict(); // stop $() as alias to jQuery()

jQuery Documentation#p=jQuery.noConflict

JQuery and JQuery Object

In general, all use of jQuery involve calling $(…) then use jQuery methods on the result. For example

// make all paragraphs red

The $(…) returns a object we'll call the jQuery Object. The jQuery Object is a array-like object, and has a .length property. [see JS: Array-Like Object]

Remember, practically all things you ever do with jQuery is to call $(…) to select some elements, you get a jQuery Object, then apply jQuery Object's method on the result.

The $(…) has several different ways to select or create or clone elements, depending on the argument's type (we'll cover below).

The jQuery Object is a array-like object, usually the selected HTML elements, but may also be newly created HTML element.

The most important thing to remember is that $(…) returns a specific object, the jQuery Object, and it has powerful methods.

What does jQuery Object's methods do?

The jQuery Object's methods let you:

A Simple Example of JQuery Use

Here's a typical example of using jQuery. It makes all selected elements red when clicked.

// add click event and handler to paragraph that has class xyz1
$( "p.xyz1" ).click(function() { $(this).css("color","red"); });

click me to make me red.

This code has this form $( css_selector ).click( ƒ );

  1. The $(…) returns a jQuery Object. It is the selected elements.
  2. The .click() is a method of jQuery Object. It is applied to the jQuery Object. It adds the event “click” to those selected HTML elements.
  3. The argument ƒ, is a event handler function. This gets attached to the click event of those selected elements.
  4. The this in the function definition has the value of each element the function is applied to. [see JS: What's the Value of “this” in Event Handler?]
  5. The function body $(this).css("color","red"); is another jQuery call. The $(this) is used as a wrapper to get a JQuery object, so that we can use its methods. We use the jQuery Object method “.css()” on it, to make the element red.

Here's the same thing without using jQuery:

var elts = document.getElementsByClassName("xyz2");
for (var i = 0; i < elts.length; i++) {
    elts[i].addEventListener("click", function (evt) { evt.target.style.color="blue"; } );

click me to make me blue.

How to Use the 「$()」

Use 「$(…)」 as Element Selector

Most common way of using $() is to use it as a CSS selector to get a list of elements.

$(css_selector)css_selector is a CSS selector string, such as "p" or "span.x3" or "div#navbar". Returns a jQuery Object containing matched elements. [see CSS Selector Syntax]
$(css_selector, context)narrow search within context. The context can be {DOM Element, document object, jQuery Object}.

What is the Difference Between jQuery() and DOM's document.querySelectorAll()?

See: What's the Difference Between jQuery Selector and DOM querySelectorAll()?

Use 「$(…)」 as Element Wrapper to Apply JQuery Method

Another common use is to pass a DOM object. The argument may be the object document, or HTML element. The purpose of this is to convert the object to jQuery Object, so you can use jQuery methods on them. (because jQuery object's methods is more convenient to use than plain DOM methods.)

$(element_obj)return a jQuery Object of argument.
$(element_array_obj)return a jQuery Object of argument.
$(object)return a jQuery Object of argument.
$(jQuery_obj)clone a jQuery Object.

Use 「$(…)」 to Create HTML Element

You can pass $() a raw HTML source string. This will create the new element.

$(html_str)Create a HTML element.
$(html_str , ownerDocument)
$(html_str, js_obj)

Use 「$(…)」 to Call a Function

Another way is to pass a function. This function will be called when document is ready.

$(ƒ)call function ƒ when document is ready.

$(ƒ) same as $(document).ready(ƒ). [see JavaScript Load Order]

jQuery Object's Methods and Properties

as mentioned before, the most important use of jQuery is to use the result jQuery Object's methods on the selected elements.

jQuery Object's Properties
$(…).lengthreturn the number of elements.
$(…)[n]return the nth element.
$(selector,…).selectorreturn the selector string selector.
$(…).toArray()converts the result into a true JavaScript Array object.
$(…).contextreturn the second arg passed to $(). If no second arg, the default is the DOM document object.
$(…).jqueryreturn a string that's the version of jQuery.

General JQuery Object Methods

Get/Set CSS Property Values

$(…).css("css_property_name") → get a CSS property's value, of the first element in $(…). Returns a string.

// get a CSS property's value, of the first selected element
$("div.x86666").css("color") // sample return value "rgb(255, 0, 0)"

test here: jQuery method css test (use your browser's web dev toolbox to play with it.)

$(…).css("css_property_name", value) → set a CSS property's value to all elements in $(…).

// set a CSS property to all selected elements

test here: jQuery method css set property test

jQuery Documentation#p=css

Get/Set HTML Attribute Values

$(…).attr("attribute_name") → Get the value of attribute attribute_name of the first element. Returns a string.

<div id="x80151" class="hh yy">something</div>
// get the class value of a html element with id x80151
$("#x80151").attr("class")      // sample output: "hh yy"

jQuery method .attr() get test

$(…).attr("attribute_name", "value") → set the value of attribute attribute_name to value, for all selected elements. Returns a jQuery Object.

<div id="id21387" class="c68614">something</div>
// set the class value of a html element with id #x80151, to "mm"

jQuery method .attr() set value test

jQuery Documentation#p=attr

Adding or Remove a HTML Class Attribute Value


If you have a link like this in your HTML:

go <a href="http://example.com/">here</a>

Now, the above JavaScript code will make it like this:

go <a class="myClassName" href="http://example.com/">here</a>

For all “<a>” tags.

This is useful because you can use CSS to define a particular style, and now you can change all elements to that style when something happens.

Add Event Handler

This adds a “click” event handler to all link tags “a”.

$("a").click( function(event){alert("hi");} );

This means, when user clicks on a link, it'll do what you want, plus the default behavior of visiting to the link.


jQuery Documentation

Liket it? Put $1 at patreon.

Or, Buy JavaScript in Depth