如何筛选QuerySelectorAll返回的元素

tim*_*ail 20 javascript

我正在开发一个javascript libarary,我使用这个函数来匹配元素:

$ = function (a)
{
    var x;
    if (typeof a !== "string" || typeof a === "undefined"){ return a;}

    //Pick the quickest method for each kind of selector
    if(a.match(/^#([\w\-]+$)/))
    {
        return document.getElementById(a.split('#')[1]);
    }
    else if(a.match(/^([\w\-]+)$/))
    {
        x = document.getElementsByTagName(a);
    }
    else
    {
        x = document.querySelectorAll(a);
    }

    //Return the single object if applicable
    return (x.length === 1) ? x[0] : x;
};
Run Code Online (Sandbox Code Playgroud)

有时我会想要过滤这个函数的结果,比如挑出一个div span或者一个#id div或其他一些相当简单的选择器.

如何过滤这些结果?我可以创建一个文档fragement,并在该片段上使用querySelectorAll方法,或者我是否必须采用手动字符串操作?

我只关心现代浏览器和IE8 +.

如果你想查看我的库的其余部分,它就在这里:https://github.com/timw4mail/kis-js

编辑:

为了澄清,我希望能够执行类似$ _(selector).children(other_selector)的操作并返回与该选择器匹配的子元素.

编辑:

所以这是我对最简单的选择器的潜在解决方案:

tag_reg = /^([\w\-]+)$/;
id_reg = /#([\w\-]+$)/;
class_reg = /\.([\w\-]+)$/;

function _sel_filter(filter, curr_sel)
{
    var i,
        len = curr_sel.length,
        matches = [];

    if(typeof filter !== "string")
    {
        return filter;
    }

    //Filter by tag
    if(filter.match(tag_reg))
    {
        for(i=0;i<len;i++)
        {
            if(curr_sell[i].tagName.toLowerCase() == filter.toLowerCase())
            {
                matches.push(curr_sel[i]);
            }
        }
    }
    else if(filter.match(class_reg))
    {
        for(i=0;i<len;i++)
        {
            if(curr_sel[i].classList.contains(filter))
            {
                matches.push(curr_sel[i]);
            }
        }
    }
    else if(filter.match(id_reg))
    {
        return document.getElementById(filter);
    }
    else
    {
        console.log(filter+" is not a valid filter");
    }

    return (matches.length === 1) ? matches[0] : matches;

}
Run Code Online (Sandbox Code Playgroud)

它采用标签,如divid或类选择器,并返回带有curr_sel参数的匹配元素.

我不想诉诸完整的选择引擎,那么有更好的方法吗?

jAn*_*ndy 22

我不认为我的问题是正确的.你为什么要"过滤"其中的结果,querySelectorAll()实际上是某种过滤器本身.如果您查询div span甚至更好#id div,那些结果已经过滤,不是吗?

但是,您可以应用如下Array.prototype.filter的静态结果querySelectorAll:

var filter   = Array.prototype.filter,
    result   = document.querySelectorAll('div'),
    filtered = filter.call( result, function( node ) {
        return !!node.querySelectorAll('span').length;
    });
Run Code Online (Sandbox Code Playgroud)

该代码首先用于querySelectorAll()查询<div>文档中的所有节点.之后它将过滤<div>包含至少一个的节点<span>.该代码没有多大意义,仅用于演示目的(以防某些SO成员想要创建donk评论)

更新

你也可以过滤Element.compareDocumentPosition.我还会告诉Elements是disconnected,followingpreceding,还是contained.请参阅MDC .compareDocumentPosition()


Sco*_*ver 12

2019 年最简洁的方法是使用扩展语法 ...加上数组文字[...],它适用于可迭代对象,例如由 返回的 NodeList querySelectorAll

[...document.querySelectorAll(".myClass")].filter(el=>{/*your code here*/})


las*_*203 6

注意:NodeList不是真正的数组,也就是说它没有诸如slice,some,map等数组方法。要将其转换为数组,请尝试Array.from(nodeList)。

参考:https : //developer.mozilla.org/zh-CN/docs/Web/API/Element/querySelectorAll

例如:

let highlightedItems = userList.querySelectorAll(".highlighted");

let items = Array.from(highlightedItems);

items.filter((item) => {
 //...
})
Run Code Online (Sandbox Code Playgroud)