There are two blocks:

<div class="myclass">1</div> <div class="myclass">2</div> 

For block 1, I generated a number, suppose '111', and for block 2 - '222'. I would like to assign identifiers to these blocks based on the generated digits. But so that they do not appear on the page of the type: <div class="myclass" data-myid="111">1</div> .

I want to hide these identifiers in the DOM tree. And at a certain point, find, access them by the generated numbers '111' and '222' to transfer / clone / delete the corresponding block.

Tell me, please, how can this be done? It is desirable only to Javascript without jQuery.

  • What problem are you trying to solve by hiding identifiers in the DOM? XY problem - AK
  • one
    And what does it mean to generate a number? Is it a random number or not? Why does the moment of its generation play a role? And why it is impossible to generate data-myid at the right time for you and contact them? - Vadim Ovchinnikov
  • @VadimOvchinnikov, what is incomprehensible? It needs to assign a unique identifier to the block, which will not be visible in HTML, but it will be able to access the element using this identifier - Yuri
  • @Yuri I want to hear personally from the corresponding version. - Vadim Ovchinnikov
  • 2
    @Pavel just nobody understands why hide it? What is the meaning, the idea of ​​such behavior? - Alexey Shimansky

1 answer 1

 // Функция, генерирующая случайное число function getRandom(min, max) { return Math.random() * (max - min) + min; } // Здесь будем хранить ссылки на все найденные элементы var mapElements = {} // В вашем случае, получаем все элементы по имени класса: var elements = document.getElementsByClassName('myclass') // Перебираем все найденные элементы for (var i = 0, l = elements.length, i < l; i++) { var element = elements[i]; // добавляем поле dataMyId к каждому элементу и присваиваем ему случайный идентификатор // Это поле, естественно не отобразится в HTML element.dataMyId = getRandom(100, 900); mapElements[element.dataMyId] = element; } 

Then, in order to use the found elements we can get them by identifier from mapElements

  • how does this all hide ids in the DOM? - Alexey Shimansky
  • one
    @ Alexey Shimansky doesn’t hide it, it just doesn’t add. After all, the dataMyId element in the DOM does not fall. - br3t
  • It would be more correct to say that it has no display in HTML - Sublihim
  • only the generation is not quite correct .. the same number can be generated several times, despite the scatter ...... you need to check / or store the generated numbers, so that with the new generation if it works out - to regenerate - Alexey Shimansky
  • @ Alexey Shimansky I agree, but the question was not about the generation of numbers. - Sublihim