jQuery CSS selectors are used in combination with jQuery method. Doing that provides an efficient way for manipulating HTML elements. It it very helpful. For example, with only a few simple commands we can modify the visual appearance of an entire set of HTML elements, not just one.
Selecting Elements by Tag Name
Even though jQuery programming implies understanding several functions from the library, almost all jQuery commands start with a CSS selector (beside the main library functions which do not require a CSS selector, but that is not covered in this tutorial.) Basic knowledge of CSS selectors is required before starting to use jQuery. However, in many instances jQuery has helped web programmers learn more about CSS selectors! It works both ways.
jQuery("*"); // Select all elements (including <doctype>, , <style>, etc.) jQuery("div"); // Select all <DIV> elements jQuery("p"); // Select all paragraphs (returns a list of elements) jQuery("#nagivation div"); // Select all <DIV> elements within an element of any type whose ID is #navigation jQuery("table tr"); // Select all table rows within all tables on the page (but avoids the table tag itself)
If you are already familiar with CSS (Cascading Style Sheets), then CSS selector anatomy used by jQuery will be trivial to understand because it’s exactly the same here. jQuery follows standards already defined by the regular CSS rules, it doesn’t make its own. (Whatever CSS you are used to writing in a file such as “style.css”, the same exact rules apply here.)
However, jQuery also adds a few of its own custom selector methods that can further extend our options (these are represented by methods, not additional CSS selectors.)
For example, what if we wanted to remove all elements of a certain type from the web page? Notice that the comma separates two tags. All elements of both types will be removed completely from the DOM (Document Object Model,) in other words, your web page.
What if we wanted to “prepend” or append elements within the selected HTML element? The following examples explain how to do this:
// Prepend (add text just at the top its opening <body> tag) $("body").prepend("<p>Watching the clouds fly by.</p>"); // Append (add) text to the very end of the tag $("body").append("This text will be added just before the closing </body> tag");
Selecting Elements by ID and CLASS Name
To select an individual
jQuery("div#windows"); // by id name "windows" jQuery("div.doors"); // select by class name "doors"
The Object “jQuery” Is the Same as the Dollar Sign Object “$”
jQuery is the name of the main library object. However, the main jQuery object can also be referred to as the dollar sign. They are synonymous. This means that typing the following line will give us the same exact thing as the lines in examples above (where we used the jQuery object):
$("div"); $("div#windows"); $("div.doors");
There is no difference between the dollar sign and jQuery object. The dollar sign itself is just a variable name like: var $ = jQuery. Where jQuery is an object that contains the entire library. This object is defined within the jQuery’s “.js” file you can download from www.jquery.com, include it in your own projects and you’re ready to start writing jQuery code!
var n = 1;
By referring to jQuery by its original name “jQuery” (and not the dollar sign) we ensure that the jQuery object does not clash with other objects already included in your project (the dollar sign is a common name for naming entire libraries). If you are absolutely sure no other library will be used on your web page, then using the dollar sign is acceptable.
You can choose to use jQuery(“div”) or its exact equivalent $(“div”), they refer to one and the same object.
In prior examples we selected all DIV elements by using tag names. We can use any legal HTML tag name such as “img”, “p”, “table”, “td”, etc.
Beyond Selecting HTML Elements by Tag Name
In order to expand on this idea, we use additional selection modifiers like the dot (.) and number symbol (#) operators. Place a “.” or a “#” in front of a selector name and it changes its meaning completely. Nothing that goes outside the standard CSS rules. We know that in order to assign a class to an HTML element we can use the class attribute.
<div class = "myclass">any HTML here</div>
We also know that in order to assign an id to an HTML element we can use the id attribute:
<div id = "myid">any HTML here</div> $("div"); // Select all DIV elements. $(".myid"); // Select one or multiple elements of class myclass. $("#myid"); // Select one unique element whose id is myid. One unique id per element.
As you can see, a CSS selector is simply a code enclosed within quotes, a combination of characters that tell jQuery which HTML elements to select.
- You can select only one HTML element.
- You can select many HTML elements at once.
- You can select elements nested within an exact element hierarchy.
Item 1 and 2 are simple. Specify an element name such as div, and all elements of type div on the page will be selected no matter where they are located. But what if you need to get specific? We can use the space character to specify a hierarchy. An explicit hierarchy could look something like this:
$("table td div");
Don’t ignore the space character between elements. The space character has a function. To an untrained eye, it may mean: select all table, td and div elements. But that’s not true. Only last element is selected in this hierarchy separated by the space character.
This means to select all div elements within any and all td tag(s) of any and all table element(s) on the page One interesting thing to understand about the space character operator is that only the last element (or the resulting set of many elements) in the hierarchy will be selected. What will be selected by this query? That depends on your HTML code
- If you have only one table on the page. All divs inside all td elements of the table element will be selected.
- If you have more than one table then: All divs inside all td elements in all existing table elements will be selected.
CSS Selectors Will Search the DOM
All other elements inside the parent are called children. A child element stems from a parent element. A child element can also be the parent to other elements. Just like in real life.
DOM is relationship between parent and children elements nested inside one another. That’s why often DOM is referred to as being a tree. In computer science, trees are common representations of data. DOM is a data tree, where each “branch” is a nested HTML element.
DOM begins at the main DOM “root” object, which contains the main HTML document – it is nothing more than the tag you are already familiar with. All other tags stem from this tag and branch out with respect to their position in the document. That’s DOM.
An example of a simple DOM structure
<html> <div> <div>something</div> <div>something else</div> </div> </html>
The DOM diagram on the left explains this code visually.
Some websites are so large that their DOM trees get very complicated. But it’s okay, we never really see the DOM. We just see the source code. But jQuery CSS selectors work with these branches to select things we need.
In situations where the website code is complex, its DOM structure will be equally complicated. So it is possible to create a CSS selector that slows down your program because it is selecting too many things in an obscure non-simple way. Imagine all the branches a selector has to travel to select elements in question. jQuery does that for us. But things can get slow.
Don’t worry about performance for now. We will touch upon performance in one of my future newsletters. This tutorial is designed to let you know how CSS selectors work at their basic level.
Even with the visual diagrams presented in this tutorial, the examples here only touch the tip of the iceberg. This is true because jQuery is so flexible about the way in which it allows us to select multiple elements and target specific hierarchies.