If for example I have the following HTML structure
<ul class="actions">
<li class="action">Action 1</li>
<li class="action">Action 2</li>
<li class="action">Action 3</li>
</ul>
And the following Javascript
$('.actions .action').each( function() {
perform an ajax request // intended pseudocode
if ajax returns some more actions { // intended pseudocode
$('.installer-actions').append('<li class="action">Another Action</li>');
}
});
The added <li class="action"> elements are not included in the each() obviously. Is there a way I can involve them in the current loop or will I need to loop through again and ignore the original .action elements?
You can’t add them to the object that
eachis iterating (the documentation doesn’t say what happens if youaddto the existing set, so we can’t rely on whatever it currently does), but you can readily enough break out your code to a function which you can call in both places:There we’re calling
doCoolThingon the new action, makingthiswithin the call the new raw DOM element (just likeeachdoes).It’s worth noting, though, that your ajax request will be asynchronous (unless you set
asynctofalse, which is a bad idea), which could impact how you would structure things. We’d have to see real code for the pseudo-code above to help there, but the concept above is sound.