What is the best way to assign a single class from an array to every list item in a particular sequence?

html

<ul class="logoUl">
    <li class="orange"></li>
    <li class="blue"></li>
    <li class="green"></li>
    <li class="pink"></li>
</ul>

SCRIPT

if (selectedCategory == 'currentAll') {

    var strString = "orange,blue,green,pink";
    var strArray = strString.split(',');

    $.each(strArray, function (index, value) {
        $("ul.logoUl > li").addClass(value)
    });
}

Within the ul element with the class logoUL, there are four list items representing an image. Occasionally, these list items may receive background colors which override their original color scheme.

Unfortunately, my current code fails to revert these colors back to their initial state if they have been altered.

Question:

Is there a way to loop through each list item individually and add one class at a time in order to restore the original color scheme of the image?

Answer №1

let colors = "orange,blue,green,pink",
    colorArray = colors.split(',');

$("<ul.logoUl > li>").each(function (index, value) {
    $(this).addClass(colorArray[index]);
});

See Demo

Without using a loop:

let colors = "orange,blue,green,pink",
    colorArray = colors.split(',');

$("<ul.logoUl > li").addClass(function (index) {
    return colorArray[index];
});

See Demo

Note:

If you want to revert back to the original color scheme of each li element after changing their classes, first remove the current class and then re-assign the original one like so:

let colors = "orange,blue,green,pink",
    colorArray = colors.split(',');

$("ul.logoUl > li")
    .removeClass() // Remove previous class
    .addClass(function (index) { // Add new class
        return colorArray[index];
    });

See Demo

Answer №2

To implement this functionality, simply

if (selectedCategory == 'currentAll') {

    var strColors = "orange,blue,green,pink";
    var colorsArray = strColors.split(',');

    $.each(colorsArray, function (key, color) {
        $("ul.logoUl > li").eq(key).addClass(color);
    });
}

Check out the live demo here: http://jsfiddle.net/joycse06/j4qqS/

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

Toggle the visibility of an element with a single button click

Below is a snippet of my sample code: SAMPLE HTML CODE: <ul> <li class="item"> item 1 </li> <li class="item"> item 1 </li> <li class="item"> item 1 </li> <li class="item"> item 1 </li> <l ...

Using jQuery to save PHP form output into an Excel spreadsheet

I have a PHP-enabled form on my website for collecting Address details. Currently, the output is sent to my email inbox. However, I would like the output data to be saved in an external Excel file named "address.xls" using jQuery/JSON. The input fields of ...

Can you explain the significance of the "row" class in Bootstrap, how it differs from containers, and how it interacts with col-***-*?

I've been browsing through the guide found at http://getbootstrap.com/css/ and I'm having trouble grasping the purpose of the "row" class. I experimented with some examples provided in the guide like: <div class="row"> <div class="c ...

Requesting a download of a file via an Ajax call from a RESTful service

I'm still getting the hang of AJAX. I've set up a request to send to the server using AJAX, and the service returns a text file. However, when the data is returned, no download box pops up. Here's the REST service that sends back the file: ...

How to position a static element using CSS

I'm trying to align an image in the center of the screen, but I've run into some trouble. Typically, this is easy by setting the width of a div and using margin: auto;. However, I also need the div to have the position: fixed; property, which see ...

Deactivate a form on the page while another form is being used

My issue involves having two forms on the same web page with identical IDs, and I'm unable to easily change them. Both forms are necessary on the page. When I submit one form, it also submits the other form as blank, resulting in duplicate submission ...

Eliminating an element from an array based on a single criterion

Here's a question that might seem simple to some: Let's say I have an array like this... var array = [ {id: 1, item: "something", description: "something something"}, {id: 2, item: "something else", description: "something different" ...

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 ...

A guide on utilizing setTimeout for repeatedly executing a function

I am facing an issue with my slideshow containing 4 pictures and pagination. I want the pictures to be displayed one by one in a loop, so I tried using the following code: function displayPictures(intervalTime) { setTimeout('$("#picgallery_pagging li ...

Javascript behavior during execution can vary from what is observed during debugging

I'm currently facing an issue while trying to debug a script. Everything seems to work fine in debug mode, but not during runtime. Here's the JavaScript function causing trouble: function Add() { ... $('#Value').val($('#V ...

Styling group headers within an unordered list using pure CSS - possible?

Hey there, I'm looking to spruce up my UL by adding group headers. Here's a sneak peek at the structure I have in mind (keep in mind this is generated dynamically from a database): <ul> <li class='group group-1'> < ...

What is the best method in ASP.NET Boilerplate for retrieving JSON data?

I have been facing an issue while working on this code, constantly running into the error message: Unexpected token o in JSON at position 1 https://i.stack.imgur.com/43Ewu.png I am struggling to troubleshoot and was hoping for some advice or tips on r ...

Click here to see the image

I'm looking to enhance an image with a hyperlink. This is the code I have so far. How can I make the image clickable? success: function(data, textStatus, jqXHR){ $.each( data, function( idx, obj ) { // $( "<img>" ).attr( "src", '/ima ...

Locate the present position of the slider element

I am currently in the process of creating a website that features pages displayed in a slider format. Each page has its own unique ID, but all share a common class called 'section'. However, I am encountering difficulty in identifying the ID of t ...

Using React Native's stylesheet to apply multiple values in a CSS statement

Here's a scenario to help clarify my question: Imagine I want to add margin to an element in the following way: const myView = () => <View style={styles.viewStyle}></View> const styles = StyleSheet.create({ viewStyle: { margin: ...

The .play() method is not functioning as expected on the Safari browser when using an audio

I'm currently in the process of constructing a website at . Everything is functioning well, including playing audio files on click using jquery. However, I am encountering an error specifically on Safari browser for iPad. The error message reads: "Ty ...

Inadequate speed and efficiency in Javascript and JQuery operations

I'm facing severe lag problems in my JavaScript code, particularly with the parallax effects being very slow. I suspect this is due to multiple executions of functions. Below is the code snippet: function tada() { $(".arrow").addClass("tada"); s ...

How come the link function of my directive isn't being triggered?

I'm encountering a strange issue with this directive: hpDsat.directive('ngElementReady', [function() { return { restrict: "A", link: function($scope, $element, $attributes) { // put watche ...

Check to see if there is a value present in a JavaScript array

I am trying to validate the content of the data array in the code below. My goal is to ensure that when a user enters a packageid (a variable in the code), and if that packageid does not exist, the "else" statement in the conditional should be triggered. ...

What is preventing me from passing a JSON array as data in a GET request using jQuery Ajax?

When sending a get request like the one below: $.ajax({ url: 'http://localhost:8000/api/points/', contentType:"application/json", dataType: "json", data: JSON.stringify({"content_type":content_type,"object_id":object_id}), t ...