jQuery Basics

Write jQuery code to change the text of a heading when the page loads

Description: The page has a heading with the text “Loading…”. When the page is ready, change it to “Welcome to jQuery”.

Hint:

  • Use $(document).ready() and the .text() method.

HTML of the page

<h1 id="title">Loading...</h1>

Solution

$(function () {
  $('#title').text('Welcome to jQuery');
});
HTML after the code runs

<h1 id="title">Welcome to jQuery</h1>

How it works

  • The ready function waits until the DOM is built, so the heading exists.
  • .text() with a value replaces the text of the element.

Read Document Ready and Set Content.

Write jQuery code to change the color and size of all paragraphs

Description: Make the text of all paragraphs blue and set the font size to 18px.

Hint:

  • Pass an object to .css() to set many properties.

HTML of the page

<p>First paragraph</p>
<p>Second paragraph</p>
<p>Third paragraph</p>

Solution

$('p').css({
  'color': 'blue',
  'font-size': '18px'
});
HTML after the code runs

<p style="color: blue; font-size: 18px;">First paragraph</p>
<p style="color: blue; font-size: 18px;">Second paragraph</p>
<p style="color: blue; font-size: 18px;">Third paragraph</p>

How it works

  • The selector p finds all three paragraphs, and the method works on every one of them without a loop.

Read CSS Methods.

Write jQuery code to count the items of a list

Description: Count the items of the list and show “Total items: N” in the paragraph.

Hint:

  • A jQuery object has a length property.

HTML of the page

<ul id="fruits">
  <li>Apple</li>
  <li>Banana</li>
  <li>Mango</li>
  <li>Orange</li>
</ul>
<p id="count"></p>

Solution

var total = $('#fruits li').length;
$('#count').text('Total items: ' + total);
HTML after the code runs

<p id="count">Total items: 4</p>

How it works

  • $('#fruits li') selects all list items, and length is the number of selected elements.

Read jQuery Selectors.

Write a simple jQuery plugin to highlight elements

Description: Create a plugin highlight() which sets a yellow background by default, and accepts a color option.

Hint:

  • Add it to $.fn, use $.extend() and return this.each().

HTML of the page

<p class="a">First</p>
<p class="b">Second</p>

Solution

(function ($) {
  $.fn.highlight = function (options) {
    var settings = $.extend({ color: 'yellow' }, options);

    return this.each(function () {
      $(this).css('background-color', settings.color);
    });
  };
})(jQuery);

$('.a').highlight();
$('.b').highlight({ color: 'lightblue' }).addClass('done');
HTML after the code runs

<p class="a" style="background-color: yellow;">First</p>
<p class="b done" style="background-color: lightblue;">Second</p>

How it works

  • The defaults and the user options are merged with $.extend().
  • The plugin returns the jQuery object, so .addClass('done') still works after it.

Read jQuery Plugins.