I have a problem with selecting dynamically-added elements, each with dynamically-defined ID; script always returns null when using getElemendById.
I want the script to first check, if element with certain ID already exists within the DOM, and if not - create one, if it does - do something else.
My code looks like this:
document.addEventListener('DOMContentLoaded', function () {
//define variables
var playersOnField = document.querySelector('.players');
//using timeBar as indicator of current time frame
var timeBar = document.querySelector('#time');
//its maximum value needs to be adjusted to the number of the frames we have
timeBar.setAttribute("max", data.player_positions.length);
//display the players position for current frame
positionPlayers = function() {
time = timeBar.value;
currentFrame = data.player_positions[time];
//check if DOM element representing each player of current frame already exists, if not - create it
for (var i = 0; i < currentFrame.length; i++) {
var playerId = currentFrame[i][0];
//ID's start with number, so they require special unicode notation
if (!!document.getElementById(`#\\3${playerId} `) == false) {
console.log('no element, let\'s create one');
var newPlayer = document.createElement('div');
newPlayer.id = `${playerId}`;
playersOnField.appendChild(newPlayer);
} else {
console.log('element already exists!');
}
}
}
//every time the bar changes its postion (and therefore its value) it should trigger the action to set up the players in the current position on the field
timeBar.addEventListener('change', positionPlayers);
timeBar.addEventListener('input', positionPlayers);
})
But the function is always returning false, and creating dozens od div's of the same ID, as getElementById never finds any of those newly-appended elements. How can I avoid this happening, preferably using vanilla JS?