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, has data-country set united-kingdom, , has data-type set partner

    or

  • has class post, has data-country set united-kingdom, , has data-type set director

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

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -