I'm creating a series of filters and it's currently "ugly code that works". I'd like to output all of the filters from an array, but I can't figure out how to assign a variable to an element's dataset
attribute. (You'll see that the code is the exact same for every filter except for what they're filtering).
Can anyone help show me how I could achieve this?
function filterList() {
const itemsNode = document.querySelectorAll(".js-filterable");
const items = Array.from(itemsNode);
const filterBrand = document.querySelector(".js-filter-brand");
const filterState = document.querySelector(".js-filter-state");
const filterCity = document.querySelector(".js-filter-city");
const filterOwner = document.querySelector(".js-filter-owner");
const filtered = document.querySelector(".js-filtered");
let filterValue;
let results;
// Listen for filter changes
if (filterBrand) {
filterBrand.addEventListener("input", function(filtered, filterValue) {
filterValue = this.value;
if (filterValue === "all") {
let results = items;
outputResults(results);
} else {
let results = items.filter(item => item.dataset.brand === filterValue);
outputResults(results);
}
});
}
if (filterState) {
filterState.addEventListener("input", function(filtered, filterValue) {
filterValue = this.value;
if (filterValue === "all") {
let results = items;
outputResults(results);
} else {
let results = items.filter(item => item.dataset.state === filterValue);
outputResults(results);
}
});
}
if (filterCity) {
filterCity.addEventListener("input", function(filtered, filterValue) {
filterValue = this.value;
if (filterValue === "all") {
let results = items;
outputResults(results);
} else {
let results = items.filter(item => item.dataset.city === filterValue);
outputResults(results);
}
});
}
if (filterOwner) {
filterOwner.addEventListener("input", function(filtered, filterValue) {
filterValue = this.value;
if (filterValue === "all") {
let results = items;
outputResults(results);
} else {
let results = items.filter(item => item.dataset.owner === filterValue);
outputResults(results);
}
});
}
// Update filtered list
function outputResults(results) {
while (filtered.firstChild)
filtered.removeChild(filtered.firstChild);
results.forEach(function(result) {
filtered.appendChild(result);
});
}
}