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
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
5 Answers
Reset to default 9/// 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.
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();
}
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
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"
You can get all the tags of an element's parents like this:
var sParents = $('#myImg').parents('*').map(function() {
return this.tagName;
}).get().join(' ');
you can also replace this.tagName with this.id for example or other attributes