What is the method to implement the addition and removal of an active class to an element using only JavaScript?

I've been working on creating a navigation menu and I've completed the HTML and CSS part. However, when it comes to implementing Javascript, I'm facing an issue. I can add a class to an element, but I'm struggling to remove the class from the remaining elements. Can someone please assist me with this?
Here's my code:

<!DOCTYPE html>
    <html>
    <head>
        <title>Toggle Navigation Class</title>

        <style type="text/css">
        * {
            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;
        }
        </style>
    </head>
    <body>
    <header>
        <nav>
            <ul onclick="myFunction(event)">
                <li><a href="#">home</a></li>
                <li><a href="#">about</a></li>
                <li><a href="#">service</a></li>
                <li><a href="#">profile</a></li>
                <li><a href="#">portfolio</a></li>
                <li><a href="#">contact</a></li>
            </ul>
        </nav>
    </header>
    <script type="text/javascript">
        function myFunction(e) {
            e.target.className = "active";
        }
    </script>
    </body>
    </html>

Here is the link to my Codepen

Answer №1

Utilize the document.querySelectorAll method to locate the element with the current active class, and then proceed to remove that class.

function myFunction(e) {
  var elems = document.querySelectorAll(".active");
  [].forEach.call(elems, function(el) {
    el.classList.remove("active");
  });
  e.target.className = "active";
}

JSFIDDLE

A different approach involves using document.querySelector instead of document.querySelectorAll.

 function myFunction(e) {
  var elems = document.querySelector(".active");
  if(elems !==null){
   elems.classList.remove("active");
  }
 e.target.className = "active";
}

JSFIDDLE 2

Edit

To avoid iterating through the entire collection, you can select the element with the active class using document.queryselector. Additionally, assign an id to the ul for targeted selection of a specific element.

function myFunction(e) {
  if (document.querySelector('#navList a.active') !== null) {
    document.querySelector('#navList a.active').classList.remove('active');
  }
  e.target.className = "active";
}
<style type="text/css">* {
  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;
}
<title>Navigation class Toggling</title>

<header>
  <nav>
    <ul onclick="myFunction(event)" id='navList'>
      <li><a href="#">home</a></li>
      <li><a href="#">about</a></li>
      <li><a href="#">service</a></li>
      <li><a href="#">profile</a></li>
      <li><a href="#">portfolio</a></li>
      <li><a href="#">contact</a></li>
    </ul>
  </nav>
</header>

Answer №2

To utilize the classList feature, you have the ability to easily add, remove, or toggle classes.

Start by removing the class name from the previous element:

// If only one element has this class
document.querySelector('.active').classList.remove('active')

Next, add the class to the new element:

e.target.classList.add('active')

Answer №3

HTML

<section class="content">
 <div>
  <h2>Title</h2>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
  <a href="#">Read more</a>
 </div>
 <aside>
  <ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
  </ul>
 </aside>
</section>

CSS

    .content {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    h2 {
      font-size: 24px;
      color: #333;
    }

    p {
      font-size: 16px;
      color: #666;
    }

    a {
      text-decoration: none;
      color: #ff4b4c;
    }

    ul {
      list-style: none;
    }

JS

    document.addEventListener('DOMContentLoaded', function() {

      const selector = 'a';
      const elems = Array.from(document.querySelectorAll(selector));

      function highlightLink(evt) {
        const target = evt.target;

         if (!target || !target.matches(selector)) {
           return;
         }

        elems.forEach(elem => elem.classList.remove('active'));
        evt.target.classList.add('active');
      };

      document.addEventListener('click', highlightLink);

    });

BTW: Check out this helpful resource: https://example.com

Answer №4

To manipulate classes in your DOM element using vanilla JavaScript, you can utilize the Element.classList property.

add: Adds specified class values to the element. Existing classes are not affected.

remove: Removes specified class values from the element.

For selecting elements based on CSS selectors, you can employ Document.querySelectorAll().

Learn more at:

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

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

If you want to mark an element as active when a user clicks on it, consider the following code snippet:

window.myFunction = function(event) {
  // Reset all menu items
  document.querySelectorAll('ul li a.active').forEach(function(item) {
  item.classList.remove('active');
})
  // Mark the selected menu item as active
  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;
}
<header>
  <nav>
    <ul onclick="window.myFunction(event)">
      <li><a href="#">home</a></li>
      <li><a href="#">about</a></li>
      <li><a href="#">service</a></li>
      <li><a href="#">profile</a></li>
      <li><a href="#">portfolio</a></li>
      <li><a href="#">contact</a></li>
    </ul>
  </nav>
</header>

Answer №5

To achieve this in vanilla JavaScript, you can follow the code snippet below:

function myFunction(element, event) {
      for (var i = 0; i < element.children.length; i++) {
        element.children[i].childNodes[0].className = "";
      }
      event.target.className = "active"; 
    }
<!DOCTYPE html>
<html>
<head>
  <title>Navigation class Toggling</title>
  
  <style type="text/css">
    * {
      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;
    }
  </style>
</head>
<body>
  <header>
    <nav>
      <ul onclick="myFunction(this, event)">
        <li><a href="#">home</a></li>
        <li><a href="#">about</a></li>
        <li><a href="#">service</a></li>
        <li><a href="#">profile</a></li>
        <li><a href="#">portfolio</a></li>
        <li><a href="#">contact</a></li>
      </ul>
    </nav>
  </header>
</body>
</html>

Answer №6

In my opinion, I recommend sticking with the document.querySelector method. This method accepts a CSS-like query and is perfect for locating an active class within the page. Upon finding it (as indicated by the if statement), we can then remove it and apply the new class to the designated target.

It is important to note that using className = "" will erase all existing classes. To maintain cleanliness in your code, it is advisable to utilize classList for all operations.

function updateClass(e) {
    var element = document.querySelector('.active');
  
    // Ensuring the element exists before removing the 'active' class
    if(element) {
      element.classList.remove('active');
    }

    e.target.classList.add('active');
}

Answer №7

Here is a helpful tip below.

//Clear all classes based on the element's ID
document.getElementById("elementIdHere").className = "";
//If you want to retain certain classes on the element, follow this example
document.getElementById("elementIdHere").className = "keepClass";

Answer №8

Java Script

const elements = document.querySelectorAll('.some-class');

elements.onclick = function(event) {
    event.classList.toggle('{custom-class}');
};

To ensure better compatibility across browsers:

elements.onclick = function(event) {
    const element = event.target;
    const classes = element.className.split(" ");
    const classPosition = classes.indexOf('{your-class}');

    if (classPosition >= 0) {
        classes.splice(1, classPosition);
    } else {
        classes.push('{your-clas}');
    }

    element.className = classes.join(" ");
});

Answer №9

window.activateMenu = function(event) {
  var elements = document.querySelectorAll('ul li a');
  for (var j = 0; j < elements.length; j++) {
    elements[j].classList.remove('active');
  }
  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: pink;
  color: #fff;
}

a.active {
  background-color: blue;
}

.active {
  background-color: red;
}
<header>
  <nav>
    <ul onclick="window.activateMenu(event)">
      <li><a href="#">home</a></li>
      <li><a href="#">about</a></li>
      <li><a href="#">service</a></li>
      <li><a href="#">profile</a></li>
      <li><a href="#">portfolio</a></li>
      <li><a href="#">contact</a></li>
    </ul>
  </nav>
</header>

Answer №10

Here is the code I created:

const navigationLinks = document.querySelectorAll('ul li a');

function addActiveClass() {
    navigationLinks.forEach((link) => {
        link.addEventListener('click', (e) => {
            e.preventDefault();
            removeActiveClass();
            link.parentElement.classList.add('active');
        });
    });
}

addActiveClass();

function removeActiveClass() {
    navigationLinks.forEach((link) => {
        link.parentElement.classList.remove('active');
    });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

jQuery fails to generate correct HTML code

I am currently working on maintaining an older Rails 3 project that I need to update with new features, particularly adding responsiveness using Bootstrap 4. The end result I am aiming for can be viewed here: http://jsfiddle.net/k1zbe4o9/. It functions pe ...

Bootstrap 4 - Static Text - Pick a Choice

When using Ajax to dynamically submit components in a form, I encountered an issue with maintaining the styling of input components when the user clicks on the add/save button. After successfully applying changes to a plain text input field using $(' ...

Mastering Authentication in React JS: Best Practices

I am currently working on integrating Backend (Express JS) and Frontend (React JS). One of the challenges I am facing is understanding how to manage sessions effectively. When a user logs in using a form built with React JS, the backend responds with a HS ...

Displaying a random div using javascript

Seeking a way to display random divs on my webpage, I came across a stackoverflow solution: Showing random divs using Jquery The recommended code can be found here: http://jsfiddle.net/nick_craver/RJMhT/ Despite following the provided instructions, I am ...

The footer lies at the bottom of the page, demarcated by

I'm struggling to position the footer at the bottom of the page with a horizontal line just above it. Despite trying various resources, I can't seem to get the footer to stay at the bottom. I'm currently using a blog template as the basis fo ...

Utilizing HTML and CSS to Position Text Adjacent to the Initial and Final Elements in a Vertical List

Exploring a simple number scale ranging from 1 to 10, I experimented with different ways to represent it. Here's my attempt: <div class="rate-container"> <p class="first">Extremely Unlikely</p> <a class=" ...

"Is there a way to retrieve a field from a different model within a Mongoose model

Presented below are two distinct MongoDB Models: Movie Model import mongoose from 'mongoose'; const movieSchema = new mongoose.Schema({ title: { type: String, required: [true, 'Please Enter the Movie Title'], trim: true, ...

Tips for Controlling an Absent Search Bar in the HTML Source Code with Selenium

I'm attempting to automate searches using Selenium in Java. Upon inspecting the search bar on the page, I noticed that it has an id of searchBox and a name of q, which could be helpful. However, these properties are not visible in the HTML when viewi ...

Creating uniform height for dynamic MdBootstrap cards

I am attempting to ensure uniform height for these cards regardless of the length of the movie title. The cards are dynamically generated and I am using swiperjs for carousel functionality. Just to clarify, these are mdBootstrap cards. Below is the code sn ...

Error: Unable to execute _this2.setState in react - potential problem with binding

I am completely new to utilizing react, and I have been encountering difficulties in pinpointing the root cause of this error that keeps popping up in the chrome console bundle.js:15316 Uncaught (in promise) TypeError: _this2.setState is not a function M ...

CSS: Adjusting the top margin of a font

I admit, the title of this question may not be the most creative, but I've hit a wall in my search for answers. It seems like I must be missing something fundamental in CSS, or perhaps my search terms are just off. Here's the issue: I have a con ...

Debouncing form inputs in VueJS with LoDash debounce on the entire form

I'm currently experimenting with implementing LoDash debounce to detect when a user stops typing on a form and trigger an event accordingly. Looking for inspiration from this helpful guide However, my goal is to extend this functionality to cover al ...

Guide to configuring an Angular Material Footer using Flex-Layout

Could someone help me with setting up the footer in my Angular Material app? I want it to: stick to the bottom when the content height is smaller than the view-port move down or get pushed down when the content height exceeds the view-port One important ...

Is it possible to work with a database file using JavaScript?

Can HTML5 and JavaScript be used to import a .db file from a local machine for CRUD operations using SQL and then export the edited file back to the local machine? Is it possible to use indexedDB in JavaScript to load data from a file and save it back onc ...

Issues with the throttling function of the setTimeout method in an

Having some trouble with my timer and function for retrieving data on button clicks. I'm trying to prevent too many rapid requests. Here's the code snippet for the timer: var timer; And the function that updates via AJAX: function doTheTh ...

Controlling the position of a <div> element using JavaScript

Is there a way to adjust the position and size of a <div>? I have already set it to float with this CSS code: div.grid_tooltip { position: absolute; left: 0px; top: 0px; } ...

Tips for disabling modal scrolling on mobile when scrolling the div inside it

Currently, I am facing an issue with a bootstrap modal. I have created a div with overflow:auto inside the modal. Everything works fine on desktop, but on mobile devices, when I scroll the content of the div, the modal itself also scrolls. How can I preven ...

Using Vue.js: Creating a Custom Filter to Easily Filter Table Data

This table contains two columns: Name, and Age. Currently, the search functionality only filters by name. However, I would like to implement filtering by age using a comparison operator such as < or >. If you want to see the code in action, check ou ...

developing both vertical and horizontal 'cross out'

I'm attempting to add a 'spacer' between buttons on my website using the word "or" with a vertical line centered above and below it. I've tried HTML <div class="footer-btn-wrap"> <div class="decor"><a href="... < ...

Acquire the information for PHP data updating

I'm currently working on a login system and data update feature that allows users to update their account information. To begin, please enter the login name of the account you wish to modify: UPDATEINPUT.HTML <html> <form method = "get" a ...