Use CSS to style elements that do not coincide with the specified data attribute

I'm currently working on developing a filter system.

The goal is that when a user clicks on a button, the ID of that specific button will be captured and then display:none; will be applied to all elements that do not have a matching data attribute provided.

This is an example of the HTML structure:

<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>

After the user clicks on a button, the variable selection is designated as either parttime or fulltime

var selection = 'fulltime';

The objective is to target elements on the page that meet the following criteria:

a) located within .job-list

b) possessing

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

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

However, the issue arises where it selects the entire .job-list and applies display:none; to that section instead of targeting the specific sub-elements that match.

JSFiddle Link: https://jsfiddle.net/h9s3szg2/

Answer №1

As outlined in the official documentation

The selection targets elements that either do not possess the specified attribute, or hold the specified attribute but not with a specific value.

Your current selector is too broad. It is capturing all divs even if they lack the attribute due to meeting the condition [data-job-type!="'+selection+'"]. To focus solely on divs with that attribute, include an additional [data-job-type] in the selector.

$(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>

A couple of side notes.

  1. hide() can be substituted for css('display', 'none')
  2. It's preferable to utilize hide() on the overarching sub container, such as grid

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on linking draggable elements

Currently, I have a set of div elements that I am able to clone and drag and drop into a specific area. Now, I am looking for a way to connect these divs with lines so that when I move the divs, the lines will also move accordingly. It's similar to cr ...

Utilizing jQuery/AJAX to dynamically load PHP pages and reveal targeted links for page display within a designated Div container

I have a MySQL table with id, name, and desc fields. I am using a PHP select query to display this data in a div. <div class="show_name"> while( $row = $data->fetch_array(MYSQLI_ASSOC)) { ?> <div><?php echo $row[' ...

Sort the jQuery elements before rearranging the sub divs

Among my various divs that contain content, I am able to sort them based on data-* attributes. This functionality is working fine, but I am facing an issue where some divs, not all, are accompanied by another div with the class "detail". After the sorting ...

Using various colors to highlight specific sections of a letter or number

I am striving to recreate the unique image shown below, particularly interested in achieving the multi-colored effect on the numbers. This aspect of having different colors for parts of the number is intriguing and I would love to learn how it's done. ...

Retrieving information through a jQuery ajax call

I've been working on creating an AJAX filter for a car list, but I've hit a roadblock in the final stage. My setup involves two files: index.php and filter.php. Within index.php, I have a form with dropdown lists and sliders. Here's the cod ...

How to style the videojs chapter menu with CSS to extend the box to the full length of the line

I am currently working on customizing the videojs CSS for the ChapterButton menu in order to make it expand to accommodate varying line lengths without wrapping. Even though I can set it to a fixed width, I require it to be able to adjust to different line ...

Utilizing jQuery for JSON parsing

Within my JavaScript code, I am working with the following array: var versions = [{"id":"454","name":"jack"}, {"id":"4","name":"rose"} {"id":"6","name":"ikma"} {"id":"5","name":"naki"} {"id":"667","name":"dasi"} ] I need to extract the name from this ar ...

List arranged in order with a hyperlink in the center and an image positioned on the right side

I am trying to create an ordered list with a link to an article in the middle and a small png image file positioned directly to the right of it. For reference, here is an image depicting the exact type of list that I am aiming to achieve: https://i.stack. ...

Tips on causing a div to overflow instead of wrapping onto a new line

Are you looking to design a slider with 3 image containers all in the same row, where the third one overflows instead of wrapping to a new line? Here is an example: Desired Design: https://i.stack.imgur.com/dKyEg.png Current State: https://i.stack.imgu ...

Placing text over an image appears to be causing the navigation links to vanish - could it be a conflict with floating elements?

As a beginner, I'm facing a rather embarrassing situation here. Picture me banging my head on the table level of embarrassment... but let's give it a shot anyways. I've got a navigation bar and an image underneath (not behind). Both seem to ...

The performance of my SVG Filter is dismal

Here is the SVG filter I am using: <svg style="visibility: hidden; height: 0; width: 0;"> <filter id="rgbShift"> <feOffset in="SourceGraphic" dx="1" dy="-1" result="text1" /> <feFlood flood-color="#FF0000" result=" ...

Reduce XSLTProcessor output by 50%

I have a persistent problem (from my perspective, at least). Every time I use XSLTProcessor.transformToFragment, the output is consistently halved compared to the input. For example, when I receive 200 entries in an XML file as a response from a webservi ...

What is the alternative to jQuery.submit now that it has been deprecated in version 3.3?

After reviewing the source code, you will find: /** * Attach an event handler to the "submit" JavaScript event, or trigger that event on an element. * * @param handler The function to be executed each time the event is triggered. * @see {@link https:/ ...

Using table.column as a function in jQuery datatabbe is not supported

When using jquery datatable, I encountered an error stating "table.column is not a function." <script> $(document).ready(function() { var table = $('#lsotable').dataTable(); $("#lsotable thead th").each( function ( i ) { ...

Locating an individual element using Selenide (Selenium) and the cssSelector method

If you have a structure of elements similar to the one shown in the image, it is possible to extract each static property using: $$('#static-information .value').get(0) or $$('.static-property .value').get(0) However, as each static p ...

What is the best way to prevent buttons from shifting when I enlarge the font size in HTML?

Is there a way to make buttons increase in size when hovered over without causing the other buttons to shift to the side? I've tried using the following code to achieve this but it's not working as expected: <style> button{transition-d ...

Delete any HTML content dynamically appended by AJAX requests

I'm currently working on a page dedicated to building orders, where the functionality is fully dependent on ajax for finding products and adding them dynamically. However, I encountered an issue when attempting to remove an item that was added via aj ...

How can I replicate the Firefox style in IE8 using Bootstrap and CSS?

My webpage is styled with Bootstrap v2 and looks great in Firefox. However, I'm struggling to apply the same CSS color style in IE8: .navbar-inverse .navbar-inner { background-color: #1b1b1b; background-image: -moz-linear-gradient(top, #fab ...

What methods does a browser use to identify SCSS files?

While exploring this html template in Chrome's inspection tool, I was amazed to see that the browser was able to detect the scss files instead of the compiled css version. To investigate further, I pressed Ctrl+U to view the page source, hoping to fin ...

Navigation bar elements arranged in a row on mobile devices with HTML

This is the navigation bar for my website using Bootstrap 4: <!-- Bootstrap-4 --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmY ...