Pixi.js Get Child Element by Name

This article explains how to retrieve a specific child display object from a Pixi.js Container using its assigned name. You will learn how to assign names to your Pixi.js objects and use the built-in getChildByName method to locate and manipulate them within your display hierarchy.

To retrieve a child element by its name in Pixi.js, you must first assign a unique string to the name property of the child object before adding it to the parent container.

Step 1: Assign a Name to the Child Object

When creating your sprite, text, graphics, or nested container, set its name property:

import * as PIXI from 'pixi.js';

const container = new PIXI.Container();

// Create a sprite and assign a name
const bunny = new PIXI.Sprite(texture);
bunny.name = "player_bunny";

// Add the sprite to the container
container.addChild(bunny);

Step 2: Retrieve the Child Using getChildByName

Once the child is added, you can access it at any time from the parent container by calling the getChildByName method with the assigned string:

const foundBunny = container.getChildByName("player_bunny");

if (foundBunny) {
    // Modify the retrieved object
    foundBunny.x = 100;
    foundBunny.y = 150;
} else {
    console.log("Child not found");
}

By default, getChildByName only searches the immediate children of the container. If the target element is nested inside another container within the parent, you can perform a recursive search by passing true as the second argument:

// Searches all nested children recursively
const deepChild = container.getChildByName("nested_child_name", true);

If no child matches the specified name, the method returns null. Always verify that the returned object is not null before attempting to access its properties.