Guide on adding or removing a class from all <li> elements except the final one

I am working with a set of list items (<li>) inside an unordered list (<ul>). I have created a JavaScript function that adds the 'active' class to the clicked item and removes it from its siblings. However, I only want this functionality to apply to all items except for the last <li> in the list.

<ul class='tabs'>
   <li>Home</li>
   <li>About</li>
   <li>Contact</li>
   <li>
     <form>
       <input type='text'/>
        <button></button>
     </form>
   </li>
</ul>

Below is the JavaScript function:

[].forEach.call(document.querySelectorAll('.tabs li'), function(item) {
        item.addEventListener('click', function(event) {
            if (item.nextSibling) {
              document.querySelector(".tabs li.active").classList.remove("active");
              item.classList.add("active");
            }
        });
    });

Answer №1

To achieve the desired result, you have two options. One is to utilize the slice method:

const listItems = Array.from(document.querySelectorAll('.tabs li'));
const selectableListItems = listItems.slice(0, -1);

selectableListItems.forEach(function(ele) {
    ele.addEventListener('click', function(e) {
        if(ele.nextSibling){
          document.querySelector(".tabs li.active").classList.remove("active");
          ele.classList.add("active");
        }
    });
});

Alternatively, you can adjust your query selector by using a pseudo-class to target all items except the last one:

document.querySelectorAll('.tabs li:not(:last-child)');

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

Creating an HTML element within an ion-slide that allows for horizontal scrolling

I am facing an issue with a HTML horizontal stripe that contains buttons which need to be scrolled horizontally inside of <ion-slide>. The user wants to swipe this horizontal list from right to left to reveal the next set of buttons. The problem aris ...

Enhance Your Website by Integrating Slick Slider with Bootstrap 4

I am currently facing a significant issue. I am attempting to integrate three div elements into my slider, and all of them maintain a Bootstrap 4 structure. The code looks like this, and it is being generated from another Jquery function where I am inserti ...

Error message: Unable to instantiate THREE.Spherical with OrbitalControls

While attempting to implement OrbitalControls.js in my Electron app, I encountered an issue related to the Spherical constructor. Uncaught TypeError: THREE.Spherical is not a constructor I am unable to locate a Sphereical.js file to resolve this error. C ...

The AddThis counter is missing the right border when integrated with Twitter's Bootstrap 3

When implementing the standard code provided by alongside Twitter's Bootstrap 3, I noticed that the right border of the counter is not displaying: ...

Why isn't my Vue.js application automatically refreshing when I add or remove an object from the array?

In my Quasar and Vue.js project, I am working on a form where I can add objects to an array for insertion into the database simultaneously. However, I am facing an issue where the additions or deletions in the array only reflect on the screen after focusin ...

ReactJS allows functions to be executed repeatedly

I'm attempting to output "asdf" to the console every second in reactjs using setInterval. Below is my code snippet: <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react.js"></script> <scr ...

Transforming an Ext.data.TreeStore data structure into a JSON format

How can I convert an Ext.data.TreeStore to a string for saving to Local Storage? I tried using Ext.encode() but it's giving me a circular structure error. Has anyone encountered this issue and found a workaround? ...

Issue with data retrieval (Uncaught (in promise) TypeError: Unable to access properties of undefined (reading 'map'))

Greetings! Upon executing this code, I encountered an error related to the map() method. Despite its apparent simplicity, the issue persists. var div_usuarios = document.querySelector('#usuarios'); var usuarios = []; fetch('https://jsonplac ...

What is the method to extract a single user instead of a group of users?

I am attempting to transition from a list of users to displaying the profile of a single user on a separate page. My goal is to achieve this using routerLink and passing the specific user's id to the next page. Although the routing is functioning co ...

Executing JQuery asynchronous calls sequentially

Recently delving into the world of Jquery, I've encountered a coding challenge: my code loops through an array and retrieves HTML from an ajax request for each iteration. $.each(arr, function (data) { $.get('/Quote/LoadQuoteItemCost', { ...

Determining the specific page or method being called in a JSP page upon submission

There is a JSP page named X.JSP that contains radio buttons and a submit button. When the submit button is clicked on X.JSP, the next page Y.JSP is displayed with parameters xxxx=1111&yyyy=2222&zzzz=3333. Is there a way to determine the page, ser ...

Angular failing to append hash to ng-href in browsers that do not support it

When I attach an ng-href to a link like this: ng-href="{{post.btn.url}}" The resulting value is: ng-href="/news/some-post" In browsers that do not support html5 mode, these links do not work properly because they require a #. How can I handle this in I ...

Dealing with CSS Overflow Issues: Fixing the Scroll Bug

My current project involves creating a page with fixed links at the top and submit buttons at the bottom. The content in the middle is scrollable using overflow:auto. I've noticed that when I resize the browser window, the scrollbar slowly disappears ...

Dual columns filling the entire page within a container

Is there a way for me to pass the background images dynamically through inline styles? I can achieve this easily with pseudo elements, but I would like the content of the right and left columns to be enclosed in a container. You can view my proposed soluti ...

Converting HTML code into executable PHP code

I'm having trouble embedding PHP into an HTML file. I modified my .htaccess to recognize HTML files as PHP, but when I attempt to open the .html file in my browser, it gets downloaded instead of being processed and shown. UPDATE: Here is what's ...

Tips for making sure an image appears in the Reader Viewer

I have created a setup using HTML/CSS to showcase images of screenshots for my product: <p>Take a look at these screenshots:</p> <div> <a href="images/pic1.png" target="_blank" title="Screenshot 1"> <img border="0" src="images/p ...

Why isn't the HTML/CSS width and height adjusting?

<!DOCTYPE html> <html> <head> <title>Demonstration of HTML, CSS, and JavaScript</title> <link rel="stylesheet" href="profilepage.css"> </head> <body> <!-- Begin your code here --> <div ...

How can I protect a text or script file from being accessed or downloaded by entering its URL directly into the browser address bar?

While working on my JSP file, I have incorporated some Java-script code but to safeguard it from being visible to clients, I decided to store it in a separate codescript.js file and load it using ajax like so: $.ajax({ cache: true, dataType: "script ...

Ways to show a component based on a specific condition being met using react and javascript

On every page, the layout component is rendered. My goal is to achieve the following: on /items page *Display Layout component only if user is admin *Do not display Layout component if user is non-admin Below is my code snippet: function Main() { con ...

What is the functioning of property as a method?

One common practice is to use a method like $('div').show(); in jQuery. This show method will make the div visible when it is called. However, what about using $('div').length;? Although length is considered a property and not a method, ...