Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

211
Visualizações
How to search for all SPAN elements inside the DIV recursively?

I'm trying to find all the SPAN elements that are inside the DIV, and the function returns an array of the SPAN found.

Below I made a recursive function, but it brings 43 SPAN, I expected 7 SPAN:

function findRecursive(myElement, elementName, element) {
    if (element == null){
        element = {'element':null, 'array':[]}
    }

    if (element['element']) {
        myElement = element['element']
    }

    if (element['array'] === undefined) {
        element['array'] = []
    }

    var arr = element['array']
    var els = myElement.getElementsByTagName(elementName)

    for (let i = 0; i < els.length; i++) {
        const e = els[i];
        if (e.tagName == elementName) {
            arr.push(e)
        }
        args = {'element':e, 'array': arr}
        findRecursive(null, elementName, args)
    }
    return arr
}

var e = document.getElementById('main')
var result = findRecursive(e, 'SPAN')
console.log(result)
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="main">
        <span>
            <span>
                <span>
                    <span>
                        <span>
                            mySpan1
                        </span>
                    </span>
                </span>
                <span>
                    <span>
                        mySpan2
                    </span>
                </span>
            </span>
        </span>
    </div>
</body>
</html>

What am I wrong with this code? I should bring 7 SPAN

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I think you may have overkilled it... ;-)

document.querySelectorAll('div[id="main"] span');

Learn more about querySelector and querySelectorAll

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda