Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I think you may have overkilled it… 😉

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

Learn more about querySelector and querySelectorAll

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading