Chartjs-JQuery insertAfter() Method only works once when inserting a Chart.js chart

0👍

With this line you select the canvas by its id:

let myChart = document.getElementById('mychart').getContext('2d');

But the second time it will not find the second canvas, but the first, because an id is assumed to be unique.

To solve this, do not use id, nor getElementById. Instead capture the canvas object at the moment it is inserted in the document, and reference that directly:

    let $canvas = $("<canvas id='mychart'></canvas>").insertAfter("h2");
//  ^^^^^^^^^^^^^^
    let myChart = $canvas.get(0).getContext('2d');
//                ^^^^^^^^^^^^^^^

Leave a comment