Why is Chart.js not attaching a second Chart when adding the container with javascript?

Problem:

I have two Chart.js charts. I want to attach the containers for these charts with javascript.
When I do this, only the second chart gets rendered properly. But the first chart is not displayed. Looking at the chart object, I found that the first chart has attached: false whereas the second has attached: true, which might be the diagnosis. But I don’t understand why this happens.

When I define the same containers in the index.html, the problem does not occur. Why is that happening?

Thank you for your help.

Working code: https://codepen.io/docoda/pen/GRdvwqV

index.html

<div id="container"></div>

index.js

// First Chart

const labels = ['January', 'February', 'March', 'April', 'May', 'June']

const data = {
  labels: labels,
  datasets: [{
    label: 'My First dataset',
    backgroundColor: 'rgb(255, 99, 132)',
    borderColor: 'rgb(255, 99, 132)',
    data: [0, 10, 5, 2, 20, 30, 45],
  }]
}

const config = {
  type: 'line',
  data: data,
  options: {}
}

// Add Chart-JS Container
const container = document.getElementById("container")
container.innerHTML += '<canvas id="myChart"></canvas>'

// Make Chart
const myChart1 = new Chart(
  document.getElementById('myChart'),
  config
)

// Second Chart

const config2 = {
  type: 'bar',
  data: data,
  options: {}
}

// Add Chart-JS Container
container.innerHTML += '<canvas id="myChart2"></canvas>'
const myChart2 = new Chart(
  document.getElementById('myChart2'),
  config2
)

console.log(myChart1, myChart2)

Solution

As LeeLenalee said, .innerHTML += will change the DOM without recreating the first canvas. You can either add the containers before creating the charts, or just use .insertAdjacentHTML("beforeend", ...) instead of .innerHTML +=.

>Solution :

The dom gets edited so the chart that is rendered is now getting a new canvas without you re making the chart, this can be fixed by first adding the canvases to the dom before creating the charts:

container.innerHTML += '<canvas id="myChart2"></canvas>'

container.innerHTML += '<canvas id="myChart"></canvas>'

// Make Chart
const myChart1 = new Chart(
  document.getElementById('myChart'),
  config
)

// Second Chart

const config2 = {
  type: 'bar',
  data: data,
  options: {}
}

https://codepen.io/leelenaleee/pen/PoeKxBZ

Leave a Reply