jQuery apply function on all div with same name

1

Hello, I have a html with several fields that repeat the same div, I want to take advantage of these divs to apply a jQuery function on all of them. What would be the best way to do this? how many times does the class repeat itself and apply a for each?

    
asked by anonymous 23.08.2017 / 15:21

2 answers

3

I would use each ()

$('div').each(function(){
     //Código da função
});

I hope I have helped.

    
23.08.2017 / 15:35
1

To apply the function to all divs with same name simply do the following:

$("[name=nomeDiv]").evento(function(){
  //Código da função
});

In this case, the function will be applied to all divs with name equal to that defined in the function.

Or, if you prefer, you can set a% common% for all these class and apply the function to divs set:

$(".nomeClass").evento(function(){
  //Código da função
});

With this, the function will be applied to all class that have divs defined.

Example using the class attribute:

jQuery(function($){
  setTimeout(function() {
  $('[name=divTeste]').fadeOut('fast');
  }, 4000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><p>OcultandoasDivscommesmonameem4segundos:</p><divname="divTeste" style="border:1px solid">
div com name igual
</div>
<br>
<div name="divTeste" style="border:1px solid">
div com name igual
</div>
<br>
<div name="divTeste" style="border:1px solid">
div com name igual
</div>
<br>
<div name="novaDiv" style="border:1px solid">
div com name diferente
</div>

In the example above, all name that have divs defined in the function will be hidden in 4 seconds.

Example using% common% for all name :

jQuery(function($){
  setTimeout(function() {
  $('.divTeste').fadeOut('fast');
  }, 4000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><p>OcultandoasDivscommesmaclassem4segundos:</p><divclass="divTeste" style="border:1px solid">
div com class igual
</div>
<br>
<div class="divTeste" style="border:1px solid">
div com class igual
</div>
<br>
<div class="divTeste" style="border:1px solid">
div com class igual
</div>
<br>
<div class="novaDiv" style="border:1px solid">
div com class diferente
</div>

In the above example, all class that have the same divs defined in the function will be hidden in 4 seconds.

    
23.08.2017 / 15:26