Search code examples
jqueryparentclosest

Find closest td from another table using class


I have a table inside the td of another table. But I am getting length as 0 when I check the length of closest td using class. My HTML and jQuery is giev below.

<div class="form-group col-md-12">
    <table class="table jewel_spec_table">
        <tbody>
            <tr class="jewel_type_field">
                <td class="jewel_type_td">
                    <table class="table">
                        <thead class="text-center">
                            <tr>
                                <th>Jewel Type</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>
                                    <select name="jewel_type" class="form-control jewel_type">
                                        <option value="test">Test</option>
                                        <option value="test">Test</option>
                                    </select>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </td>
                <td class="spec_table">

                    <p>Test</p>
                    <!-- We need content here -->

                </td>
                <td>
                    <div class="text-right">
                        <a class="btn-xs btn-info add_jeweltype"><i class="fa fa-plus"></i></a>
                    </div>
                </td>
            </tr>
        </tbody>
    </table>
</div>

I use below script to add some content to the closest td with class spec_table

$(document).on('change',".jewel_type",function(){
    $(this).closest('.spec_table').html('New content');
});

Any idea why it is showing 0 always?


Solution

  • try:

    $(document).on('change',".jewel_type",function(){
        alert($(this).parents('.jewel_type_field').find('.spec_table').length);
    });