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

Asked

Viewed 221 times

5

What is the best way to make the "filter" method like jQuery’s or Zepto’s 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"
  • check out my new edited response, I think that’s what you want.

3 answers

3

Explanation:

Using pure Javascript you would have to go through in your Document all the elements that have the tag <p> using the function document.getElementsByTagName(), and then store them in an array for easy iteration between them and then use a repeat loop to check if each of them has the class middle or not, and store them in another array only the ones you have, and then you will have the Array that you can see in the console with only the elements that have Middle class, as a HTMLCollection which is nothing more than an HTML Array of 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’ll get the return of:

[p.middle, p.middle]

Functional example in Jsfiddle

-- EDIT --

But you want a use similar to the .filter() jQuery in more aspects, besides taking all the elements with the provided tag, then I suggest using this function that you can send any selector to it in the same way that Voce uses 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.Iddle, p.Iddle]

And running:

filter('#middle');

Would return:

Nodelist[p#Middle]

Note: unfortunately Jsfiddle did not work and the reason is still unknown, but if you run on your browser console it works correctly.

  • Paulo, thank you for the answer, but the code I passed above was just an example of one of the functionalities of the method .filter() original. Also have to filter by ID’s, attributes and accept a function as parameter, but the part of the function I already know how to implement. My biggest doubt is filter the elements previously selected by my method $(), i.e., I already have an array of elements, but I don’t know if filtering each part of the selector (by regex, for example) would be the best option.

2


In the case of your example, nor would it be necessary to filter. Can be solved with a single selector:

var elementos = document.querySelectorAll('p.middle');

A simple way to implement the filter is to take two sets of elements, and compare them all with everyone. Certainly there are more efficient ways to implement the function, but this is well didactic:

function filter(selElementos, selFiltro) {
    var els = document.querySelectorAll(selElementos);
    var filtro = document.querySelectorAll(selFiltro);
    var saida = [];
    for(var i=0; i<els.length; i++) {
        for(var j=0; j<filtro.length; j++) {
            if(els[i] == filtro[j]) {
                saida.push(els[i]);
            }
        }
    }
    return saida;
}

Demo no jsfiddle

0

var cls = 'middle';
var tag = 'P';

var lista = document.getElementsByTagName(tag);
for (var i = 0; i < lista.length; i++)
{
    if ((' ' + lista[i].className + ' ').indexOf(' ' + cls + ' ') > -1)
    {
        // tratar o elemento com a classe
    }
}
  • Miguel, thank you for the reply, but the code I passed above contains only one of the functionalities of the method .filter() original. I intend to make an equivalent method in all the functionalities of filter by jQuery: http://api.jquery.com/filter/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.