For every row of odd table switch table cells using jQuery

I work in a CMS and have little control over HTML. I am relying on jQuery to manipulate this table. A client of mine wants to change the title and image for each line.

The desired layout will look something like this:

[Image][Title]
[Title][Image]
[Image][Title]
[Title][Image]

      

This is a simplified version of what I am working with:

<tbody>
<tr class="odd">
    <td class="views-field-title"></td>
    <td class="views-field-field-services-image-fid"></td>
    <td class="views-field-value0"></td>
</tr>
<tr class="even">
    <td class="views-field-title"></td>
    <td class="views-field-field-services-image-fid"></td>
    <td class="views-field-value0"></td>
</tr>
<tr class="odd">
    <td class="views-field-title"></td>
    <td class="views-field-field-services-image-fid"></td>
    <td class="views-field-value0"></td>
</tr>
<tr class="even">
    <td class="views-field-title"></td>
    <td class="views-field-field-services-image-fid"></td>
    <td class="views-field-value0"></td>
</tr>
</tbody>

      

I am new to jQuery and am struggling with .each () functions. This is as far as I could get:

$(".views-field-title").after($(".views-field-field-services-image-fid"));

      

+3


source to share


2 answers


You can do this to change the order in the chances, just change the order of the children

 $(function() {
        jQuery.each($(".odd"), function() { 
            $(this).children(":eq(1)").after($(this).children(":eq(0)"));
        });
    });

      



Here the violin works with her. http://jsfiddle.net/77pHb/

0


source


What about:

$("tr.odd .views-field-field-services-image-fid").after(function () {
    return $(this).prev();
});

      

Here's what's going on:



  • The selector returns each column "image" of each row of an odd table.
  • A function .after

    can take a function. This function is executed once for each element in the jQuery object.
  • Inside the function, we go to .after

    , we return the element we want to insert after the current element we are iterating over. In our case, we want the element immediately preceding the one we are looking at (the "title" element). We can get this using .prev

    .

Example: http://jsfiddle.net/6zAN7/10/

0


source







All Articles