Reputation: 813
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
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