Part 3. jQuery Basics: Pseudo selectors

Published on: July 19, 2013 Written by: Thokozani Mhlongo

 jQuery Pseudo selectors

Pseudo selectors are very useful. You might often find yourself using them quite often when building web applications too. You may be familiar with some of these selectors - CSS selectors - such as :hover , :visited , etc. They are preceded with a colon behind them and a typical example is the CSS selector a:hover selector which applies your specified styles to a hyperlink when you hover over it. You might find yourself in a situation where you create a web form with multiple checkboxes or radio buttons, and you might want to perform certain validation/computation or perform some action based on what a user checks on that form. A live example would be Gmail. If you take a look at your Gmail's user interface, you will notice that with every email listed on your inbox has a checkbox next to it that you can tick and when you do so you'll see that at the top of that list actions suddenly show up such as deleting on what you've selected, marking those items as read, and so forth. In the case of an application similar to that of Gmail, we can use pseudo selectors in determining which items were checked. You can review all the selectors on the jQuery selectors API documentation

Let's get started

In this tutorial we are going to covering a lot of these selectors using jQuery. We will also create an example on how to tell the number of items selected on a list. Take a look at the following code, we are going to be using our knowledge we've gained from our last tutorial on events and animations. If you haven't viewed the tutorial then click here before you continuing with this one. In this example we are going to be fading out the "first" paragraph when a button is clicked.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
    <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />

    <title>jQuery Pseudo Examples</title>
    <script type="text/javascript" src="/jquery-1.8.2.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('#fadeOurFirstParagraph').click(function() {
               $('p:first').fadeOut(500);
            });
        });
    </script>
</head>

<body>
    <button id="fadeOurFirstParagraph">Click to fade out the first button</button>

    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>
    <br />
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>
    <br />
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>
    <br />
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>
</body>
</html>  


If you take a look at the highlighted line above we have used the :first selector on the <p> tag specified on our $(...). What we are saying here is fade out the first paragraph only. We can also fade out the last paragraph by replacing our highlighted line above with this one:

$('p:last').fadeOut(500);


Let's take a look at an example where we'd like to fade out a paragraph that's not the first nor even the last. In that case there's a selector called :eq(N) where N is the position where the paragraph is on the document. The N starts at 0 onwards. So lets try fading out the second paragraph which is at index 1. Look at the following code which does exactly that:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
  <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />

  <title>jQuery Pseudo Examples</title>
    <script type="text/javascript" src="/jquery-1.8.2.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('#fadeOurSecondParagraph').click(function() {
                $('p:eq(1)').fadeOut(500);
            });
        });
    </script>
</head>

<body>
    <button id="fadeOurSecondParagraph">Click to fade out the first button</button>

    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>
    <br />
    
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>
    <br />
    
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>
    <br />
    
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>
</body>
</html>  


Now lets play around with even and odd. I'm sure you've seen tables which have one color for all odd rows and another color for all event rows (Especially on web hosting websites). One technique to accomplish that table style would be to use the :even and :odd selectors on rows of that table. What you would do is define two CSS classes (either call them .even-table-row and .odd-table-row) and have them define their background value, then you can apply those classes by using the pseudo selectors. NOTE: We will cover using CSS classes with jQuery later on. For now though just focus on the point we're trying to make on selecting HTML elements based whether they are even or odd. Take a look at the following code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
  <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />

  <title>jQuery Pseudo Examples</title>
    <script type="text/javascript" src="/jquery-1.8.2.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('#fadeOurEvenParagraphs').click(function() { 
                $('p:even').fadeOut(500);
            });
        });
    </script>
</head>

<body>
    <button id="fadeOurEvenParagraphs">Click to fade out the first button</button>

    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>
    <br />
    
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>
    <br />
    
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>
    <br />
    
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>
</body>
</html>


Now again, just like the :eq(N) selector the index starts at 0. Now when running this example don' freak out if you see the first and the third paragraph fade out when you specify the :even selector. THEY START FROM ZERO! The first paragraph is 0 (even in jQuery) and the second is 1 (odd) and the third paragraph is 2 (even), and so on and so on.... In jQuery we can also find an element based on what text it contains. An example could be a spell checking application. In this example we going to doing the same concept of fading out text from the screen but this time based on a word. Take a look at the code below:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
  <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />

  <title>jQuery Pseudo Examples</title>
    <script type="text/javascript" src="/jquery-1.8.2.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('#fadeOutByWord').click(function() { 
                $("p:contains('ipsum')").fadeOut(500);
            });
        });
    </script>
</head>

<body>
    <button id="fadeOutByWord">Click to fade out by word</button>

    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>
    <br />
    
    <p>This is the second paragraph</p><br />
    
    <p>This is the third paragraph</p><br />
    
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>
    <br />
</body>
</html>


We used the :contains(...) selector and specified the word we wanted to find in within a paragraph and fade that paragraph out. In this case we have two paragraphs that contain this word and they both fade out when we test the code on our browser. 

Our little scenario

Let's look at some situations where you might use a pseudo selector. Suppose you're creating a web application that takes skills of a certain user for their profile. You provide all your skills as a list of checkboxes:

 

Now this is common on some forms where a user can select any number of provided choices. In this case we are only going to alert how many the user has selected by using the :checked selector. And we do that by the following code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
  <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />

  <title>jQuery Pseudo Examples</title>
    <script type="text/javascript" src="/jquery-1.8.2.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('#getCheckedCount').click(function() { 
                alert( $('input[type=checkbox]:checked').length );
            });
        });
    </script>
</head>

<body>
    <button id="getCheckedCount">Get number of selected skills</button>

    <h2>Skills form</h2>
    <form>
        <input type="checkbox" id="css" /><label for="css">CSS</label><br />
        
        <input type="checkbox" id="jquery" /><label for="jquery">jQuery</label><br />
        
        <input type="checkbox" id="html" /><label for="html">HTML</label><br />
        
        <input type="checkbox" id="xml" /><label for="xml">XML</label><br />
        
        <input type="checkbox" id="json" /><label for="json">JSON</label><br />
        
        <input type="checkbox" id="python" /><label for="python">Python</label><br />
    </form>
    
</body>
</html>  

As the highlighted line suggests, we retrieve all the checkboxes that were checked by the user. jQuery then puts these checkbox elements into an array and used .length to find out how many of those checkboxes were selected. Also remember that an HTML checkbox is an input type. So when we have to specify that when selecting on $(...)

Conclusion

We've seen how we could use pseudo selectors to your advantage and we've also highlighted a few scenarios where you would need to use them. Remember to also review the API documentation on selectors.

Comments