Created
October 19, 2016 11:03
-
-
Save lesleh/ac7ef37dd0e343135036137f95465d20 to your computer and use it in GitHub Desktop.
Filter html elements based on a given string and array of selectors
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
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