views:

15

answers:

1

I would like to add a Title attribute to a row and the value is retrieved from the row's sibling which is hidden, unless clicked. I wanted to make it generic enough to handle when some screens don't have the hidden row with the text.

Here is the first pass that works:

$(function() {
  $("td.commandText pre").each(function(index) {
    $(this).parent().parent().prev().attr('Title', $(this).text());
  });
});

Any ideas to make that more elegant?

Here is an example of the HTML table I am working with:

<table class="maingrid">
  <thead>
    <tr>
      <th>Session ID</th>
      <th>User Name</th>
      <th>Start Time</th>
      <th>End Time</th>
    </tr>
  </thead><tbody>
    <tr class="record">
      <td id="174">174</td>
      <td>user1</td>
      <td>8/2/2010 4:00:09 PM</td>
      <td></td>
  </tr>
  <tr>
     <td class="details hide commandText" colspan="4">
       <pre>Sample Text to show as a tooltip</pre></td>
     </tr>
  <tr>
     <td class="details hide" colspan="4" style="color:red"><pre>no errors</pre></td>
  </tr>
    <tr class="record">
      <td id="175">175</a></td>
      <td>user1</td>
      <td>8/2/2010 4:00:09 PM</td>
      <td></td>
  </tr>
  <tr>
     <td class="details hide commandText" colspan="4">
       <pre>Sample Text to show as a tooltip</pre></td>
     </tr>
  <tr>
     <td class="details hide" colspan="4" style="color:red"><pre>no errors</pre></td>
  </tr>
</tbody>
</table>
+1  A: 

You can use .closest() to make it a bit shorter, like this:

$(function() {
  $("td.commandText pre").each(function(index) {
    $(this).closest('tr').prev().attr('Title', $(this).text());
  });
});

Other than that, there's not much more elegance to gain here.

Nick Craver