Friday, April 29, 2011

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 <div><a><img id="myImg"/></a></div>
GetParents('myImg'); will return "div a" something like that

From stackoverflow
  • 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

    altCognito : But that parent has a parent and so on and so forth.
    eteubert : That's right, thank you. I edited my answer.
  • /// 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 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 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();
    }
    

0 comments:

Post a Comment