The following JavaScript has a variable parList which is global.
At the start during the init function another function is called which fills the variable with paragraph elements from the page with the initial two that exist.
When adding another paragraph (sentence) via the Add button the paragraph is added to the page as expected.
The bizarre thing is the variable is being updated as they are added.
Not what I expected to see when I went to use it.
My primary question is why is it so?
var ParList;
function getPars() {
var len;
ParList = document.getElementById('pars').getElementsByTagName('p');
len = ParList.length;
alert("Original number of paragrahs in the list is\
\
" + len);
}
//
function setPar(item) {
var newEle, txtNode;
newEle = document.createElement('p');
txtNode = document.createTextNode(item);
newEle.appendChild(txtNode);
document.getElementById('pars').appendChild(newEle);
}
//
function addPar() {
var done = false, addItem;
do {
addItem = prompt("Add a sentence.");
if (addItem === null) {
done = true;
} else if (addItem === '') {
alert("Must be sumpin to add\
\
Try again");
} else {
setPar(addItem);
done = true;
}
} while (!done);
//
//ParList has now incremented..
//
alert("the number of paragraphs in the list is now\
\
" + ParList.length);
}
//
function init() {
//
document.getElementById('add').addEventListener('click', addPar, false);
getPars();
}
<div id="pars">
<p>Bizare things are happening.</p>
<p>Click Add to see.</p>
</div>
<p>
<input id="add" type="button" value="Add">
</p>
Originally this was in a module and removed for testing.
It has been tested in multiply modern browsers and all behave the same so it must be standard behaviour.
Searching with appropriate keywords has results that are not relevant.