How can I add and remove an active class to an element in pure JavaScript

前端 未结 9 1182
被撕碎了的回忆
被撕碎了的回忆 2020-12-17 20:29

I am trying to make a navigation menu I did all the HTML and CSS when come to javascript I am struck in the middle I am able to add a class to the

9条回答
  •  心在旅途
    2020-12-17 20:39

    You can use "pure" JavaScript Element.classList to add and remove a class from your DOM element.

    add: Add specified class values. If these classes already exist in attribute of the element, then they are ignored.

    remove: Remove specified class values.

    Use Document.querySelectorAll()to returnsa elements within the document that match the specified group of CSS selectors.

    More info at:

    https://developer.mozilla.org/en/docs/Web/API/Element/classList

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

    Regarding your code, you can mark as active your element when User click on it using the following code:

    window.myFunction = function(event) {
      // reset all menu items
      document.querySelectorAll('ul li a.active').forEach(function(item) {
      item.classList.remove('active');
    })
      // mark as active selected menu item
      event.target.classList.add("active");
    };
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    
    header {
      width: 100%;
      height: auto;
      max-width: 600px;
      margin: 0 auto;
    }
    
    nav {
      width: 100%;
      height: 40px;
      background-color: cornflowerblue;
    }
    
    ul {
      list-style-type: none;
    }
    
    li {
      display: inline-block;
    }
    
    a {
      text-decoration: none;
      padding: 8px 15px;
      display: block;
      text-transform: capitalize;
      background-color: darkgray;
      color: #fff;
    }
    
    a.active {
      background-color: cornflowerblue;
    }
    
    .active {
      ackground-color: red;
    }

提交回复
热议问题