find the relative element with jQuery
Starting with element loaded up in $elem
var $closestRelativeParent = $elem.parents().filter(function() {
// reduce to only relative position or "body" elements
var $this = $(this);
return $this.is('body') || $this.css('position') == 'relative';
}).slice(0,1); // grab only the "first"
I assume that you'd want to know this in order to calculate the position of the child from it's first relative parent. I would suggest that the better approach would be to just use jQuery's .offsetParent()
calculation, which will also look for parents of position fixed
and absolute
, as these will have a similar impact on the child's position.
That said, here's a quick mock-up of how you might go about using .offsetParent()
to calculate it's relative position (see JSFiddle):
// Given a target, find it's first offset parent, and work out the targets position
// relative to the parent, by deducting their respective .offset() values
var $target = $("#bar"),
$offsetParent = $target.offsetParent(),
oTarget = $target.offset(),
oParent = $offsetParent.offset(),
posTop = oTarget.top - oParent.top,
posLeft = oTarget.left - oParent.left;
// Validate this works by cloning #bar and positioning the clone directly on top
// Result should be a blue "bar" rather than a "red" one.
$target.clone().appendTo($offsetParent).attr("id", "confirm").css({
top: posTop,
left: posLeft
});