Skip to content

Instantly share code, notes, and snippets.

@lesleh
Created October 19, 2016 11:03
Show Gist options
  • Save lesleh/ac7ef37dd0e343135036137f95465d20 to your computer and use it in GitHub Desktop.
Save lesleh/ac7ef37dd0e343135036137f95465d20 to your computer and use it in GitHub Desktop.
Filter html elements based on a given string and array of selectors
import $ from "jquery";
export default class ElementFilter {
constructor(container, elementSelector, searchSelectors) {
this.container = container || $(document);
this.elementSelector = elementSelector;
this.searchSelectors = searchSelectors;
}
// Filter the items by the given text
filter(text) {
let matching = this.findMatchingElements(text);
this.container.find(this.elementSelector).not(matching).hide();
matching.show();
}
// Find all elements in container
findElements() {
return this.container.find(this.elementSelector);
}
// Find elements in container that match given text
findMatchingElements(text = "") {
if (text == "") {
return this.findElements();
} else {
let selector = this.buildSearchSelector(text);
return this.findElements().find(selector).closest(this.elementSelector);
}
}
// Build the jQuery selector for finding matching elements
buildSearchSelector(text) {
text = text.replace("\"", "\\\""); // wtf
return this.searchSelectors.map((selector) => {
return `${selector}:caseless_contains("${text}")`;
}).join(", ");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment