I am trying to work out why I can not access the nested function in a similar way as I can when I am just accessing an un-nested function (maybe there is a better way to explain this.
In other words, this works:
<html>
<head>
<title>Working with elements</title>
</head>
<script type="text/javascript">
var my_div = null;
var newDiv = null;
function addElement()
{
// create a new div element
// and give it some content
newDiv = document.createElement("div");
newContent = document.createTextNode("Hi there and greetings!");
newDiv.appendChild(newContent); //add the text node to the newly created div.
// add the newly created element and it's content into the DOM
my_div = document.getElementById("org_div1");
document.body.insertBefore(newDiv, my_div);
}
</script>
<body onload="addElement()">
<div id='org_div1'> The text above has been created dynamically.</div>
</body>
</html>
This does not work:
<html>
<head>
<title>Working with elements</title>
</head>
<script type="text/javascript">
var my_div = null;
var newDiv = null;
function addElement()
{
this.getFieldset = function() {
// create a new div element
// and give it some content
newDiv = document.createElement("div");
newContent = document.createTextNode("Hi there and greetings!");
newDiv.appendChild(newContent); //add the text node to the newly created div.
// add the newly created element and it's content into the DOM
my_div = document.getElementById("org_div1");
document.body.insertBefore(newDiv, my_div);
}
}
</script>
<body onload="addElement.getFieldSet()">
<div id='org_div1'> The text above has been created dynamically.</div>
</body>
</html>
It’s because you never executed
addElement()in the second case in order to execute thethis.getFieldset = ...assignment.You could change your code to
EDIT
See example at this fiddle.