add class to next sibling element In Javascript


How could I add toggle class? When I click on anchor tag it should add class to only next sibling element ( .treeUlChild ). i tried a lot and try to find solution but couldn’t. I am new and this is my first project in javascript. here is my html code.

    <div id="treeList" class="treeDiv">
    <ul class="treeUl">
            <a href="#">GUIDELINES</a>
            <ul class="treeUlChild treeLevel2">
                <li><a href="#"> Guidlines 1</a></li>
                <li><a href="#"> Guidlines 2</a></li>
                <li><a href="#"> Guidlines 3</a></li>
                <li><a href="#"> Guidlines 4</a></li>
            <!-- End Child Ul -->
            <a href="#">AFTER-SALES</a>
            <ul id="test" class="treeUlChild treeLevel2">
                <li><a href="#">xyz</a></li>
                    <a href="#">def</a>
                    <ul class="treeUlChild treeLevel3">
                            <a href="#">  ASSETS</a>
                            <ul class="treeLevel4">
                                <li><a href="#">DIGITAL</a></li>
                                <li><a href="#">OOH</a></li>
                                <li><a href="#">POS</a></li>
                                <li><a href="#">PRINT</a></li>
                                <li><a href="#">SOCIAL GIF</a></li>
                                <li><a href="#">SOCIAL VIDEOS</a></li>
                            <!-- End Child Ul -->
                    <!-- End Child Ul -->
            <!-- End Child Ul -->
    <!-- End treeUl -->

This is my javascript code.

document.querySelector('#treeList ul li a').addEventListener("click", function(){


There is very simple way using Bootstrap by the way. But if you want to do that with pure Javascript, you’re on the right way to it.

So first, transform your query selector into a object e.g:

var el =  document.querySelector('#treeList ul li a');

forEach method, querying the single object clicked in the array of multiple objects:


Add functions to your elements:

<li><a onclick="yourFunctionName()" href="#"> Guidlines 1</a></li>
<li><a onclick="yourFunctionName()" href="#"> Guidlines 2</a></li>
<li><a onclick="yourFunctionName()" href="#"> Guidlines 3</a></li>
<li><a onclick="yourFunctionName()" href="#"> Guidlines 4</a></li>

ps: you can simplify this.

Structure your function:

function myFunctionName(){

Source: stackoverflow