Skip to content

Selector

Selectors are at the core of jQuery, written as $('#dom-id').

Why was jQuery invented? Let's review the cumbersome code often used for DOM manipulation:

javascript
// Find by ID:
let a = document.getElementById('dom-id');

// Find by tag:
let divs = document.getElementsByTagName('div');

// Find <p class="red">:
let ps = document.getElementsByTagName('p');
// Filter class="red":
// TODO:

// Find all <tr> inside <table class="green">:
let table = ...
for (let i = 0; i < table.children; i++) {
    // TODO: Filter <tr>
}

This code is tedious, especially when dealing with hierarchical relationships, like finding all <tr> within a <table class="green">. A recursive search for all child nodes is often needed.

jQuery selectors help quickly locate one or more DOM nodes.

Find by ID

If a DOM node has an id attribute, use jQuery as follows:

javascript
// Find <div id="abc">:
let div = $('#abc');

Notice that #abc starts with #. The returned object is a jQuery object.

What is a jQuery object? It is similar to an array, with each element referencing a DOM node.

For the above search, if the <div> with id abc exists, the returned jQuery object looks like:

javascript
[<div id="abc">...</div>]

If it does not exist:

javascript
[]

In summary, jQuery selectors will not return undefined or null, so you don’t have to check with if (div === undefined).

You can convert between jQuery and DOM objects:

javascript
let div = $('#abc'); // jQuery object
let divDom = div.get(0); // Assuming div exists, get the first DOM element
let another = $(divDom); // Wrap the DOM back into a jQuery object

Typically, you don't need to get the DOM object; using the jQuery object is more convenient. If you do have a DOM object, simply call $(aDomObject) to convert it into a jQuery object.

Find by Tag

Finding by tag is straightforward:

javascript
let ps = $('p'); // Returns all <p> nodes
ps.length; // Count how many <p> nodes are on the page

Find by Class

To find by class, prefix the class name with a .:

javascript
let a = $('.red'); // Returns all nodes with class="red"
// For example:
// <div class="red">...</div>
// <p class="green red">...</p>

Many nodes have multiple classes; you can find nodes that include both red and green:

javascript
let a = $('.red.green'); // Note: no space!
// Matching nodes:
// <div class="red green">...</div>
// <div class="blue green red">...</div>

Find by Attribute

A DOM node can have many attributes beyond id and class, making attribute selection useful:

javascript
let email = $('[name=email]'); // Find <??? name="email">
let passwordInput = $('[type=password]'); // Find <??? type="password">
let a = $('[items="A B"]'); // Find <??? items="A B">

When attribute values include spaces or special characters, enclose them in double quotes.

You can also use prefix or suffix searches:

javascript
let icons = $('[name^=icon]'); // Find all DOMs with name starting with "icon"
// For example: name="icon-1", name="icon-2"
let names = $('[name$=with]'); // Find all DOMs with name ending with "with"
// For example: name="startswith", name="endswith"

This method is especially suitable for class attributes, unaffected by multiple class names:

javascript
let icons = $('[class^="icon-"]'); // Find all DOMs with class starting with "icon-"
// For example: class="icon-clock", class="abc icon-home"

Combined Selection

Combine the above simple selectors for more specificity. If we use $('input[name=email]'), we avoid finding a <div name="email">:

javascript
let emailInput = $('input[name=email]'); // Won't find <div name="email">

Similarly, combining tag and class searches is common:

javascript
let tr = $('tr.red'); // Find <tr class="red ...">...</tr>

Multiple Selectors

Multiple selectors can be combined using ,:

javascript
$('p,div'); // Selects both <p> and <div>
$('p.red,p.green'); // Selects <p class="red"> and <p class="green">

Note that the selected elements are ordered as they appear in HTML, without duplicates. For example, <p class="red green"> will not be selected twice by $('p.red,p.green').

Practice

Use jQuery selectors to select specified elements:

  1. Select only JavaScript
  2. Select only Erlang
  3. Select both JavaScript and Erlang
  4. Select all programming languages
  5. Select name input
  6. Select email and name inputs
html
<div id="test-jquery">
    <p id="para-1" class="color-red">JavaScript</p>
    <p id="para-2" class="color-green">Haskell</p>
    <p class="color-red color-green">Erlang</p>
    <p name="name" class="color-black">Python</p>
    <form class="test-form" target="_blank" action="#0" onsubmit="return false;">
        <legend>Register New User</legend>
        <fieldset>
            <p><label>Name: <input name="name"></label></p>
            <p><label>Email: <input name="email"></label></p>
            <p><label>Password: <input name="password" type="password"></label></p>
            <p><button type="submit">Register</button></p>
        </fieldset>
    </form>
</div>

Run to see results:

javascript
let selected = null;

selected = ???;

// Highlight result:
if (!(selected instanceof jQuery)) {
    return console.log('Not a valid jQuery object!');
}
$('#test-jquery').find('*').css('background-color', '');
selected.css('background-color', '#ff8000');
Selector has loaded