Web pages generate a different number of div blocks with the same id. Blocks

<div id="block"></div> 

pages can be from one to 5, but no more. To access each block you need to number them. For example:

HTML

  <div id="block_1"></div> <div id="block_2"></div> ... 

How to number id?

JavaScript does it. But, if the blocks are smaller than indicated, setAttribute is empty.

Cannot read property 'setAttribute' of null (...)

 for (var i = 1; i < 5; i++) { var el = document.getElementById('block'); el.setAttribute('id', el.getAttribute('id') + i ); } 
  • use the class - Stanislav Grot
  • and how then to refer to the numbered elements? - Grundy Nov.
  • if (el) { el.setAttribute(...); } else { break; } if (el) { el.setAttribute(...); } else { break; } - Igor
  • Grundy var el = document.getElementById('block_1'); - Viher
  • one
    @Viher you just do not know how to use it. - Igor

3 answers 3

To correct the current code, you can simply change the loop: you need to remain in the loop until getElementById stops finding the elements with the specified id

 for (var el = document.getElementById('block'), i = 1; el != null; el = document.getElementById('block'), i++) { el.setAttribute('id', el.getAttribute('id') + i); } 
 div { border: solid 5px; margin: 2px; } #block1 { border-color: red; } #block2 { border-color: green; } #block3 { border-color: blue; } #block4 { border-color: yellow; } 
 <div id="block"></div> <div id="block"></div> <div id="block"></div> <div id="block"></div> 

But it is better not to generate the same id, but to assign the class immediately.

  • Great! Thank you! You can also add + ('_list_') + i for beauty. - Viher
  • Almost like mine ... - Qwertiy ♦
  • @Qwertiy, aha :-) I only wrote the explanation longer, and didn’t write for short :) - Grundy
  • Although it is not clear why the attribute instead of the property. And I had to write a sample by id in two places. - Qwertiy ♦
  • "Abbreviated" - is it about anything at all? - Qwertiy ♦

 for (var i=1, b; b = document.getElementById('block') /* assignment */; ++i) { b.id += '-' + i; } 
 [id]:after { content: attr(id) } 
 <div id="block"></div> <div id="block"></div> <div id="block"></div> <div id="block"></div> <div id="block"></div> <div id="block"></div> <div id="block"></div> <div id="block"></div> <div id="block"></div> <div id="block"></div> 

    Give them all a general class, for example .block

    And also give everyone a class with a number

     <div class="block block-1"></div> <div class="block block-2"></div> <div class="block block-3"></div> 

    Thus, you can give general styles to all of them at once through the .block class, and also if you need a unique style for a particular block, give it and separately.

    Or did you want to dynamically give classes to blocks, through a script?