I have several <li>
and I need trigger a click event over all them when the page is loaded. I have tried doing this with a loop but it's not working. Any help?
<ul>
<li class="du">One</li>
<li class="du">Two</li>
<li class="du">Three</li>
</ul>
jQuery(document).ready(function() {
var list = $('.du');
for (i = 0; i <= list.length; i++) {
$(list).click();
}
});
I have several <li>
and I need trigger a click event over all them when the page is loaded. I have tried doing this with a loop but it's not working. Any help?
<ul>
<li class="du">One</li>
<li class="du">Two</li>
<li class="du">Three</li>
</ul>
jQuery(document).ready(function() {
var list = $('.du');
for (i = 0; i <= list.length; i++) {
$(list).click();
}
});
Share
Improve this question
edited Jan 4, 2016 at 11:29
Rory McCrossan
338k41 gold badges320 silver badges351 bronze badges
asked Jan 4, 2016 at 11:22
AntonioAntonio
3952 gold badges4 silver badges15 bronze badges
0
2 Answers
Reset to default 5You don't need to loop, just select all the .du
elements and call click()
. jQuery will raise the event on all matched elements in the set by itself:
$('.du').click();
Example fiddle
Also note that to loop over a set of elements selected with jQuery you should use the each()
method, and refer to the element of the current iteration using the this
keyword:
$('.du').each(function() {
console.log(this);
});
Instead, you can simply do
$('.du').click(); // Will trigger click on all .du
In your code pick the element from list and click
jQuery(document).ready(function(){
var list = $('.du');
for(i=0;i<=list.length;i++){
list.eq(i).click();
}
});