Filtering Queries in JQuery and in Native JavaScript

Omar Barguti
1 min readApr 20, 2021

JQuery is capable of filtering query results through the ‘filter()’ function. The function takes in a CSS selector or a function. If the function returns something ‘truthy’, the element is kept in the result set. Otherwise, it gets rejected. In the following block of HTML code, the ‘filter()’ function is used to select the labels that has the class ‘red’ assigned to them:

var labels = $('.mainDiv label')// Using a CSS selector with the filter() function
var filteredLabels = labels.filter('.red');
// Passing in a function to the filter() function
var filteredLabelsWithFunction = labels.filter(function(index, item) {
return $(item).hasClass('red');
});

Native JavaScript provides a similar ‘filter()’ function available on Javascript arrays. However, the ‘filter()’ function is not available on legacy browsers (i.e. IE7/8) so it will need to be polyfilled accordingly. One major difference from the JQuery ‘filter()’ function though is that the native JavaScript array function does not accept CSS selectors. It only takes in functions. To select all the labels with the class ‘red’ on them, the ‘document.querySelectorAll()’ can be used to find all the labels. However, since that function returns a ‘NodeList’ object, it will need to be converted to an array first:

// Convert the NodeList result to an array
var labels = [].slice.call(document.querySelectorAll(".mainDiv label"));
var filteredLabels = labels.filter(function(item, index) {
return item.classList.contains('red');
});

--

--

Omar Barguti

An enthusiastic architect and full-stack developer with many years working with enterprise software and cloud services in multiple domains.