How can i get access to a Highcharts chart through a DOM-Container

前端 未结 9 833
轮回少年
轮回少年 2020-12-02 11:55

When i render a highcharts-chart to a div container, how can i get access to the chart object through the div-Container? i dont want to make the chart variable global.

9条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-02 12:36

    @elo's answer is correct and upvoted, though I had to tidy it a little to make it clearer:

    const myChartEl = document.getElementById('the-id-name');
    const myChart = Highcharts.charts[myChartEl.getAttribute('data-highcharts-chart')];
    

    myChart then becomes a live Highcharts object that exposes all current props present in the chart that's rendered in the myChartEl. Since myChart is a Highcharts object, one can chain prototype methods right after it, extend it or refer to it.

    myChart.getTable();
    myChart.downloadXLS();
    setTimeout(() => Highcharts.fireEvent(myChart, "redraw"), 10);
    

    One can also get myChart through .highcharts(), which is a jQuery plugin:

    var myChart = $("#the-id-name").highcharts();
    

    The jQuery plugin approach above requires jQuery to be loaded before the plugin is used, and of course the plugin itself. It was the absence of this plugin that got me into looking for alternative ways to accomplish the same with pure vanilla JavaScript.

    By using the pure JS approach I was able to do what I needed (the second code snippet) without having to rely on jQuery:

提交回复
热议问题