add class to next sibling element In Javascript

Tags:



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">
        <li>
            <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>
            </ul>
            <!-- End Child Ul -->
        </li>
        <li>
            <a href="#">AFTER-SALES</a>
            <ul id="test" class="treeUlChild treeLevel2">
                <li><a href="#">xyz</a></li>
                <li>
                    <a href="#">def</a>
                    <ul class="treeUlChild treeLevel3">
                        <li>
                            <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>
                            </ul>
                            <!-- End Child Ul -->
                        </li>
                    </ul>
                    <!-- End Child Ul -->
                </li>
            </ul>
            <!-- End Child Ul -->
        </li>
    </ul>
    <!-- End treeUl -->
</div>

This is my javascript code.

document.querySelector('#treeList ul li a').addEventListener("click", function(){
    document.querySelector('.treeUlChild').nextSibling.classList.toggle('done');
});

Answer

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:

el.forEach(yourFunctionName());

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(){
document.querySelector('.treeUlChild').nextSibling.classList.toggle('done');
}


Source: stackoverflow