A nice selector to remove this horrible code
-
05-07-2019 - |
Question
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
Solution
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.
OTHER TIPS
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...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow