.parents() without jquery - or querySelectorAll for parents [duplicate]

限于喜欢 提交于 2019-11-27 08:25:36

Just cause I'm a nice guy! In the future always make sure you have some code in your question, or they will more than likely be closed / downvoted :/

But you would want to use a while() loop since we don't know the exact number of parents we have

jsFiddle Demo

function getParents(el, parentSelector /* optional */) {

    // If no parentSelector defined will bubble up all the way to *document*
    if (parentSelector === undefined) {
        parentSelector = document;
    }

    var parents = [];
    var p = el.parentNode;

    while (p !== parentSelector) {
        var o = p;
        parents.push(o);
        p = o.parentNode;
    }
    parents.push(parentSelector); // Push that parentSelector you wanted to stop at

    return parents;
}

Useage: Returns an Array of "parents"

// 2nd param optional, bubbles up to document
getParents( document.getElementById('me') ); 

// get all parents starting from -me- up to ID -outerParent-
getParents( document.getElementById('me'), document.getElementById('outerParent') );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!