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]
-- 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.
check out my new edited response, I think that’s what you want.
– Paulo Roberto Rosa