May 27, 200915

Targeting Advanced Elements in jQuery

CSS was built on the idea of separating display from structure in an HTML document. jQuery was built on similar principals, with the idea of separating behavior from structure. If you are familiar with jQuery, then you probably know about selecting elements by class or ID. jQuery contains a wealth of other ways to select elements when using just classes and Ids won’t cut it. Using these selectors are great when you are working with many HTML elements, and allows you to do very impressive things with very small amounts of code.

All In The Family

The terms ‘children’ and ’sibling’ elements are a common term in the computer world. When talking about HTML, child elements are elements that are inside of another element, which is called their parent element. Elements that are on the same level in the child-parent hierarchy are called siblings.

Check out the code example below:

<div id=’Family_Tree’>
  <div id=’Uncle_Joe’>
    <p> Mary Sue </p>
    <p> Billy Joe </p>
  </div>
  <div id=’Papa_Bear’>
    <ul class=’pets’>
      <li>Sparky</li>
      <li>Spot</li>
      <li>Muffin</li>
    </ul>
  </div>
  <div id=’Mama_Bear’>
    <div> Jane Doe</div>
  </div>
</div>

In this example, Uncle_Joe and Papa_Bear are siblings. The pets list is a child of Papa_Bear, and Sparky,Spot, and Muffin are all grandchildren of Papa_Bear. Mama_Bear and Papa_Bear are also siblings(ewww!).

With jQuery, we can target any single element or any group of elements using selectors. We’ll be using the example HTML in all of our examples. If you want to play along at home, you may want to copy it and add some styling to it so they can easily be distinguished.

Selecting Children

One of the simplest ways to select children is using the ‘>’ operator. When using a jQuery object, put the parent element first, then the children of that element you want to target.

Here are some examples:


$(“#Family_Tree > *”) //Selects all children of Family_Tree
$(“#Family_Tree > div”) //selects all divs inside of family tree.

Both of these examples will return the three divs of Uncle_Joe, Mama_Bear, and Papa_Bear. It will not target children of children.

Selecting Siblings

The simplest way of getting sibling elements is to use the sibling function. Due to the chaining of jQuery functions, you can use a jQuery object with the method attached as a jQuery object.

Here’s an example of the syntax:


$(’#Papa_Bear’).siblings(); //selects all the siblings

There is a parent() function that can be chained this way as well, returning the parent object of an element. Here’s an example combining all of our family functions. With this jQuery code, every time you click on one of the children of Family_Tree, it toggles the other two:


$(function(){
  $(’#Family_Tree > div’).click(function(){
    $(this).siblings().slideToggle(500);
  })
});

Not a bad effect for only 5 lines of code, eh?

Iteration

Understanding iteration is great if you ever have a group of elements you need to manipulate in a organized fashion. An image rotator is a good example of when you would want to use this. jQuery has a number of selectors to help with this.

Selecting First and Last

There are two ways to do this, one is with the :first and :last selectors, which can give you the first and last instances of any selector.


$(“div :first”); //selects the first div on the page
$(“ul li :last”); //selects the last li in all uls.

If you are looking at elements that belong to another element, for example li tags inside of a ul, then you can use the :first-child and :last-child selectors, along with the children() method. The two examples below would return Uncle_Joe and Mama_Bear from the Family_Tree div:


$(“#Family_Tree).children(’:first-child’);
$(“#Family_Tree).children(’:last-child’);

Notice that these two jQuery objects are exactly the same:


$(’#Family_Tree > *’);
$(’#Family_Tree’).children();

Selecting Next and Previous

There are four functions for selecting next and previous, that work in a similar way to the siblings() function. They are next(), prev(), nextAll(), and prevAll(). next() and prev() will return the direct next or previous element (if it exists), while nextAll() and prevAll() predictably return all of the next or previous elements relative to an element.

Selecting a Specific Element

in addition to the :first-child and :last-child selectors, there is also the :nth-child selector. This is followed by the number of the element. Note that it is one-based, not zero-based.

Here’s an example:


$(’#Family_Tree :nth-child(2)); //returns the ‘Papa_Bear’ element

Conditionals

Sometimes you may need to see if an element has a certain attribute or matches a certain selector. For this, we have the is() function. Unlike most other jQuery functions, this will return a boolean instead of another instance of the jQuery object.

The example below combines what we’ve learned from the previous sections to cycle through the three divs inside of the Family_Tree. Add a link outside of the Family_Tree div, and then try the following jQuery code:


var Target = $(’#Family_Tree’).children(’:first-child’);
Target.css(”color”,”#c00?);

$(’a').click(function(){
  Target.css(”color”,”#000?);
  if(!Target.is(’:last-child’)){
    Target = Target.next();
  }
  else{
    Target = Target.siblings(’:first’);
  }

  Target.css(”color”,”#c00?);
});

You’ll see that as you click through the elements, it rotates which text is red. This can be really handy if you ever need to build an image rotator or something similar in jQuery.

Other Selectors

jQuery has a ton of other selectors available, to many to mention here. You can check out the jQuery documentation on selectors, or a jQuery cheat sheet. You can target literally everything about an HTML element using them.
When used properly, targeting elements in jQuery like can save you lots of coding, and allow you to do things you wouldn’t be able to do otherwise. It also makes it possible to do everything you want to do without using inline JavaScript, which makes your code easier to read and maintain.

If you have any questions about targeting advanced elements in jQuery, or jQuery questions in general, be sure to drop us a line in the comments!

15 Comments

  • Marco
    May 27, 2009

    Interesting approach and well explained article.

    Just one question, why the arrow:
    $(“#Family_Tree > div”)

    This would work too, wouldn’t it:
    $(“#Family_Tree div”)

    Keep up the great work!

  • seb
    May 27, 2009

    @Marco: $(”#Family_Tree > div”) will search only first level children of #family_Tree. It is more restrictive search and also more optimized.

  • Joel R.
    May 27, 2009

    The arrow allows you to select (>) all divs within the family tree. The arrow basically signals the “selection” of the divs. I haven’t tried it without it, but perhaps it does work without it :)

  • saintberry
    May 27, 2009

    @Marco

    The > is used to only select direct children DIVs. If $(“#Family_Tree div”) was used as the selector it would select ANY div that sits at ANY level under the #Family_Tree element.

    That is to say, if you had a div inside #Uncle_Joe it would be selected, with #Family_Tree > div, it would not.

  • Joel R.
    May 28, 2009

    Thank you all for your comments!

  • Balaji
    May 28, 2009

    Wow, I hadn’t thought about it that way before. Good write up, very clearly written. Have you written previously about jquery? I’d love to read more

  • Egypt Web Design
    May 28, 2009

    Thanks for the article it really help a lot :-)

  • Farid Hadi
    May 29, 2009

    This is a great article. This one definitely gets bookmarked. Thanks!

  • Anthony Alexander
    Jun 2, 2009

    Why are all these tutorials labeled JQuery .. This is CSS, as used by Jquery, there was nothing JQuery specific. This is just a CSS selectors tutorial, if that.

  • Links a gogo | Chris' Blog
    Jun 4, 2009

    [...] Targeting Advanced Elements in jQuery: Ein paar Beispiele, wie man mit jQuery genau das Element findet, das man sucht. [...]

  • Targeting Advanced Elements in jQuery | Web 2.0 Design Blog
    Jun 8, 2009

    [...] More here:  Targeting Advanced Elements in jQuery [...]

  • VPS Web Hosting
    Jun 10, 2009

    Great article about the uses of jQuery. Thanks for the help!

  • The Technology Post for May 27th | rapid-DEV.net
    Jun 14, 2009

    [...] jQuery – Targeting Advanced Elements in jQuery – Design Reviver (Suggested by Elijah Manor) [...]

  • egypt web design
    Oct 26, 2009

    thanks for the nice article.

  • jQuery Week: 10 Plugins for Manipulating CSS & HTML - Purpleurbia.com
    Nov 3, 2009

    [...] that. It lets you change yet another one of those ugly default parts of the web with jQuery. Targeting advanced elements One of the best parts of jQuery is its ability to use advanced selectors, and this indepth guide [...]

Leave a Comment

Ask a Question at Design Reviver Answers