Check if element exists before trying to call getContext

๐Ÿ‘:0

See Document.getElementById(). That returns null if an element with the specified ID is not found. You could do something like this:

var chart = document.getElementById("line-unfilled-chartjs");
var ctx;
if (chart) {
    ctx = chart.getContext("2d");
    // do something with context
} else {
    // handle no chart
}

๐Ÿ‘:0

You could use one of this two variant, javascript or jquery

// javascript 
var elem = document.getElementById('line-unfilled-chartjs'),
    ctx1;
if (elem !== null){
   // element exist
   ctx1 = elem.getContext("2d");
}

// with jquery
elem = $("#line-unfilled-chartjs");
if (elem.length !== 0)
{
    // element exist
    ctx1 = elem.getContext("2d");
}

Leave a comment