Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How TO – Add Active Class to Current Element

I have a jsp page for the sidebar that I’d like to add an action class to when someone clicks on it. I’m taking the instructions of w3schools.com. link = https://www.w3schools.com/howto/howto_js_active_element.asp
but I’m not sure how to alter it to match my code I’m as I’m a javascript newbie. Any suggestions?


<body>
<div class="col-md-3" id="DIV">
    <ul class="nav nav-pills nav-stacked hidden-sm hidden-xs">
        <li role="presentation" class="active"><a href="${webHome}/home">Dashboard</a></li>
        <li role="presentation"><a href="${webHome}/task">Task List</a></li>
        <li role="presentation" >
            <a href="${webHome}/app?domainId=${userSession.domainId}">Applications</a>
        </li>
    </ul>
</div>

<script>
    // Add active class to the current button (highlight it)
    var header = document.getElementById("DIV");
    var btns = header.getElementsByTagName("presentation");
    for (var i = 0; i < btns.length; i++) {
        btns[i].addEventListener("click", function() {
            var current = document.getElementsByClassName("active");
            current[0].className = current[0].className.replace(" active", "");
            this.className += " active";
        });
    }
</script>
</body>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Replace

var btns = header.getElementsByTagName("presentation");

with

const btns = header.querySelectorAll("li[role=presentation]");

https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelectorAll

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading