[SOLVED] A-Frame dynamically add objects to a-scene (JS, Html)

Issue

This Content is from Stack Overflow. Question asked by sebastian kull

I’m trying to add elements to the a-scene tag with innerHTML
the following code doesn’t work. I would like to make a small world with Perlin Noise 3D
I don’t want to write code for each block I want to render. Any idea how I can make this work?

<html lang="en">
<head>
    <title>A-Frame</title>
    <script src="https://aframe.io/releases/1.3.0/aframe.min.js"></script>
    <script src="https://unpkg.com/perlin-noise-3d"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
    <script>

    </script>
</body>
</head>
<body>


<a-scene id="scene">
</a-scene>

<script>
    $("#scene").innerHTML = '<a-box position="-1 0.5 -3" rotation="0 45 0" color="#4CC3D9"></a-box>'

</script>



Solution

You need to create elements via document.createElement() and append it to the scene with parent.appendChild(node) for them to work properly:

const scene = document.querySelector("a-scene");
const box = document.createElement("a-box");
box.setAttribute("color", "red");
box.setAttribute("position", "0 1 -3");
scene.appendChild(box);
<script src="https://aframe.io/releases/1.3.0/aframe.min.js"></script>
<a-scene>
</a-scene>


This Question was asked in StackOverflow by sebastian kull and Answered by Piotr Adam Milewski It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?