On Jun 17, 5:16 am, "Jon Slaughter" <Jon_Slaugh...@Hotmail.comwrote:
[...]
Actually I'm not using a link. I jus want to toggle the display state of an
object that is related to some other object. I have done this
function toggleDisplay(id, loc)
{
var val = id.parentNode.childNodes;
If you only want divs, then you might try:
var divs = id.parentNode.getElementsByTagName('div');
It may not be what you want as it will get all the descendant divs,
not just the direct children of parentNode.
var loc = (loc == null) ? 0 : loc;
If no value is passed to loc, its value will be 'undefined'. So while
the above "works", it isn't strictly true. You may prefer:
var loc = loc || 0;
so that if loc evaluates to false (i.e. it is undefined, false, null
or zero) it will be assigned a value of zero. Otherwise, it is
assigned its current value.
>
for (i=0; i<val.length; i++)
You should keep i local with var, and getting val.length every time is
inefficient, consider:
for (var i=0, len=val.length; i<len; i++)
{
var k = 0;
There's no need to declare k on every loop (it doesn't do any harm,
it's just not necessary), you can declare it outside and just set its
value here.
if (val[i].nodeName=="DIV")
It's better to store values if they are going to be used a number of
times rather than looking them up. Declare val earlier (say at the
start with k), then:
val = val[i];
if (val.nodeName.toLowerCase() == 'div'){
{
if (k == loc) (val[i].style.display == 'none') ?
val[i].style.display = 'block' : val[i].style.display = 'none';
or
val.style.display = (val.style.display == 'none')? '' : 'none';
k++;
}
}
return;
If there is no return value, there's no need for return here.
}
Which lets me toggle a div that is a certain sibling of some object. (for
some reason I couldn't get nextSibling to work right(had to use it twice to
get the adjacient div and I guess it had to do with text blocks or
something)).
Some browsers insert #text nodes to preserve whitespace, e.g. Given
the following HTML:
<div>
<p>
<p>
</div>
in firefox the div will have 3 child nodes (#text, p, p), in IE there
will only be 2 (p, p). So you can happily use nextSibling if you
filter out the nodes you don't want (which is what you are doing with
the childNodes collection).
>
Anyways, what I'm using does seem to work. I'd rather have used css to do
the toggling but guess thats impossible ;/
Not at all, you can add/remove class values or edit the CSS rule
directly, take your pick. Where you do the display:none bit in you
current function, you could add or remove a class instead. It is
frequently used where more than a simple 'hide' is required.
--
Rob