Jquery Tutorial : Selections And Dom Traversing

Forums » Bookshelf » Jquery Tutorial » Selections And Dom Traversing

2. Selection and DOM Traversal

Before you start doing any interactions with your page you need to select one or more elements in your page.

This chapter will illustrate different ways to select elements on your page.

You will also learn jQuery techniques for traversing the document object model (DOM) — that is, finding parent elements, siblings, etc. from an original selection.

2.1. Selection

  • You must first select elements before you can manipulate them in any way.

    • jQuery does an excellent job at selecting elements (that was the original purpose of jQuery).
    • Selection is based on the open source Sizzle selector engine.
    • It provides support for most CSS1-3 selectors, plus its own custom extensions.
  • jQuery selection returns a jQuery object.

    • The jQuery object represents 0 or more elements in your document.
    • The jQuery object is derived from the “global” jQuery function object, so it has access to all methods and properties defined in the jQuery function object.
    [Warning]Warning

    If no elements match the selection, the result is a jQuery object representing 0 elements. You can use the object’s .length property to determine the number of elements it represents. For example, $('div').length returns the number of <div> elements in the page

  • We are going to discuss different categories of selectors, but not all selectors are covered here. See http://api.jquery.com/category/selectors/ for a complete list and description of supported jQuery selectors.

2.2. Basic Selectors

Basic jQuery selectors work the same as CSS selectors:

$('p');
Selects all the <p> elements in your page
$('*');
Selects all elements on the page
$('.status');
Selects all elements with the class status
$('#header');

Selects the element with the id header

[Note]Note

You should not use the same id for more than one element. If you do so and if you perform a selection by id, only the first matched element in the DOM will be returned

$('p, li, .status, #nav');
Selects all <p> and <li> elements, all elements with the status class, and the element with the id nav.

2.3. Hierarchy Selectors

jQuery hierarchical selectors also work the same as CSS selectors:

$('#footer span');
Selects the <span> elements that are descendants of the element with the id footer.
$('ul > li');
Selects the <li> elements that are immediate children of <ul> elements.
$('h2 + p');
Selects the <p> elements that are immediately preceded by an <h2> element.
$('h2 ~ p');
Selects all <p> elements following an <h2> element that have the same parent as the <h2> element.

2.4. Selection By Attribute

Another powerful selection type is selection by attribute:

$('a[href]');
Selects all <a> elements that have an href attribute.
$('a[href="http://mrkn.co/f/271"]');
Selects all <a> elements whose href attribute exactly matches "http://mrkn.co/f/271".
$('a[href*="goo.gl"]');

Selects all <a> elements whose href attribute contains "goo.gl". For example, this would match:

<a href="http://goo.gl/DeSyV" class="url">Interesting link</a>
$('a[href^="http://bit.ly"]');

Selects all <a> elements whose href attribute starts with "http://bit.ly". For example, this would match both of these elements:

<a href="http://bit.ly/eU3ccR" class="url">One link</a>
<a href="http://bit.ly/jqcon11SF" class="url">Another link</a>
$('a[href$=".pdf"]');

Selects all <a> elements whose href attribute ends with ".pdf". For example:

<a href="http://mrkn.co/docs/info.pdf" class="url">Download PDF version</a>
$('p[lang|="en"]');
Selects all <p> elements whose lang attribute matches either "en" or "en-\*", where * can be anything.
[Note]Note

A detailed explanation on selection by attribute can be found at the following URL: http://api.jquery.com/category/selectors/attribute-selectors/

2.5. Form Selectors

jQuery also comes with useful selectors related to forms.

$(':button'); , $(':checkbox'); , $(':file'); , $(':image'); , $(':password'); , $(':radio'); , $(':reset'); , $(':submit'); , $(':text');
Selects all <input> elements of the specified type.
$(':input');
Selects all form elements, including <textarea> and <select> elements.
$(':checked');
Selects all checkbox and radio elements that are checked.
$(':selected');
For <option> elements, returns the selected option(s).
$(':disabled'); , $(':enabled');
Selects all disabled/enabled form elements.
[Note]Note

It’s recommended to precede these selectors with a tag name or some other selector; otherwise, the universal selector (*) is implied (e.g., $(":checkbox") implies $("*:checkbox")).

The following will serve as an example to demonstrate form selectors:

<form name="foodieform">
  <fieldset>
    <legend>Search a recipe:</legend>
    <label for="txt_recipe_name">Recipe name:</label>
    <input type="text" name="txt_recipe_name" id="txt_recipe_name" />
    <label for="meal_type">Type of meal:</label>
    <select id="meal_type" name="meal_type">
      <option value="Apetizer" selected>Apetizer</option>
      <option value="Entree">Entree</option>
      <option value="Drinks">Drinks</option>
      <option value="Desert">Desert</option>
    </select>
  </fieldset>
  <fieldset>
    <legend>Choose a type of food</legend>
    <input type="checkbox" name="food_type" value="French" checked>French</input>
    <input type="checkbox" name="food_type" value="Italian">Italian</input>
    <input type="checkbox" name="food_type" value="Mexican">Mexican</input>
    <input type="checkbox" name="food_type" value="Chinese">Chinese</input>
  </fieldset>
  <fieldset>
    <legend>Skills required</legend>
    <input type="radio" name="food_skills" value="1"/>Easy
    <input type="radio" name="food_skills" value="2"/>Medium
    <input type="radio" name="food_skills" value="3" checked/>Hard<br/>
  </fieldset>
  <input type="button" name="form-button" id="form-button" value="search"/>
  <input type="reset" name="form-reset" id="form-reset"/>
</form>
  • $(':checked'); would select:

    <input type="checkbox" name="food_type" value="French" checked>French</input>
    <input type="radio" name="food_skills" value="3" checked/>Hard<br/>
  • $(':radio'); would select:

    <input type=​"radio" name=​"food_skills" value=​"1">
    <input type=​"radio" name=​"food_skills" value=​"2">​
    <input type=​"radio" name=​"food_skills" value=​"3" checked>
  • $(':reset');:: Selects reset elements. In this case:

    <input type=​"reset" name=​"form-reset" id=​"form-reset">
  • $(':selected'); would select:

    <option value=​"Appetizer" selected>​Appetizer​</option>
  • $(':text'); would select:

    <input type=​"text" name=​"txt_recipe_name" id=​"txt_recipe_name">
[Note]Note

More information on form selectors is available here ⇒ http://api.jquery.com/category/selectors/form-selectors/

2.6. Position Filters

jQuery allows you to filter the elements selected based on their position in the collection. For example:

$('.article:eq(2)');
Selects the third element with the class article. Elements in a collection are numbered starting with 0.
$('.article:gt(1)');
From the collection of all elements with the class article, select all elements following the second one.
$('.article:lt(3)');
From the collection of all elements with the class article, select up to the first three.
$('.article:first');
Selects the first element with the class article
$('.article:last');
Selects the last element with the class article
$('.article:odd');
Selects the odd elements out of all the elements with the class article (zero-based index: 1,3,5,etc)
$('.article:even');
Selects the even elements out of all the elements with the class article (zero-based index: 0,2,4,etc)
[Note]Note

The order of elements in a collection is determined by the order in which they appear in the document.

2.7. Other Filters

Other useful jQuery filters include:

$(p:contains('Marakana'));
Selects all <p> elements that contain the string "Marakana", either directly or in any of the child elements. The text matching is case sensitive.
$('div:has(h2)');
Selects all <div> elements that have at least one <h2> element as a descendant.
$('option:not(:selected)');
Selects all <option> elements that are not selected.
$('p:hidden'); , $('p:visible');

Selects all <p> elements that are hidden/visible. An element is considered hidden if:

  • It has a CSS display value of none
  • It is a form element with type="hidden"
  • Its width and height are explicitly set to 0
  • An ancestor element is hidden, so the element is not shown on the page

2.8. jQuery Method Chaining

  • The value returned from a jQuery selection is an instance of a jQuery object.

    • You can then invoke methods on that object to manipulate the HTML elements it represents. For example, css() to query and set CSS properties, attr() to query and set HTML attributes, addClass() to add one or more classes, etc.
  • The value returned by most of these manipulator methods is the same jQuery object.

    • That means that you can chain method calls on the object. Here is an example:

      $('.status')
          .css('backgroundColor','yellow')
          .attr('title', 'Training by Marakana');

      This selects the elements with the class status, sets the background color of the selected elements to yellow, and then sets the title attribute of the selected elements.

2.9. DOM Traversal

  • Starting with a jQuery object representing the results of a selection, you have the ability to traverse the DOM.

    • jQuery provides methods for selecting the children, the parents, and the siblings of each element in the wrapped set.
    • Most of these methods accept an option jQuery selector argument, which filters out traversed elements that don’t match the filter.
    • The value returned by these methods is a jQuery object representing the newly selected elements.
    • There are a large number of traversal methods, including:

      $('.article').children('p');
      Selects all <p> elements that are direct first-level children of the elements with the class article.
      $('.article').find('p');

      Selects all descendant <p> elements contained in elements with the class article

      [Note]Note

      The difference between .children() and .find() is that the .children() method only travels a single level down in the DOM.

      $('h2').prev();
      Selects the set of elements that immediately precede <h2> elements.
      $('h2').next('p');

      Selects the set of <p> elements that immediately follow <h2> elements.

      [Note]Note

      In this example, if the element immediately following an <h2> is not a <p>, it is not included in the set of elements returned.

      $('#form-button').siblings('fieldset');
      Gets all the siblings that are <fieldset>
      $('.menu-li2').parent();
      Gets the parent elements of elements having the class menu-li2
  • For more information on DOM traversal, see: http://api.jquery.com/category/traversing/

2.10. Filter Methods

  • Starting with a jQuery object representing a set of elements, you also have the ability to apply a filter method to obtain a subset of elements.

    • The value returned by these methods is a jQuery object representing the subset of elements.
    • Filter methods include:

      $('#content h2').first(); , $('#content h2').last();
      Selects the first/last of the <h2> elements contained within the element whose id is content.
      $('#menu > li').eq(1);
      Selects the second <li> element within the element whose id is menu.
      $('li').filter(':even');
      Selects the even-numbered elements in the set of <li> elements.
      $('div').not('.article');
      Selects the <div> elements that do not have the article class.
      $('li').has('ul');
      Selects the <li> elements that have a <ul> descendant.
  • For more information on filter methods, see: http://api.jquery.com/category/traversing/filtering/

2.11. Advanced Method Chaining

  • Combining method chaining with traversal methods can mix several related actions into one statement. For example:

    $('#selected')
        .css('backgroundColor', 'yellow')
        .parent()
        .addClass('current');
  • An important method to know when doing traversal and chaining is the .end() method.

    • The .end() method ends the most recent filtering/traversal operation in the current chain and returns the set of matched elements to its previous state. Here is an example:
    $('.article')               // 1
        .find('p').css('color','green') // 2
        .end()              // 3
        .find('h2').css('color','red'); // 4

    1 1

    Select elements with the class article.

    2 2

    Select all <p> descendants and set their text color to green.

    3

    Return to the previous selection (elements with the article class).

    4

    Select all <h2> descendants and set their text color to red.