📖 Lecture 2—Selecting and Hiding HTML DOM elements

This is lecture 2 of the Beginning jQuery course. Make sure you have read lecture 1 and can code basic HTML and JavaScript.

In this lecture, we focus on the basic elements selection and toggling visibility.

Selecting DOM elements

Most of the jQuery commands apply actions and behaviors to a selected DOM element. So the first step is to get familiar with jQuery’s selector.

Here are some examples:

// select all anchor link.
$("a")
// select all list item.
$("li”)
// select input button with ID “submit-button”
$("input#submit-button")

The following demo page provides a collection of selector examples. You may toggle the selectors on the left and view the highlights of the selected elements on the right side.

http://codylindley.com/jqueryselectors/

For the full selector list, you may check out the following jQuery documentation.

http://api.jquery.com/category/selectors/

Showing and Hiding elements

After we select the elements, we perform an action (or a series of actions) on the selection. These actions may be toggling visibility, manipulating elements or registering events handling.

One basic action is to display and hide the selected elements. We usually achieve that by show() and hide() method.

For example, imagine that it’s a gmail-like web app, when user clicks on the “Compose Mail” button, we show a composer dialog.

Gmail new mail screenshot

To do so, we select the new-mail element—let’s assume it’s #new-mail—and call the

show acrion on it.

$('#new-email').show();

Of course, we need to show the dialog only after the user clicks on the compose button. So here is the click event handler.

$('#compose-button').click(function(){
  $('#new-mail').show();
});

We will cover the event handling in lecture 3.

Here is a full demo on the email composing form’s toggling HTML and JavaScript:

http://codepen.io/makzan/pen/yyxwMp

JavaScript best practices

When you’re writing more JavaScript, you should start learning to write the JavaScript in the right way. There are many essays and books discussing the best practices that we should follow. The following lists few of them that I highly recommend you to check them out.

JavaScript and jQuery books

If you would like to read book for more details, I recommend the following books.

Head First jQuery — The head first series contains lots of illustrations. This is definitely the jQuery for absolute beginner.

HTML and CSS book too if you are new to HTML and CSS.

JavaScript: The Good Parts — This is a must read book if you want to master the JavaScript language. This books shows you how JavaScript use prototype for object-oriented programming.

Class 2 demo

Link to class 2 selecter test

–Thomas Mak

Next Page → Lab 2—Adding and Removing class

← Previous Page Lab 1—Basic HTML and jQuery exercises


Last updated at 2017-04-24. Show version history

Comments

no comments yet.