简体   繁体   中英

How to append a div to the body?

I am supposed to assign .moon and .planet to the "planet" class and add a background colour to it, so I need to create a div. I have no idea on how to append a div to the body.

The code below shows what I'm currently trying. Please point out my mistake(s).

 <html> <head> <meta charset="utf-8"> <title>Challenge: Create a solar system</title> <style> body { background-color: black; padding: 10px; } .planet { width: 100px; height: 100px; border-radius: 50%; text-align: center; padding: 10px; position: relative; } .moon { position: absolute; width: 30px; height: 30px; border-radius: 50%; background: rgb(237, 237, 237); } </style> </head> <body> <script> var bodyEl = document.querySelector("body"); for (var i = 0; i < planetsNode.length; i++) { var planetsNode = document.createElement("div"); planetsNode[i].className += "planet"; planetsNode.body.backgroundColor = "rgb(235, 12, 235)"; document.body.appendChild(planetsNode); } </script> </body> </html> 

You are accessing the variable 'planetsNode' before it gets created and you are accessing body from 'planetNode' element while assigning background color.

Hope this might help.

<script>
 var body = document.querySelector("body");

 var planetsNode = document.createElement("div");       
 planetsNode.className = "planet";

 body.style.backgroundColor = "rgb(235, 12, 235)";
 body.appendChild(planetsNode);
</script>

I don't know why you are using loop.

You are trying to access 'length' property of the 'planetsNode' variable before it has been created. If you are looking to create a new div for each planet create an array of planets and loop through them.

<script>
    var planets = [
        ["Mercury", "46.3, 46.3, 46.3"],
        ["Venus", "80.4, 78.4, 76.1"], 
        ["Earth", "34.9, 37.3, 51.4"], 
        ["Mars", "99.6, 52.9, 37.3"],
        ["Jupiter", "85.1, 74.9, 65.1"], 
        ["Saturn", "86.3, 73.7, 50.6"],
        ["Uranus", "76.5, 91.4, 92.5"],
        ["Neptune", "28.2, 47.5, 98.8"]
    ];

    for (var i = 0; i < planets.length; i++) {

        var planetNode = document.createElement("div");
        planetNode.style.backgroundColor = "rgb(" + planets[i][1] + ")";

        var nameNode = document.createTextNode(planets[i][0]);
        planetNode.appendChild(nameNode);

        var body = document.querySelector("body");
        body.appendChild(planetNode);
    }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM