javascriptchartist.js

Targeting elements that are not direct children in HTML using Javascript?


I am using Chartist.js for some charts and I need to target some elements inside the chart in order to generate some elements that are related to them. Is there a way to target such deeply nested child elements inside the "chart1". I need to target the "g" elements with the classes of "ct-series-a", "ct-series-b", etc... But since there are multiple charts on the page that ALSO have elements with these class names, I need to only target the ones that are contained in the chart with the id of "chart1".

HTML Mock-up

<div id="chart1" class="ct-chart">
<svg>
<g>
<g class="ct-series ct-series-a"></g>
<g class="ct-series ct-series-b"></g>
<g class="ct-series ct-series-c"></g>
</g>
</svg>
</div>

Solution

  • Somthing like this should help you.

    const chart1 = document.getElementById("chart1");
    const seriesA = chart1.getElementsByClassName("ct-series-a")[0]
    console.log(seriesA.className)
    // I did use className , for reducing console data to show u the result in console .
    <div id="chart1" class="ct-chart">
      <svg>
        <g>
          <g class="ct-series ct-series-a"></g>
          <g class="ct-series ct-series-b"></g>
          <g class="ct-series ct-series-c"></g>
        </g>
      </svg>
    </div>