here is a basic program, I don't understand why this is not working:
a object class, houseObject.js:
var string;
function createSentence(paragraph){
this.string = paragraph;
}
function getString(){
return string;
}
The program for running:
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript" src="houseObject.js"></script>
<script>
var temp = new createSentence("hello world");
var string = temp.getString();
var para=document.createElement("p");
var node=document.createTextNode(string);
para.appendChild(node);
</script>
</head>
<body>
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var element=document.getElementById("div1");
element.appendChild(para);
</script>
</body>
</html>
My second question is: why cant I put
var element=document.getElementById("div1");
element.appendChild(para);
inside the head section of the html. Is it because html is a script program, it hasn't read the body section yet?
Thanks in advance
head, the elementdiv1doesn't exist (yet). Place your scripts in the end of your HTML, or use window.load or document.DOMContentLoaded events.jQuery(document).ready- using jQuery also eliminates headaches about attachEvent/addEventListener, selecting elements by id, classes and other quirks