PDA

View Full Version : how do you capture array of sibling elements?


bcamp1973
10-07-2006, 08:25 PM
i have a function that's supposed to change the class of an <li> to "open" onclick and change all of it's sibling <li>s classes to "shut". However, i'm not capturing the siblings correctly and I'm not sure what needs to be changed. Here's the code...


<script type="text/javascript" language="javacript">
function toggle() {
this.className='open';
var items=this.parentNode.getElementsByTagName('li');
for(var i=0,len=items.length;i<len;i++) {
if(items[i]!=this) items[i].className='shut';
}
}
</script>

<div>
<ul>
<li class="open" onclick="toggle()">One<a href="x">This is a test</a></li>
<li class="shut" onclick="toggle()">Two<a href="x">This is a test</a></li>
<li class="shut" onclick="toggle()">Three<a href="x">This is a test</a></li>
</ul>
</div>


...and this seems to be the offending line as it's not returning a value...

var items=this.parentNode.getElementsByTagName('li');

i've never used parentNode before so maybe the syntax is a bit off?

bcamp1973
10-07-2006, 10:32 PM
solved it!

<script type="text/javascript">
// <![CDATA[
function toggle(which){
which.className = "open";
var items = which.parentNode.getElementsByTagName("LI");

for(var i = 0; i < items.length; i++){
if(which != items[i])
items[i].className = "shut";
}
}
// ]]>
</script>

<div>
<ul>
<li class="open" onclick="toggle(this)">One<a href="#">This is a test</a></li>
<li class="shut" onclick="toggle(this)">Two<a href="#">This is a test</a></li>
<li class="shut" onclick="toggle(this)">Three<a href="#">This is a test</a></li>
</ul>
</div>