Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

208
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda