Ad

Change Date-attribute Value After Selecting Element With Equal Class

- 1 answer

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
Ad

Answer

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.

Ad
source: stackoverflow.com
Ad