modern-web-design-and-development

(Brent) #1

element’s ancestry, not a whole bunch of them, so I tend to use this more
than parents(). Say we wanted to know whether an element was a
descendant of another, however deep in the family tree:


1 if ($('#element1').closest('#element2').length == 1)

(^2) alert("yes - #element1 is a descendent of #element2!");
3 else
(^4) alert("No - #element1 is not a descendent of #element2");
Tip: you can simulate closest() by using parents() and limiting it to
one returned element.
1 $($('#element1').parents('#element2').get(0)).css('background',
'#f90');
One quirk about closest() is that traversal starts from the element(s)
matched by the selector, not from its parent. This means that if the selector
that passed inside closest() matches the element(s) it is running on, it
will return itself. For example:
1 $('div#div2').closest('div').css('background', '#f90');
This will turn #div2 itself orange, because closest() is looking for a


, and the nearest
to #div2 is itself.

2. .position() vs. .offset()


These two are both concerned with reading the position of an element —
namely the first element returned by the selector. They both return an
object containing two properties, left and top, but they differ in what the
returned position is relative to.