Currently, I am dynamically constructing a list of entries utilizing data retrieved from the server.
Each entry is associated with a parent. My objective is to extract the parent's name from the DOM by locating its ID. This process works effectively if the parent entry already exists on the page. However, it encounters errors if the parent entry is not present.
<div class="the_entry">
<h4></h4>
<select></select>
</div>
<script>
const the_entry = document.querySelector('.the_entry');
const parsed_data_from_server = [
{ entry_id: 0, entry_name: "zero", parent_id: 2},
{ entry_id: 1, entry_name: "one", parent_id: 2},
{ entry_id: 2, entry_name: "two", parent_id: 2},
];
parsed_data_from_server.foreach((entry_from_the_server) => {
// new div
const new_entry = the_entry.cloneNode(true);
the_entry.parentNode.insertBefore(new_entry, the_entry);
new_entry.querySelector('h4').innerText = entry_from_the_server.entry_name;
new_entry.querySelector('h4').id = entry_from_the_server.entry_id;
// new option
const new_option = document.createElement('option');
new_entry.querySelector('select').appendChild(new_option);
new_option.value = entry_from_the_server.parent_id;
const name = document.querySelector(`[id="${entry_from_the_server.parent_id}"]`)
new_option.innerText = name.innerText; // this will fail because no element with that id exists YET
});
</script>
I am considering using promises to generate the option elements once the list processing is completed. Nonetheless, passing new_entry and entry_from_the_server is necessary for this task.
Here is my attempted solution...
let promises = [];
parsed_data_from_server.forEach((entry_from_the_server) => {
// new div
const new_entry = the_entry.cloneNode(true);
the_entry.parentNode.insertBefore(new_entry, the_entry);
new_entry.querySelector('h4').innerText = entry_from_the_server.entry_name;
new_entry.querySelector('h4').id = entry_from_the_server.entry_id;
// create a promise
promises.push(new Promise((resolve, reject) => {
resolve(new_entry, entry_from_the_server);
}));
} );
Promise.all(promises).then((new_entries) => {
new_entries.forEach((new_entry) => {
// new option
const new_option = document.createElement('option');
new_entry.querySelector('select').appendChild(new_option);
// where do I get entry_from_the_server from?!
new_option.value = entry_from_the_server.parent_id;
new_option.innerText = document.querySelector(`[id="${entry_from_the_server.parent_id}"]`).innerText;
})
} );
Everything seems to be in order until the final stage... How can I acquire the second argument? Is there a way to achieve this?