0

So, I have the following structure:

<div class="conf">
  <canvas id="world"></canvas>
</div>

and I have the following line of code:

context = $('#world').get(0).getContext('2d');

which returns:

Cannot read property 'getContext' of undefined"

and i don't know why.

I already tried various variations like $('#world')[0] and $('canvas')[0] and $('canvas').get(0)

but I was not able to fix it :(

So I am asking here where is my fault?

EDIT: This is the code I am trying to run in my environment. Interestingly it is working here^^

Environment: VSCode

$(function() {

  function trigger() {
    console.log('triggered');
    let context;
    context = $('#world').get(0).getContext('2d');
    context.beginPath();
  context.fillStyle = "white";
  context.arc(200, 100, 30, 0, Math.PI * 2, true);
  context.fill();
  }



  $(document).on("click", "#test", function(e) {
    trigger();
  });
});
html,
body, .conf {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: #111;
}

.button {
  position: absolute;
  top: 0;
  left: 10px;
}
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 
 </head>
 <body>

   <button id="test">
     Button
   </button>

   <div class="conf">

     <canvas id="world"></canvas>

   </div>

 </body>
 
 </html>
  • That means `$("#world")` didn't match any elements, which means that the DOM elements described by the HTML at the top of the question aren't in the DOM yet as of when your code runs. See the answers to the [linked question](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) for the various reason that might be. – T.J. Crowder Nov 26 '20 at 11:00
  • So I put my whole code in a document ready as your linked question suggests it. But still the same result. I tried it with a snippet in a sandbox with a button as trigger. – HoffErik-JohnerInst Nov 26 '20 at 11:17
  • Putting the code in a `ready` callback doesn't guarantee that the element will be in the DOM unless the HTML is in the document when it's sent from the server (and no previous code has removed it). The key point is: It's not finding the `id="world"` element because it's not in the DOM. Only you can see why that is. You could update your question with a runnable [mcve] demonstrating the problem using Stack Snippets (the `[<>]` toolbar button); [here's how to do one](https://meta.stackoverflow.com/questions/358992/) and we could tell you *why* it's not there, but that's what's going on. – T.J. Crowder Nov 26 '20 at 11:24
  • 1
    (I'm happy to do that, btw, if you want to update the question. It'll still be a duplicate, but duplicate questions aren't necessarily a bad thing. They can help people searching in different ways by helping them find the canonical answer via the link.) – T.J. Crowder Nov 26 '20 at 11:31

0 Answers0