Hello i am learning JS actually i try to fetch some data from an API, i have fetch all the work from api/works and display them in a div but now i need to create 3 button who represent the 3 category who regroup all works, i created dynamically the buttons but now i need to put a function on these button to display the api/works from the category id give (example button 1 represent category id 1 and when i click, all api/works from category id 1 are displayed, same for 2nd et 3rd button) there is the json format for data
[
{
"id": 1,
"title": "Abajour Tahina",
"imageUrl": "http://localhost:5678/images/abajour-tahina1651286843956.png",
"categoryId": 1,
"userId": 1,
"category": {
"id": 1,
"name": "Objets"
}
}
i don't know how said fetch all works but with categoryId 1, hide all and display these categoryId of works
if someone know how to do this or documentation to doing this
document.getElementById("button").addEventListener("click", function(){
// Clear the container element
document.getElementById("works").innerHTML = "";
// Make GET request to API endpoint for all works with categoryId 1
fetch("http://localhost:5678/api/works?categoryId=1")
.then(response => response.json())
.then(data => {
// Loop through the list of works
data.forEach(function(work) {
// Create a new HTML element for each work
var workElement = document.createElement("div");
workElement.innerHTML = "Work ID: " + work.id + "<br>" + "Title: " + work.title + "<br>" + "Content: " + work.content;
// Append the new HTML element to the page
document.getElementById("works").appendChild(workElement);
});
})
.catch(error => console.log(error));
i tried this but he give me all /works the url http://localhost:5678/api/works?categoryId=1 not working for me i think
put console.log on the function that handle the click on button to see if the function is actualy triggerd.
i think because your buttons are dynamically added javascript can't recognize them.