Skip to content
Tutorials Center
My learning

Topics

Lesson 54 of 56 ยท Practice and Review

Practice Exercises with Solutions

Fifteen graded jQuery exercises on selectors, traversal, DOM changes, events, effects, AJAX stand-ins and plugins, each with a hint and a runnable solution.

Reading about jQuery gets you halfway; the rest comes from typing code and watching it fail. This page gives you fifteen exercises, ordered roughly from easy to hard, that cover the whole course. Each one has a short task, a hint, and a complete runnable solution in an editor that you can change.

The best way to use them is to cover the solution, solve the task in a blank page of your own, and only then compare. If your code differs from the solution but does the same job, that is fine: there is rarely one right way. Ask whether yours is shorter, safer or easier to read, and what would change if the page grew. Difficulty is marked with stars: one star is a direct application of one lesson, two stars combine two or three ideas, three stars need design decisions.

Fifteen exercises, seven topics

Selecting Exercises 1 and 2
Traversing Exercises 3 and 4
Changing the DOM Exercises 5 to 7
Events Exercises 8 to 10
1 / 2

All solutions are self-contained. Where a real server would be needed, a small function with the same promise interface plays its part, as in the AJAX lessons.

Selecting elements

Task. A page contains internal links (href="#...") and external ones (href="https://..."). Add the class external to every external link and report how many there were. External links should get a small arrow from CSS.

Hint. An attribute selector can test the beginning of a value. See basic selectors.

Exercise 1: external links

The selector a[href^="http"] means "anchors whose href starts with http". The .addClass() call returns the same collection, so .length is available right away. The click handler is only there so that the demo links do not navigate inside the preview.

Exercise 2 (one star): highlight passing rows

Task. A table lists students and scores. Highlight every row with a score of 50 or more.

Hint. The score is text in the second cell. Use .filter() with a function, from the filtering methods lesson.

Exercise 2: passing rows

Inside the callback this is the raw row element, so it is wrapped with $(this) before using jQuery methods. Remember that .text() returns a string; converting it with Number() is what makes the comparison numeric.

Traversing the DOM

Exercise 3 (two stars): a breadcrumb from a nested menu

Task. A nested menu marks the current page with the class current. Print a breadcrumb such as Docs > Guides > Configure that lists all ancestor items, starting with the outermost.

Hint. .parentsUntil() collects ancestors up to (not including) a boundary, nearest first. See traversing up.

Exercise 3: breadcrumb

The ancestors arrive nearest first (Guides, then Docs), so .reverse() on the plain array puts them in reading order. The current item is not among its own ancestors, which is why it is pushed at the end.

Exercise 4 (two stars): column totals

Task. Add a "Total" row to a sales table that sums each numeric column.

Hint. Loop over the header cells and use the cell index to pick the same column in every row. See working with collections.

Exercise 4: column totals

.index() without arguments returns the position of the cell among its siblings, which is also the column number. The nested .each() loops look like a lot, but for a few hundred cells they are instantaneous.

Changing the DOM

Exercise 5 (one star): build a list from data

Task. Turn an array of objects into a list of links inside #links. Each item has a name and a slug; the link should point to # plus the slug.

Hint. $("<a>", { href, text }) creates an element with properties. See inserting content.

Exercise 5: list from data

Passing text in the properties object uses .text() internally, which is why the angle brackets in the third name appear literally. All items are inserted with one .append().

Exercise 6 (two stars): replace elements and keep their content

Task. Replace every <b> in a paragraph with a <strong> that contains the same content. Show the new HTML below the paragraph.

Hint. .replaceWith() accepts a function. Moving the old children with .contents() keeps nested markup. See removing and replacing.

Exercise 6: b to strong

Using .contents() moves the actual child nodes, so the nested <i> survives. Building the replacement from .html() would also work but re-parses the markup; moving nodes is cleaner.

Exercise 7 (two stars): move the selected item up and down

Task. Make list items selectable by clicking. Two buttons move the selected item one place up or down. Show the current order as text.

Hint. .before() and .after() move an element that is already in the page. Check that there is a neighbour first.

Exercise 7: reorder a list

When the selected item is already first, .prev() is an empty collection and .before() on it does nothing, so there is no need for an if. Methods on empty collections quietly do nothing, which is one of jQuery's best features.

Events

Exercise 8 (one star): a counter with limits

Task. Build a counter with plus, minus and reset buttons. The count never goes below zero, and the minus button is disabled at zero.

Hint. Keep the number in a variable and write one render() function. See handling events.

Exercise 8: counter

The minus button is disabled at zero, and the handler guards against going negative as well, in case another piece of code triggers the click. Never rely on the interface alone to protect a rule.

Exercise 9 (two stars): add and remove items with delegation

Task. An input and an Add button add items to a list. Every item has a Remove button. Use one delegated handler for the removal, ignore empty input and show a message when the list is empty.

Hint. See event delegation. Create items with .text().

Exercise 9: dynamic list

One handler on the list serves all current and future Remove buttons. Using a submit handler on the form means both the button and the Enter key work.

Exercise 10 (two stars): a live character counter

Task. Show how many characters are left in a textarea limited to 40. Turn the counter orange below 10 and red when the limit is exceeded.

Hint. The input event fires on typing and pasting. .toggleClass(name, state) takes a boolean.

Exercise 10: character counter

The final .trigger("input") runs the handler once at start so the counter is correct before the first keystroke.

Effects and animation

Exercise 11 (one star): an FAQ with slideToggle

Task. Clicking a question slides its answer open or closed. The button must report its state with aria-expanded.

Hint. See fading and sliding.

Exercise 11: FAQ toggle

The new state is worked out from aria-expanded itself, not from the element's visibility, because the visibility changes only at the end of the animation. .stop(true, true) finishes any running slide first, so quick double clicks cannot get the button and the panel out of step.

Exercise 12 (three stars): animate a number

Task. When the page loads, count a number from 0 up to 1,250 over one second, with thousands separators. A button replays the animation.

Hint. .animate() works on any object with numeric properties; the step option runs on each frame. See custom animations.

Exercise 12: counting up

The animated object is just { n: 0 } wrapped in jQuery: no element is involved. .stop(true) before resetting prevents two animations from fighting if Replay is pressed quickly.

AJAX with stand-ins

Exercise 13 (two stars): loading, success and failure

Task. Two buttons load "user 1" and "user 2" from a stand-in server. While loading, show "Loading..." and disable the buttons. Show the name on success. User 2 does not exist: show the error message in red.

Hint. Use .done(), .fail() and .always(). See deferreds and promises.

Exercise 13: loading states

.always() is the right place to re-enable the buttons, since it runs after both outcomes. If you put it in .done() only, a failed request would leave the page stuck.

Exercise 14 (three stars): two requests in parallel

Task. A product page needs a price and a shipping cost from two independent stand-in endpoints. Start both requests at the same time and, when both have finished, print the total. If either fails, print a single error.

Hint. $.when() combines promises. See Deferreds, promises and Ajax events.

Exercise 14: $.when

The two delays are 400 and 600 ms, and the total waiting time is about 600 ms rather than 1,000, because the requests overlap. $.when() rejects as soon as one promise rejects.

Plugins

Exercise 15 (three stars): write an autoNumber plugin

Task. Write a plugin $.fn.autoNumber(options) that prefixes each matched element with a number: "1. ", "2. ", and so on. Options: start (default 1) and separator (default ". "). It must be chainable and must not number an element twice if called again.

Hint. Return this.each(...), merge options with $.extend, and remember work done with .data(). See writing your own plugin.

Exercise 15: autoNumber plugin

Returning inside .each() with a bare return; skips to the next element, like continue. The text node is prepended so any existing child elements stay untouched, and the chained .css() proves that the plugin returns the collection.

Bonus: how-to recipes

These small recipes are the kind of questions that come up in interviews and on real projects. Each one is short enough to write from memory. Try them in a blank page first.

Recipe set 1: forms and numbers

  • Select all text when a field gets focus. Use the focus event and call .select(). On some browsers a mouseup default action clears the selection again, so also cancel the next mouseup once.
  • A character counter for a textarea. Listen to input (not keyup, which misses paste and drag), count this.value.length, and show the remaining characters.
  • Read a CSS number. .css("width") returns a string such as "240px". Use parseFloat() to turn it into a number, or .width(), which already returns a number without the unit.
  • Namespaced handlers. Attach with .on("click.menu", fn) and remove just those with .off(".menu"), as in Event Basics.
Select on focus, character counter, CSS numbers, namespaces

Recipe set 2: visual recipes

  • Zebra stripes. In CSS, tr:nth-child(even) { background: ... } is the best answer. In jQuery you would write $("tr:even").addClass("stripe"), but :even counts from zero and is deprecated, so the CSS version or .filter(":nth-child(even)") is preferred. Remember to re-stripe if the table changes, or let the CSS do it.
  • Smooth scrolling to a section. Animate the scroll position of html, body: $("html, body").animate({ scrollTop: $(target).offset().top }, 400). Modern browsers do this with the CSS scroll-behavior: smooth. Limit the use of the jQuery version to cases where you need a callback after the scroll.
  • A news ticker. Show one headline at a time. Every few seconds fade the current one out, show the next, and wrap around at the end. Keep the timer in a variable so you can pause on hover.
  • A count-up number. You can animate any number with .animate() on a plain object and the step callback; the object is not an element, so nothing is drawn except what you write yourself.
Zebra stripes, ticker and count-up

The countUp function is a real plugin in 10 lines: it returns this.each(...) so it chains, and it animates a throw-away object { n: 0 }. This is the same trick many "counter" plugins use.

How did you do?

Count the exercises you solved without looking: 1 to 5 means you know the basics; 6 to 10 means you are productive with jQuery; 11 to 15 means you can build and maintain real pages with it. For every exercise you missed, go back to the lesson linked in its hint and redo it from memory a day later.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In Exercise 3, why is .reverse() called on the array and not on the jQuery object?

    A jQuery collection is array-like, not an array. .get() returns a real array, which has reverse(). The ancestors come nearest first, so they must be reversed to read from the outermost.
  2. 2. Why does .always() fit the last step of Exercise 13?

    Cleanup that must happen regardless of the outcome belongs in .always(), such as hiding spinners and re-enabling buttons.
  3. 3. What makes the plugin in Exercise 15 chainable?

    Plugins return the collection they received so that callers can continue with .css(), .addClass() and so on. this.each() returns this.
  4. 4. In Exercise 7, why is no if statement needed when the selected item is already first?

    An empty jQuery collection is perfectly valid; calling methods on it simply has no effect, so no error is thrown.

Summary

  • Exercises 1 and 2 practise attribute selectors and .filter() with a function.
  • Exercises 3 and 4 use .parentsUntil(), .index() and nested .each() to walk the tree.
  • Exercises 5 to 7 build, replace and move nodes while keeping user data safe with .text().
  • Exercises 8 to 10 combine event handlers, delegation and .toggleClass() with a state argument.
  • Exercises 11 and 12 use .slideToggle() and .animate() on a plain object with a step callback.
  • Exercises 13 and 14 use stand-in promises with .done(), .fail(), .always() and $.when().
  • Exercise 15 packages the pattern into a chainable plugin with options and per-element state.

For preparation of a different kind, continue with jQuery Interview Questions.