Francesca
Francesca

Reputation: 28138

Apply CSS to elements that do not match the data attribute

I'm trying to create a sort of filter.

When a user clicks a button, it will grab the ID of that button, and apply display:none; to all elements that do not match the data attribute given.

HTML:

<div class="job-list">
    <div class="row">
        <div class="grid half">
            <div class="job-item" data-job-type="fulltime">
                <h3>Marketing &amp; Communications Manager</h3>
                <h4>Central London -  salary competitive</h4>
            </div>
        </div>

       <div class="grid half">
           <div class="job-item" data-job-type="parttime">
               <h3>Senior PR &amp; Media Manager</h3>
               <h4>Central London -  salary dependent on experience</h4>
           </div>
       </div>
   </div>

When the user clicks on a button, the var selection is set as either parttime or fulltime

var selection = 'fulltime';

I am then trying to match elements on the page that are:

a) within .job-list

b) have data-job-type="[the selection var set above]"

$('.job-list div[data-job-type!="'+selection+'"]').css('display','none'); 

However what I find is that it selects the entire of .job-list and applies display:none; to that, rather than the sub-elements that match?

JSFiddle https://jsfiddle.net/h9s3szg2/

Upvotes: 1

Views: 617

Answers (1)

AmmarCSE
AmmarCSE

Reputation: 30557

According to the documentation

Select elements that either don't have the specified attribute, or do have the specified attribute but not with a certain value.

Your selector is over aggressive. It is selecting all divs even if they do not have the attribute because they fullfill the condition [data-job-type!="'+selection+'"]. Add an extra [data-job-type] to the selector to target only divs with that attribute

$(document).ready(function() {
  $('.button').click(function() {
    var selection = 'fulltime';
    $('.job-list div[data-job-type][data-job-type!="' + selection + '"]').closest('.grid').hide();
  });
});
.job-item {
  width: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div class="button">Click me!</div>
<div class="job-list">
  <div class="row">
    <div class="grid half">
      <div class="job-item" data-job-type="fulltime">
        <h3>Marketing &amp; Communications Manager</h3>

        <h4>Central London -  salary competitive</h4>

      </div>
    </div>
    <div class="grid half">
      <div class="job-item" data-job-type="parttime">
        <h3>Senior PR &amp; Media Manager</h3>

        <h4>Central London -  salary dependent on experience</h4>

      </div>
    </div>
  </div>
</div>

Some side notes.

  1. hide() can be used in place of css('display', 'none')
  2. It is better to hide() the overall sub container, in this case, grid

Upvotes: 3

Related Questions