I have a list set up as follows:
HTML Code:
<ul>
<li><div class="menuopen" title="Toggle Subtasks" onclick="toggleSubTasks(this);"></div>List Item
<ul>
<li>Sub List Item
<ul>
<li>Sub Sub List Item</li>
</ul>
</li>
</ul>
</li>
</ul>
The relevant css:
Code:
ul {
margin-left: 25px;
list-style: none;
}
.menuopen {
width: 12px;
height: 12px;
margin: 3px 3px 0 0;
background: transparent url(images/downarrow.png) left top no-repeat;
cursor: pointer;
display: inline-block;
}
.menuclosed {
background: transparent url(images/rightarrow.png) left top no-repeat;
}
I am attempting to set up the function toggleSubTasks(element) to toggle on/off the ul tags directly descendant from the parent ul tag. The code I have is as follows (note, this is set to be used on a div inside the parent ul tag):
Code:
function toggleSubTasks(element) {
// Get the parent list
var parentList = element.parentNode;
// Set up array of unordered lists inside our parent element
var subTask = parentList.getElementsByTagName('ul');
// if element background includes "rightarrow" it is closed, otherwise it is open
if (element.style.background.match("rightarrow") != null) {
// is currently closed, so open all submenus
for (var i = 0; i < subTask.length; i++)
subTask[i].style.display = "block";
// Change arrow to downarrow
element.style.background = "transparent url(styles/images/downarrow.png) left top no-repeat";
}
else {
// is currently open, so close all submenus
for (var i = 0; i < subTask.length; i++)
subTask[i].style.display = "none";
// Change arrow to rightarrow
element.style.background = "transparent url(styles/images/rightarrow.png) left top no-repeat";
}
}
This works great, but toggles all ul tags that are descendant from the parent, not just the direct children. As the getElementsByTagName method returns all tags in the order that they are found, not the heirarchy that they are in, I can't think of a way to limit it to just the direct children. Is there perhaps a better way to approach this so that I can affect just the direct children lists of the parent list item?
|