I have been teaching myself JS and Jquery primarily for GM scripts (im not a programmer by day) and tried to come up with a solution to append a DIV to another DIV for every single listing on autotrader.com. They are siblings under multiple parents. The full code is here http://userscripts.org/scripts/review/83865 and working.
I came up with this:
var counter=0;
$('.dealer-info').each(function(){
$(this).appendTo($('.car-info')[counter]);
counter=counter+1;
});
Is there a more elegant way to do this?
Any advice would be appreciated as i want my code to be simpler.
Regards,
anthony
.each()provides the index as the first variable to the callback function, so you can do this:Since
.appendTo()just gets flipped around to.append()internally it’s less wasteful and a bit easier on the eyes to do it this way using.eq()to get the item at that index.To be more performant, you should keep a reference to
.car-infooutside the loop, like this: