Home > Net >  How to search for all SPAN elements inside the DIV recursively?
How to search for all SPAN elements inside the DIV recursively?

Time:12-16

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

CodePudding user response:

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

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

Learn more about querySelector and querySelectorAll

  • Related