How to move elements with the same classes?

  • 0
    <div class="a1">1</div>
    <div class="a1">2</div>
    <div class="a1">3</div>
    <div class="z36">4</div>

    For example, we have 4 blocks and 3 of them have the same classes, one has a different class (for variety), the essence is that when clamping on some of the "a1" elements, it moves behind the cursor and when released, it remains where it was released (usual dragging and dropping, I think its essence is clear).

    I did it with the ID elements, but with the classes I don't, it is much more profitable to add one class to the elements than to each new ID.

    Please write how to do it only in JS.
    JavaScript Anonymous, Mar 2, 2019

  • 2 Answers
  • 0
    You can add id to elements using JS.

    For example, something like this:

    document.querySelectorAll('div.a1').forEach(e => { = "a1_" + (window.new_id ? ++new_id : new_id = 1);

    But this is just an example. The best optimization depends on a specific site and on the nuances of a specific task. Although, if there are 5-10 elements, you can forget about optimization, just not setInterval :)

  • 0
    By pressing the button, determine which element is currently the cursor. And it doesn't matter that it has an ID, class, artifacts ... you simply define one specific element and save it to a variable. The cursor moves and you move an element from the variable behind it. You can do without classes altogether
    Matthew Cooper

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!