javascript - Mutually Exclusive Data Attribute Selectors -
is possible select elements based on mutually exclusive data attributes, example: i'd .show() divs data attribute of country="united-kingdom" , type="partner" or "director"? like:
$('.post[data-country="united-kingdom"]&[data-type="partner,director"]').show(); or
$('.post[data-country="united-kingdom"]&[data-type="partner"]or[data-type="director"]').show();
i'd .show() divs data attribute of country="united-kingdom" , type="partner" or "director"?
then want selector group:
$('.post[data-country="united-kingdom"][data-type="partner"], .post[data-country="united-kingdom"][data-type="director"]').show(); that says: match element which
has class
post, hasdata-countrysetunited-kingdom, , hasdata-typesetpartneror
has class
post, hasdata-countrysetunited-kingdom, , hasdata-typesetdirector
the "or" part comes ,, makes selector group rather single selector.
in comment, you've said:
the user might select ten or more of each taxonomy term requires generating loads of permutations of conditional.
in case, may better off filter:
var countries = ["united-kingdom"]; // created inputs var types = ["partner", "director"]; // then
var results = $(".post[data-country][data-type]").filter(function() { var $this = $(this); return countries.indexof($this.attr("data-country") != -1 && types.indexof($this.attr("data-type") != -1; }); in es2016 or above, use array#includes — gives simple boolean — instead of array#indexof have check against -1; , there'a polyfill can use in es2015 , earlier...:
var results = $(".post[data-country][data-type]").filter(function() { var $this = $(this); return countries.includes($this.attr("data-country") && types.includes($this.attr("data-type"); }); this can taken further:
var criteria = {}; // inputs, ... criteria["country"] = ["united-kingdom"]; criteria["type"] = ["parter", "director"]; then
var keys = object.keys(criteria); var selector= ".post" + keys.map(function(key) { return "[data-" + key + "]"; }).join(); var results = $(selector).filter(function() { var $this = $(this); return keys.every(function(key) { return criteria[key].includes($this.attr("data-" + key)); }); }); and long we're thinking es2015 , es2016:
const keys = object.keys(criteria); const results = $(selector).filter(() => { const $this = $(this); return keys.every(key => criteria[key].includes($this.attr("data-" + key))); }); or if want go crazy:
const keys = object.keys(criteria); const results = $(selector).filter(() => keys.every(key => criteria[key].includes(this.getattribute("data-" + key))) );
Comments
Post a Comment