0

I have a function for my rpg game that simulates grabbing an element in a create js container object by removing it from the container (thereby removing it from the stage) when the player gets near it.

function grabIt(NPC_id, index) {
    console.log(ContainerOfAnimals.children[index].id);
    var childToRemove = document.getElementById(ContainerOfAnimals.children[index]);
    console.log(childToRemove);
    ContainerOfAnimals.removeChild(childToRemove);
}

The first console.log gives correct id of child: 21

But when I want to grab the child container object using getElementById, the child is null.

Why is this?

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
user3871
  • 12,432
  • 33
  • 128
  • 268
  • You seem to be missing the `.id` on `ContainerOfAnimals.children[index]` inside of the `document.getElementById()`. Nonetheless, you don't need to requery the DOM for the element (by `id`). Just use `ContainerOfAnimals.removeChild(ContainerOfAnimals.children[index]);` – Ian Aug 15 '13 at 16:31
  • `.id` refers to the specific child's `id`. `index` refers to its index in the collection. Like I said, don't even use this way anyways, since you already have a reference to the element with `ContainerOfAnimals.children[index]` and you can call `removeChild` with that – Ian Aug 15 '13 at 16:34

1 Answers1

3

EaselJS elements have an id property but there aren't DOM elements. They're plain JavaScript objects (instances of a subclass of DisplayObject). And they're not added to the DOM tree.

Therefore, you can't get them by using document.getElementById.

To remove your element, simply do

 ContainerOfAnimals.removeChild(ContainerOfAnimals.children[index]);

or (faster)

 ContainerOfAnimals.removeChildAt(index);
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • Okay, I know I need to use that to remove the element. I wasn't aware, however, that EaselJS element ids aren't DOM elements... The reason I was going this route was because of this question http://stackoverflow.com/questions/18254816/javascript-extremely-confused-on-removing-elements-from-container – user3871 Aug 15 '13 at 16:43
  • 2
    The answer on this question was totally false. – Denys Séguret Aug 15 '13 at 16:58
  • I appreciate you letting me know... I started going down the wrong path as to why the heck it wouldn't work given it was a DOM element.. which it isnt – user3871 Aug 15 '13 at 17:54