Search code examples
javascriptjquerycssclone

Copy content from one TD to another with Jquery?


I want to copy the dates from the top td and put each one in the corresponding td below so I can then style with CSS to put all info on one line. This is coming from a WordPress plugin that I can't change. I currently have this:

<table>
  <tr>
    <td class="table-dates">Fri 15</td>
    <td class="table-dates">Fri 16</td>
  </tr>
  <tr>
    <td class=“table-times”>
      <a href="">9:30pm</a>
      <br>
      <a href="">9:30pm</a>
    </td>
    <td class=“table-times”>
      <a href="">4:30pm</a>
      <br>
      <a href="">6:30pm</a>
    </td>
  </tr>
</table>

My goal is this below, obviously I'll delete the td with table-dates class as I'll no longer need them:

<table>
  <tr>
    <td class="table-dates">Fri 15</td>
    <td class="table-dates">Fri 16</td>
  </tr>
  <tr>
    <td class=“table-times”>
      <span>Fri 15</span>
      <a href="">9:30pm</a>
      <br>
      <a href="">9:30pm</a>
    </td>
    <td class=“table-times”>
      <span>Fri 16</span>
      <a href="">4:30pm</a>
      <br>
      <a href="">6:30pm</a>
    </td>
  </tr>
</table>

I just need to know if this possible and what approach I should be looking at to achieve this. Thanks.


Solution

  • Using jQuery can be done just like this.

    $(document).ready(function() {
      $(".table-dates").each(function(i,e) {
      	var elem = $("<span/>").append($(e).html());
      	$("table").find(".table-times")[i].prepend(elem.html());
      });
     
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table>
    <tr>
    <td class="table-dates">Fri 15</td>
    <td class="table-dates">Fri 16</td>
    </tr>
    <tr>
    <td class="table-times">
    <a href="">9:30pm</a>
    <br>
    <a href="">9:30pm</a>
    </td>
    <td class="table-times">
    <a href="">4:30pm</a>
    <br>
    <a href="">6:30pm</a>
    </td>
    </tr>
    </table>