I have a function that it creates a span with id, however I need this id to be generated dynamically.
$("#lista").append("<span id='span'><br> " + label + " - R$" + valor + "</span>" );
I have a function that it creates a span with id, however I need this id to be generated dynamically.
$("#lista").append("<span id='span'><br> " + label + " - R$" + valor + "</span>" );
Count how many span
s containing id
that starts with "span" and adds with +1
. This will create a new id
sequential:
var label = "label";
var valor = "10,00";
function addSpan(){
var span_id = $("#lista span[id^='span']").length+1; // novo id
$("#lista").append("<span id='span" + span_id + "'><br> " + label + " - R$" + valor + " - id: span"+ span_id +"</span>" );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="lista"></div>
<button onclick="addSpan()">Adicionar span</button>