Equivalent to jQuery or Zepto's .filter() method in pure javascript

Question:

What is the best way to make "filter" method like jQuery or Zepto in pure javascript?

I want to implement this method in my library:https://github.com/acauamontiel/mantis-js/blob/master/src/traversing.js#L3

HTML

<p>Lorem Ipsum</p>
<p class="middle">Lorem Ipsum</p>
<p class="middle">Lorem Ipsum</p>
<p>Lorem Ipsum</p>

JS

$('p').filter('.middle'); // Retorna somente o "p" que tiver a classe "middle"

Answer:

Explanation:

Using pure Javascript you would have to go through all the elements that have the <p> tag in your Document using the document.getElementsByTagName() function, and then store them in an Array for easy iteration between them and then use a loop to repeat check if each one of them has the middle class or not, and store them in another array only the ones that have it, and then you will have the Array that you can see in the console with only the elements that have the Middle class, like an HTMLCollection that nothing is more than an Array of HTML Elements.

Solution:

Javascript code:

function filter(tagName,classe){
    var aryP = document.getElementsByTagName(tagName);
    var len  = aryP.length;
    var aryPMiddle = [];
    for (var i=0;i < len; i++){
        if (aryP[i].getAttribute('class') == classe){
          aryPMiddle.push(aryP[i]);
        }
    }
    console.log(aryPMiddle);
    return aryPMiddle;
}

Then just run the function:

filter('p','middle');

And you will get the return of:

[p.middle, p.middle]

Functional example in JSFiddle

— EDIT —

But you want a use similar to jQuery's .filter() in more aspects, besides getting all the elements with the given tag, so I suggest using this function that you can send any selector to it in the same way you use it in jQuery:

function filter(selector){
    var aryPMiddle = document.querySelectorAll(selector);
    console.log(aryPMiddle);
    return aryPMiddle;
}

Example of use:

With the following HTML:

<p id="middle">Lorem Ipsum</p>
<p class="middle">Lorem Ipsum</p>
<p class="middle">Lorem Ipsum</p>
<p>Lorem Ipsum</p>

Running:

filter('.middle');

would return:

NodeList[p.middle, p.middle]

And running:

filter('#middle');

would return:

NodeList[p#middle]

Note: unfortunately in JSFiddle it didn't work and the reason is still unknown, but if you run it in your browser's console it works correctly.

Scroll to Top