I recently began to code on a small frontend project in javascript. I came across the following problem:
Code Part 1
const startFeed = document.getElementById('startFeedButton');
const stopFeed = document.getElementById('stopFeedButton');
startFeed.addEventListener("click", () => {
api.streamingFunction(callback(response){
appendResponseToDom(response);
}
}
stopFeed.addEventListener("click", () => {
endStreamingFunction();
}
The 'api.streamingFunction' is part of a library and streams data via websocket. The 'callback' gets repeatedly called every time new data is available. It'll let you do something with the data inside the callback function. 'endStreamingFunction' closes the websocket. Now the 'appendResponseToDom' function takes a piece of the data and appends it to the Dom like so:
Code Part 2
const someWhereInDom = document.getElementById('somewhere');
function appendResponseToDom(apiData) {
const newHTML = document.createElement("div");
newHTML.innerHTML = `
<div class="data">${apiData}</div>
<button id=${runningIndex}>Click here</button>
`
someWhereInDom.appendChild(newHTML);
}
Each button has a running index to uniquely select it. I didn't specify how runningIndex is evaluated in the code above.
What I want to do now is:
- select every button uniquely after the newHTML has been inserted into the Dom (by adding event listeners) (and optionally in parallel stream new data via websocket)
Is this possible ? How would I usually do that ? Maybe you can point me in the right direction, thanks.