Simple jQuery

Simple jQuery

This post is part of a project to move my old reference material to my blog. Before 2012, when I accessed the same pieces of code or general information multiple times, I would write a quick HTML page for my own reference and put it on a personal site. Later, I published these pages online. Some of the pages still get used and now I want to make them available on my blog.

Photo by [Charlie Harutaka]( by Charlie Harutaka

jQuery is a fast, concise, JavaScript library that simplifies how to traverse HTML documents, handle events, perform animations, and add AJAX.

Including it in a Page

The simplest method is to use the jQuery CDN and include jQuery just before the closing </body> tag.

<!doctype html>

  <script src=""></script>
      $(function() {
        // Put your jQuery code here.

Selecting Elements

Most methods in jQuery require you to target an element(s) on the page. Selection looks like this:


Selects all <p> elements.


Selects an element that has the id “target”. For example <div id=”target”>.


Selects all elements with the class “selectme”. For example <div class=”selectme”> or <li class=”selectme”>.

For more information about selecting elements, visit

Manipulating Selected Elements

In all three of the examples above, the method being called was doSomething(). There’s no such method as doSomething() in the default jQuery library, but here are some real ones you can use:


Adds the class “highlight” to every span on the page.

$('p').html('Replacement text.');

Sets the HTML inside every <p> to “Replacement text.”

$('img#header').attr('alt', 'Sky with clouds');

Changes the “alt” attribute of <img id=”header” …> to “Sky with clouds.”

For more information about manipulation, visit


Events are a way to perform an action when a condition is met. Some examples are:

$('#target').click(function() {
  // Do something.

Executes when the user clicks on “target.”

$('#target').hover(function() {
  // Do something.

Executes when the user hovers over “target.”

$('#target').focus(function() {
  // Do something.

Executes when “target” gains focus (user clicks or tabs into it).

Learn more about events at