jQuery

jQuery is a JavaScript library that simplifies common tasks that once required many lines of code (e.g., AJAX, DOM manipulation, and event handling), and wraps them inside a single method call.

Usage

jQuery can be added to a website by either downloading the library from jQuery.com or including it from a CDN.

Including a downloaded library looks like this (downloaded into the same directory as the page using it):

<head>
<script src="jquery-3.6.0.min.js"></script>
</head>

Including from a CDN (in this case Google) looks like this:

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.js"></script>
</head>

Syntax

jQuery syntax consists of selecting HTML elements and then performing some sort of action on them.

$(selector).action()

The following syntax is used:

  • $(): A leading function used to access jQuery.
  • selector: Uses CSS selector syntax for selecting HTML elements.
  • action: One of the many jQuery methods to be performed on the selected element(s).

It is best practice to perform jQuery actions only after the document is finished loading, otherwise, some actions might fail. To insure this, it is best to enclose jQuery code inside a document-ready event:

$(document).ready(function(){
  // jQuery code goes here
});

Below is a list of jQuery methods:

jQuery

.click()
Attaches an event handler to the "click" event of an HTML element.
.dblclick()
Attaches an event handler to the "double-click" event of an HTML element.
.hide()
Hides an HTML element.
.html()
Gets or sets the contents of an HTML element.
.show()
Shows a hidden HTML element.
.text()
Gets or sets the text of an HTML element.

Contributors

Interested in helping build Docs? Read the Contribution Guide or share your thoughts in this feedback form.

Learn JavaScript on Codecademy