Commonly Confused Bits Of jQuery

on Tuesday, 4 March 2014

1. .parent() vs. .parents() vs. .closest()


PARENT(SELECTOR)


This simply matches the one immediate parent of the element(s).






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.

CLOSEST(SELECTOR)


This is a bit of a well-kept secret, but very useful. It works like parents(), except that it returns only one parent/ancestor.
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:
$('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()



position() calculates positioning relative to the offset parent — or, in more understandable terms, the nearest parent or ancestor of this element that has position: relative. If no such parent or ancestor is found, the position is calculated relative to the document (i.e. the top-left corner of the viewport).
offset(), in contrast, always calculates positioning relative to the document, regardless of the position attribute of the element’s parents and ancestors.


3. .css(‘width’) and .css(‘height’) vs. .width() and .height()

.css(‘width’) and .css(‘height’) return value in string with "px"
.width() and .height() return value in integer so calculation.





0 comments :

Post a Comment