views:

72

answers:

2

Hi, can anyone offer a selector to do away with this horrible chunk of code:

// img is the image element...
var descriptionContent = $(".descriptionContent", img.parent("td").parent("tr").next("tr"));

The html looks like this:

<table>
    <tr>
        <td><img /></td>
    </tr>
    <tr>
        <td><div class="descriptionContent" /></td>
    </tr>
    <!-- Repeat n times -->
</table>

Given a user has clicked on the img, I need to get the next (and only the next) .descriptionContent element.

Thanks,
K

+5  A: 

Since you're worried about wrapping the image in something, Try this:

var descriptionContent = $(".descriptionContent", img.closest("tr").next("tr"));

The closest command finds the nearest ancestor matching the given selector. See here.

Walt W
didn't know that. thanks!
janoliver
Didn't know that either, thanks Walt! - works a treat.
Kieron
Yeah it's kinda handy :) Happy to help.
Walt W
A: 

I think you're going to hear alot about the way this is structured in general. If you eliminate the table, a lot of this problem goes away.

Something like:

<div class="imgAndContent">
  <img src="blah.jpg">
  <span class="someDescription">Description.</span> <!-- or div, you choose based on your need -->
</div>

Then you can simply do...

var descriptionContent = $(this).next();

When the user clicks...

altCognito
The table is valid, it's tabular data.
Kieron
Well, I suppose two columns of data is still a table. Not quite black and white, but I hear you.
altCognito