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

Troubleshooting Ajax Errors with MailChimp

Currently, I have been using a method by @skube to submit a Mailchimp form. It has been working successfully so far, but I would like to be able to display any error messages from Mailchimp on my website. For example, if someone is already subscribed, pro ...

Is there a way to modify or alter the layout specifically for mobile devices?

Currently, my desktop version displays the image first followed by content (h1, p, button), and then repeats in that order. However, I would like to restructure the HTML for the mobile version to make it more user-friendly. How can I achieve this without d ...

What is the best method for submitting an ajax form post when it is dynamically loaded within a bootstrap modal window?

Need some help with a Bootstrap modal form that is not submitting via AJAX as intended. When the form is submitted, the entire page reloads instead of having the data posted in the background. How can I fix this while keeping the page state? Below is the c ...

The Jssor bullet navigator is not visible on the webpage

Currently, I am working on implementing a full-width slider with arrow navigators, bullet navigators, and captions using the Jssor plugin. Rather than copying and pasting example code, I decided to tackle this project independently with just a little guida ...

Unlocking the JSON array of data in JavaScript: A step-by-step guide

Hey there, I need help extracting an array from a JSON data structure. Here's an example of my JSON object: { Data1 : { Data2 : "hello", Data3 : "hi" }, Data4 : { Data5 : "this is Karan", } } I'm looking ...

Why is it that every time I write this code, the localhost gets redirected and a message pops up saying

<?php include("connect.php"); if(isset($_POST['submit'])) { $qonax=@$_POST['qonax']; $subject=@$_POST['subject']; $insert="INSERT INTO subject(ID,Qonax,Subject)VALUES('','$qonax', ...

Off Canvas left navigation menu using Bootstrap

I am working on creating a responsive layout for a webpage using Bootstrap. On larger displays, such as desktop resolutions, I want the webpage to show the header and left navigation as normal. However, when the site is resized to that of tablets or mobile ...

Creating and sending HTML formatted emails using Django 1.7

The function send_mail() now accepts a new parameter - html_message. Check out the official documentation for more details. I have an email.html file and I need to send an html version of my message using Django 1.7. Can someone provide me with an example ...

What causes my CSS styles to vanish upon refreshing the page in Next.js?

After setting up a CSS folder within my app directory and importing the files into components for use, I noticed that the styles are applied initially. However, upon refreshing the page, they all disappear. I attempted to resolve this issue by going back ...

Color of Bootstrap tooltip arrow outline and fill

How can I customize the background color and border color of the tooltip arrow in Bootstrap 4? $(function() { $('[data-toggle="tooltip"]').tooltip() }) .tooltip-main { width: 15px; height: 15px; border-radius: 50%; font-weig ...

Issues with the alignment of columns using Bootstrap framework

I've created a design in Photoshop using the Bootstrap 12-column guide, but when I try to implement it using Bootstrap, the results are completely off. https://i.stack.imgur.com/vQwOt.png Here's my HTML code: <!DOCTYPE html> <html lan ...

Validation for HTML5 does not appear when inputmask is used for entering mobile numbers

One problem that I have encountered is when using the input type = "text" with required = "required" for a mobile number along with an input mask. In this scenario, if a user does not enter any value, the HTML5 validation message does not appear. Instead, ...

Why is the Django image URL redirecting to an HTML template instead of the media file?

I created a Django application with a template that includes an image. However, I encountered an issue where the server is attempting to display the image using the redirect link from the HTML template instead of retrieving it from the media file. For ins ...

Encountering issues with accessing image files located in the public folder of my Next.js project - Receiving a 404 Error message

I am currently facing an issue with my Next.js project where I am unable to use image files from the public folder. Despite checking that the file paths, names, and extensions are correct, as well as ensuring my configurations are accurate, I keep encounte ...

Applying a gradient overlay to an image using CSS

Feeling a bit frustrated with this issue. I'm working on my Joomla website utilizing Phoca Gallery, and the code it generates includes the following: <img class="pg-image" src="/images/phocagallery/other/thumbs/phoca_thumb_m_something.jpg" alt="So ...

The press of the Enter key does not trigger the button

I'm facing an issue with a form that has just one field for user input and a button that triggers some jQuery to hide the login form when clicked. However, pressing enter after entering text causes the page to refresh... I'm starting to think th ...

Tips on how to dynamically update information with Angular

Looking to dynamically update data when a user selects an option from a dropdown menu using the Angular framework This is what I currently have: <div> <button type="button"> {{tests[0].test}} </button> <ul c ...

What steps do I need to take in order to create a web-based file uploader that supports simultaneous uploads of multiple files

Is there a way to create the ability for users to upload multiple files at once on a Django/Python/jquery website, similar to the Gmail file selection feature? I am looking to allow users to select multiple files from their browser file selector and uplo ...

What is the best way to generate a JavaScript variable using information from SQLite?

I found the examples provided in the JavaScript edition of the Missing Manual series to be extremely helpful! OG.Q. I have explored various options but have not been able to find a solution to my problem yet. This is what I am trying to achieve: Save u ...

What is the best way to trigger a function following a user's selection from a form-control on a webpage?

I am looking for a way to automatically execute a function when a year is selected without needing a button. I am using HTML, JavaScript, and bootstrap 5. Any suggestions on how to achieve this? Thank you. function onSelect() { console.log('Hel ...