- Part 1: Adding and Loading the Library
- Part 2: Using Selectors
- Part 3: Reacting to Events
- Part 4: Ajax
One of the core operations jQuery was designed to solve is better traversal of the document object model (DOM). While it supplies functions like getElementById(), getElementsByClassName(), and querySelector(), these can be complicated to use and often require many lines of code to complete common tasks. jQuery helps with this task through the same functionality all three of the DOM functions also use: selectors.
jQuery has a long list of possible combinations of things that can searched for in an HTML document. From searching for an element by ID, elements by their classes, and even children elements that are at a certain depth (level) away, many different types of elements can be found easier using jQuery.
Using a selector starts with the dollar-sign, $. In jQuery, a selector starts with the dollar-sign and then the selector in quotations within parentheses following it. This is a function call that uses the selector as a search parameter.
Selector usage returns either no results, one element, or multiple elements. For the case of returning multiple elements, the list will be an array.
Manipulating Elements Using Selectors
Finding elements is only half of the designed purpose of jQuery. The second core purpose is to manipulate those elements once found. jQuery has many different functions for changing the content, attributes, and placement of elements.
One of the commonly used functions is append(). This inserts content at the end of any existing element matching the selector on which it is applied. This is a common way to change the document through finding certain elements and adding to their existing content.
When is the document ready?
One of the most common problems when using jQuery is understanding when elements are loaded and ready. In order for an element to be found using a selector, it must exist. However, knowing when certain elements exist can be a confusing issue during loading times and across browsers that handle things in different ways.
jQuery has a solution for this problem in its .ready() function. This will be called after all of the elements are loaded and ready to be found or changed. It can also be written with the shortcut $(), which is increasingly more common.
When using the .ready() or its shortcuts, code using jQuery can be included as separate files or, when in the same document, after the elements on which they act.