Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VincentVToscano/cf9f004ef2ff8b61fc585149f712c69f to your computer and use it in GitHub Desktop.
Save VincentVToscano/cf9f004ef2ff8b61fc585149f712c69f to your computer and use it in GitHub Desktop.
Search for Substring Matches within a NodeList
// Vars
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
const search_input = document.getElementById('product-search_input');
const search_products = document.querySelectorAll('data-product');
const searchVis = function (query, data) {
for (let i = 0; i < data.length; i++) {
if (!query || data[i].getAttribute('title').toLowerCase().indexOf(query) > -1) {
data[i].style['display'] = 'inline';
} else {
data[i].style['display'] = 'none';
}
}
};
// Services & Utilities
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
/**
* searchVis --- Query each title attribute of an element in a Nodelist
* @param query The user’s search query
* @param data NodeList representing a list of the document's elements inn which to query against
*/
const searchVis = function (query, data) {
for (let i = 0; i < data.length; i++) {
// Uses title attribute but this could easliy be altered to be a arguement you pass in to be dynamic or
// simply swap this out for another attribute
if (!query || data[i].getAttribute('title').toLowerCase().indexOf(query) > -1) {
data[i].style['display'] = 'inline';
} else {
data[i].style['display'] = 'none';
}
}
};
// Event handling
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
search_input.addEventListener('keyup',onSearch);
/**
* onSearch --- As the user types a query in the search field, this method is run
* @param evt
*/
function onSearch(evt) {
const target = evt.target;
if (target && target.type === "search") searchVis(target.value.toLowerCase(),search_products);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment