MiltonMethod
MiltonMethod

Reputation: 1

Add sequential numbers within a div container with jquery

I want to add sequential IDs to all divs within a parent container so it looks like this.

<div id="parent">
  <div id="id1">content</div>
  <div id="id2">content</div>
  <div id="id3">content</div>
</div>
<div id="parent">
  <div id="id1">content</div>
  <div id="id2">content</div>
  <div id="id3">content</div>
</div>

Currently it is looking like this:

<div id="parent">
  <div id="id1">content</div>
  <div id="id2">content</div>
  <div id="id3">content</div>
</div>
<div id="parent">
  <div id="id4">content</div>
  <div id="id5">content</div>
  <div id="id6">content</div>
</div>

This is my code:

 $("#parent").children().each(function(i){
        $(this).attr("id","id" + (i+1));
    })

Upvotes: 0

Views: 284

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337626

Firstly, note that your initial HTML is invalid as you cannot have multiple elements with the same #parent id.

Assuming that's just a typo in the question, then you can do what you require by looping through the .parent divs separately, then using find() within that to iterate through the child div. Note that you can use an implicit loop over the children by providing a function to prop() which accepts the current index as an argument.

$('.parent').each((_, el) => $(el).find('div').prop('id', i => `id${i + 1}`));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">
  <div>content</div>
  <div>content</div>
  <div>content</div>
</div>
<div class="parent">
  <div>content</div>
  <div>content</div>
  <div>content</div>
</div>

Upvotes: 2

Related Questions