1
Hello, I have an html with several fields that repeat the same div, I want to take advantage of these Divs to apply a jQuery function in all of them. What would be the best way to do that? accounts how often the class repeats and apply a for each?
1
Hello, I have an html with several fields that repeat the same div, I want to take advantage of these Divs to apply a jQuery function in all of them. What would be the best way to do that? accounts how often the class repeats and apply a for each?
4
I would use each()
$('div').each(function(){
//Código da função
});
I hope I’ve helped.
1
To apply the function to all divs with even name just 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 define a class common to all of these divs and apply the function by class definite:
$(".nomeClass").evento(function(){
//Código da função
});
With this, the function will be applied to all divs who have the class definite.
Example using the attribute name:
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>Ocultando as Divs com mesmo name em 4 segundos:</p>
<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="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 above example, all divs who actually own name set in function will be hidden in 4 seconds.
Example using a class common to all divs:
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>Ocultando as Divs com mesma class em 4 segundos:</p>
<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="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 divs which have the same class set in function will be hidden in 4 seconds.
Browser other questions tagged jquery
You are not signed in. Login or sign up in order to post.
Wouldn’t using a class be simpler? could for a portion of that code?
– rray
$('.nome-da-classe').each(function(){ ...- I think that’s what you’re looking for. but you can show the HTML you have and what you want to do?– Sergio