π:1
You could compress the document.getElementById function which is a peeve for me too
const gEBID = document.getElementById;
var ctx = gEBID('myChart');
var ctx2 = gEBID('myChart2');
var ctx3 = gEBID('myChart3');
var ctx4 = gEBID('myChart4');
var ctx5 = gEBID('myChart5');
var ctx6 = gEBID('myChart6');
π:1
You could store each id selector in an array before looping over the array and making a selection to operate onβ¦
const selectors = [
'#myChart', '#myChart2', '#myChart3', '#myChart4', '#myChart5', '#myChart6'
]
selectors.forEach(selector => {
const chart = document.querySelector(selector)
console.log(chart)
// do something
})
<div id="myChart"></div>
<div id="myChart2"></div>
<div id="myChart3"></div>
<div id="myChart4"></div>
<div id="myChart5"></div>
<div id="myChart6"></div>
However, this is what css classes and querySelectorAll
do very efficiently.
const myCharts = document.querySelectorAll('.chart')
myCharts.forEach(chart => {
console.log(chart)
// do something
})
<div class="chart" id="myChart"></div>
<div class="chart" id="myChart2"></div>
<div class="chart" id="myChart3"></div>
<div class="chart" id="myChart4"></div>
<div class="chart" id="myChart5"></div>
<div class="chart" id="myChart6"></div>