Czarq92 Czarq92 - 7 months ago 13
Javascript Question

Get div from div list with specific class

I have

list
of
div
and want get
div
when contain specified class like
state-expanded
. For example I have got two different
divs
:

<div class="row-popular state-expanded no-sibling-group">
<span class="cell cell-id-name" style="flex: 1 1 63px;">
<span>TEST</span>
</span>
</div>

<div class="row-popular state-collapsed no-sibling-group">
<span class="cell cell-id-name" style="flex: 1 1 63px;">
<span>OTHER</span>
</span>
</div>


First
div
have state
state-expanded
and second
state-collapsed
.
I want get value of
span
where class in
div
is
state-expanded
.

This
list
declaration:

var allDivs = document.getElementsByTagName('div');


In example as I write above, It should return value
TEST
. Please only
JavaScript
- not
jquery
etc.

Any idea how get it?

Answer

You can use querySelectorAll to select all divs and then check each to see if it includes class DEMO

var divs = document.querySelectorAll('div');
for (var i = 0; i < divs.length; i++) {
  if (divs[i].getAttribute('class').includes('state-expanded')) {
    console.log(divs[i].querySelector('span').innerHTML);
  }
}

Edit: also if you want to change text of that last span child you can do it like this Demo

Comments