this is my first question here, so I'm little bit nervous ;) My problem is, how to add selector with options to DOM. Main question is that I have api to get data and the value of options should be added from this api. At the beginning I create button to start the function, but then code doesn't work. Here is my code:
const btn = document.createElement("button");
btn.setAttribute("id", "getCurrencies");
btn.innerHTML = "Click me!";
document.body.appendChild(btn);
btn.addEventListener("click", (e) => {
fetch("https://api.frankfurter.app/latest")
.then((response) => response.json)
.then((data) => {
const selectEL = createElement("select");
const currencies = Object.entries(data.rates).forEach(([code, value]) => {
const optionEl = createElement("option");
// optionEl.setAttribute("value", code);
optionEl.innerHTML = ($[code], $[value]);
selectEL.appendChild(optionEl);
});
document.body.appendChild(selectEL);
})
.catch((err) => console.log(err));
});
You have multiple mistakes. Start debugging your code piece by piece. If you first look at the console you will get error "ReferenceError: createElement is not defined"
Then you fix those and get the next error "TypeError: Cannot convert undefined or null to object"
Then you fix the json call. You will now get error "ReferenceError: $ is not defined" This means $ is not defined and the transpiler has no idea what to do. By looking at your code:
optionEl.innerHTML = ${code} - ${value};Now it starts to work.
So start by debugging from the beginning. Remove code lines and read what the console prints for you.
See working example without code splitting: https://codepen.io/shnigi/pen/NWvNwXQ
You should do it like this:
$(document).on('click','#getCurrencies',function(){
// ...
});
This binds a click event to the document and all child elements within it. This method is referred to as delegated event handling.