jQuery Tutorial by Example

By Xah Lee. Date: . Last updated: .

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.

As of 2018, you may not want to use JQuery, becuase JavaScript and browsers today have lots of the same features of jquery, builtin.

Add JQuery Lib

Add the following to your pages:

<script defer src="http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

or

<script defer src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-3.3.1.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.

as of 2018-10-28, latest is version 3.3.1

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 defer 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 Dollar Sign in JavaScript]

To stop $ as alias to jQuery, call:

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

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 array-like object, and has a .length property.

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 do jQuery Object's methods do?

The jQuery Object's methods let you:

and more.

A Simple Example of JQuery Use

Here is 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 $(cssSelector ).click(f );

  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 f, is a event handler function. This gets attached to the click event of those selected elements.
  4. The this in the function body has the value of each element the function is applied to. [see What is 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 is 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.

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

What is the Difference Between jQuery 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.

Use $() to Call a Function

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

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

Note, $(f) is same as $(document).ready(f). [see JS: Load Order, defer, async, module]

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.

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

General JQuery Object Methods

Get/Set CSS Property Values

$().css(cssPropertyName)
get a CSS property's value, of the first element in $(). Return a string.
// get a CSS property's value, of the first selected element
$("div.x86666").css("color"); // sample return value "rgb(255, 0, 0)"
$().css(cssPropertyName, value)
set a CSS property's value to all elements in $().
// set a CSS property to all selected elements
$("div.e11191").css("color","green")

Get/Set HTML Attribute Values

$().attr(AttributeName)
Get the value of attribute AttributeName of the first element. Return 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"
$().attr(AttributeName, value)
set the value of attribute AttributeName to value, for all selected elements. Return a jQuery Object.
<div id="x21387" class="c68614">something</div>
// set the class value of a html element with id #x80151, to "mm"
$("#x21387").attr("class","mm")

Add/Remove Class Attribute Value

$("a").addClass("x")
add class "x" for all "a" elements.
$("a").removeClass("x")
remove class "x" for all "a" elements.

Add Event Handler

$("a").click( function(e){alert("hi");} )
add a “click” event handler to all link tags “a”.
BUY ΣJS JavaScript in Depth