Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically create divs with incremented id using jquery

I have a text I want to append multiple divs but the id should be changed dynamically. e.g:

<div id=first>text</div>
<div id=first0>text</div>
<div id=first1>text</div>
<div id=first2>text</div>
<div id=first3>text</div>
<div id=first4>text</div>
<div id=first5>text</div>

Any help? thanks..

like image 242
subho das Avatar asked Oct 28 '11 07:10

subho das


2 Answers

Your title and question content seem to disagree with each other. I am assuming you are wanting to create div's where each id sequentially increments each time one is created?

$(function(){
  var count = 0;
  $('#append').click(function(){
    $('#parent').append('<div id="first'+count+'">text</div>');
    count++;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="append">Add DIV</a>
<div id="parent"></div>
like image 191
Hailwood Avatar answered Nov 19 '22 13:11

Hailwood


You can change it with .attr():

$('#first').attr('id', 'first6')
like image 11
PiTheNumber Avatar answered Nov 19 '22 12:11

PiTheNumber