DOM element not ready

I haven’t had any luck finding an answer to this yet.

I’m loading a game element from HTML and then attempting to access and update a DOM element from within a custom class.

The HTML is being preloaded in my scene:

  preload() {
    this.load.html("example", "assets/forms/example.html");
  }

Then added to the DOM in my class:

export class Example extends Phaser.GameObjects.Container {
  constructor(scene, x = 0, y = 0) {
    super(scene, x, y);

    this.form = this.scene.add.dom(300, 400).createFromCache("example");
    const name = this.form.getChildByName("company-name");
    name.setText("Some text");
  }
}

The setText call results in a TypeError because the name variable is null. If I wrap the setText call in a 1 second setTimeout, there is no error because the DOM node is present in the DOM. I was assuming there would be an event listener I could hook into to modify the DOM element once it’s loaded, but I can’t find one.

Anyone suggest what the right approach is here?

I guess this.form.on("onload", callback, scope) could work, but it shouldn’t be necessary…

I did try that yesterday, and again just now, but the callback never gets called. I can see the content displayed on screen, so I know it’s been loaded. Reading around it yesterday, it seems there’s no DOM event fired when new DOM elements are added.

Are you sure there is an element named company-name?

I tried this in game-objects/dom-element/form-input and it worked correctly:

 var element = this.add.dom(400, 300).createFromCache('nameform');
 var field = element.getChildByName('username');

console.assert(field);
console.log(field);

This won’t work as an HTML element has no setText() method. Probably it should be

name.value = "Some text";

Thanks samme, it wasn’t quite that but you did set me looking the right direction. Firstly I should have been using getChildByID, and then to set the value, it’s the textContent property.

this.form = this.scene.add.dom(300, 400).createFromCache("example");
const name = this.form.getChildByID("company-name");
name.textContent = "Some text";

But why did it work after 1 second?

I think I must have been mistaken. I was pretty tired when I doing it. I don’t understand how I wouldn’t have seen the same error after the timeout.