Tips

Targeting Advanced Elements in jQuery

May 27, 2009 • By

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!

(Visited 350 times, 1 visits today)