Reputation: 83
I have tried solutions found in similar questions regarding Javascript, however, none of those solutions have worked. The script still continues to target ALL of the elements instead of just the last one. Below I have included my last attempt to get this to work. I have a chart with an id of "mainChart" and inside that chart, there is a "ct-series-b" element that contains "ct-bar" elements. I need to target the last "ct-bar" element contained within "ct-series-b" each time the script is run. How can I do this?
I have tried all of these solutions: Shortest way to get last element by class name in javascript and at best, it still targets all of the "ct-bar" elements.
JS
const Chart = document.getElementById("mainChart");
const series = Chart.querySelectorAll('.ct-series-b > .ct-bar')
var last = Chart.querySelectorAll('.ct-series-b > .ct-bar:nth-last-of-type(1)')
Upvotes: 0
Views: 92
Reputation: 83
I had to use a for loop to get it to do what I wanted. Now it properly labels each bar in the chart.
JS
var series = Chart.querySelectorAll('.ct-series-b > .ct-bar')
for (var i = 0; i < data.length; i++) {
var seriesLabel = data.labels[i]
$(series[i]).attr("ct:info", seriesLabel)
}
Upvotes: 0
Reputation: 16576
You can use the :last-child
selector. Note that this will get the last .ct-bar
under each .ct-series-b
, so if you only wanted it under one of them you could adjust the query.
const Chart = document.getElementById("mainChart");
const last = Chart.querySelectorAll('.ct-series-b > .ct-bar:last-child')
console.log(last[0].textContent);
console.log(last[1].textContent);
<div id="mainChart">
<div class="ct-series-b">
<div class="ct-bar">1</div>
<div class="ct-bar">2</div>
<div class="ct-bar">3</div>
<div class="ct-bar">4</div>
</div>
<div class="ct-series-b">
<div class="ct-bar">5</div>
<div class="ct-bar">6</div>
<div class="ct-bar">7</div>
<div class="ct-bar">8</div>
</div>
</div>
Upvotes: 1