i have a javascript to hide/unhide 2 elements in my html at the same time. It worked fine when it was only one but now for some reason some elements only dissapear when i click twice, i dont know where is the mistake, here’s the code in case anyone finds something wrong thanks.
The function unhides two elements whos div id’s are given (xdivID and divID) and keeps the parent and the grandparent visible (idParent idUncle)
function doubleunhide(xdivID, divID, idParent, idUncle) {
var xitem = document.getElementById(xdivID);
if(xitem){
xitem.className='unhidden';
}
var item = document.getElementById(divID);
if(item) {
item.className='unhidden';
}
var elements = getElementsByClassName(document, "unhidden");
var n = elements.length;
for (var i = 0; i < n; i++) {
var e = elements[i];
if ((e.id != divID) && (e.id != xdivID) && (e.id != idParent) && (e.id != idUncle)){
e.className='hidden';
}
}}
And here’s how it is implemented in the html:
<div id="prj" class="hidden" style="margin-left:1em">
<a href="javascript:doubleunhide('prj011', 'prj01numbers', 'prj', 'nil');" style="text-decoration:none; color: rgb(0,0,0)" id="prj01link">Project 01</a> <br>
<a href="javascript:doubleunhide('prj021', 'prj02numbers', 'prj', 'nil');" style="text-decoration:none; color: rgb(0,0,0)" id="prj02link">Project 02</a> <br>
<a href="javascript:doubleunhide('prj031', 'prj03numbers', 'prj', 'nil');" style="text-decoration:none; color: rgb(0,0,0)" id="prj03link">Project 03</a> <br>
Project 04<br>
Project 05<br>
</div>
The problem is that then you use native
node.getElementsByClassName()the resulting array is ‘live’ – it changes dynamically then you change page. In your case – then you executee.className='hidden';theelementsarray is changed and becomes smaller – current element are wiped out because it is no loger fit your search criteria what you passed in togetElementsByClassName(). But your code still thinks there is same elements and iterate over it. You trying get undefined node eventually, get errors and script broke.To avoid this you can iterate in reverse order: