1

I have a div like this:

<div id="masterDiv">
  <div id="childDiv" class="3" ></div>
  <div id="childDiv" class="5" ></div>
  <div id="childDiv" class="10" ></div>
</div>

How can I make value from attribute class become sequence number when clicked? Like this:

<div id="masterDiv">
  <div id="childDiv" class="1" ></div>
  <div id="childDiv" class="2" ></div>
  <div id="childDiv" class="3" ></div>
</div>
Karl Gjertsen
  • 4,690
  • 8
  • 41
  • 64
pajar
  • 43
  • 2
  • 7

4 Answers4

2
$(document).ready(function(){
    $("#masterDiv > div").each(function(i, item){
        $(this).attr("class", i + 1);      
    });            
});​
Teun Zengerink
  • 4,277
  • 5
  • 30
  • 32
1

Ideally id values should be unique. That is the whole purpose of using an id. In your case instead of id make use of multiple class names

<div id="masterDiv">
 <div class="childDiv 3" ></div>
 <div class="childDiv 5" ></div>
 <div class="childDiv 10" ></div>
</div>

then try this (I've slightly modified Rory's solution)

$(".childDiv").each(function(index) {
 $(this).removeClass().addClass(index + 1).addClass("childDiv");
});
Prashanth Thurairatnam
  • 4,353
  • 2
  • 14
  • 17
0

Try this:

$(".childDiv").each(function(index) {
    $(this).removeClass().addClass(index);
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • this code will remove the value of attr class. I have found the solve from Mytho. thanks for help. – pajar Apr 21 '12 at 10:25
0

Code sample:

$("#masterDiv > div").attr("class", function(arr) {return "classname"+arr;})
});
Karl Gjertsen
  • 4,690
  • 8
  • 41
  • 64