Find elements of a class Eno jQuery and add a parameter to them

Asked

Viewed 683 times

1

I need to do a function in jQuery or Javascript, which finds all items with a particular css class and add a parameter for this class, a different color for example.

I will put on a button, after clicking the first time, the second time he has to remove this parameter.

<button type="button" id="btn">Clique</button>
<div class="mudar">TEXTO QUE VAI MUDAR DE COR</div>
<div class="mudar">TEXTO QUE VAI MUDAR DE COR</div>
<div class="mudar">TEXTO QUE VAI MUDAR DE COR</div>
<div class="mudar">TEXTO QUE VAI MUDAR DE COR</div>
...

3 answers

3

I think that’s what you want:

var contaCliques = 0;
$("#btn").click(function() {
    if (contaCliques == 0) {
        $(".mudar").addClass("outraCor");
        contaCliques++;
    } else {
        $(".mudar").removeClass("outraCor");
    }
});
.outraCor {
     background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="btn">Clique</button>
<div class="mudar">TEXTO QUE VAI MUDAR DE COR</div>
<div class="mudar">TEXTO QUE VAI MUDAR DE COR</div>
<div class="mudar">TEXTO QUE VAI MUDAR DE COR</div>
<div class="mudar">TEXTO QUE VAI MUDAR DE COR</div>

Click on the blue button "Execute" above and see working.

When performing, the first time you click the button "Clicking", he adds the color and the second time he removes it. The third time on, nothing happens.

2


You can use the function toggleClass jQuery if you want to add or remove each click on the button, example:

$("#btn").click(function(){
  $(".mudar").toggleClass("tx-blue");
});
.tx-blue{
  color:blue;  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="btn">Clique</button>
<div class="mudar">TEXTO QUE VAI MUDAR DE COR</div>
<div class="mudar">TEXTO QUE VAI MUDAR DE COR</div>
<div class="mudar">TEXTO QUE VAI MUDAR DE COR</div>
<div class="mudar">TEXTO QUE VAI MUDAR DE COR</div>

  • 1

    Exactly what I wanted friend, thank you very much.

1

See the code below working:

// JAVASCRIPT


$('#btn').click(function(){
  $(".mudar").toggleClass('red');
});
/* CSS */
.red {
  background-color: red;
  }
<!-- HTML -->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<button type="button" id="btn">Clique</button>
<div class="mudar">TEXTO QUE VAI MUDAR DE COR</div>
<div class="mudar">TEXTO QUE VAI MUDAR DE COR</div>
<div class="mudar">TEXTO QUE VAI MUDAR DE COR</div>
<div class="mudar">TEXTO QUE VAI MUDAR DE COR</div>

What the toggleClass will do is check if the class red exists: if it does not exist it adds and if it exists it removes. Something similar to:

  if($('.mudar').hasClass('red')){
    $('.mudar').removeClass('red');
  }else{
    $('.mudar').addClass('red');
  }

Browser other questions tagged

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