A. Seidel A. Seidel - 5 months ago 9
HTML Question

How do I select all "sub" elements inside "main" elements

<div class="main">
<p>I don't want this</p>
<div class="sub">I want this</div>
</div>

<div class="main">
<p>I don't want this</p>
<div class="sub">I want this</div>
</div>


Anyone know how to select all "sub" elements inside "main" elements.
I've tried
document.getElementsByClassName("main").getElementsByClassName("sub")


But that doesn't work. To clarify I want to get all "sub" elements inside "main" classes but can't quite figure out how. Any help would be appreciated

Answer

Simply use a CSS selector with document.querySelectorAll():

var subs = document.querySelectorAll('.main .sub');

However your posted HTML doesn't place the .sub elements inside the .main elements; they're siblings; in which case:

var subs = document.querySelectorAll('.main + .sub');

Or:

var subs = document.querySelectorAll('.sub');
Comments