Tell me how to use jQuery to find all divs with a specific class and distribute non-duplicate id to them
3 answers
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> |
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
|