This code enables dropdown onclick, but it only add class when I press ABC link and when I try to add .drop
class to GHI nothing happens. Also I found solutions how to do this with jQuery, but I need this vanilla JS, no jQuery please.
HTML
<ul>
<li><a href="javascript:">ABC</a>
<ol>
<li><a href="#">A</a></li>
<li><a href="#">B</a></li>
<li><a href="#">C</a></li>
</ol>
</li>
<li><a href="#">DEF</a></li>
<li><a href="javascript:">GHI</a>
<ol>
<li><a href="#">G</a></li>
<li><a href="#">H</a></li>
<li><a href="#">I</a></li>
</ol>
</li>
<li><a href="#">JKL</a></li>
<li><a href="#">MNO</a></li>
</ul>
JavaScript
<script>
var btn = document.querySelector('ul li a');
var drp = document.querySelector('ol');
btn.onclick = function()
{
drp.classList.toggle('drop');
}
</script>
CSS
.drop
{
display: block;
}
EDIT: Here is Vanilla JS dropdown I made: https://jsfiddle.net/vh6tywjs/11/
You want to use something like this:
var btn = document.querySelectorAll('ul li a');
for(var b = 0; b < btn.length; b++){
btn[b].onclick = function()
{
if(this.parentNode.querySelector('ol') != null){
this.parentNode.querySelector('ol').classList.toggle('drop');
}
}
}
When you click on an anchor link, get the containing li then search for the ol, after that toggle the class drop. Otherwise drp will always return the first ol in the document. You need querySelectorAll to select all matching elements as was mentioned in the comments. Finally, you need to apply the onclick event to each of the anchor links.