G
Giacomo
I work on a page structured like:
<h2> ... </h2>
<div ="div1" class="show"> ... </div>
<h2> ... </h2>
<div id="div2" class="show"> ... </div>
<h2> ... </h2>
<div id="div3" class="show"> ... </div>
---
I obtain the list of h2 by getElementsByTagName and I'd like to
associate to every h2 the onclick attribute in order to call a function
to hide the first div following each of the h2.
I tried:
***
window.onload = function init()
{
var h2 = document.getElementsByTagName('h2');
for ( var i=0; i<h2.length; i++ )
{
div = h2.nextSibling;
while ( div.tagName != 'DIV' )
{
div = div.nextSibling;
}
// these two lines are a trick, but it's absolutely horrible...
h2.name = div.id;
// ...but I can't find a way to set the onclick attribute
h2.onclick=function () {showhideElement(this.name)};
}
function showhideElement(id)
{
var el = document.getElementById(id);
if ( el.className != "hide" )
{
el.className = "hide";
} else {
el.className = "show";
}
}
***
Obviously, there's a CSS:
***
..hide {
display: none;
}
..show {
display: block;
}
***
As I said, the two lines are a trick, but I tries unsuccessfully all
these ways:
//h2.onclick=showhideElement('div.id');
//h2.onclick=showhideElement(div.id);
//h2.addEventListener('click',showhideElement (div.id),false)
//h2.onclick=function () {"showhideElement ('" + divId.id + "');"};
Who can help me? Please, answer me only if you are very sure and you
have tested the solution proposed.
Thanks in advance,
Giacomo.
<h2> ... </h2>
<div ="div1" class="show"> ... </div>
<h2> ... </h2>
<div id="div2" class="show"> ... </div>
<h2> ... </h2>
<div id="div3" class="show"> ... </div>
---
I obtain the list of h2 by getElementsByTagName and I'd like to
associate to every h2 the onclick attribute in order to call a function
to hide the first div following each of the h2.
I tried:
***
window.onload = function init()
{
var h2 = document.getElementsByTagName('h2');
for ( var i=0; i<h2.length; i++ )
{
div = h2.nextSibling;
while ( div.tagName != 'DIV' )
{
div = div.nextSibling;
}
// these two lines are a trick, but it's absolutely horrible...
h2.name = div.id;
// ...but I can't find a way to set the onclick attribute
h2.onclick=function () {showhideElement(this.name)};
}
function showhideElement(id)
{
var el = document.getElementById(id);
if ( el.className != "hide" )
{
el.className = "hide";
} else {
el.className = "show";
}
}
***
Obviously, there's a CSS:
***
..hide {
display: none;
}
..show {
display: block;
}
***
As I said, the two lines are a trick, but I tries unsuccessfully all
these ways:
//h2.onclick=showhideElement('div.id');
//h2.onclick=showhideElement(div.id);
//h2.addEventListener('click',showhideElement (div.id),false)
//h2.onclick=function () {"showhideElement ('" + divId.id + "');"};
Who can help me? Please, answer me only if you are very sure and you
have tested the solution proposed.
Thanks in advance,
Giacomo.