jQuery Tutorial by Example

, , …,
Want to master JavaScript in a week? Buy Xah JavaScript Tutorial.

This page is a basic tutorial on JQuery. To use JQuery, you should know the basics of the JavaScript language. 〔➤ 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. jQuery's home page is at jquery.com.

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>

or

<!-- 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 & 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.

「$()」 & 「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. 〔➤ JavaScript: 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
$("p").css("color","red");

The $(…) returns a object we'll call the jQuery Object. The jQuery Object is a array-like object, and has a .length property. 〔➤ JavaScript: What's 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. 〔➤ JavaScript: What's 「this」 in a eventhandler?
  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.

syntaxmeaning
$(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. 〔➤ CSS Selector Syntax
$(css selector, context)narrow search within context. The context can be {DOM Element, document object, jQuery Object}.

What's 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.)

syntaxmeaning
$(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.

syntaxmeaning
$(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.

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

$(ƒ) same as $(document).ready(ƒ). 〔➤ JavaScript Execution Order; HTML5 Asynchronous JavaScript

jQuery Object's Methods & 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
syntaxmeaning
$(…).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
$("div.e11191").css("color","green")

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"
$("#id21387").attr("class","mm")

jQuery method .attr() set value test

jQuery Documentation#p=attr

Adding or Remove a HTML Class Attribute Value

$("a").addClass("myClassName");
$("a").removeClass("myClassName");

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

blog comments powered by Disqus