Day 4 – Advanced Selectors

Description

This example demonstrates selecting/targeting specific elements in order to apply unique styles to those otherwise un-unique elements. For example, in an unordered list, jQuery advanced selectors allow us to target specific li elements in numerous ways.

Some basic selectors include:

  • 'li:first'
  • 'li:last'
  • 'li:even' (zero based so the first li is actually even, not odd)
  • 'li:odd' (zero based)
  • i:nth-child(4)
    • gets the fourth li
  • li:eq(4)
    • gets the fifth li --> this one is zero based so it assumes the first one is zero, so asking for 4 will actually return the fifth li
  • li a[title=title]
    • this gets the a with the title attribute of 'title' directly after an li

In the example below, we are targeting all a elements that directly follow an li (li > a) and adding a class="alert" to those elements. We then have a style for a elements with a class of "alert" so that we know our script is working properly.

See the jQuery documentation for further explanation and examples of advanced selectors.

Demo:

If you view the source, you can see that our 'a' elements within 'li' have a class of alert added to them (our jQuery worked!). Then, our styles make those 'a's' with the class 'alert' red (.alert {color: red;}).

The Code:

HTML

<ul>
    <li>List Item 1</li>
    <li>List Item 2</li>
    <li><a href="#" title="not title">List Item 3</a></li>
    <li>List Item 4</li>
    <li><a href="#" title="title">List Item 5</a></li>
    <li>List Item 6</li>
    <li>List Item 7</li>
  </ul>

CSS

.alert {color: red;}

jQuery

<script src="js/jquery.min.js"></script>  <!-- This links to the jquery framework.  Remember that it must be in your project folder in a folder named 'js' -->
<script type="text/javascript" charset="utf-8">
    $(function() {
        $('li>a').addClass('alert'); // this adds a class of 'alert' to all a elements that follow an li.  Our styles (see stylesheet) then changes the color of these selected elements.
    });
  </script>

Download Source

View the ThemeForest.net Screencast »

Post a Comment

Your email is never shared. Required fields are marked *