jQuery Basics: Part 2: Using Selectors

jQuery Basics

jQuery is a JavaScript library designed to simplify the processes of traversing and manipulating elements in client-side HTML. It is an open source library commonly found on many sites.

Using Selectors

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.

Selector Options

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.


Screenshot 2018-10-24 12.37.31

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

Screenshot 2018-10-24 12.37.31

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.

Depending on the task, this could be be done through using text() for text content or even html() to change the inner HTML of the element or to overwrite 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.

Screenshot 2018-10-24 13.00.07

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.

Play with the example on Repl.it!