views:

20

answers:

3

Hi,

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

A: 

So you want to append each element with class "dealer-info" to each element with the class "car-info"?

Does $(".dealer-info").appendTo($(".car-info")); not do this?

matt b
I tried that and really hoped that would work but it takes all 15 .dealers divs on the page and appends to each .car - so i get 15 divs in each .car.
7null
A: 

Along the lines of your code, but a little bit more jQuery way. Haven't tried this, but should work fine.

$('.dealer-info').each(function(index, value){
     $(this).appendTo($('.car-info').eq(index));
});
Teja Kantamneni
Thanks i tested and it works.
7null
+1  A: 

.each() provides the index as the first variable to the callback function, so you can do this:

$('.dealer-info').each(function(i) {
  $('.car-info').eq(i).append(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-info outside the loop, like this:

var cars = $('.car-info');
$('.dealer-info').each(function(i) {
  cars.eq(i).append(this);
});
Nick Craver
Cool, thanks. I tried and it works great.
7null
@7null - Welcome :) Be sure to accept answers on this and future questions as you go via the check-mark beside whichever helped you most :)
Nick Craver