I'm not very experienced with Javascript, and I've encountered a frustrating issue.
My problem arises from having a list that contains other lists. I have a script that toggles the visibility of these lists on click. However, I also want to toggle/add a class to the link itself once it has been clicked.
This is an example of my list structure:
<ul>
<li><a href="#" onclick="toggle('item1');">Click something</a>
<ul id="item1" style="display: none;">
<li>Something ...</li>
<li>Something something</li>
</ul></li>
<li><a href="#" onclick="toggle('item2');">Click something else</a>
<ul id="item2" style="display: none;">
<li>Something more...</li>
<li>Something something less?</li>
</ul></li>
</ul>
Below is the script I am using:
<script type="text/javascript">
function toggle(id) {
var v = document.getElementById(id);
if (v.style.display == '') {
v.style.display = 'none';
v.classList.remove("selected");
} else {
v.style.display = '';
v.classList.add("selected");
}
}
</script>
The functionality for showing and hiding the list works correctly, but the class is not being added or removed as intended.
Here is the CSS code:
a:link {
color: #000000;
text-decoration: none;
}
a:hover, a.selected {
color: #005b97;
text-decoration: none;
padding-left: 2px;
}
Thank you in advance for any help!
Warmest regards, Benjamin