43

I'm working on a javascript library, and I use this function to match elements:

$ = 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;
};

There are occasions where I would want to filter the result of this function, like pick out a div span, or a #id div or some other fairly simple selector.

How can I filter these results? Can I create a document fragment, and use the querySelectorAll method on that fragment, or do I have to resort to manual string manipulation?

I only care about modern browsers and IE8+.

If you want to look at the rest of my library, it's here: https://github.com/timw4mail/kis-js

Edit:

To clarify, I want to be able to do something like $_(selector).children(other_selector) and return the children elements matching that selector.

Edit:

So here's my potential solution to the simplest selectors:

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;
    
}

It takes a tag like div, an id, or a class selector, and returns the matching elements with the curr_sel argument.

I don't want to have to resort to a full selector engine, so is there a better way?

3
  • Apart from educational purposes why is your library better then existing ones?
    – Raynos
    Commented Jul 22, 2011 at 14:30
  • @Raynos I'm trying to create a minimalistic, modular library that doesn't have to deal with the stupidities of JScript in IE6/7
    – timw4mail
    Commented Jul 22, 2011 at 14:32
  • I guess that's pretty unique. Most libraries deal with IE6/7.
    – Raynos
    Commented Jul 22, 2011 at 14:36

5 Answers 5

39

Note: NodeList is not a genuine array, that is to say it doesn't have the array methods like slice, some, map etc. To convert it into an array, try Array.from(nodeList).

ref: https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelectorAll

for example:

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

highlightedItems.filter((item) => {
 //...
})
0
34

I don't think I get the question right. Why would you want to "filter" the result of querySelectorAll() which infact, is some kind of a filter itself. If you query for div span or even better #id div, those results are already filtered, no ?

However, you can apply Array.prototype.filter to the static result of querySelectorAll like follows:

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

That code would first use querySelectorAll() to query for all <div> nodes within the document. Afterwards it'll filter for <div> nodes which contain at least one <span>. That code doesn't make much sense and is just for demonstrative purposes (just in case some SO member wants to create a donk comment)

update

You can also filter with Element.compareDocumentPosition. I'll also tell if Elements are disconnected, following, preceding, or contained. See MDC .compareDocumentPosition()

5
  • 1
    Sometimes I need to get the parent or children of the current element.
    – timw4mail
    Commented Jul 22, 2011 at 14:20
  • Does an element list/node list always inherit from the Array prototype?
    – timw4mail
    Commented Jul 22, 2011 at 14:26
  • Hmm...that's helpful, but then I still have to have the node to compare with.
    – timw4mail
    Commented Jul 22, 2011 at 14:42
  • Well, a possible use could be to have multiple different Selectors (simply because the DOM is different), but then you still want to clean those elements from a certain elements, which are always present. Of course, this looks like, something went wrong in the architecture in the first place, but we all have been there... Commented Feb 2, 2017 at 10:30
  • Thanks this answer made me realise I should filter using the querySelector instead of filtering the selection twice.
    – FroboZ
    Commented Nov 22, 2020 at 12:19
19

Most concise way in 2019 is with spread syntax ... plus an array literal [...], which work great with iterable objects like the NodeList returned by querySelectorAll:

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

1
  • Looks like a beautiful but expensive way to do it though (in older browsers).
    – Ivan
    Commented Jun 12, 2020 at 14:22
3

Some browsers that support qsa also support a non-standard matchesSelector method, like:

element.webkitMatchesSelector('.someSelector')

...that will return a boolean representing whether element matched the selector provided. So you could iterate the collection, and apply that method, retaining positive results.

In browsers that don't have a matchesSelector, you'd probably need to build your own selector based method similar to the selector engine you're building.

4
  • 1
    Well, I'd prefer to avoid browser-specific functions.
    – timw4mail
    Commented Jul 22, 2011 at 14:25
  • @timw4mail: Yes, but you could test for the existence of the browser-specific ones, and use it if available, or use your engine if not. If you tried to use a temporary container like a fragment, you'd need to remove the element from its location, and place it inside. Probably not what you want.
    – user113716
    Commented Jul 22, 2011 at 14:27
  • @Raynos: :o) It's pretty new. I heard about it when reading one of the jQuery release notes. I think they said they lobbied for it.
    – user113716
    Commented Jul 22, 2011 at 14:30
  • 1
    From 1.4.3 release notes "The jQuery project petitioned the browsers to add the new matchesSelector method (writing up a test suite, talking with vendors, and filing bugs) and the whole community gets to reap the excellent performance benefits now."
    – user113716
    Commented Jul 22, 2011 at 14:32
1

Use Array.from() with filter() array methods.

For example, ".myClass" is set on input elements and you want to return all inputs where value is not empty. You can use this:

Array.from(document.querySelectorAll(".myClass")).filter( el => el.value !== "")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.