I am adding content to my HTML through JS by using innerHTML. But now when I try to access a class attached to that content I just get null. How would I access the class?
fetch(url)
.then((response) => {
return response.json();
}).then(data => {
for (var i=0; i < data['data'].length; i++){
var attributes = data.data[i].attributes,
title = attributes.title,
descr = attributes.description,
author = attributes.author,
available = attributes.available,
year = attributes.year,
id = data.data[i].id;
var div = document.createElement("div");
div.innerHTML = `title = ${title},
descr = ${descr},
author = ${author},
available = ${available},
year = ${year}
<button type="button" value="${id}" class="delete">delete</button>`
document.querySelector('.movieList').appendChild(div)
}
});
const btns = document.querySelectorAll(".delete");
console.log(btns);
I have tried .getElementByClassName, but it also doesn't work :/
It's a timing issue. You need to call querySelectorAll after you appended the elements.
Try to put const btns = document.querySelectorAll(".delete"); right after document.querySelector('.movieList').appendChild(div).
Currently, the moment when you try to find the buttons, they are not there, yet.