Reputation: 1031
please I have the following markup :
<div class="item"> 1 a </div>
<div class="item"> 2 b </div>
<div class="item"> 3 c </div>
After a click on a button, I want to increase using jQuery the value of the three elements by 2 and get :
<div class="item"> 3 a </div>
<div class="item"> 4 b </div>
<div class="item"> 5 c </div>
Please any help ?
Thanks a lot
Upvotes: 1
Views: 142
Reputation: 382334
You may do this in your button's event handler :
$('.item').each(function(){
$(this).html(
$(this).html().replace(/(\d+)/, function(v){return parseInt(v,10)+1})
);
});
This increments the first number in your items (if you want to increment any number, just change the regex to /(\d+)/g
).
Upvotes: 3
Reputation: 9
Look into the .appendTo class HERE
With .appendTo(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted into the target container.
Upvotes: 0
Reputation: 5336
You should modify your html like this:
<div class="item"> <span>1</span> product </div>
<div class="item"> <span>2</span> product </div>
And the your Javascript should be:
$('.yourbutton').click(function(){
$( '.item' ).each(function(){
var actual = parseInt( $(this).find( 'span' ).html() );
$(this).find( 'span' ).html( actual + 1 );
});
});
Upvotes: 1