Search code examples
javascriptjqueryhtmlcanvascanvasjs

Get content of <div> knowing its id


I am trying to get the content of a element of which I know partially the id.
The foo variable is correctly generated, but I cannot get it to return a chart object from the div element.
This is the jQuery code I am using:

$(".addViewport").click(function () {                   

  var foo = "#" + $(this).parent().children('div[id$="_chart"]').attr('id');

  var chart = foo.CanvasJSChart();

  chart.options.axisX.viewportMaximum += 86400000;
  chart.render();

});

And this is the html:

<div id="temperature">
    <div id="temperature_chart" style="height: 300px; width: 100%;"></div>
    <button class="addViewport">Viewport +</button>
</div>

The chart library I am using is called CanvasJS and it has a method called .CanvasJSChart(); to get the chart from specific div element.Screenshot


Solution

  • This line returns a string ("#temperature_chart"):

    var foo = "#" + $(this).parent().children('div[id$="_chart"]').attr('id');
    

    and that's why this line cannot work:

    var chart = foo.CanvasJSChart();
    

    foo needs to become a jQuery object in order for all that to work. For example:

    var foo = $(this).parent().children('div[id$="_chart"]');