Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

219
Vistas
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 +=.

almost 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

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:

const container = document.getElementById("container")
container.innerHTML += '<canvas id="myChart2"></canvas>'
container.innerHTML += '<canvas id="myChart"></canvas>'

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

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

// Second Chart

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

// Add Chart-JS Container
const myChart2 = new Chart(
  document.getElementById('myChart2'),
  config2
)

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

almost 4 years ago · Santiago Trujillo Denunciar

0

You need to add a new div for each new chart for it to work.

index.html

<div id="container"></div>
// Add a new div for the 2nd chart
<div id="container2"></div>

index.js

// ...

// Declare the var for the 2nd div container
const container2 = document.getElementById("container2")

// Add Chart-JS Container using the 2nd div
container2.innerHTML += '<canvas id="myChart2"></canvas>'
const myChart2 = new Chart(
  document.getElementById('myChart2'),
  config2
)

Working codepen here https://codepen.io/SuperNoobi/pen/rNvzQQr

almost 4 years ago · Santiago Trujillo Denunciar

0

You need to initialize the charts once the DOM is loaded:

...

document.addEventListener("DOMContentLoaded", () => {
  // Make Chart
    const myChart1 = new Chart(
      document.getElementById('myChart'),
      config
    )

    const myChart2 = new Chart(
      document.getElementById('myChart2'),
      config2
    )
});

...

Pen: https://codepen.io/mavyfaby/pen/xxjLQQM

almost 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda