Joe Saad
Joe Saad

Reputation: 1950

How to get the offsetParent() which is relative only

I have searched this one a bit now. Is there a way to get only the offsetParent() of an element where that parent is positioned relative only? I don't want other parents with all positions. Just the parent that has relative position.

I was thinking of something like

$('myelement').offsetParent().css('position','relative');

I want it to return only the first positioned parent that has relative position but this won't solve it, I know.

Upvotes: 0

Views: 395

Answers (2)

TLindig
TLindig

Reputation: 50090

What about a loop?

function findRelative(selector) {
   for(var $e = $('selector'); $e.css('position') !== 'relative'; $e = $e.offsetParent()) {
      if($e.length === 0) return null;
   }
   return $e;
}

Upvotes: 1

adambullmer
adambullmer

Reputation: 1012

Here's the solution in practice: http://jsfiddle.net/tYQPy/

Assuming you want the parent closest to the child container, all you need is a little recursion. =)

function findOffsetParent(target) {
    var parent = target.offsetParent();

    if (parent.css('position') === 'relative') {
        return parent;
    }
    else {
        return findOffsetParent(parent);
    }
}

Feed the parameter to that function a jQuery selected element, and it will return to you the jQuery selection of the relative positioned parent.

Note, that this will be very cumbersome if you need to iterate through a lot of elements.

Written with jQuery seeing that you have jQuery in your initial question

Upvotes: 2

Related Questions