modern-web-design-and-development

(Brent) #1

parent(selector)


This simply matches the one immediate parent of the element(s). It can
take a selector, which can be useful for matching the parent only in certain
situations. For example:


1 $('span#mySpan').parent().css('background', '#f90');
2 $('p').parent('div.large').css('background', '#f90');

The first line gives the parent of #mySpan. The second does the same for
parents of all

tags, provided that the parent is a div and has the class
large.


Tip: the ability to limit the reach of methods like the one in the second line
is a common feature of jQuery. The majority of DOM manipulation methods
allow you to specify a selector in this way, so it’s not unique to parent().


parents(selector)


This acts in much the same way as parent(), except that it is not
restricted to just one level above the matched element(s). That is, it can
return multiple ancestors. So, for example:


1 $('li.nav').parents('li'); //for each LI that has the class nav,
go find all its parents/ancestors that are also LIs

This says that for each

  • that has the class nav, return all its parents/
    ancestors that are also
  • s. This could be useful in a multi-level
    navigation tree, like the following:


    1 <ul id='nav'>

    (^2)

  • Link 1
    (^3)

  • Free download pdf