brianrhea brianrhea - 1 year ago 46
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


<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
divs and add a class of
if their
matches neither

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);
=> 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
in Underscore, but am unable to get it right.

Answer Source

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;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download