Get all div inside a tbody without jquery

Asked

Viewed 78 times

1

I have the following structure in my HTML:

    <!-- O número de tbody's sera gerado dinamicamente, de acordo com o número de estados -->
<tbody name="tbodyEstados">
    <tr style="background:#F5F5F5;">
        <td>
            Nome do estado
        </td>
    </tr>
    <tr>
        <td>
            <!-- o número de div's será gerado dinamicamente -->
            <div name="divOficina">
                <label>
                    Nome de uma oficina
                    <input type="hidden" value="id_do_objeto">
                </label>
            </div>
        </td>
    </tr>
</tbody>

Through javascript, I’m using the Document.getElementsByName('tbodyEstados') function to get an array of all tbody’s of states, but then I need to iterate each of the items in that list and take them from within, separately for each state, the div elements that are with the name: "divOficina". Does anyone know how I can do it?

  • The element tbody should not repeat itself several times in the same table. Revise your logic. You could take directly the Divs divOficina with document.getElementsByName('divOficina')

  • The problem with directly using Document.getElementsByName('divOficina') is that I won’t know which of these divs are within which state specifically.

  • Add a status attribute when typing div. Ex.: <div name=divOficina estado=DF>...</div>. When making a loop on Divs, you check the attribute like this: minhaDivOficina.getAttribute('estado').

  • It is recommended that custom attributes be prefixed by data- to avoid incompatibilities https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes, https://answall.com/questions/190859/attributespersonalizated-html

1 answer

2


You can split the search in two steps, first with document.getElementsByName('tbodyEstados'); and then with tBody.getElementsByName('divOficina'); within a loop you execute the logic you need. Something like this:

const tbodyEstados = document.getElementsByName('tbodyEstados');
tbodyEstados.forEach(parent => {
    const divOficina = parent.getElementsByName('divOficina');
    // aqui podes usar `divOficina ` e `parent` que são respectivamente o 
    // elemento interior e exterior que procuras...
});

Browser other questions tagged

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