Question

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;

});
Was it helpful?

Solution

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/.

OTHER TIPS

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top