It seems that you were trying something like
<div id="a"></div>
<div id="a"></div>
toggle_visibility('a');
The problem is that each id must be unique in the document, so document.getElementById
returns a single element, not a collection of elements.
Then, if you want to have more than one element with the same id, you should use classes instead.
<div class="a"></div>
<div class="a"></div>
function toggle_visibility(cl){
var els = document.getElementsByClassName(cl);
for (var i = 0; i < els.length; i++){
var s = els[i].style;
s.display = s.display === 'none' ? 'block' : 'none';
}
}
toggle_visibility('a');
If you want to make it work with multiple classes, use
var toggle_visibility = (function() {
function toggle(cl) {
var els = document.getElementsByClassName(cl);
for(var i = 0; i < els.length; i++){
var s = els[i].style;
s.display = s.display === 'none' ? 'block' : 'none';
}
}
return function(cl) {
if (cl instanceof Array){
for(var i = 0; i < cl.length; i++){
toggle(cl[i]);
}
} else {
toggle(cl);
}
};
})();
toggle_visibility('myclass');
toggle_visibility(['myclass1','myclass2','myclass3']);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…