TypeError: div.appendChild is not a function

Hi,
I’m still struggling with javascript’s scope.
I’m trying to refactor some code drawing four shapes in four different canvas contexts I did locally. I manually found a solution to draw the four shapes but in one canva element as at the bottom of this notebook https://observablehq.com/@maliky/test-canvas.

For the factorizing, I thought of doing a function

set_contexts = function(div, n){
  let cvs = {};
  for (let i = 0; i < 4; i++){
    let id = `cvs${i}`
    let canvas = DOM.canvas(dim.sub.x, dim.sub.y);  // and with .getContext('2d');  // TypeError: Argument 1 of Node.appendChild does not implement interface Node.
    
    // thinking that this will add a new <canvas> node to the div
    div.appendChild(canvas)
    
    // and then save the <canvas> node in the cvs array
    cvs[id] = canvas;  
  }

  // returning an object with the modified div and the array of canvas DOM elements
  return {div: div, cvs: cvs};
}

to create and add the different canvas element in an object so I could loop over them. but I get a div.appendChild is not a function error and I don’t understand why?

Could you please teach me why ?

1 Like

In your test cell, you have a line which reads:

  let canvas = set_contexts(4).cvs.cvs1;

This causes set_contexts to be called with div set to 4 and n set to undefined. Since div = 4 in set_contexts, div doesn’t have a method called appendChild which explains the TypeError you’re seeing.

The fix is to use this instead:

  let canvas = set_contexts(div, 4).cvs.cvs1;

That way, div in set_contexts is a reference to div in test, and n is set to 4.

1 Like

Thank so much you bgchen. I am a terrible programmer and coding alone is so difficult. I really greatfull for you help.