brianrhea brianrhea - 6 months ago 8
Javascript Question

Add a class to a div where partial match of attribute value doesn't match any values in separate array

Say I have the following array of divs which I've assigned to a var

fileTypes


<dd data-param-type="facetFilters" data-param-value="document_type:pdf">PDFs</dd>
<dd data-param-type="facetFilters" data-param-value="document_type:document">Documents</dd>
<dd data-param-type="facetFilters" data-param-value="document_type:spreadsheet">Spreadsheets</dd>
<dd data-param-type="facetFilters" data-param-value="document_type:presentation">Presentations</dd>
<dd data-param-type="facetFilters" data-param-value="document_type:image">Images</dd>


And I also have the following Object:

{email: 80, pdf: 27}


What's the best way to loop through the
fileTypes
divs and add a class of
disabled
if their
data-param-value
matches neither
email
or
pdf
?

I'm using the following to extract the param-value after the :

var type = $(item).data('param-value');
var regex = /type:(.*)/;
var match = regex.exec(type);
console.log(match[1]);
=> pdf // (document, spreadsheet, etc)


What I can't quite solve is a clean way to find the divs that don't contain a match. I've taken a crack at
_.filter
and
_.difference
in Underscore, but am unable to get it right.

Answer

You are using jQuery, so it's filter method can be used for filtering the matching elements:

// get the object keys
var keys = Object.keys({email: 80, pdf: 27});

$('dd[data-param-value]').filter(function() {
   var key = $(this).data('param-value').split(':')[1];
   return $.inArray(key, keys) === -1;
}).addClass('disabled');

https://jsfiddle.net/vxduagky/

Comments