Condition with Jquery: Add attribute when it is not a certain class

Asked

Viewed 61 times

0

In jQuery I know that:

$("#minhaDiv .classe").attr("display","block");

Displays all child elements of the parent element #minhaDiv containing the class .classe, but I do not know how to make the condition when it is not elements with the class.

I have several elements div within a form, and the select upon receiving the event .change() hide all Divs that do not contain classes .classe, Handler is done, the switch to verify the value of select and hide each class according to the option.

I don’t know how to hide all the child elements inside #minhaDiv which does not contain the class .classe

1 answer

1


You can use the selector :not for that reason:

$("#minhaDiv").find(":not(.classe)").show();

Example

let $container = $('#container');

$('#impares').on('click', function() {
    $container.children().show()
    $container.find(':not(.impar)').hide()
})

$('#pares').on('click', function() {
    $container.children().show()
    $container.find('.impar').hide()
})

$('#todos').on('click', function() {
    $container.children().show()
})
#container > .item {
  display: inline-block;
  width: 50px;
  height: 50px;
  background-color: tomato;
}

.item.impar { background-color: gold !important; }
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

<button id="pares">Pares</button>
<button id="impares">Ímpares</button>
<button id="todos">Todos</button>

<hr>

<div id="container">
    <span class="item impar">1</span>
    <span class="item">2</span>
    <span class="item impar">3</span>
    <span class="item">4</span>
    <span class="item impar">5</span>
    <span class="item">6</span>
    <span class="item impar">7</span>
    <span class="item">8</span>
 </div>

  • Thanks Fernando, as needed, this is news to me, I tried to search in English too but had not found. abs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.