Last active
July 14, 2022 20:37
-
-
Save VincentVToscano/cf9f004ef2ff8b61fc585149f712c69f to your computer and use it in GitHub Desktop.
Search for Substring Matches within a NodeList
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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