Highcharts Tips – Accessing chart object from container id

Given the following container for Highcharts, how do you access the appropriate chart object from the container’s id?

<div id="containerId"></div>

Let’s see how we can get a handle of the chart object to display the title

Highcharts 3.0.1+

Highcharts 3.0.1 has made it fairly straightforward like most jQuery plugins

var chart=$("#containerId").highcharts();

Highcharts 2.3.4+

For Highcharts 2.3.4+ the array Highcharts.charts could be used in conjunction with the data-highcharts-chart attribute to get the position of the chart in the array

var index=$("#containerId").data('highchartsChart');
var chart=Highcharts.charts[index];

Highcharts.charts    

An array containing the current chart objects in the page. A chart’s position in the array is preserved throughout the page’s lifetime. When a chart is destroyed, the array item becomes undefined.

If you have only a single chart on your page, you can smartly predict the index to be 0 and skip the first step

var chart=Highcharts.charts[0];

All Versions

For versions before 2.3.4 you would need to track/manage the object yourself. We could use a map/object to store the charts by Id

var window.charts={}; 
function foo(){
  new Highcharts.Chart({...},function(chart){  
      window.charts[chart.options.chart.renderTo] = chart;
  });
}

function bar(){
  var chart=window.charts["containerId"];
}

If you have only a single chart on the page, you could simplify to just a window.chart  object

function foo(){
   window.chart=new Highcharts.Chart({...});
}

function bar(){
   var myChart=window.chart;
}

References