How to get atributes from sketch it's parent element

I’ve made a P5 sketch in instance mode. Now, I wanted to get to know some of the settings from it’s parent element. Like dimensions.

For this I thought a good starting point would be to be able to know who is it’s parent. Doing a console.log( sketch ); I found out it has the id in the sketch object.

This is my abstracted sketch. As you can see I actually create two sketches.

var p5Back = function( sketch ) {

	console.log( sketch );

	let parentDivId =;
	console.log( parentDivId );

let sketch_01 = new p5( p5Back, ‘sketch_01’ );
let sketch_02 = new p5( p5Back, ‘sketch_02’ );

But this last console.log prints TypeError: sketch.canvas is undefined

Anyone knows what I’m doing wrong? :slight_smile:

1 Like

The canvas is created at the beginning of setup so it’s undefined when you line of code runs. You’ll have to run it after the after createCanvas() happens in setup. There’s an implicit createCanvas(100, 100) at the beginning of setup if you don’t put one in.

Try something like:

const p5Back = function(sketch) {
  sketch.setup = function() {
    let parentDivId =;
    console.log(parentDivId); // prints "" which is the id of the body element

Check out the parent() documentation for a more streamlined approach to getting and setting a parent.


Also I don’t know if you saw the section in the wiki about parent elements but it might be helpful.

1 Like

Yes!, that’s it. Placing it inside setup did the trick.
Ah yes, I’ll take a look at the documentation. It was the wiki page where I found out about the instance mode in the first place.

Thank you very much!

1 Like