Tips on assigning class names to list items

I have a series of HTML li elements. In this scenario, if the 3rd li element is marked as active, then I would like to set the 1st and 2nd li elements as complete. To achieve this, I will first remove any existing classes from the 1st and 2nd li elements, and then add the complete class. Additionally, when the 3rd li element has the active class, I want the 4th li element to be half-complete. Lastly, the last li element should not have any class associated with it.

<ul>
  <li class="complete">Coffee</li>
  <li class="complete">Tea</li>
  <li class="active">Milk</li>
  <li class="half-complete">Milk</li>
  <li>Milk</li>

</ul> 

Answer №1

Check out this handy jQuery solution:

$('ul li').on('click', function() {
  $('ul li').removeClass('active complete half-complete');
  
  $(this).prevAll('ul li').addClass('complete');
  $(this).addClass('active').next('ul li').removeClass('complete').addClass('half-complete');
  
  console.log($('ul').html());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li class="complete">Coffee</li>
  <li class="complete">Tea</li>
  <li class="active">Milk</li>
  <li class="half-complete">Milk</li>
  <li>Milk</li>
</ul>

Answer №2

<ul>
    <li class="item1">Coffee</li>
    <li class="item2">Tea</li>
    <li class="item">Milk</li>
    <li class="item3">Milk</li>
    <li class="delivered-item">Milk</li>
</ul>


  let deliveredParent = document.querySelector(".delivered-item").parentElement;
  let children = [...deliveredParent.children];
  for(let i = 0; i < children.length; i++){
    let child = children[i];
    if(child.classList.contains("delivered-item")) break;
    child.className = "complete-item";
  }

Note: "half-completed" is now excluded.

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

Can JavaScript be used to dynamically update drop down lists in a gridview?

My gridview has multiple fields including PreviousPoints, GainedPoints, and TotalPoints. In edit mode, PreviousPoints is not editable, GainedPoints is a dropdown list, and TotalPoints is also a dropdown list. Whenever the selected value in GainedPoints ch ...

Version 1 of Vue.js is not compatible with Ajax-loaded HTML files

Currently, I am encountering a minor issue with loading content through ajax requests. I am in the process of developing a web application where everything is located on one page without any reloading. To achieve this, I have split the content into separa ...

Checking the validity of user input statements

When 2 conditions are met, both error links and messages will display on top of each other. If an input is 0, the validation statement for empty inputs will also trigger. Additionally, if one input is not numeric but the other is, PHP will calculate the va ...

What is the best way to add elements to an array that has not been globally initialized as an empty array?

Let's say I have a variable called, let Info and an array like this one, let arr1 = [4,5,6] I need to add the elements from arr1 into Info as an array, Here is what I attempted, for(let i =0;i<arr1.length;i++){ Info = [] Info = Info.push ...

Retrieve information and display it in a text field using ajax

Hi there, I'm having some trouble with my current code and would appreciate any help you can offer. My goal is to filter data in a search box and display the corresponding results in text boxes. I've been searching online for hours trying to find ...

Enhancing functionality through the press of a button

I wrote a script that, upon button click, finds the closest location to your current position by searching through an array. It then locates the corresponding entry in another array and adds a number to that entry. However, I encountered a problem with app ...

Populating lists using AJAX technology

There are four select lists on my page. The first list's content loads upon page load, while the contents of the other lists depend on the selected item in the previous list. I have a function that fetches data from a URL address for each list. This ...

Sorting a list with anchor tags alphabetically using Javascript/JQuery

Here is a list of services: <ul id="demoOne" class="demo"> <li><a href='http://site/Service.aspx?shId=1154'>Copy service for files from folder 12</a></li> <li><a href='http://site/Service.aspx? ...

Troubleshooting: CSS Selectors Hover Functionality Not Functioning as

I am having an issue where the styling does not change the display to block when hovering. Any insights or feedback would be greatly appreciated. <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="t ...

Changing Pages in MVC Using JavaScript Language

Whenever I select a city on the map displayed on my homepage, a pop-up window opens up with relevant information. The issue arises when I try to navigate to the detail page of the project by clicking on the body of this pop-up window. Unfortunately, I have ...

Unable to execute internal functional tests due to this error: [POST http://localhost:4444/wd/hub/session] unable to connect - ECONNREFUSED

Currently working with node 0.12 and intern 3 in order to execute functional tests, but encountering the following error: SUITE ERROR Error: [POST http://localhost:4444/wd/hub/session] connect ECONNREFUSED at Server.createSession <node_m ...

Ensuring that my divs remain stationary despite changes in the size of the browser window

Hey there! I'm new to web design/development and I've been working on a simple website to get the hang of things. I managed to make my webpage look good at full screen, but as soon as I resize the window, everything starts shifting around and it ...

Ways to create a horizontal navigation menu using jQuery UI

Hey there, I'm really enjoying all the jQuery UI features! I have a question about the navigation menu - for some reason, I can't seem to get it to display horizontally. I've been playing around with the CSS but I must be missing something ...

The navigation bar components created with Bootstrap are experiencing issues with their active state functionality

I created a Navbar using Bootstrap code but I am facing an issue where the 'active' state is not being applied to the Navbar elements on my webpage. I have been attempting to add and remove the active class on the Navbar elements, but I have bee ...

You won't find the "Go to Definition" feature for CSS classes in Visual Studio 2013

In my research on VS2012 documentation, I came across information stating that I should be able to right click a class name in my code and navigate to its definition. This feature is supposed to open the corresponding CSS file and take me directly to where ...

What could be causing the issue of angular data-binding not functioning properly in conjunction with jquery

Currently, I am working on the angular tutorial project known as angular-phonecat, and I have reached step 5. Out of sheer curiosity, I decided to replace the original angular ajax method with a jquery ajax method while keeping everything else unchanged. ...

What is the method for displaying a message in an invalid feedback?

I'm having trouble with displaying an error message in the invalid feedback section (confirm password) when the password does not match the confirm password using jQuery. However, even after deleting a single character from the password, the error mes ...

Content is missing from the response of the AngularJS $http request

Attempting to retrieve content from a website using Angular's $http service. The request seems to be successful as console.log(response.data) displays most of the content but is missing some parts. Check out my code below: $http = angular.element(doc ...

Avoid closing the login modal/popup form if there is a validation error

Is there a way to prevent the popup login form from closing after submitting it if there is a validation error? I am working with node.js and ejs as my view engine. Login html form: <div class="modal"> <div class="modal__box" ...

A collection of functions embedded within a JSON data structure

I am working with a website that provides data in a JSON-like format similar to the following: { "name":"tom jones", "no": 123, "storedproc": function(){ callbuyer(0123); } } Currently, I am using $. ...