jQuery DOM

Write jQuery code to add a new list item from a text field

Description: When the user clicks “Add”, the text of the input must be added as a new list item, and the input must be cleared. Do not add empty text.

Hint:

  • Use .val(), $('<li>').text(...) and .append().

HTML of the page

<input type="text" id="task" value="Buy milk">
<button id="add">Add</button>
<ul id="todo"></ul>

Solution

$('#add').on('click', function () {
  var text = $('#task').val().trim();

  if (text === '') {
    return;
  }

  $('<li>').text(text).appendTo('#todo');
  $('#task').val('');
});

$('#add').click();
HTML after the code runs

<input type="text" id="task" value="Buy milk">
<button id="add">Add</button>
<ul id="todo">
<li>Buy milk</li>
</ul>

How it works

  • trim() removes spaces, so an empty text is not added.
  • We create the li and set the text with .text(), which is safe against HTML in the input.
  • .val('') clears the field.

Read Add Elements.

Write jQuery code to remove a list item when it is clicked

Description: Clicking on the “Delete” button of an item must remove that item. It must also work for the new items.

Hint:

  • Use a delegated event on the list and .closest('li').remove().

HTML of the page

<ul id="list">
  <li>Item 1 <button class="del">Delete</button></li>
  <li>Item 2 <button class="del">Delete</button></li>
</ul>

Solution

$('#list').on('click', '.del', function () {
  $(this).closest('li').remove();
});

// a new item added later
$('#list').append('<li>Item 3 <button class="del">Delete</button></li>');

$('.del').eq(0).click();    // delete the first
$('.del').eq(1).click();    // delete what is now the second (the new one)
console.log('items left: ' + $('#list li').length);
Console output

items left: 1

HTML after the code runs

<ul id="list">
<li>
Item 2
<button class="del">Delete</button>
</li>
</ul>

How it works

  • The handler is on the list, so it also works for the items which are added later.
  • closest('li') finds the item of the clicked button.

Read Event Delegation and Remove Elements.

Write jQuery code to change the image source when a thumbnail is clicked

Description: The thumbnails have the big image address in a data-big attribute. Clicking a thumbnail must show the big image.

Hint:

  • Use .data('big') and .attr().

HTML of the page

<img id="big" src="images/one-big.jpg" alt="One">
<img class="thumb" src="images/one-small.jpg" alt="One" data-big="images/one-big.jpg">
<img class="thumb" src="images/two-small.jpg" alt="Two" data-big="images/two-big.jpg">

Solution

$('.thumb').on('click', function () {
  $('#big').attr({
    src: $(this).data('big'),
    alt: $(this).attr('alt')
  });
});

$('.thumb').eq(1).click();
HTML after the code runs

<img id="big" src="images/two-big.jpg" alt="Two">

How it works

  • .data('big') reads the data-big attribute of the clicked thumbnail.
  • .attr({...}) sets two attributes at the same time.

Read Get Content and Set Content.

Write jQuery code to find the total of a table column

Description: Add all prices of the table and show the total in the last row.

Hint:

  • Use .each(), parseFloat() and the .text() method.

HTML of the page

<table id="cart">
  <tr><td>Pen</td><td class="price">10</td></tr>
  <tr><td>Notebook</td><td class="price">45.50</td></tr>
  <tr><td>Eraser</td><td class="price">5</td></tr>
  <tr><td>Total</td><td id="total"></td></tr>
</table>

Solution

var total = 0;

$('#cart .price').each(function () {
  total += parseFloat($(this).text());
});

$('#total').text(total.toFixed(2));
console.log('Total = ' + total);
Console output

Total = 60.5

HTML after the code runs

<td id="total">60.50</td>

How it works

  • each() runs for every price cell, and we add the number to the total.
  • toFixed(2) shows two digits after the decimal point.

Read jQuery each().

Write jQuery code to add alternate row colors to a table

Description: Give the class even to the rows at position 2, 4, … and the class odd to the others.

Hint:

  • :nth-child() in the selector, or the index of each().

HTML of the page

<table id="t">
  <tr><td>Row 1</td></tr>
  <tr><td>Row 2</td></tr>
  <tr><td>Row 3</td></tr>
  <tr><td>Row 4</td></tr>
</table>

Solution

$('#t tr:nth-child(even)').addClass('even');
$('#t tr:nth-child(odd)').addClass('odd');
HTML after the code runs

<table id="t">
<tbody>
<tr class="odd">
<td>Row 1</td>
</tr>
<tr class="even">
<td>Row 2</td>
</tr>
<tr class="odd">
<td>Row 3</td>
</tr>
<tr class="even">
<td>Row 4</td>
</tr>
</tbody>
</table>

How it works

  • :nth-child(even) is a CSS selector, so it is fast and standard.
  • The classes are used by CSS for the colors.

Read jQuery Selectors.