Dynamic Entry Animation in JavaScript: Unique ID Change Only Occurs Once

Dynamic entry animations apply only to the first element because duplicate IDs interfere with unique selection. How can I ensure each new entry receives a unique ID for its animation?

New JS approach:

type Student = { uid: string };
let studentsArr: Student[] = [];

function registerStudent(evt: Event) {
  evt.preventDefault();
  const studentObj = { uid: 'stu_' + Date.now() };
  studentsArr.push(studentObj);
  document.getElementById('display').innerHTML += `<div id="${studentObj.uid}">New Student</div>`;
  setTimeout(() => {
    const node = document.getElementById(studentObj.uid);
    if (node) node.id = 'anim_' + studentObj.uid;
  }, 3000);
}

Alternative HTML and CSS can be built similarly.

hey, i fixed it by not changing the id. i just add a data-attr for animation so the original id stays intact. keeps things simple and avoids any mixups when other scripts access the element, ya know?

Your approach for generating unique IDs using timestamps is practical and easy to implement. However, based on my experience, dynamically changing an element’s ID might lead to unforeseen issues if other scripts rely on that identifier. A more reliable solution could be to leave the generated ID intact and simply add a unique class to trigger the animation. This maintains the integrity of the element’s primary identifier while still allowing for distinct animations on each entry. This approach has helped me avoid conflicts and made my animations more maintainable across large projects.