I have a function whose destination is to work onClick event.
So, we have for example 4 Span elements and 4 Div elements.
The Spans are Tabs-buttons which I would like to “open” those Divs.
The 1st Span onClick would (open) change the style.display of the 1st Div in “block”, from “none”, and so on for the next Spans.
This piece of code works very well, but it changes only the design of elements.
function activateSup(s) {
var workTable = s.parentNode.parentNode.parentNode.parentNode.parentNode;
var spans = workTable.getElementsByTagName("span");
var supDivs = workTable.getElementsByClassName("supDiv");
for (var i = 0; i < spans.length; i++) {
spans[i].style.backgroundColor = "";
spans[i].style.border = "";
}
s.style.backgroundColor = "#5eac58";
s.style.border = "2px solid #336633";
}
I’ve tried to add the code below into my function to achieve what I want, but It does not work.
var getIndex = function(s) {
for (var index = 0; s != s.parentNode.childNodes[index]; index++);
return index;
}
for (var d = 0; d < supDivs.length; d++) {
if (getIndex == d) {
supDivs[d].style.display = "block";
}
else {
supDivs[d].style.display = "none";
}
}
I’m not exactly sure what you’re trying to do, but one thing I noticed is this:
This code is comparing
getIndextod, which means it’s comparing an integer (d) to the functiongetIndex, instead of the result of the function callgetIndex(spans[d])(which is an integer, liked).But what I think you’re really trying to do, is getting the index of the clicked
<span>so you can show the<div>with the matching index (and hide the rest). To achieve this, the code could be changed like so:Instead of the function
getIndex, this just saves the correctindexinside the firstforloop.There are many more improvements that could be made to this code, like rewriting it so you don’t need that ugly
s.parentNode.parentNode.parentNode.parentNode.parentNodeand working with CSS classes instead of manually setting the style. But I’ll leave that to the reader.