DOM Filtering with jQuery - What You Need to Know

We have already given an introduction to the jQuery library, showing how useful it can be for web designers and developers: it simplifies the JavaScript syntax for lots of useful DOM-related tasks and it can dramatically speed up the routines to select DOM elements. Now it’s time to expand your abilities to select and manipulate the elements you need: Welcome to filtering.


A quick overview

The filters

  • .eq()

    When using one of the traversing methods, like .children(), you get a jQuery object with possibly multiple elements: with .eq(i) you can select the element with the position indicated by the index i. The index of the first element starts from 0 and can also be a negative integer; in this case the selection starts at the end of the set, rather than at the beginning.

    <ul>
        <li>
          <b>Item A</b>
        </li>
        <li>
          <strong>Item B</strong>
        </li>
        <li>
          <em>Item C</em>
        </li>
        <li>
          <b>Item D</b>
        </li>
        <li>
          <em>Item E</em>
        </li>
    </ul>

    $(‘ul’).children().eq(0) ⇒ Item A
    $(‘ul’).children().eq(-2) ⇒ Item D

  • .has()

    This method constructs a new object with all the selected elements that contain at least one supplied selector, in the following example the b tag.

    $(‘ul’).children().has(‘b’) ⇒ Item A and Item D

  • .is()

    The .is() method may seem similar to the above-mentioned .has(), since it checks the collection against the supplied selector, but actually it’s totally different. The .is() method not only accepts a selector as an argument but also a function, an element, or an object. However, the main difference between the methods is that .is() does not return a jQuery object but performs a test against the argument, therefore returning true or false.

    $( "ul" ).click(function( event ) {
      var target = $( event.target );
      
      if ( target.is( "b" ) ) {
        target.css( "background-color", "red" );
    }});
  • .first() and .last()

    These methods return the first and, respectively, the last element of a jQuery collection. They do not accept any arguments but can be chained as usual.

    $('ul').children().first().has('b') ⇒ Item A
    $('ul').children().last().has('b') ⇒ No items
    $('ul').children().last().has('em') ⇒ Item E

  • .slice()

    With this method we can filter our jQuery object with the aid of two indices, the starting and ending position. The element at the ending index is not included, so .slice(0, 3) returns three elements and not four. Only the starting index is mandatory; if the ending one is omitted, all the elements up to the end of the jQuery object are included. Indices can also be negative; in this case the starting position is at the end of the object.

    $(‘ul’).children().slice(1, 4) ⇒ Item B, Item C, Item D
    $(‘ul’).children().slice(1, -2) ⇒ Item B, Item C

  • .not()

    The purpose of this selector is to exclude items from a collection; it accepts a selector or a function as an argument. The elements of the collection are tested against the selector and the ones that don’t match are included in the new collection.

    $('ul').children().not(':first-child, :last-child') ⇒ 
    Every item except A and E

  • .filter()

    This method tests the collection against a selector, an object, or a function and constructs a new jQuery object consisting of the matching elements. The list of possible selectors is pretty long: 

    :first Selects the first matched element of the selector's returned set
    :last Selects the last and single instance of the element matching the selector's returned set
    :even Selects the even elements with a zero-based index within the matched set
    :odd Selects the odd elements with zero-based indexing within the matched set
    :eq(index) Selects the element that is equal to the given index n within the matched set
    :gt(index) Selects all elements that are greater than the given zero-based index within the matched set
    :lt(index) Selects all elements that are less than the given zero-based index within the matched set
    :animated Selects all elements that are currently being animated at the time the selector is run
    :header Selects all header elements (H1...H6)
    :not Selects all elements that do not match the given selector
    :checkbox Selects all elements that match the type checkbox
    :contains(text) Selects a string of text (case sensitive)
    :disabled Selects all elements that are disabled
    :enabled Selects all elements that are enabled
    :file Selects all elements of a specific file type

    $('ul').children().filter(':gt(1)').css('color', 'violet') ⇒ Item C, Item D, Item E
    $('ul').children().filter(':even').css('color', 'violet') ⇒ Item A, Item C, Item E

Filtering is often used in conjunction with traversing: we get a collection of items and we refine the choice in a more specific way. Pointing out the usefulness of these handy methods is surely unnecessary: jQuery offers an impressive array of tools to easily select whatever element we need. Although this is usually just the starting point, having a firm command of the traversing and filtering possibilities is a solid foundation for programming a jQuery plugin or a complex function. It’s always nice to remember that these results can be achieved with standard JavaScript as well (often referred to as “vanilla JavaScript”) but the advantages offered by the jQuery library allow us to write code more easily and quicker, leaving more time to concentrate on advanced JavaScript logic.

Ready to start? Create your free account now

More great blog posts from Alessandro Loverde

  • Tighten Your CMS Security

    A small investment early in the deployment phase can go a long way to creating a secure environment. Fine tuning permissions Every CMS allows administrators to set permissions for different users or groups and, for the sake of better security, one should check that editors can only do what they...

  • Image Optimization: A Comprehensive Roundup - pt.1

    In the beginning, the World Wide Web was all about optimization. Standard speed was around 3 kb per second, and hosting space larger than 5 MB was expensive. Then broadband became available for everyone, and web designers grew less and less obsessed with image optimization. Nowadays, younger web...

  • Video Tutorial: Building a React App - pt5: Working with External Data

    In the previous part of this tutorial we explored components: the distinctive React feature. We did no magic because we wanted to focus on the basic structure of components, but now the time has come to explore the advantages of generating code employing external data. Replacing hard-coded with...

  • Five Quick Tips Before You Start Your Next SaaS Project

    There are many web apps around, some good, some bad, some are kind of life-changing while others lay almost forgotten, but making a SaaS app is something definitely bigger; a good programmer and a talented designer are not enough. The concept of Software as a Service looks far ahead and...

  • Strategies for a Multilingual Website

    Having a website just in English may be okay for most businesses. In fact, even if you occasionally need to reach foreign visitors, you can expect that whoever is interested in your services has enough knowledge of English to clearly understand what you are offering. But if you sell something...

  • HTTPS and SEO: How to Cover your Assets and Avoid Common Pitfalls

    Back in 2014, Google started to consider making the use of a secure connection (HTTPS) a parameter in their search algorithm. It began with just a 1% weight over all the other factors, but they pushed it further and further; and now, in 2018, every professional website must be served through a...

  • WordPress and SEO; Costly Missteps to Avoid

    WordPress is often a popular choice for a website builder and it is appreciated by many because it gives the users a lot of freedom regarding tools and plugins. Unfortunately, this approach is not good for your SEO because WordPress does not offer many SEO tools out of the box and, if you don't...

  • Video Tutorial: Building a React App - pt3: Code Components

    In the previous part of this tutorial we have converted an existing HTML page into a React app, but we have not seen much interactivity so far. In this new chapter we start exploring one of the most interesting React features, the components. Let's build something dynamic We are going to create...

  • Rising Stars and Falling Comets in the CSS Universe

    CSS is our friend; the relationship between it and web designers has been a bit turbulent over time, but near the end of the first decade of the new millennium, it settled down with mutual love and respect (in the meantime Internet Explorer has met its fate but nobody mourns the loss, right?)....

  • A Bit of SASS Magic: Automatic Text Color in CSS

    We already talked about SASS and how it can revolutionize your approach to writing CSS. We talked about variables and indenting; powerful features but easy to handle nevertheless. We mentioned that SASS has more advanced functions, and in this article we are going to explore a handy one. The SASS...

  • This Is How We Do It - The TROX Case Study

    TROX understands the art of handling air like no other company. It’s a dynamic firm and, through research and development, TROX became a global leader of innovation in ventilation systems. A business can be efficiently run only with efficient tools and TROX has chosen Scrivito to manage over 70...

  • How to Up Your UX Best Practices for Mobile Apps - pt2

    One central guideline for a designer is to have a clear understanding of the medium, the way users will interact with our design. It can be a television, a computer, a book, or any number of things: design is everywhere. A mobile phone is not just a small computer; it has its own unique features...

  • How to Up Your UX Best Practices for Mobile Apps - pt1

    The concept of mobile apps has greatly evolved: with the first apps, developers tried to replicate the same experience of a desktop but, given the limited resources, the results were pretty different and, in some cases, disappointing. A more modern approach is to create mobile apps that offer the...

  • Video Tutorial: Building a React App - pt2: Installation

    In the first post of this video tutorial series, the basics of React.js were covered. Now it’s time to move a bit forward: we will install React.js and configure it. Eventually, the web page of the standard web application will show up in the browser. The installation process The very first step...

  • Obscure HTML 5 Features That May Make Your Day

    Stumbling into one of those popular, so called “cyber cafès” means that nowadays you will probably find tables occupied by hipster-like web designers, delighting themselves into glorifying the moment when they embraced SASS, React.js, jQuery, Node JS, Ember, Bootstrap, Angular and others. Well...

  • You Asked For It - Scrivito Features & Benefits

    The web is changing at a truly fast pace! New technologies break into the market more rapidly than before. The period of caution and skepticism grows shorter, as the IT world has finally understood the impact of being stuck for too long on technologies which are reliable but outdated. The time to...

  • Getting Sassy with SASS - Your First Steps

    CSS is great and there would be no web without it: if you have been involved enough to remember the state of the web in the late nineties, you will immediately get the point (probably, along with a couple of shivers). Unfortunately, CSS has its limitations and they are not easy ones; that’s why...

  • DOM Traversing with jQuery - What You Need to Know

    The Document Object Model (DOM) is an object-oriented representation of a web page which can be modified with a scripting language, like JavaScript: we can think of the DOM as a representation of an HTML page in a way JavaScript can understand. JQuery is a very popular JavaScript library that...

  • Tips & Guidelines for A Better Mobile UX - pt2

    Mobile websites are not just a trend; they meet the user’s demand for a better and more rational use of their time. If we are already out of the office and need to check if the product we want to buy is effectively in the store we are confidently heading to, it’s nice to be able to check this on...

  • Tips & Guidelines for A Better Mobile UX - pt1

    When the iPhone came out it started the mobile web revolution: for the first time, we could browse web pages on a mobile phone in a decent and usable way. As soon as people had started to do that, the limits of the resizing technology used became evident, accompanied by a high demand for a...

  • Five Quick Tips to Learn JavaScript Faster

    JavaScript has been around quite a while now and we can almost consider it part of the ”old wide web”. But the JavaScript we use now has evolved immensely since its first days. We could better say that what really evolved were the projects that had JavaScript as their core and that made the web...

  • Video Tutorial: Building a React App - pt1: Introduction

    Anybody interested in Javascript development has likely stumbled on MVC frameworks, a term that is pretty much going strong recently and defines a library built according to the “model - view - controller” design pattern. React.js is a Javascript library that acts as the “view” part of an MVC...

  • Traditional, Headless or Decoupled: The New State of CMSs

    Headless CMS is a term that has been on everybody’s lips recently, along with Content as a Service and Decoupled CMS. Actually, these three concepts are very closely related; you can’t talk about any of them without citing the others as well but, for a better insight on the topic, talking about...