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

The jQuery Object's methods let you:

and more.

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( 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 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". Return 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 querySelectorAll?

see jQuery Selector vs 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 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.

$(…).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("css_property_name")
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("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")

Get/Set HTML Attribute Values

$(…).attr("attribute_name")
Get the value of attribute attribute_name 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("attribute_name", "value")
set the value of attribute attribute_name 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”.

back to DOM Scripting Tutorial

Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog