没有jquery的.parents() - 或者父母的querySelectorAll [英] .parents() without jquery - or querySelectorAll for parents

查看:315
本文介绍了没有jquery的.parents() - 或者父母的querySelectorAll的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

使用matchesSelector js检查event.target.parentElement

我有一个dom对象,我想将它的父母,所有父母与一个选择器匹配,比如 querySelectAll(),但对于父母而不是孩子。类似于jQuery的.parents('selector')方法,但我不需要任何后向兼容性。另外,请不要图书馆。我将取一个布尔返回值。

I have a dom object, I'd like to match its parents, all parents, against a selector, like querySelectAll(), but for parents instead of children. Similar to jQuery's .parents('selector') method, but I do NOT need any back-wards compatibility. Also, no libraries please. I will totes take a boolean return value.

我可以自己写这个作为递归函数/ for / while使用 matchesSelector()。我正在寻找鲜为人知的方法或更有效的代码。

I CAN write this myself as a recursive function/for/while using matchesSelector(). I'm looking for little-known methods or more efficient code.

保存任何处理都是值得的。想想成千上万的匹配支票,甚至更多。

Saving any processing is worth it. Think tens of thousands of match checks, or more even.

推荐答案

只是因为我是一个好人!在将来,请务必确保您的问题中包含一些代码,否则它们很可能会被关闭/投票:/

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 :/

但您可能希望使用 while()循环,因为我们不知道我们拥有的父母的确切数量

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

jsFiddle演示

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') );

这篇关于没有jquery的.parents() - 或者父母的querySelectorAll的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆