Seleção Elementos

Asked

Viewed 28 times

2

I have the following structure below HTML,.

<tr>
    <td class="descricao">Texto01</td>
    <td class="btn-l"><button type="button">Leitura Confirmada</button></td>
</tr>
<tr>
    <td class="descricao">Texto02</td>
    <td class="btn-l"><button type="button">Leitura Confirmada</button></td>
</tr>
<tr>
    <td class="descricao">Texto02</td>
    <td class="btn-l"><button type="button">Leitura Confirmada</button></td>
</tr>

2 answers

4

You will use:

Example:

$('[type=button]').on('click', function() {
    let descricao = $(this).closest('tr').find('.descricao').text();
    console.log(descricao);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>

<table>
    <tr>
        <td class="descricao">Texto01</td>
        <td class="btn-l"><button type="button">Leitura Confirmada</button></td>
    </tr>
    <tr>
        <td class="descricao">Texto02</td>
        <td class="btn-l"><button type="button">Leitura Confirmada</button></td>
    </tr>
    <tr>
        <td class="descricao">Texto03</td>
        <td class="btn-l"><button type="button">Leitura Confirmada</button></td>
    </tr>
</table>

  • I have even made suggested implementation, but it makes me all TR elements within the table tag. I am not running fução by clicking. Code: var descricatDoc = $('[type=button]'). Closest('tr'). find('td.Description'). text();

  • Yes, it is the expected one. You are selecting all buttons and searching for all descriptions. If you use click as I used, will only pick up the description of tr of the button clicked. That’s why $(this), because it refers to the button just clicked, and not all others.

0

    $('button').on('click', function() {
        el = $(this).closest('tr').children('td.descricao');
        el.css('background-color', 'lightgreen');
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
    <tr>
        <td class="descricao">Texto01</td>
        <td class="btn-l"><button type="button">Leitura Confirmada</button></td>
    </tr>
    <tr>
        <td class="descricao">Texto02</td>
        <td class="btn-l"><button type="button">Leitura Confirmada</button></td>
    </tr>
    <tr>
        <td class="descricao">Texto03</td>
        <td class="btn-l"><button type="button">Leitura Confirmada</button></td>
    </tr>
</table>

  • 1

    The Closest won’t work because td.descricao is not Parent of button on no level.

  • Wrong read, now it’s fixed.

  • 1

    Sorry to be annoying, but td.descricao is button Parent sibling and not button itself. :|

Browser other questions tagged

You are not signed in. Login or sign up in order to post.