-2

Where am I doing wrong? Why this snippet of javascript code dosen't work?

This must be easy, but I just don't know why, I'm really a newbie at this

<!DOCTYPE html>
<html>
<body>

<p id="demo">Click the button to make a BUTTON element.</p>

<button onclick="myFunction()">Try it</button>

<script type="text/javascript">

function myFunction()
{
var bodyel = document.getElementById("body");
var block = document.createElement("div");
block.innerHTML = "whatever";
bodyel.appendChild(block);
};


</script>

</body>
</html>

5 Answers 5

2

Your <body> element does not have an "id" attribute at all, let alone one whose value is "body".

You could do this:

<body id=body>

Or this:

var bodyel = document.getElementsByTagName('body')[0];

Or just:

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

12 Comments

document.body.. is enough
Not sure why you reverted my edit. The id attribute should have quotes around it.
@EvanTrimboli quotes are not required in HTML.
@EvanTrimboli why, if they're not required? What's the benefit of adding 2 bytes to the size of the page? Remember, people on mobile devices literally pay for those bytes!
Try adding 2 classes to an element without using quotes. Or any attribute with some kind of special character. Or if you're embedding attributes dynamically via some server-side language. It's a convention that's so widely used that you'd struggle to find many counter-examples.
|
0

Here is the problem

var bodyel = document.getElementById("body"); //body is not id

You can use

getElementsByTagName('body')[0];

or

var b = document.body;

1 Comment

getElementsByTagName('body')[0]
0

Change the line:

var bodyel = document.getElementById("body");

To the following

var bodyel = document.body;

Comments

0

The body does not need to be called with a id

and if yes you have to add that id.

<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to make a BUTTON element.</p>
<button onclick="myFunction()">Try it</button>
<script type="text/javascript">
function myFunction() {
 var bodyel = document.body;
 var block = document.createElement("div");
 block.innerHTML = "whatever";
 bodyel.appendChild(block)
}
</script>
</body>
</html>

Comments

0

Fiddle

You need to change your code a little:-

var bodyel = document.getElementsByTagName("body")[0];

Rest will work. Have a look at this fiddle. Also try looking into document-body-appendchildi

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.