Daniel O.
Daniel O.

Reputation: 813

Finding only the parent DIV's and then child DIV's within the parents with Vanilla JS

Give the following HTML;

<!DOCTYPE html>
<html>
<head>
    <title>DIV Test</title>
</head>
<body>
<div>
    <h1>Hello 1</h1>
    <div>
        <h1>Hello 1</h1>
    </div>
        <div>
        <h1>Hello 2</h1>
    </div>      
</div>
<div>
    <h1>Hello 2</h1>
    <div>
        <h1>Hello 1</h1>
    </div>
        <div>
        <h1>Hello 2</h1>
    </div>      
</div>
<div>
    <h1>Hello 3</h1>
    <div>
        <h1>Hello 1</h1>
    </div>
        <div>
        <h1>Hello 2</h1>
    </div>      
</div>
<div>
    <h1>Hello 4</h1>
    <div>
        <h1>Hello 1</h1>
    </div>
        <div>
        <h1>Hello 2</h1>
    </div>      
</div>
<div>
    <h1>Hello 5</h1>
    <div>
        <h1>Hello 1</h1>
    </div>
        <div>
        <h1>Hello 2</h1>
    </div>      
</div>

</body>
</html>

How would I use Vanilla JS to return only the parent divs? For example, using the code var x = document.getElementsByTagName("div"); at the moment it will return 15 div's, what code could I use to return only the parent div's which would be 5?

Upvotes: 0

Views: 57

Answers (2)

Damith
Damith

Reputation: 437

document.querySelectorAll("body > div");

Upvotes: 0

j08691
j08691

Reputation: 207923

You can get the top level divs with document.querySelectorAll('body > div')

For example, document.querySelectorAll('body > div').length to get the count.

Upvotes: 2

Related Questions