jQuery at a glance

August 7, 2023 - Reading time: 9 minutes

What

A very popular JavaScript library which offers a lot of methods for common tasks. It includes useful features such as:

  • HTML/DOM manipulation
  • CSS manipulation
  • HTML event methods
  • Effects and animations
  • AJAX
  • Utilities

How

  1. Download or use CDN such as Google's in head section:
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
  2. And start using jQuery methods in a separate document when all DOM is built
    $(document).ready(function(){
      // jQuery methods go here...
    });
    Using jQuery within the document calling it is also fine, it's just a suggestion for clarity.

Syntax

Basic syntax

Basic syntax is: $(selector).action();

The selector is mainly CSS (for instance "#id") but can also be the keyword this to find the current element.

Event syntax

Event syntax is: $(selector).eventname();

Use vanilla JavaScript event names. A noticable special event would be hover() (combination of mouseenter() and mouseleave())

Chaining

Run multiple jQuery methods by chaining them:

$(selector)
     .action1()
     .action2
     .action3

(indentation and line breaks are fine)

Selection of methods

Effects

$(selector).hide(speed,callback); (same goes with .show() and .toggle(), parameters are optional)

DOM Manipulation

Get or set existing nodes

$(selector).text(); // the text content of selected element
$(selector).html(); // the HTML content of selected element
$(selector).val(); // the value of form fields
$(selector).attribute("attributename"); // the attribue value

Without parameters, you'll get. For setting, pass a parameter

$("#test1").text("Hello world!");
$("#test1").attribute("href", "https://another.website");

Note that .text, .html and .val methos come with a callback function having 3 parameters: the index of the current element in the list of elements selected and the original value. For instance:

 $("#test").html(function(i, origText){
    return "Old html: " + origText + " New html: Hello <b>world!</b>
    (index: " + i + ")";
  });

Add or remove nodes

To add content at the end of the selected element, use .append("new content") and use .prepend("new content") to add at the begining of the select element.

You can also target the position right after the targeted element with .after() and before with... .before().

The methods acceps several parameters.

Remove the selected element with .remove() or remove all childs within the selected element  with .empty().

You can also filter down what should be removed by passing one or more CSS selectors, separated with comas, as a parameter $("p").remove(".test, .demo"); .

CSS Manipulation

$(selector).addClass(); // add class (could be several)
$(selector).removeClass(); // remove class (could be several)
$(selector).toggleClass(); // adds or remove class given
$(selector).css("propertyname"); // the property value

Separator between classes is a blank space $("#div1").addClass("important blue");

In .css method, if you want to pass property + value, use this syntax:

  • single: $("p").css("background-color", "yellow");
  • multiple: $("p").css({"background-color": "yellow", "font-size": "200%"});

DOM navigation

Basic syntax  $(selector).relation();

It is possible to add an optional parameter (a CSS selector) to filter the search.

Up tree

$(selector).parent() // returns direct parent element
$(selector).parents() // returns all ancestor elements up to document's root
$(selector).parentsUntil("div") // returns all ancestor elements in between

Down tree

$(selector).children() // returns all direct children
$(selector).find() // returns all descendant elements down to last descendant

Right / left tree

  • siblings() // all sibling elements
  • next() // next sibling element
  • nextAll() // all next siblings elements
  • nextUntil() // all siblings in between
  • prev() // previous sibling element
  • prevAll() // all previous siblings elements
  • prevUntil() // all siblings in between (backwards)

Filter

Most basic filtering methods are first(), last() and eq() to select a specific element based on its position.

And also of course filter(): elements that don't match are removed from the selection and not(): the opposite.

AJAX

load

Load data from a server and return it in the selected element: $(selector).load(URL,data,callback);

Optional callback function can have these three parameters:

  • responseTxt - resulting content if the call succeeds
  • statusTxt - status of the call
  • xhr - XMLHttpRequest object

Example from W3schools.com:

$("button").click(function(){
$("#div1").load("demo_test.txt", function(responseTxt, statusTxt, xhr){
if(statusTxt == "success")
alert("External content loaded successfully!");
if(statusTxt == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
});
});

get / post

You can also exchange data with a sever using an HTTP request (GET or POST).

$.get(URL,callback);
$.post(URL,data,callback);