I need to change the value date of each element, but in the end of the loop all elements are given the same attribute = /
fiddle
var el = $(".div-parent").find(".div-children");
$(el).each(function( index ) {
el.attr('data-attr',parseInt(el.attr('data-attr'))+1);
});
$(el).each(function( index ) {
$(".div-parent").append('<br/>elemment '+el.attr('data-attr'));
});
output:
elemment 1
elemment 2
elemment 3
elemment 4
elemment 4
elemment 4
desired output:
elemment 1
elemment 2
elemment 3
elemment 2
elemment 3
elemment 4
Based on the jQuery in your fiddle, it sounds like you want:
Updated Example
$(".div-parent .div-children").each(function(index) {
$(this).attr('data-attr', parseInt($(this).attr('data-attr'), 10) + 1);
$(".div-parent").append('<br/>elemment ' + $(this).attr('data-attr'));
});
The problem was that you were getting the data-attr attribute of the first element in the jQuery object each time. In other words, 1 was being incremented 3 times (since you looped over the elements 3 times), resulting in 4. Access the attribute of the current element on each iteration by accessing this.
As a since note, you should probably specify a radix value in the parseInt function. In this case, 10.
Using clone(). I prefer this approach since using this gets you the entire object and then you can change its attribute as needed.
var el = $(".div-parent").find(".div-children");
$(".div-parent").append("<br/>");
$(el).each(function( index ) {
var el_new = $(this).clone();
el_new.attr('data-attr',parseInt($(this).attr('data-attr')) + 1);
el_new.text("elemment " + (parseInt($(this).attr('data-attr')) + 1));
$(".div-parent").append(el_new);
});
Example : https://jsfiddle.net/DinoMyte/koez1mt1/3/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With