alekzajic
11/16/2017 - 2:56 PM

get parent element

Functions for geting the parent element in Javascript

var getParentNode = function(elem, level) { 
    level = level || 1; 
    for (var i = 0; i < level; i++) {
        if (elem != null) {
            elem = elem.parentNode; 
        }
    }
    return elem; 
}
// 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') );
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;
}