skip to Main Content

I have an html structure like following

<div class="fieldset-wrapper">
  <div data-index="one">...</div>
  <div data-index="two">...</div>
  <div data-index="three">...</div>
  <div data-index="four">...</div>
</div>

I want to hide only the div elements with ‘data-index’ attribute value ‘one’ & ‘three’.
I have tried the following, but it is not working.

$('.fieldset-wrapper div:not([data-index="one"]):not([data-index="three"])').hide();

How should I do this ?

2

Answers


  1. You have to use the filter method.
    First, select all the div then filter the divs which you want to hide then call the hide method

    $('.fieldset-wrapper div').filter('[data-index="one"], [data-index="three"]').hide();
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <div class="fieldset-wrapper">
      <div data-index="one">1...</div>
      <div data-index="two">2...</div>
      <div data-index="three">3...</div>
      <div data-index="four">4...</div>
    </div>

    Alternatively, you can do this as well.

    $('.fieldset-wrapper div[data-index="one"], .fieldset-wrapper div[data-index="three"]').hide();
    
    Login or Signup to reply.
  2. No need to filter – you can add the container as context if you want to be more specific

    I want to hide only the div elements with ‘data-index’ attribute value ‘one’ & ‘three’

    $("div[data-index=one],div[data-index=three]",".fieldset-wrapper").hide()
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <div class="fieldset-wrapper">
      <div data-index="one">One</div>
      <div data-index="two">Two</div>
      <div data-index="three">Three</div>
      <div data-index="four">Four</div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search