views:

3079

answers:

4

How to get all element parents using jquery? i want to save these parents in a variable so i can use later as a selector.
such as <div><a><img id="myImg"/></a></div>
GetParents('myImg'); will return "div a" something like that

+2  A: 

Every element has only one real parent. To access and save it, write the following:

myParent = $("#myElement").parent();

If you need the parents parents too, use .parents()

See documentation for further information:

http://docs.jquery.com/Traversing/parent#expr

http://docs.jquery.com/Traversing/parents#expr

eteubert
But that parent has a parent and so on and so forth.
altCognito
That's right, thank you. I edited my answer.
eteubert
+3  A: 

/// Get an array of all the elements parents:

allParents = $("#myElement").parents("*")

/// Get the nested selector through an element's parents:

function GetParents(id) {
    var parents = $("#" + id).parents("*");
    var selector = "";
    for (var i = parents.length-1; i >= 0; i--) {
        selector += parents[i].tagName + " ";
    }

    selector += "#" + id;

    return selector;
}

GetParents('myImage') will return your nested selector: HTML BODY DIV A #myImage

Note sure why you'd want this but its reuseable as a selector.

+1  A: 

You can use parents() to get your immediate parent, and their parents on up the tree. you can also pass a selector as an arg to only get parents that match a certain criteria. For instance:

$('#myelement').parents('[id$=container]')

to get all parents who have an id attribute whose value ends with the text "container"

digitaljoel
+3  A: 

You don't need to grab their selectors, as you can use them directly with jQuery afterwards.

If you want to use all parents later, you can do something like:

var parents = $("#element").parents();
for(var i = 0; i < parents.length; i++){
  $(parents[i]).dosomething();
}
Seb