Question

I have an HTML structure like so:

<tr class="v65-productDisplay-row"></tr>
<tr class="v65-productDisplay-row PriceAndButton"></tr>
<tr class="v65-productDisplay-row PhotoLine"></tr>
<tr class="v65-productDisplay-row"></tr>
<tr></tr>
<tr class="v65-productDisplay-row"></tr>
<tr class="v65-productDisplay-row PriceAndButton"></tr>
<tr class="v65-productDisplay-row PhotoLine"></tr>
<tr class="v65-productDisplay-row"></tr>
<tr></tr>
<tr class="v65-productDisplay-row"></tr>
<tr class="v65-productDisplay-row PriceAndButton"></tr>
<tr class="v65-productDisplay-row PhotoLine"></tr>
<tr class="v65-productDisplay-row"></tr>
<tr></tr>
...and so on

I am trying to target each PriceAndButton TR and insert it after each corresponding PhotoLine TR. Here is the code I have so far but it's not working as of yet:

        jQuery(".PriceAndButton").each(function() {
            var IndexValue = $(this).index();
            $(this).insertAfter(".PhotoLine:eq(" + IndexValue + 1 + "");
        });

My thoughts were to get the index value of each PriceAndButton element and insert it after the PhotoLine TR where its eq equals the index value + 1. This should work right since the PhotoLine TR is always immediately after?

Was it helpful?

Solution

Your code (I fixed the closing parenthesis):

".PhotoLine:eq(" + IndexValue + 1 + ")";

will concatenate as a string. If IndexValue equals 3, then you'll get the string .PhotoLine:eq(31) instead of .PhotoLine:eq(4). What you meant was:

".PhotoLine:eq(" + (IndexValue + 1) + ")";

But even then it won't work quite right.

For simplicity, you can avoid using eq at all by instead selecting .next('.PhotoLine') (or just .next(), but I like to be accurate to avoid unexpected surprises):

$('.PriceAndButton').each(function(i,el) {
    $(this).insertAfter($(this).next('.PhotoLine'));
});

http://jsfiddle.net/mblase75/YWaYN/

OTHER TIPS

You can just use the jQuery next method like so:

$(".PriceAndButton").each(function() {
    var self = $(this);
    self.insertAfter(self.next());
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top