简体   繁体   中英

Active class navigation sidebar with anchors

I have a navigation sidebar with several anchors in an xsl document. Based on Adding active class for two anchor tags suggestions, I have tried to apply the same script, but I don't see why there is no modification of the style according to CSS.

<script>
     <![CDATA[
       document.querySelectorAll("#menu-hermeneutics li > a").forEach(a => {
          a.addEventListener("click", () => {
              a.addClass('active'); 
          });
       });]]>
</script>
<ul id="menu-hermeneutics">
    <li><a href="#general-overview">General Overview</a></li>
    <li><a href="#context-overview">...</a></li>
    <li><a href="#result-overview">...</a></li>
    <li><a href="#clanA">...</a></li>
    <li><a href="#aff-clanA">...</a></li>
    <li><a href="#clanB">...</a></li>
    <li><a href="#aff-clanB">...</a></li>
    <li><a href="#DR">...</a></li>
    <li><a href="#clanUNK">...</a></li>                
</ul>

And CSS:

#menu-hermeneutics > .active {background-color: grey; color: white; font-weight: 700; margin-right: 100px; width: 200px; }

In advance, thanks for your kind help.

First of all, your code at document.querySelectorAll("#menu-hermeneutics li > a") means it's gonna query all a tag and add class active if clicked on it, but your css below, it's different. #menu-hermeneutics >.active means it will select #menu-hermeneutics 's children (here is li , not a ) with class active because you are using > . If you want to css at all children a only, you can do this #menu-hermeneutics a.active You can take a look at here for more details. Hope it would help

Thanks to the suggestions of @ThienHuynh and a colleague, this is the correct code:

var links = document.querySelectorAll("#menu-hermeneutics li a");
  for (const link of links) {
    link.addEventListener("click", (e) => {
    var target = e.target;

    links.forEach(function(currentLink) {
        currentLink.classList.remove('active');
    });

      // if target already had .active. remove it. Otherwise, add it
      target.classList.toggle('active');
    })
    }

Note: see my comment below regarding > vs &gt --it was the main problem to avoid a bug.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM