'Cannot create Chart using Chart.JS @ 2.9.4

I am trying to create a chart using Chart.JS (v2.9.4) but am unable to. Here is the relevant HTML

      <canvas
        id="groupPerformanceChart"
        class="lineClass"
        width="340"
        height="220"
        style="margin-top: 2px; height: 220px; width: 340px;"
      ></canvas>

and here is the relevant JS

  var ctx = $("#groupPerformanceChart");
  if (!ctx) {
    console.log("Context not available");
    return
  }
  else {
    console.log("Context available", ctx)
  }
  let myChart = new Chart(ctx, {
    type: "line",
    data: {
      labels: currLabels,
      datasets: dataSet,
    },
    options: {
      responsive: true,
      scales: {
        yAxes: [
          {
            ticks: {
              beginAtZero: true,
              max: 10,
            },
          },
        ],
      },
    },
  });

and here is what it says in the console:

Context available 
jQuery.fn.init {context: document, selector: '#groupPerformanceChart'}

Failed to create chart: can't acquire context from the given item

Interestingly, the chart shows up sometimes if I trigger HMR in dev environment but obviously this won't work for production. I also have other charts in other places that are created the same way and work fine so this one has me stumped.



Solution 1:[1]

The problem is most likely that you have the chart inside a template, which causes it not to be rendered in the moment that you are running the jQuery selector and constructing the chart.

jQuery will always return a value even if no objects have been found. So your check will always say that a context has been found. To fix this, you have to check the length of the jQuery result:

var ctx = $("#groupPerformanceChart");
if (ctx.length <= 0) {
  console.log("Context not available");
  return;
}
else {
  console.log("Context available", ctx)
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MrCodingB