0Pricing
jQuery Academy · Lesson

Pseudo-Class and Custom Selectors

Understand built-in pseudo-classes like :has(), :not(), and :nth-child(), then learn to create your own custom selectors for reusable element filtering.

Pseudo-Class and Custom Selectors is a free jQuery Academy lesson on CoddyKit — lesson 2 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the jQuery Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Unlock Power with Pseudo-Classes

Welcome to Advanced Selectors! Today, we'll explore pseudo-classes, special keywords added to selectors to define a special state of the selected element.

  • They let you target elements that aren't easily selected by standard HTML attributes or names.
  • Think of them as dynamic filters for your selections.

They start with a colon (:), like :hover or :first-child.

Target by Position: :nth-child()

The :nth-child() pseudo-class selects elements based on their position among a group of siblings. It's incredibly useful for styling lists or table rows.

  • :nth-child(n): Selects the nth child.
  • :nth-child(odd): Selects odd-numbered children.
  • :nth-child(even): Selects even-numbered children.

The counting starts from 1 for the first child.

Styling with :nth-child(odd/even)

Let's see how :nth-child(odd) and :nth-child(even) can quickly apply alternating styles, like zebra stripes in a list.

Try running this example to see the effect:

$(document).ready(function() {
  // Selects odd list items and makes their text blue
  $('li:nth-child(odd)').css('color', 'blue');
  // Selects even list items and makes their text green
  $('li:nth-child(even)').css('color', 'green');
});

// HTML Structure (imagine this is in your page):
// <ul>
//   <li>Item 1</li>
//   <li>Item 2</li>
//   <li>Item 3</li>
//   <li>Item 4</li>
// </ul>

Advanced :nth-child() Formulas

You can use more complex formulas inside :nth-child() like An+B. Here, A represents a cycle size, and B is an offset.

  • :nth-child(3n): Selects every 3rd child (3rd, 6th, 9th...).
  • :nth-child(3n+1): Selects the 1st, 4th, 7th... child.

This allows for very precise interval-based selections.

Excluding Elements with :not()

The :not() pseudo-class allows you to exclude specific elements from a selection. It's like saying, "select all paragraphs, except those with the class 'intro'".

  • It takes another selector as an argument: :not(selector).
  • This is powerful for refining existing selections without writing complex new ones.

Using :not() in Practice

Imagine you want to add a border to all list items except the very first one. :not(:first-child) is perfect for this.

See how :not() helps us exclude the first item:

$(document).ready(function() {
  // Selects all list items that are NOT the first child
  $('li:not(:first-child)').css('border-top', '1px solid gray');
});

// HTML Structure:
// <ul>
//   <li>First Item</li>
//   <li>Second Item</li>
//   <li>Third Item</li>
// </ul>

Selecting Parents with :has()

The :has() pseudo-class is unique: it selects an element if it contains at least one element that matches the selector passed as an argument.

  • It's like asking, "Give me all <div>s that have a <p> tag inside them."
  • This allows you to select parents based on their children's characteristics.

Highlighting with :has()

Let's say you want to highlight only those <div> containers that contain an image. :has('img') can do this efficiently.

Run this code to see which div gets a border:

$(document).ready(function() {
  // Selects divs that contain an image and adds a border
  $('div:has(img)').css('border', '2px solid red');
});

// HTML Structure:
// <div id="container1">
//   <p>Text only</p>
// </div>
// <div id="container2">
//   <img src="example.png" alt="An image">
//   <p>Text and image</p>
// </div>

Custom Selectors: Extend jQuery

What if jQuery's built-in selectors aren't enough? You can create your own custom pseudo-selectors! This lets you filter elements based on highly specific, custom logic.

  • You register them using jQuery.expr[':'].
  • This makes your selection code cleaner and reusable.

It's an advanced feature for truly unique filtering needs.

Building a Custom :contains-word()

Let's create a custom selector called :contains-word() that finds elements containing a specific whole word, not just a substring.

This example defines :contains-word() and then uses it:

$(document).ready(function() {
  // Define a custom pseudo-selector ':contains-word'
  $.expr[':']['contains-word'] = $.expr.createPseudo(function(word) {
    var pattern = new RegExp('\b' + word + '\b', 'i');
    return function(elem) {
      return pattern.test($(elem).text());
    };
  });

  // Use the custom selector to find paragraphs containing 'hello'
  $('p:contains-word("hello")').css('background-color', 'yellow');
});

// HTML Structure:
// <p>Say hello world!</p>
// <p>Another paragraph.</p>
// <p>Hello there!</p>

Pseudo-Class Challenge

Consider the following HTML:

<ul>
  <li class="special">One</li>
  <li>Two</li>
  <li class="special">Three</li>
  <li>Four</li>
  <li class="special">Five</li>
</ul>

Which jQuery selector would target only 'Two' and 'Four'?

Recap: Pseudo-Classes & Custom Selectors

You've mastered powerful jQuery selection techniques!

  • Pseudo-classes (like :nth-child(), :not(), :has()) let you select elements based on their state or relationship to other elements.
  • :nth-child() targets elements by position, even with formulas.
  • :not() excludes elements from a selection.
  • :has() selects parents based on their children.
  • You can even create your own custom pseudo-selectors with jQuery.expr[':'] for highly specific filtering.

Keep practicing these to refine your DOM targeting!

Frequently asked questions

Is the “Pseudo-Class and Custom Selectors” lesson free?

Yes — the full text of “Pseudo-Class and Custom Selectors” is free to read here on the web, and the jQuery Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the jQuery Academy course, upgrade to CoddyKit PRO.

What will I learn in “Pseudo-Class and Custom Selectors”?

Understand built-in pseudo-classes like :has(), :not(), and :nth-child(), then learn to create your own custom selectors for reusable element filtering. You practise jQuery Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start jQuery Academy?

No prior experience is required. jQuery Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 3, so you can start here or from the beginning and move at your own pace.

How long does the “Pseudo-Class and Custom Selectors” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this jQuery Academy lesson?

Yes. Every jQuery Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Advanced Attribute Selectors
  2. Pseudo-Class and Custom Selectors
  3. Efficient DOM Traversal Techniques
← Back to jQuery Academy