How can I preserve a set of (copies of) objects from the original DOM, so the set retains its original values despite DOM changes?
For example:
<body class="toc endnotes">
And runs a script including this:
function runFunxForBodyClasses()
{
var bodyClass = document.getElementsByTagName("body")[0].className.trim();
if( bodyClass ){
// multiple body classes are space-delimited per html/css
var bodyClasses = bodyClass.split(" ");
if( bodyClasses.length > 0 ){
var h2s = document.getElementsByTagName("h2");
var anchors = getAnchors();
// debugging
alert(anchors.length);
// functions called below, affect the DOM and return void
if( bodyClasses.indexOf('toc') > -1 ){
addToc(h2s);
}
if( bodyClasses.indexOf('endnotes') > -1 ){
addEndNotes(anchors);
}
// ... other irrelevant ones here
}
}
}
function getAnchors()
{
return document.getElementById("main").getElementsByTagName("a");
}
function addEndNotes(anchors)
{
if( anchors.length < 1 ){
return;
}
// debugging
alert(anchors.length);
// ...
With the variable anchors
, I'm trying to preserve a list of anchor objects as it was when the page came from the server, and use that as input for addEndNotes()
.
What addEndNotes()
gets however is a list of anchor objects as modified by addToc()
. addToc()
adds links on h2's in a table of contents, say 'n' items. It does not use variable anchors
nor anything of the same name.
Yet the second alert reports a number of items in anchors
that is (original number + 2n): this list is being affected by changes in the DOM after anchors
is declared and before it is used again.
Originally initialization of anchors
was in global scope, but I learned from a page about variable scope that it's not really initialized until later if it's outside a function. So I put the anchor-getting in that function, but this made no difference in result.
Re another language I would say I'm wanting copies instead of references, how does one do this in JS?