1

Having the following html structure:

<tr class="invisible">
    <td align="center">
        <a class="i_edit" data-target="30"></a>
    </td>
    <td class="category">
        <span class="f_type" style="background-image: url(/admin/assets/img/f_type_3.gif);"> Tests </span>
    </td>
    <td style="background-color: blue;">
        <select class="behaviour" name="behaviour" style="opacity: 1;">
            <option selected="" value="1" style="opacity: 1;">Por noticias destacadas</option>
            <option value="2" style="opacity: 1;">Por fecha</option>
        </select>
    </td>
</tr>

Which is the best/fastest way to access class .i_edit inside:

$('.behaviour').change(function(){

        $(this).closest('.i_edit').css('background-color', 'red'); //doesn't work
        $(this).parent().closest('.i_edit').css('background-color', 'red'); //doesn't work
        $(this).parent().parent().find('.i_edit').css('background-color', 'red'); //this works

    return false;

});
Alex
  • 7,538
  • 23
  • 84
  • 152

2 Answers2

8

None of the three.

Use $(this).closest('tr').find('.i_edit'), because it's readable and still works when the structure of your DOM changes.

See also: http://api.jquery.com/closest/.

Blazemonger
  • 90,923
  • 26
  • 142
  • 180
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • 1
    @Radu `` elements are dropped when they're not contained within a table: http://jsfiddle.net/veVqH/3/ – Rob W Jul 26 '12 at 17:20
  • I didn't think of that, though it does make sense! Thanks for the tip. – Radu Jul 26 '12 at 17:21
  • Actually, now that I think of it more, I'd expect that tr elements would be wrapped in a table rather than be dropped.. just based on how unclosed tags are automatically closed by many browsers. – Radu Jul 26 '12 at 17:27
-1

first, do a .parents('tr.invisible) then do a .find('.i_edit')

$('.behaviour').change(function(){
    var obj_this = $(this)

    obj_this.parents('tr.invisible').find('.i_edit').css('background-color', 'red');

   return false;
});

also save the $(this) into a variable, if ever you need to use it more than once.

var obj_this = $(this)
fedmich
  • 5,343
  • 3
  • 37
  • 52