Getting Started with jQuery (Part 1): How to Manipulate the DOM

What Is jQuery and Why Should We Learn It?

jQuery is a very popular JavaScript library that was first released back in January 2006. It was created to make it easier and simpler to write JavaScript codes that controlled webpages. Due to its simplicity and an easy learning curve, jQuery grew quickly in popularity amongst web developers like yourself, who have used it for building small one page sites all to way to larger, full-fledged web applications.

If you want to learn JavaScript and have been having some issues following tutorials on the web or have almost given up due to the complexity of the JavaScript language, then it will be a good idea to start with jQuery first. jQuery abstracts JavaScript concepts into an easy and intuitive library which can be easily learned by anyone and be productive almost immediately.

What Are the Advantages of Using jQuery?

Using a library like jQuery has multiple benefits over plain, vanilla JavaScript, especially if you are targeting multiple types of browsers across different platforms. This is because jQuery internal core libraries shield you from the differences of JavaScript codes across different browsers. This means that when you call a jQuery function, jQuery takes your
command and internally translates it into the JavaScript that is suitable for the browser which your application is displayed on.

This allows you to focus on your code and the functionality of your app rather than dealing with JavaScript differences across browsers.

In addition to this, jQuery has many powerful but easy to use selector helpers to allow you to select and manipulate elements on your web page with ease. Besides having a very powerful and flexible selector engine, jQuery also allows you to do animations and transitions easily, making your webpage even more interactive.

jQuery also includes an AJAX library at its core, meaning you can use it to call other web services that are on the Internet.

For example, you can easily use jQuery to query the OpenWeather API to get weather information for specific locations, or you can get the exchange rates for currencies. We will explore this functionality in later tutorials in this series.

In summary, jQuery is a matured product with a large community. This is a huge advantage because it makes it easy to find help if you need it and if you require something that jQuery doesn’t provide out of the box, you will most probably find a jQuery-compatible plugin which probably already does what you have envisioned.

What Will Be Learned from This Series of jQuery Tutorials

In this series of jQuery tutorials, we will be going through various core jQuery functionalities, such as HTML and DOM manipulation, selector queries, event handling, CSS manipulation, jQuery animations and AJAX capabilities which you can use to query external web services and embed their results onto your own web page.

Part 1: HTML and DOM manipulation

jQuery allows you to quickly and easily change text and HTML elements on your webpage. You can add colors, change sizes or even make certain elements appear and disappear by using it’s powerful inbuilt selector queries. We will cover some of these selectors in this tutorial.

Getting Your Feet Wet

To get you up to speed quickly, we will be doing our initial code examples in jsFiddle to get you to familiarize with the jQuery syntax. In the later tutorials, we will then learn how to include the jQuery library into your own HTML code.

Diving In

In this tutorial, we are going to be using a list of names of students in a class. We will then use jQuery selectors to manipulate the name list, by hiding or showing the names that we want to display when different filters buttons are pressed.

I have provided the skeleton HTML for you. Open your browser and navigate to the skeleton.
In the provided HTML code, I have a simple HTML list marked by the <ul> tag and each of the student’s names are between the <li> tags to form the list. I have also mocked up 3 buttons which, when pressed, filters the list of students.

Filtering by Class

Currently, we have a list of students that are displayed on our jsFiddle screen. Let’s add an HTML class to each of the student tags to identify their gender.

We insert the “class” attribute in each tag that is surrounding each student. If the student is a boy, we will append “class=’boy’” to the li tag, else if the student is a girl, we will append “class=’girl’” to the respective tag.

Now we come to the buttons. We need to give a unique identity to each of the buttons because each button is supposed to perform a different kind of filter. Let’s assign each of our buttons a unique name with the attribute “id“.

Side Note: Why did we use a class for the students but an id for the button?

Both “id” and “class” allows you to specify the type of the HTML tag. However, the “id” tag must be unique throughout the whole HTML page. For example, if a button has an id of “btnShowAllStudents“, there should not be another button with the same id.

But what if we need to specify the same type for multiple HTML tags? That is where the “class” attribute comes in. In our example, we have multiple tags that represent boys and girls, hence we can specify the “class” attributes of boys and girls across the multiple HTML tags.

jQuery can then use these attribute values to select the individual tags based on your selector rules.

Showing Only One Selection from the Class Roster

To show only boys, we can use the jQuery class selector. The jQuery syntax for selecting all the tags based on a class is “$(‘.yourclassname’)“.
We can then tell jQuery to show or hide the elements selected by using the “show()” or the “hide()” method.

Let’s explore how we can use this knowledge to filter and show only the boys from our list.

First, we tell jQuery to select all the tags that have the class of “boys” and we use the “show()” method to show all the boys.
$(‘.boy’).show();

Next, we will need to hide all the girls. In this case, we use the “hide()” method on the tags that have the class “girl“.
$(‘.girl’).hide();

The code for the button to show boys looks like this:

$(‘.boy’).show();
$(‘.girl’).hide();

This will select all the tags marked as boys to show and hides all the tags that are marked as girls.

Now, we need to execute this code when the “Show Boys” button is clicked. We need to select the button via its “id” and tell jQuery to respond to the click event like so:
$(‘#btnShowOnlyBoys’).click(function(){ // What needs to happen when button is clicked });

The code above tells jQuery to listen for a click event on the button with an id of “btnShowOnlyBoys“. The inner function will contain the code which we want to execute upon the button click.

The jQuery code now looks like this:

Exercise 1: Show Only Girls from the Class Roster

Now it’s your turn! Can you code a jQuery function that is activated by button id “btnShowOnlyGirls” and when clicked, only the name of the girls in the list should appear? Let’s take a pause here while you try to code the function yourself.

Have you tried it?

If you got it, congrats!
Just in case you are stuck, the code should look like this:

Exercise 2: Showing All Students

Now that you have learned how to show certain groups of students based on their gender, try coding the button with id “btnShowAllStudents” yourself. This button, when clicked, should show all the students. Try it yourself first before looking at the
solution.

The solution as follows:

Selection via HTML Tag

In the previous exercise, to show the whole list of names again, you used the “show()” method on both the boys and girls HTML tags. jQuery can also select HTML tags in addition to selecting HTML tags by class and id. In this case, we can tell jQuery to look for all the HTML tags that are list items or <li></li> and show them.

So, instead of invoking the “show()” method on both the boy and the girl selectors, you can select all the <li> tags like so:

More Selectors Fun

Now that we know how to filter by class and ID and even HTML tags, how about we just want to show the first boy or the first girl on the name list?

jQuery offers us two additional selectors which can be added on to existing selectors, they are the “:first” and the “:last” query selector.

In our class list, the first boy will be Jason. To show only Jason, we need to apply the class filter for “boy” and also add the “:first” selector to tell jQuery we want to show only the first boy on the list.

Let’s code this up!
First, let’s add another 2 buttons to our class roster page. The first button, when clicked, should only show the first boy on the list. The second button, when clicked, should only show the first girl on the list.

Our HTML code now looks like this:

Let’s get jQuery to listen to our new buttons and insert our code to show only the first boy on the class roster.
The jQuery code now looks like this:

The code first hides all the HTML tags of all the names in the class then only selects the first boy on the list and shows it.

Exercise 3: Show the First Girl on the Class Roster

There is another button to show the first girl on the list. Try to write the code which triggers this filter action.

Challenge Exercise for This Tutorial: Show the Last Boy and the Last Girl on the Class Roster

For this challenge, we are going to show the last boy and the last girl on the class roster list. Previously, we learnt that jQuery provides us with a “:first” and a “:last” selector which selects the first item in the list and the last item in the matched selected list respectively.

We have also learned how to get the first boy and the first girl name to appear by using the “:first” selector.

In this challenge, you need to accomplish the following:

  1. Add 2 new buttons which show the last boy and the last girl.
  2. Add code which will be triggered when the respective buttons that you have added in (1) are clicked.

Do try to solve it yourself first before referring to the solution.

If you are stuck and need help, you can refer to the completed solution.

Conclusion 

Congratulations on making it this far!

In this tutorial, you have learned how to get jQuery to filter and interactively display the HTML content that you want. You also learn how to trigger jQuery code by listening to clicks from specific buttons.

In the next tutorial, we will expand our class roster application and learn more ways which we can filter the content which we want to display.

1
0
CategoriesTags

Related Posts