Forum Moderators: open
As the subject says, I would like to have a toggle button to change the display of all elements - <div>'s in this case - with a given class from "block" to "none".
I'm a JS hack, like many I suppose. I can do this with id's, but with a class it seems to be a different problem...
So, I would like something like this:
<a href="#" onclick="ToggleClass(x);">Toggle on/off</a>
<div class="x">This div can be toggled on or off</div>
Seems so simple... But I'm having trouble finding an equivalent to getElement by ID for classes...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title></title>
<style type="text/css" media="all">
div.mydiv {
border:1px solid red;
color:green;
}
</style>
</head>
<body>
<div id="wrapper">
<div class="mydiv">some text</div>
<div class="mydiv">some text</div>
<div class="mydiv">some text</div>
<div class="mydiv">some text</div>
<div class="mydiv">some text</div>
</div>
<script type="text/javascript">
if (document.getElementById){
var i;
var x = document.getElementById('wrapper').document.getElementsByTagName('div');
function bchange(){
for (i=0;i<x.length;i++){
if (x[i].className.indexOf('mydiv')!=-1){
x[i].firstChild.nodeValue='some other text';
x[i].style.color='blue';
x[i].style.backgroundColor='yellow';
x[i].style.border='2px dashed black';
}
}
}
}
</script>
<p><a href="javascript:bchange();">change</a></p>
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title></title>
</head>
<body>
<div id="wrapper">
<div class="mydiv">some text</div>
<div class="mydiv">some text</div>
</div>
<script type="text/javascript">
if (document.getElementById){
var i;
var x = document.getElementById('wrapper').document.getElementsByTagName('div');
function toggle(){
for (i=0;i<x.length;i++){
if (x[i].className.indexOf('mydiv')!=-1){
x[i].style.display=='none'?x[i].style.display='block':x[i].style.display='none';
}
}
}
}
</script>
<p><a href="#" onclick="toggle();return false;">Toggle on/off</a></p>
</body>
</html>