Mastering the Art of Utilizing jQuery CSS Selectors

Is it possible to apply a jQuery selector on dynamically created divs generated from a JavaScript loop?

The divs are being created using a for loop and each div is assigned a class.

minus = textbox1 - textbox2;

var count = 0;
var a;
for (x = textbox1; x >= minus; x--) {
    a = count++;
    $('body').append('<div class="drag' + a + '" >' + x + '</div>');
}

I am facing issues in adding css selectors to these dynamically created divs

var colors = ["#42ae18","#eabc00","#147cc4","#FF6EB4","#ed4329","#8d33aa","#00b971","#e9681b","#a2b3d4","#0b863c","#eabc00","#7027a5","#c83131","#00a1de","#0bc1b6","#FF6EB4","#10a0b6","#FF6EB4","#eedfd3","#362819","#FFD700"];
var i = 0;
$(".drag").each(function(){
    $(this).css("color",colors[i]);
    if(i == colors.length-1)
    {
        i = 0;
    }
    else
    {
        i++;    
    }
});

Here's the complete code snippet:

$("#submitBtn").click(function(){    
    var x;
    var minus;
    var textbox1= new Number($("#value1").val());
    var textbox2= new Number($("#value2").val());    

    var colors = ["#42ae18","#eabc00","#147cc4","#FF6EB4","#ed4329","#8d33aa","#00b971","#e9681b","#a2b3d4","#0b863c","#eabc00","#7027a5","#c83131","#00a1de","#0bc1b6","#FF6EB4","#10a0b6","#FF6EB4","#eedfd3","#362819","#FFD700"];
    var i = 0;
    $(".drag").each(function(){
        $(this).css("color",colors[i]);
        if(i == colors.length-1)
        {
            i = 0;
        }
        else
        {
            i++;    
        }
    });

    minus=textbox1-textbox2;

    var count=0;
    var a;
    for(x=textbox1;x>=minus;x--){
        a=count++;
        $('body').append('<div class="drag'+a+'" >' +x+ '</div>');
    }       
});

Answer №1

To apply the attribute starts with selector, you can use the code snippet below.

var colors = ["#42ae18", "#eabc00", "#147cc4", "#FF6EB4"," #ed4329", "#8d33aa", "#00b971", "#e9681b", "#a2b3d4", "#0b863c", "#eabc00", "#7027a5", "#c83131", "#00a1de", "#0bc1b6", "#FF6EB4", "#10a0b6", "#FF6EB4", "#eedfd3", "#362819", "#FFD700"];
var i = 0;
$("[class^=drag]").each(function () { //modify selector as needed
    $(this).css("color", colors[i]);
    if (i == colors.length - 1) {
        i = 0;
    }
    else {
        i++;
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="drag0">!!!!!</div>
<div class="drag1">!!!!!</div>
<div class="drag2">!!!!!</div>
<div class="drag3">!!!!!</div>
<div class="drag4">!!!!!</div>
<div class="drag5">!!!!!</div>
<div class="drag6">!!!!!</div>
<div class="drag7">!!!!!</div>
<div class="drag8">!!!!!</div>

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

Issue with Submit Button Functionality in Django Form Submission

I'm currently facing an issue with an HTML template I built using Bootstrap. My problem lies in the fact that I have a JavaScript function that dynamically adds rows to a Django form with specific fields whenever I need to. However, when I add a row, ...

Oops! It seems like there was an issue trying to access a property that doesn't exist (specifically, the

Encountering an error on the HomeScreen of my project I aim to manipulate the state of my HomeScreen Page using redux. The data is fetched from an API (an array of items) and then displayed on the screen. However, despite all these processes, an error me ...

Having Difficulties Initiating Click Actions on Save Buttons Located in Child Components

I'm facing a challenge with triggering click events on save buttons located in child components within my React app. Within my parent component called AddQuestionsPage, I have multiple instances of a child component named Question. Each Question comp ...

What is the best way to use two buttons to sort the table's column type?

I need to sort the type column. There will be two buttons, one to filter aquatic animals and the other to filter all animals except aquatic ones. <button type="button" onclick="Aquatic()">Aquatic</button> <button type="button" onclick ...

How to transfer data from local storage to PHP using Ajax

Is there a way to pass values from JavaScript to PHP that are stored in local storage? JavaScript let cartItems = localStorage.getItem("productsInCart"); var jsonString = JSON.stringify(cartItems); $.ajax({ url:"read.php", method: "post", da ...

The navigation bar I created using Bootstrap is functioning properly on desktop, but when viewed on mobile devices, it is causing the text in the body to overlap. Can

In the image provided, it is clear that the Navbar is overlapping with the text in the body. What steps can I take to correct this issue? You can see how it appears on desktop here. Below is the code for the Navbar: <nav class="navbar navbar-expan ...

What is the rationale behind Angular 2 and Angular 4's use of banana brackets? Is there a particular reason for this departure from AngularJS's pattern?

Although not directly related to coding, the syntax in AngularJS can still be followed: <input ng-model="hero.name" placeholder="name" type="text"> Here is an example of the syntax used in Angular 2 and its newer versio ...

AngularJS fails to trigger window scroll event

Although I have come across similar inquiries regarding this issue, none of the solutions have proven to be effective for me. Currently, I am working with AngularJS and I am attempting to detect the scroll event. Despite trying numerous variations to capt ...

"Troubleshooting: Unable to Display Success Message After jQuery Ajax Post

After setting up a simple $.ajax() post to delete a task, I'm encountering an issue where the success function is not firing. Despite successfully deleting the task, the alert within the success function is not displayed. Can anyone provide insight in ...

Using Node.js to retrieve table data from a URL

My journey with Node JS and express is just beginning as I dive into building a website that serves static files. Through my research, I discovered the potential of using NodeJS with Express for this purpose. While I have successfully served some static HT ...

Designing a personalized carousel component in Angular

Looking to replicate this design, any tips? I'm aiming for a carousel layout with developers listed in a project, where the center item is larger than the others. Any guidance on how to achieve this look? ...

From a single array to four separate arrays

I currently have an array structured as follows: [{ "coin": "AION", "profit": "3.10", "timestamp": "2021-01-26 00:48:01" }, { "coin": "BTC", "profit&quo ...

Converting a date from PHP to JavaScript

My PHP code generates the following date: <?php date_default_timezone_set('Europe/London'); echo date('D M d Y H:i:s O'); ?> Additionally, I have a JavaScript/jQuery script that displays this date on the website: setInterval( ...

What is causing my browser to retrieve JSON response from Express?

Scenario: I've designed a website that features a form with a POST action. The objective is for users to input their email addresses into the form. Once an email is submitted, a POST request is dispatched to the server. By utilizing Express and the M ...

Selected selector failing to function properly

I have been diving into the world of jQuery selectors and wanted to share a small example I created. The idea is to display what has been selected from a dropdown menu, but unfortunately, my example isn't functioning properly. I must be making a small ...

Bootstrap grid button with maximum flexibility

I am currently exploring the intricacies of the bootstrap grid system. My goal is to create a set of buttons that look like this: https://i.sstatic.net/V5meG.png Each button should expand to fill the width and height of its container. However, when a b ...

Transform the hue of symbols within D3-legend

I am attempting to modify the appearance of symbols in a legend. The variable below represents the available symbol types: var symbolTypes = { "triangleUp": d3.svg.symbol().type("triangle-up"), "circle": d3.svg.symbol().type("circle") }; I use this varia ...

What is the best way to handle and fix incorrect characters?

I have a JavaScript code snippet that is designed to check for invalid characters in a string. The only allowed characters are a-z, A-Z, 0-9, and -: var str = 'Some string!', invalid_characters = []; if (/^[a-zA-Z0-9-]*$/.test(str) == false ...

Eager loading BelongsToMany results in retrieving multiple objects for every association

Within my application, I have established two models: User and EconomicActivity. These models are linked together through a relationship called UserEconomicActivity, which uses a BelongsToMany association. In the User model, the association is defined as f ...

Using jQuery AJAX to make an HTTP POST request while also including a ValidateAntiForgeryToken for

I am currently working on implementing a jQuery Ajax request to the controller method in ASP.NET MVC Core. Here is the jQuery code snippet: var mydata = JSON.stringify({ "ID": $('#ID').val(), "text": $.trim($( ...