Tallan's Technology Blog

Tallan's Top Technologists Share Their Thoughts on Today's Technology Challenges

jQuery Part 1: jQuery Basics

Dylan Barrett

Introduction

Welcome to my first blog post on the topic of jQuery. This is the first part of a three part series. This post will cover most of the basic features of jQuery. The next post will wrap up the basic jQuery features and go through an example using what we learned. The final post will cover jQuery’s more advanced features and include another example.

What is jQuery?

jQuery is a Javascript library. At its core, jQuery enables authors to easily select and manipulate the elements of an HTML page. But jQuery is much more than just that. jQuery was designed for extension. There are over a thousand plugins available for jQuery with functionality ranging from rich UI features to Ajax. With all of this power it is easy to see why jQuery has become one of the web’s most loved Javascript libraries.

Where to Get jQuery

jQuery is available for download from jQuery.com. You can download the library right from the home page. There are two versions available. The production version has a tiny footprint of just 24KB! The code has been compressed though, so if you feel like reading through the actual library code to see how jQuery works then you should download the development version. Once you download the library, simply add the script reference to your HTML file and you are good to go!

Core jQuery

Selectors

The central feature of jQuery is its ability to make finding the elements that you want to manipulate ridiculously easy. To find elements jQuery uses something called a selector. These are the same selectors that are available in CSS, so if you already know how to use CSS (If you don’t, then you should learn!) then you will be able to directly apply your knowledge to jQuery. For those of you who don’t know CSS, a selector is, in essence, a string that defines a pattern that identifies a set of elements that you would like to apply a style to or, in the case of jQuery, manipulate with Javascript. The selectors available in jQuery are very powerful and allow you to easily apply your code to whatever elements you like.

There are many types of selectors. The most simple specify an HTML tag. For example, the selector img will match all image elements in the HTML. Other common types of selectors include:

#identifier
This will match all elements that have an id of the whatever follows the number sign (if you are following the rules of valid HTML, you should only have one element on the page per id)
.class
This will match all elements that have a class of whatever follows the period
*
This will match any element

You can also combine selectors:

img, p
A comma between selectors will allow you to match many patterns. In this example we are matching any images AND any paragraph elements
div p
If a space separates selectors then it will match any element hierarchy that matches the pattern. An element following the space does not have to be a direct descendant of the previous element, but can also be any generation of descendant (for example, a grandchild) of the preceding element. In this example, we will match any paragraphs that are located somewhere within a div element
div > p
Using the greater than sign is similar to using a space, except the element on the right must be a direct child of the element on the left. In this example we are matching all paragraphs that are directly below the div tag in the hierarchy
div.myClass
You can combine an html element with the class syntax to specify the HTML element must have the class given. In this example, We are selecting all div elements with a class of “myClass”.

jQuery selectors also include ways to filter the match:

div:has(p)
This will match only divs that contain a paragraph element somewhere within its descendent hierarchy.
div:not(:has(p))
This will match only divs that do not contain a paragraph element somewhere within its descendent hierarchy

This is only the tip of the iceberg. jQuery supports many more selectors that allow you have very precise control over which elements you are selecting.

The jQuery Function

Now that we have covered selectors, we can talk about the jQuery function. The jQuery function is at the heart of the library and has many overloads. We will be covering two of these overloads. The first overload simply takes in a string containing a selector. This version of the jQuery function uses the selector passed to it to find and return all elements matched by selector. Another overload of the jQuery function takes in a function. The purpose of this overload is to be able to run the code in the passed in function once the DOM tree for the page is ready to be worked with. This works much better than the onready event because, unlike the onready event, this overload of the jQuery function does not need to wait for images or page assets to finish loading. This allows us to work with the page as soon as possible. By default, jQuery gives an alias for the jQuery function. The dollar sign ($) can be used in the place of “jQuery”.

The Wrapped Set

You may be wondering what the first version of the jQuery function returns. This functions returns an object called the wrapped set. The wrapped set is essentially an array of all the elements matched by the selector. Most jQuery functions are called upon the wrapped set and commonly returns the wrapped set after the main body of the function runs. This allows jQuery functions to be chained together, making it very easy to accomplish a lot with a single line of code.

Traversing the DOM

Sometimes once you have a wrapped set containing a group of DOM elements, you may want to obtain a new wrapped set based on the initial wrapped set. For example, we may want a wrapped set containing all of the parent elements of the elements of the current wrapped set. jQuery provides a number of functions that provide functionality like this. If we wish to obtain a set of all of the parent elements of all of the paragraph elements on the page we would write: $(‘p’).parent(). The first part of this statement uses the dollar sign alias of the jQuery function to find all of the paragraph elements on the page. Next, the parent function is called on the wrapped set of paragraphs and returns a wrapped set of all of the parent elements of the paragraphs.

Manipulation

Now that we can find the elements that we are interested in, what can we do with them?

Manipulating Attributes

jQuery provides functions which allow you to manipulate the attributes of wrapped set elements easily. If we wish to read the value of an attribute we can use the attr function. The attr function takes in a string of the attribute name and returns the value of the attribute for the first element of the wrapped set. An overload of the attr function allows you to set the value of an attribute for all elements of the wrapped set. This is done by passing a second argument containing the value. For example, if we wish to set the alt attribute of an image with an id of “myImage” to the value of the image’s title attribute we would write: $(‘#myImage’).attr(‘alt’, $(‘#myImage’).attr(‘title’)). If you wish to do this for each member of the wrapped set instead of just the first we can take advantage of the each function. The each function allows you to define a function that will be run on each element of the wrapped set. Within the function, the “this” keyword refers to the element. For example:

$('img').each(function() {
  $(this).attr('alt', $(this).attr('title'));
});

This code will take all the images on the page and set their alt attribute to the value of their title attribute.

Manipulating CSS

jQuery also allows you to easily work with the styling of the elements of the wrapped set. We will cover four functions: css, addClass, removeClass, and toggleClass. The css function works similarly to the way the attr function works. Passing it the name of a CSS property will return the value of the property for that element. Passing it the name of the CSS property and a value will set the property to that value for the element. For example, $(‘div.special’).css(‘color’, ‘red’) sets the text within all div elements with class “special” to a red color.

The addClass function allows you to add classes to HTML elements. The function accepts a string containing a space separated list of classes that you wish to add to the element. For example, $(‘div:has(p)’).addClass(‘special’) will add the class “special” to all div elements that have a paragraph element within them. If the class already is associated with the element then nothing happens. The removeClass function is similar to addClass. It also accecpts a space separated string of classes. The classes you pass to the function will be removed if they are declared on the element. The toggleClass function will either remove a class from the element if it exists on the element or it will add a class to the element if it does not already exist on the element. Assuming we have a div with class “bad” and id “myDiv”, if we run the code $(‘#myDiv’).toggleClass(‘bad good’) then we will remove the bad class form the div and add the good class to the div.

Other Manipulation

Sometimes we may wish to manipulate the position of elements within the DOM. One example of this is the append function. This function will append an element to the end of the children of the selected element in the wrapped set. The overload we will be covering takes a single string containing valid HTML tags. The DOM objects for the HTML you specify will be generated and appended onto the elements you specify in the wrapped set. Take a look at this example: $(‘div.myClass > ul’).append(‘<li>New item</li>’). This code will append a new list element onto any unordered list that is a direct child of a div element with class “myClass”.

Conclusion

That’s about all that I am going to cover for now. We looked at the core features of jQuery that allow us to find elements on the page based on the power of CSS selectors as well as many functions that operate on the elements in the wrapped set. These functions allow us to easily manipulate any element on our page.

Want to Learn More?

If you want to learn more jQuery, be sure to read that next part of this article. I will be covering the topics of events and effects, as well as showing a fun example demonstrating all of the skills we have learned. Keep in mind that I am only covering a very small subset of what is available in the jQuery library. I suggest you check out the jQuery documentation page at jQuery.com. The documentation for jQuery is excellent and provides many useful examples. If books are more your style then I would strongly recommend the book jQuery In Action by Bear Bibeault and Yehuda Katz. I have read through the entire first edition of the book and it was very helpful. The second edition just came out and it looks very similar except that it contains much more coverage of the jQuery UI plugin (which will be covered a little in Part 3 of this article). You should definitely check it out. The next part of this article should be posted soon. See you then!

Tags: JavaScript, jQuery,

1 Comment. Leave new

Nice. Complete explanation for the basic. I can use it as a reference. Thank you.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

\\\