0
<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

A. Seidel
  • 43
  • 1
  • 1
  • 7
  • 1
    document.getElementsByClassName("main") returns array of elements, so you need to loop on each one and run getElementsByClassName("sub") – chriss Jun 19 '16 at 20:09
  • 1
    See [CSS selector for class descendant within a class](http://stackoverflow.com/q/11475553/1529630) and [What does getElementsByClassName return?](http://stackoverflow.com/q/10693845/1529630) – Oriol Jun 19 '16 at 20:11

4 Answers4

4

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');
David Thomas
  • 249,100
  • 51
  • 377
  • 410
1

Your code doesn't work, because the result of document.getElementsByClassName("main") is a HTMLCollection (a kind of list of elements), so you'd need to iterate over each item in this list and call .getElementsByClassName("sub") on each of the elements and concatenate all resulting lists.

But there is a simpler way. Today's browsers support document.querySelectorAll, so you can use

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

Also none of the .sub elements in your sample code is nested inside .main. So, the result of the above would anyway be empty.

Rafael
  • 18,349
  • 5
  • 58
  • 67
0

Currently in your example you have no child classes in your HTML. Your HTML should look like this instead:

<div class="main">I don't want this
    <div class="sub">I want this</div>
</div>
Mitchel Jager
  • 435
  • 4
  • 18
0

document.getElementsByClassName("sub") will be enough to select the .sub elements in your example.

Johannes
  • 64,305
  • 18
  • 73
  • 130