selecting root element in jquery

后端 未结 9 814
粉色の甜心
粉色の甜心 2021-01-18 04:06

I need to be able to select the root element from a fragment without knowing the node types, class, id or hierachy.

9条回答
  •  猫巷女王i
    2021-01-18 04:51

    I may be misunderstanding the question, but assuming by root you mean the point at which the parent is a different tag to the child then the following should work.

    function GetRoot(element) {
        while(element.parent().attr("tagName") == element.attr("tagName")) {
            element = element.parent();
        }
    
        return element;
    }
    

    This basically walks up the tree until it finds a parent that is a different tag and then returns the item. For your example that would mean that if your element was in a , , or whatever it would detect it as the root and return it.

    Making a custom jquery selector with this should be possible too, but is obviously more complicated.

    It should also be fairly easy to extend this to take an integer that defines the level. All you'd need to do is walk down the tree to the specified depth once you've found the root and return those elements.

提交回复
热议问题