Web Development with jQuery®

(Elliott) #1

Adding to a Selection (^) ❘ 59
not include element #2 itself. So, this selection will include

  • The Shire
  • and
  • Fangorn
    Forest
  • .


    Adding to a Selection


    Finally, I introduce you to the add() method. The add() method is the inverse to the not() method,
    and it is used to add to an existing selection. The following HTML, again, represents places in
    Middle Earth:

    <!DOCTYPE HTML>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="content-type"
    content="application/xhtml+xml; charset=utf-8" />
    <meta http-equiv="content-language" content="en-us" />
    <title>Places in Middle-Earth</title>
    </head>
    <body>
    <ul id='middleEarthPlaces'>
    <li>The Shire</li>
    <li>Fangorn Forest</li>
    <li>Rohan</li>
    <li>Gondor</li>
    <li>Mordor</li>
    </ul>
    <ul id='middleEarthMorePlaces'>
    <li>Osgiliath</li>
    <li>Minas Tirith</li>
    <li>Mirkwood Forest</li>
    </ul>
    </body>
    </html>

    A simple demonstration of the add() method is to make an initial selection, such as
    $('ul#middleEarthPlaces li'), which selects all the <li> elements in the fi rst <ul> element. Then
    you can add to that selection with a class like this:

    $('ul#middleEarthPlaces li').add('ul#middleEarthMorePlaces li');

    The resulting selection now includes all the <li> elements present in the document because you fi rst
    selected the <li> elements in the fi rst <ul> element, and then you added to that selection the <li>
    elements of the second <ul> element.

    Like the not() method, you can add elements to a selection using the result of a jQuery selection,
    just like this:

    $('ul#middleEarthPlaces li').add($('ul#middleEarthMorePlaces li'));

    You can also use direct DOM object references, like this:


    http://www.it-ebooks.info

    Free download pdf