最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get all element parents using jquery? - Stack Overflow

programmeradmin2浏览0评论

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

Share Improve this question edited Apr 14, 2009 at 18:43 Amr Elgarhy asked Apr 14, 2009 at 18:37 Amr ElgarhyAmr Elgarhy 68.9k70 gold badges192 silver badges310 bronze badges
Add a comment  | 

5 Answers 5

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

发布评论

评论列表(0)

  1. 暂无评论