Just the weekly tutorials.

How to Select HTML Elements Using jQuery CSS Selectors

Selecting HTML Elements Using CSS Selectors is probably the first task a JavaScript programmer learns after installing jQuery on their website, previously explained in another article on this website How to Add jQuery To Your Web Page.

jQuery's CSS selectors follow standard CSS rulesets. CSS selectors are passed as a text-string to the main jQuery object. Which is also known by the dollar sign "$" function or the JavaScript object conveniently named "jQuery".

$("DIV").css( { "color", "red" } );

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.

The following examples demonstrate jQuery CSS selectors at work. We will modify the very HTML of the page you are looking at right now. I attached jQuery events to these buttons. So when they are clicked (or tapped), you will see something happen on the screen. These are the effects produced by jQuery's css() method.

Change the background color of this page Click on this button to see what it does.

Select all <DIV> elements on this page and change their border style to "1px solid blue": Click on this button to see what it does.

Select all <P> elements on this page and change their border style to "1px solid red": Click on this button to see what it does.

This article goes beyond selecting HTML elements by tag name (native Javascript function to do that is document.getElementsByTagName, however, jQuery simplifies that to a simple string of text containing the tag name.) This tutorial will also cover selection hierarchy principles (using space character) and how CSS selectors relate to the DOM Document Object Model.

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.

A jQuery function call consists of the jQuery object, opening parenthesis and the command inside single or double quotes. In other words we are simply calling a JavaScript function named jQuery (which is part of the jQuery library,) and passing an argument of type string (which is the CSS selector) to it as one of its parameters. Let's take a look at several different ways to learn how to select various HTML elements of different types by tag name, id, class name, and so forth:

jQuery("*"); // Select all elements (including <doctype>, <head>, <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 <DIV> element we could refer to it by its ID or CLASS name. The same syntax rules apply.

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!

If you are familiar with JavaScript, you probably already know that you can create variables. For example, the following line will create a variable n and make it equal 1.

var n = 1;

The dollar sign is a valid variable name, too. But why is it used interchangeably? jQuery is a JavaScript library that can be included in any web project along with any other library (that can, too, be named as the dollar sign). According to rules of JavaScript we know that two variables cannot share the same name.

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.

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

CSS Selectors Will Search the DOM

CSS selectors work exclusively with the JavaScript's DOM or Document Object Model. Many operations take place internally, hidden from our eyes. You already know how to nest HTML elements within other elements. One element can be inside another. The HTML element containing others inside is called the parent element.

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 <HTML> 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.

Second Part of CSS Selector Tutorial

Just the weekly tutorials.