0

I have to print "Hello, Mars", but something is wrong. I've tried to add paragraph.appendChild(text) too but it not works.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        const body = document.getElementById("body")
        const paragraph = document.createElement("p")
        const text = document.createTextNode("Hello, Mars")
        body.appendChild(paragraph)
    </script>
</body>
</html>
2
  • 4
    Your <body> element does not have the id "body"; it has no id at all. Use document.body instead. Commented Sep 2, 2021 at 13:49
  • 4
    You also never do anything with text Commented Sep 2, 2021 at 13:50

1 Answer 1

1

Two things here:

Firstly, you never add text to the created paragraph, which would be done by adding this:

paragraph.appendChild(text);

Secondly, using getElementById() you are selecting an item that would have id="body", not the <body> element on your page. You can get the body using document.body as follows:

const body = document.body;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.