Tell me how to use jQuery to find all divs with a specific class and distribute non-duplicate id to them

    3 answers 3

    js:

    $("div.example").each(function() { $(this).removeAttr("class").attr("id", "div" + Math.random()); }); 

    html:

     <div class="example"> Π”ΠΈΠ²1 </div> <div class="example"> Π”ΠΈΠ²2 </div> 

    The result will be something like:

     <div id="div0.37647746794184855"> Π”ΠΈΠ²1 </div> <div id="div0.6064644234577623"> Π”ΠΈΠ²2 </div> 

    jsfiddle

      The attr function can take a second parameter to a function that returns an attribute value.

       $('.block').attr('id', function(index) { return 'number' + (index + 1); }) 
       #number1 { background: red; } #number2 { background: green; } #number3 { background: blue; } #number4 { background: yellow; } #number5 { background: cyan; } 
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> <div class="block">1</div> <div class="block">2</div> <div class="block">3</div> <div class="block">4</div> <div class="block">5</div> 

        If you use a sequence number for each subsequent block, then like this:

         $(document).ready(function(){ var i = 1; // Π²Π²ΠΎΠ΄ΠΈΠΌ порядковый Π½ΠΎΠΌΠ΅Ρ€ Π² ΠΏΠ΅Ρ€Π΅ΠΌΠ΅Π½Π½ΡƒΡŽ $('.block').each(function(){ // ΠΏΠ΅Ρ€Π΅Π±ΠΈΡ€Π°Π΅ΠΌ всС Π±Π»ΠΎΠΊΠΈ ΠΏΠΎ классу $(this).attr('id','number'+i); // присваиваСм Π°Ρ‚Ρ€ΠΈΠ±ΡƒΡ‚ id i++; // ΡƒΠ²Π΅Π»ΠΈΡ‡ΠΈΠ²Π°Π΅ΠΌ порядковый Π½ΠΎΠΌΠ΅Ρ€ Π² ΠΏΠ΅Ρ€Π΅ΠΌΠ΅Π½Π½ΠΎΠΉ Π½Π° Π΅Π΄ΠΈΠ½ΠΈΡ†Ρƒ }) }) 
         #number1 {background: red;} #number2 {background: green;} #number3 {background: blue;} #number4 {background: yellow;} #number5 {background: cyan;} 
         <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> <div class="block">1</div> <div class="block">2</div> <div class="block">3</div> <div class="block">4</div> <div class="block">5</div> 

        • Then it's easier to take an index from argumegts of functions .each (function (i) {}) - Jean-Claude
        • Yes, but I did, taking into account that the actual version of the id in the question is not specified, and, most likely, it is not the serial number of the block that is needed. And in this case, my answer is clearer, and the numbers for id are easier to manipulate. - lexxl