Explanation:
Using pure Javascript you would have to loop through all elements that have the <p>
tag using the document.getElementsByTagName()
function in your Document, and then store them in an Array for easy iteration between them and then use a repeat loop to check that each of them has the class middle
or not, and stores them in another array only those that have, and then you 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 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]
- EDIT -
But you want a similar use with .filter()
of jQuery in more ways, in addition to getting all the elements with the supplied tag, then I suggest to use this function that you can send a selector any for it in the same way that you use no jQuery:
function filter(selector){
var aryPMiddle = document.querySelectorAll(selector);
console.log(aryPMiddle);
return aryPMiddle;
}
Example usage:
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');
Return:
NodeList [p.middle, p.middle]
And running:
filter('#middle');
Return:
NodeList [p # middle]
Note: unfortunately in JSFiddle did not work and the reason is still unknown, however if you run in the console of your browser works correctly.