By clicking, dynamically add unique classes along with incrementing numerical values

I have a span tag and a button tag

<span class="myspan">1</span>
<button id="add">Add +1</button>
var arr=["myspan1","myspan2","myspan3","myspan4"} 

In order to add more span tags with new classes from the array and increase the values by clicking the button, I aim for an output like this:

<span class="myspan1">1</span>
<span class="myspan2">2</span>
<span class="myspan3">3</span>
<span class="myspan4">4</span>

Although I've attempted to achieve this using ` this JsFiddle

, I have not been successful in adding class names to the new appended tags from the array.

For those struggling with similar challenges, here is another helpful link demonstrating how to append tags with new classes from an array: http://jsbin.com/nojipowo/2/edit?html,css,js,output ... Despite various attempts, I am yet to achieve my desired output...enter code here

The following snippet showcases how the value increases upon each click:

<script>    var i = 0;    function buttonClick()    {i++;     document.getElementById('inc').value = i;    }    </script>    <button onclick="buttonClick();">Click Me</button>    <input type="text" id="inc" value="0"></input>

Seeking assistance for another attempt to achieve my desired output...

var i=6;
var backgrounds = ["myspan1", "myspan2", "myspan4"];
var elements = document.getElementsByClassName("myspan");var len = backgrounds.length;

$("#add").click( function() {
(i < elements.length){


  $(".new-field").append('<span class="myspan">1</span><script');
    var value = parseInt($(".myspan").text(), 10) + 1;
    elements[i].className += ' ' + backgrounds[i%len];
    i++;
    $(".background").text(i);    
    }
});
*/
<span class="myspan">1</span>

<button id="add">Add +1</button>
<div class="new-field">
  
</div>

Answer №1

<script>    let count = 0;    function increaseCount()    {count++;     document.getElementById('display').value = count;    }    </script>    <button onclick="increaseCount();">Increase Count</button>    <input type="text" id="display" value="0"></input>

Answer №2

Check the span length using parseInt($(".myspan").length). Utilize Array#forEach to iterate over the array instead of incrementing i. The function parseInt is used to convert the string to a number.

var i=6;
var backgrounds = ["myspan1", "myspan2", "myspan4"];

var len = backgrounds.length;

$("#add").click( function() {
var len = parseInt($(".myspan").length)
backgrounds.forEach(function(a){
  $(".new-field").append('<span class="'+a+'">'+(len++)+'</span>');
    })
    console.log($(".new-field").html())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="myspan">1</span>

<button id="add">Add +1</button>
<div class="new-field">
  
</div>

Answer №3

Feel free to check out the JSFiddle example. I hope this provides some assistance!

HTML :

<div id="mainContainer"> 
<span class="myspan">1</span>
</div>
<button id="add">Add +1</button>

JS :

var arr = ["myspan1", "myspan2", "myspan3", "myspan4"];

$("#add").on("click", function() {
var spans = $("span");
var classList = [];
$.each(spans, function() {
    var elemCls = $(this).attr('class').length > 1 ? $(this).attr('class').split(' ') : $(this).attr('class');
    if (elemCls) {

        $.each(elemCls, function() {

            classList.push(this.toString());
        });
    }
}); 
$.each(arr, function(i, e) {

    if ($.inArray(e, classList) == -1) {

        $("#mainContainer").append("<span class='" + e + "'>" + parseInt(spans.length + 1) + "</span>");
        return false;
    }
});
});

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

The <hr> element creating a line beneath a connected div

Currently, I am in the process of designing a website with three main divs all on one page. To visually separate these divs, I have included a subtle horizontal line. The horizontal line between the first and second div looks correct as intended. However ...

Implementing various onclick button interactions using Vanilla Javascript

I'm looking to update the value of an input when a user clicks on one of my "li" tags, but I want to do it without relying on jQuery. The HTML below shows two sample list tags and I need help with determining how to differentiate between them in the i ...

Is it more beneficial to categorize REST-based modules/controllers by resource or by specific action/feature?

I'm facing a scenario that goes like this: Endpoint 1: Retrieve all books in the United States owned by John with a GET Request to /country/us/person/john/books Endpoint 2: Get all books owned by John in every country with a GET Request to /person/j ...

Are Global variables supported in the EXT JS framework?

When working with Java and C++, it is common practice to store a variable globally so that its value can be accessed from anywhere within the project. For example, if I am working inside a class named Residence and saving an INT as the residenceNumber to a ...

Strategies for unbinding jQuery events that have been added following an ajax request

Is there a way to clear the dynamically registered events after an Ajax load? In my web application, when a user clicks a button, a pop-up form is launched using FancyBox: $('.launchPopUp').click(function(){ var url = 'something'; ...

Does the webpack style loader load only application-specific CSS, or is it designed to handle all CSS files?

I am in the process of improving the modularity of my front-end design by delving into webpack. This tool provides a style loader, which enables you to import a css file and inject it into the document like this: require("style/url!file!./file.css"); // = ...

Tips for adjusting the position of an object when resizing the window

The problem at hand is as follows: Upon refreshing the page, my object is initially positioned correctly. However, resizing the window causes the object to resize and reposition correctly. But, if I refresh the page after resizing the window, the object i ...

Using an HTML file as the source for an image in the <img src=""> tag is a simple process that can greatly enhance the visual appeal of your webpage

My goal is to utilize an html file as the source for an image file within the <img src=""> tag in order to prevent mixed-content warnings when using an http image over https. For instance: index.html: <img src="./image.html" > image.htm ...

The jQuery Ajax call is hitting the error callback even though the response shows a readyStatus of 4 and a status of 200

I am encountering an issue with my application that uses jQuery Ajax call. It works perfectly fine in IE9, Firefox, and Chrome. However, in IE 8, it triggers the error callback even when the response has a readyStatus of 4 and status of 200. Here is the r ...

Struggling to adjust the timeout to exceed 60 seconds

I have been attempting to set a timeout for 120 seconds or more, but no matter what I try, the requests are timing out after only 60 seconds. Things I have tried include: $.ajax({ url: URL, timeout: 120000, success: function(html){ co ...

Is there a way to set columns as initially hidden in MaterialTable?

I have a MaterialTable with many columns, and some of them are not always necessary to display. I am looking for a way to hide these columns unless the user specifically selects them. I attempted to use the hidden: true property in the column configuratio ...

Combining Ionic 3 with epubJS

Greetings. I've been attempting to access ePub files in my Ionic 3 test app without success. epubjs has been installed via npm. Here is the package.json contents: { "name": "app_name", "author": "Author", "homepage": "http://example.com/", ...

How to position two Bootstrap 4 Navbars side by side

I'm currently experiencing an alignment issue with two stacked navbars in my code. I want to align the upper navbar with the lower one, but I've tried various approaches without much success. Is there a problem with the buttons or something else ...

The complexity surrounding various versions of jQuery, the .noConflict method, and the jQuery migrate feature

I was tasked with making a large-scale website responsive, and decided to utilize Bootstrap as the framework. However, I encountered issues due to the jQuery version (v1.8.2) being used. In my development environment, I resolved this by including the follo ...

implement adding a division element to the DOM using the append

I am facing an issue with this particular code. The intended functionality is to create multiple divs in a loop, but it seems to be dysfunctional at the moment. Upon clicking, only one div appears and subsequent clicks don't trigger any response. < ...

"Prop serves as a blank slate within the child component of a React application

My current challenge involves integrating a search bar into a parent component. Despite successful logic in the console, I am experiencing a reduction in search results with each character entered into the search field. The issue arises when attempting to ...

Connecting a Date object by using :value and @input within a VueJS component

Successfully linking a date form input with a date object using :value and @input instead of v-model as outlined in this method has been a great ongoing experience. It allows for displaying and modifying the date in the form input, as well as saving the up ...

Is there a way to initiate animations seamlessly?

Instead of relying on a plugin, I decided to create a simple marquee from scratch. It was a fairly easy process and it works well overall. However, there is one thing that bothers me - the animation starts off slow and then speeds up. Is there a way to mai ...

Request Timeout: The server took too long to respond and the request timed out. Please try again later

I'm encountering an issue when attempting to send a dictionary as a JSON to the express API. The error message I keep receiving is: Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={_NSURLErrorFailingURLSessionTaskErrorKe ...

Image optimization using media queries

In the scenario where the maximum width is 1220px, I want to change the main display to column. This is what I have implemented: @media (max-width: 1220px) { .main { flex-direction: column; } However, when the width reaches 1220px, the image disap ...