So far, we’ve covered the basics of how A-Frame interacts with JavaScript and DOM APIs to produce VR experiences. In this lesson, we’ll learn more about manipulating the scene through JavaScript and how to dynamically add new objects after the A-Frame scene has been initialized.

Components modularize code, make logic and behavior visible from HTML, and ensure that code is executed at the correct time. We’ve been adding our components in the <script> tag at the head of the HTML file. In this lesson, we’ll create a separate JavaScript file to make our components more modular.

Note: Don’t try to put A-Frame-related JavaScript in a raw <script> tag after <a-scene> as we would with traditional 2D scripting because doing so would result in an incorrect order of code execution.

Getting entities by querying and traversing

The DOM serves as a scene graph, and one of its remarkable features is that it offers various tools for traversing, querying, finding, and selecting elements through functions such as the .querySelector() and .querySelectorAll() methods.

The querySelector() method

If we want to grab an element from the scene graph, we use this function. We can give the entity’s ID as the argument to this function. For example, we can get the scene element by:

Get hands-on with 1200+ tech skills courses.