Native JS Implementation of jQuery's parents
发布于 2026-07-06 08:38:34
1 次浏览
function getParents(el, parentSelector /* optional */) {
// console.log(el);
// 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);
return parents;
}
/* Or */
/**
* Find ancestor elements of the DOM to see if they contain the id or class specified by parentSelector
* @param el The DOM element to start from
* @param parentSelector The id or class name of the ancestor element to find
* @returns boolean|HTMLElement
* // getParents(document.getElementById('ResTableList'), '#main或者.main');
*/
export function getParents(el, parentSelector) {
if (!parentSelector ||
parentSelector === undefined) {
throw new Error('Please pass the id or class name of the parent element to search, e.g., #id or .classname');
}
// Default matching type
var type = 'className';
var splitF = '.';
// If the first character is #, it means the passed selector is an id
if (parentSelector.indexOf('#') === 0) {
type = 'id';
splitF = '#';
}
// Split the string according to type
var selector = parentSelector.split(splitF)[1];
function getP(el) {
// Get the parent element of the current element
var p = el.parentNode;
// If the parent element is document, it means we've reached the top level, meaning no matching ancestor found
if (p === document) {
return false;
}
// If the parent element's id or class contains the selector
if (p[type].indexOf(selector) > -1) {
// If it contains, return this element
return p;
} else {
// If not, then recurse. Need to return the recursive function, otherwise there will be no return value
return getP(p);
}
}
var final = getP(el);
return final;
}
getParents(document.getElementById('ResTableList'), '#main');
getParents(document.getElementById('ResTableList'), '.main');
If one of its parent elements contains the element to be searched, return it; otherwise return false
暂无评论。