How to obtain an element that is within two or more elements?

Asked

Viewed 37 times

0

I am using the method querySelector to obtain an element that is within three elements of <div> as in the code below:

<div class="main">
    <div>
        <div>
            <span>Elemento Alvo</span>
        </div>
    </div>
</div>

The problem is that if I use the selector ".main > span" the method returns nothing, unless I put the other elements in the selector this way:

document.querySelector(".main > div > div > span");

I’d like to know how I can get the target element without needing to make your relatives explicit. I know it is possible to do this with Jquery, but I want to know how I do in pure JS.

1 answer

4


The selector > that you are using is for immediate descendants, ie, .main > div means a div child of an element with the main class. To catch descendants on any level, simply use a space:

document.querySelectorAll(".main span"); // Todos os spans dentro de .main

Browser other questions tagged

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