From Code Self Study Wiki
Jump to: navigation, search

This page has notes about jQuery.

jQuery Resources

jQuery Plugins

Selecting and Traversing

Selecting examples:

// all children
$("ul li");
// direct children only
$("ul > li");
$("ul li:first");
$("ul li:last");
$("ul li:odd");
$("ul > li:even");
// multiple selectors
$("#block-5, .author-pic");

Traversing is faster than selecting:


You can use methods instead of filters:


Walking the DOM:

// limit to direct children



Loop through array, like to add some list items to an unordered list:

someThings = [ "a", "list", "of", "things", "for", "the", "unordered", "list" ]
  function() {
    $("ul").append("<li>" + this + "</li>"); // the <ul></ul> should be on the page somewhere

TODO: difference between jQuery's each and JavaScript's forEach.

Getters and Setters

Pass the method a value and it sets it. Leave it blank and it gets it.


attr and removeAttr

The attr method sets all the matching elements but gets only the first value in a set. See also map.

Here are some examples:

  // get the value of the class on the first <ul> on the page
  x = $("ul").attr("class");
  // add target="_blank" to each link on a page
  $("a").attr("target", "_blank");
  // remove target="_blank"



  // get info about the CSS
  // set some CSS
  $("p").css("font-size", "20px"); // can also use camelCase
  // style all links on a page using camelCase and an object
  $("a").css({ backgroundColor: "blue",
               color: "white" });
  // apply a new style
  // remove a style

You can also toggleClass.



// get the value of an input field by its ID
x = $("#firstname").val();
// set the value of an input field by its ID

text and html

// get the old title
x = $("head title").text();
// set a new title
$("head title").text("New title " + x)
// get the contents
// inster some text
$("#intro").html("Some new text");

data and removeData

Doesn't work with <applet>, <embed>, and <object>.

// assign some data
$("#testid").data("x", 5);
// retrieve the data
// remove it


From Evan's presentation:

$('#myButton').click(function () {
    var a, b, c;
    $.getJSON('json/a.json').then(function (x) {
        a = x;
        return $.getJSON('json/b.json');
    }).then(function (x) {
        b = x;
        return $.getJSON('json/c.json');
    }).then(function (x) {
        c = x;
        alertJSON([a, b, c]); 

Interesting way to run through URLs and fetch them with promises:

$('#myButton').click(function () {
    var ps = _.map(urls, getDiyPromise);

Changing Document Structure


  • append and prepend add things to the beginning or end of an element
  • before and after add things before or after the element tags.
  • replaceWith

This example is from JavaScript: The Definitive Guide:

// replace the <h2>s with <h1>s while keeping the content
$("h2").each(function() {
  var h2 = $(this);
  h2.replaceWith("<h1>" + h2.html() + "</h1>");


These variations work in the other direction:

  • appendTo and prependTo
  • insertBefore and insertAfter
  • replaceAll
// put a <br> before <p> elements


Copy elements instead of moving them.


  • wrap() -- puts a new element around the existing tags
  • wrapInner -- puts a new element inside the existing tags
  • wrapAll() -- wrap all but the specified tag (may also group them?)


// wrap a span around all <i> elements
$("i").wrap('<span class="highlight"></span>');

Deleting Elements

  • empty()
  • delete()
  • remove()
  • detach()
  • unwrap()


Since jQuery 1.7, I think you're supposed to use .on() instead of these directly. So, .click() becomes something like:

function notify() { alert("clicked"); }
$("button").on("click", notify);
  • blur()
  • change()
  • click()
  • dblclick()
  • error()
  • focus()
  • focusin()
  • focusout()
  • keydown()
  • keypress()
  • keyup()
  • load()
  • mousedown()
  • mouseenter()
  • mouseleave()
  • mousemove()
  • mouseout()
  • mouseover()
  • mouseup()
  • resize()
  • scroll()
  • select()
  • submit()
  • unload()


Use .on() instead of .bind(), but it appears in older code.

.bind( eventType [, eventData ], handler(eventObject) )

Here is an example from the docs:[1]

  click: function() {
    // do something on click
  mouseenter: function() {
    // do something on mouseenter

Undo it with .unbind().


Animated Scroll to Anchor

$("a[href^=#]").click(function () {
    $("html, body").animate({
        scrollTop: $($(this).attr("href")).offset().top
    }, 1000);
    return false;


  1. http://api.jquery.com/bind/