Selecting multiple second instances of a queryselectorAll element?

38 views Asked by At

I am using Chartist and I need to send some data to the repeated second occurrence of an element. For example, there are two "ct-bar" elements inside every "ct-series" element. I need to select the second "ct-bar" element that is contained in each of the "ct-series" elements. I have tried doing this with a for loop and some other ways to no avail. How can I achieve this?

JS

const series = xChart.querySelectorAll('.ct-series .ct-bar')
for (var i = 0; i < series.length; i++) {
                        this.element = series[i];
                        var seriesNext = series[1]
                    }
2

There are 2 answers

0
Nick On BEST ANSWER

You can use the :nth-child(2) css selector to just grab the 2nd ct-bar child under each ct-series. See below for how this would work.

const series = document.querySelectorAll('.ct-series > .ct-bar:nth-child(2)')
for (var i = 0; i < series.length; i++) {
  console.log(series[i].textContent);
}
<div class="ct-series">
  <span class="ct-bar">foo 1</span>
  <span class="ct-bar">bar 1</span>
</div>
<div class="ct-series">
  <span class="ct-bar">foo 2</span>
  <span class="ct-bar">bar 2</span>
</div>

0
Barmar On

Use the :nth-child() selector to get the 2nd child of each series.

const bars = xChart.querySelectorAll('.ct-series > .ct-bar:nth-child(2)');