Topics for quiz five

Quiz five will focus on jQuery.

Review of jQuery basics

Every jQuery expression begins with an application of the jQuery $() function. Depending on what value you pass to this function it serves various purposes.

$('#result')

The most commonly used form uses a selector expression with a # in it to locate an element by its id. The example above locates the element whose id value is 'result'.

$('ul#steps li')

This form of the selector targets a set of elements. In this example we start by locating a ul element whose id is 'steps', but then go on to select all of the li elements in that ul.

$('<tr>')

This form of the selector is used to create a new element. This example creates a new tr element.

$(document)

This is used to access the document object.

$(this)

This form is used in a function that is attached to a button. This selector allows you to access the button the function is attached to.

Once you have used the $() function to locate, access, or create an element on the page you can apply one or more jQuery methods to the object. The table below some of the most commonly used jQuery methods, along and provides a link to a page where you can read more about that method.

Method nameDocumentation
htmllink
textlink
removelink
appendlink
attrlink
addClasslink
removeClasslink
vallink
showlink
hidelink
readylink
clicklink

Many of these methods come in two forms: one form without parameters and one form with parameters. For example, using the text() method without parameters reads the text content of an element:

if($(this).text() == 'Lunch')

The example above reads the text content of a button and checks to see if it equals 'Lunch'. The form of text() with parameters is used to set the text content of an element.

$('#result').text('You owe $'+amount+'.')

Sample questions

Once again, I will ask two types of question. In the first type of question I will show you some jQuery code and ask you to describe what the code does. In the second type of question I will ask you to write some jQuery code to achieve a particular effect.

Here are some sample questions with solutions.

1. What does the code below do?

var duration = $('#duration').val();

Answer: This reads the value of the element whose id is 'duration' and stores that value in the variable duration.

2. Write a jQuery expression that hides the div whose id is 'second'.

Answer:

$('div#second').hide();

3. Write some code that adds a new li element with text content 'Green' to the ul element whose id is 'colors'.

Answer:

var newLi = $('<li>');
newLi.text('Green');
$('#colors').append(newLi);