Skip to content Skip to sidebar Skip to footer

How To Get All Element Parents Using Jquery?

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

Solution 1:

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();
}

Solution 2:

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

Solution 3:

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"

Solution 4:

You can get all the tags of an element's parents like this:

var sParents = $('#myImg').parents('*').map(function() {                
      returnthis.tagName;
    }).get().join(' ');

you can also replace this.tagName with this.id for example or other attributes

Post a Comment for "How To Get All Element Parents Using Jquery?"