I don't know but this question might have simplest of all the answers but I am unable to understand.
I basically wanted to replicate a simple HTML code
<p></p>
using Javascript. If I simple write <p></p>
in html then I get the following rendered elements:
<html><head></head><body><p></p></body></html>
I created an html file and wrote the following code in it.
<script>
var para = document.createElement('p');
</script>
I rendered this file in the browser and found the following elements being rendered.
<html>
<head>
<script>
var para = document.createElement('p');
</script>
</head>
<body></body>
</html>
apparently my element is not created. My guess was I did not have any parent specified so it did not create that. Since body is a default DOM element, I then thought of getting the body dom element and append para as a child to it so I wrote the following code:
<script>
var body = document.getElementsByTagName('body')[0];
var para = document.createElement('p');
body.appendChild(para);
</script>
but still I didn't get it to work. The following was rendered:
<html>
<head>
<script>
var body = document.getElementsByTagName('body')[0];
var para = document.createElement('p');
body.appendChild(para);
</script>
</head>
<body>
</body>
</html>
and I got an Uncaught TypeError: Cannot read property 'appendChild' of undefined, which is telling me that variable body has a value undefined
, but why is their no body element according to JS? What is the basic of DOM elements and how are they created when rendered, I need to understand the fundamentals behind this.