0

First sorry for my English, I am from Spain. I am new working with Javascript and the problem is that when I try to create a node with Javascript, it does not run.

Checking with firebug I discovered that "document.body is null" even though I have specified.

I facilitated the snippet of code that fails:

// Crear nodo de tipo Element
var parrafo = document.createElement("p");
// Crear nodo de tipo Text
var contenido = document.createTextNode("Hola Mundo!");
// Añadir el nodo Text como hijo del nodo Element
parrafo.appendChild(contenido);
alert(document.body)
// Añadir el nodo Element como hijo de la pagina
document.body.appendChild(parrafo);
1
  • thanks for your help, I am new to the web and I'm learning to use, being English I have some difficulties to understand it, I'll do it slowly but I will have to do Commented Mar 12, 2015 at 12:02

1 Answer 1

1

If you have that script in the head element, it will run before document.body exists. Instead, move it to the end of the file, just before the closing </body> tag.

Here's an example showing that document.body is null for code running before the opening <body> tag has been parsed:

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>No Body</title>
<script>
alert(document.body === null); // true
</script>
</head>
<body>
<script>
alert(document.body === null); // false
</script>
</body>
</html>
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.