Ways to dynamically assign a class to a div

I am facing an issue with dynamically adding a class to my code. I have been using the addClass method, but it is not meeting my requirements as expected. Below is the snippet of my code:

 <div id="form-copy">
   <div class="abc">
       Here resides some important code....
   <div>
 <div>

This is what I have tried so far:

  var p = 0;
  for(var i =0; i<n;i++){
    $(".abc:first").clone(true).appendTo("#form-copy")
    $(".abc").addClass( "dynamicClass"+ ++p);
  }

The current output looks like this:
 If n=3
     <div class="abc dynamicClass1 dynamicClass2 dynamicClass3">...</div>
     <div class="abc dynamicClass1 dynamicClass2 dynamicClass3">...</div>
     <div class="abc dynamicClass1 dynamicClass2 dynamicClass3">...</div>

However, I am aiming for the following desired output:
  If n=3
     <div class="abc dynamicClass1">...</div>
     <div class="abc dynamicClass2">...</div>
     <div class="abc dynamicClass3">...</div>

Please assist me in achieving the desired output. Thank you.

Answer №1

for(let count = 0; count < num; count++){
    $(".first-element:first").clone().appendTo("#copy-form").addClass("newClass" + (count + 1));
  }

Answer №2

UPDATE: Check out this revised code snippet:

<div id="form-copy">
  <div class="abc" id="abc">
    Insert valid code here....
 </div>
</div>

var counter = 0;
for( var index = 0; index < totalItems; index++ ){
    $(".abc:first").clone(true).appendTo("#form-copy")
    $("#abc").removeClass().addClass( "abc dynamicClass"+ ++counter);
}

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

Identify all the CHECKBOX elements that are visible and not concealed

On my page, I have various checkboxes - some with hidden=true and others with hidden=false attributes. Despite trying to use a selector or jQuery to locate checkboxes with the hidden property, I am still facing some challenges. My goal is to differentiate ...

The getimagesize() function encountered an error: "unable to access stream - file or directory does not exist"

I'm encountering a problem and I'm not sure how to solve it? Below is the script I'm using: <?php include('../include/cfg.php'); if($approval_system == 1) { $ap = 1; } else { $ap = 0; } $path = "../uploads/"; function resi ...

Smoothly scroll down to the bottom of the page with a jQuery button using the anchor

Recently, I've been working on setting up a navbar with buttons that smoothly scroll down to specific sections when clicked. However, as a beginner in jquery, I'm having some trouble figuring out how to make it work seamlessly. Can anyone guide ...

Set up a JavaScript function that triggers an alert if two numbers are determined to be equal

I created a code snippet that should display an alert message when a button is clicked, indicating whether two random numbers generated are equal or not. The random numbers must be integers between 1 and 6. I implemented this functionality in JavaScript bu ...

Is it possible to combine margin auto with a transform on the left simultaneously?

While examining a webpage, I noticed a positioning issue and decided to remove some CSS code to determine the root of the problem. It appears that the navbar has a 1px gap on the left side from the edge of the screen. After removing the last two lines of c ...

The Form Element's FormData() form is consistently void of any content

My attempts to upload a File with Ajax have been unsuccessful as the FormData is always empty. Below is the code I am using: <html> <head> <link rel="stylesheet" href="../website/css/bootstrap.min.css"> </head> <body> &l ...

Guide on integrating an HTML and CSS register form in Django

I have successfully created a responsive register and login using HTML and CSS. Instead of utilizing the standard register form and login provided by Django upon configuration, I want to apply my own custom template. To summarize, while I am familiar with ...

Python Selenium encountering issue with selecting search bar

I have been attempting to use Selenium to search for courses on and scrape the results. However, all the selectors I have tried so far have failed, resulting in empty arrays when printed. I am confused as to why these selectors are failing and what is the ...

The header and footer are not extending across the entire width of the page

While testing on a responsive screen, I noticed that the header and footer both decrease in width instead of maintaining 100% width as intended. The issue only occurs when I reduce the width of the screen. body{ margin: 0; padding: 0; box-si ...

Achieving Full Height and Width of Tab Panel with Bootstrap 4.3

I recently upgraded to bootstrap 4.3 and discovered the handy sizing classes m-* and w-* for setting element height and width. After successfully achieving 100% height and width for the container, I'm now looking to apply these dimensions to the tab-p ...

Retrieving the identifiers of intersecting divs within a stationary container during scroll movements

As I have a fixed div in my layout, when I scroll some other divs tend to overlap the fixed div. My question is, how can I retrieve the id of the overlapping div using jQuery? I'm relatively inexperienced with jQuery, so any help would be appreciated. ...

Generating CoffeeScript script that calls a class

It seems like I'm facing some difficulties here and not making much progress. I wrote a class using Coffeescript: # CoffeeScript App= Title:"" TopMenu:[] AddTopMenu:(title,count,icon)-> Record= ...

How to utilize $(this) with different selectors in JQuery?

Similar Query: Jquery multiple selectors with this Can $(this) be used with multiple selectors? I attempted: $('#helper').click(function() { $(this + " #divname").html()); }); Unfortunately, it never seems to work. My goal is to ensure tha ...

Method for ensuring events in jQuery are fired in sequence

Currently, I am in the process of making multiple ajax calls from the browser to a service. However, I want to ensure that I am considerate to the server by not overwhelming it with all the requests at once. Is there a common method or practice for seque ...

Can I make this SCSS code functional within CSS styling?

I stumbled upon this interesting +/- toggle button design on a codepen here The only problem is that the CSS processor used in the codepen is SCSS, and when I try to convert it to CSS, it stops functioning. My website project is using CSS, and when I try ...

The object you are attempting to use does not have the capability to support the property or method called 'after'

When attempting to add a div tag dynamically using javaScript, I encountered an issue with the .after function not working in IE9+. The error message "SCRIPT438:Object doesn't support property or method 'after'" appeared in the console. If a ...

The CSS 'top' attribute is without impact

As I begin my journey with CSS, I am eager to grasp some of its behaviors. In the CSS file, the following code is defined: #spa { position : absolute; top : 8px; left : 8px; bottom : 8px; right : 8px; min-height : 500px; min-width : 500px ...

Upon successful completion of the Ajax call, refresh the page without causing any blinking

Hey there, I'm facing an issue with my website, I've implemented ajax to fetch data from my API, and upon successful retrieval, I need to reload the page to display the information, However, sometimes the page blinks before reloading, while oth ...

Accessing a jstl variable within javascript script

I need to access a JSTL variable within a JavaScript function. The JavaScript code submits a form. $("#userSubmit").on('submit', function () { document.getElementById("userForm").submit(); }); In the server-side code - request.setAttribu ...

IE is giving an "Access is denied" message when making an Ajax request

I have implemented an AJAX request to check the response of websites like this: $.ajax ({ url: 'https://www.example.com', cache: false, success : function() { alert(new Date() - start) }, }) This code fun ...