I wrote a piece of code to add HTML elements when the page loads (I am using AJAX to get images from Unsplash). I successfully added the HTML parts, and they show in the HTML when I inspect the element.
But I am unable to then use document.querySelectorAll() on those elements, because I get an empty NodeList. I want to be able to use document.querySelectorAll('.class') to get the element collection by class.
const catsUrl = 'https://api.unsplash.com/collections/10501588/photos/?MYAPI';
let imageHTML = [];
const xhr = new XMLHttpRequest;
xhr.onreadystatechange = function () {
if(xhr.readyState === 4 && xhr.status === 200) {
let carouselImgs = JSON.parse(xhr.responseText);
for (let i = 0; i < carouselImgs.length; i++) {
let imgURL = carouselImgs[i].urls.regular;
imageHTML.push(`<div class="img-group slide"><img class="img-fluid carousel-img" src="${imgURL}" alt="${carouselImgs[i].alt_description}"></div>`);
}
for(let j = 0; j < imageHTML.length; j++) {
let node = document.createRange().createContextualFragment(imageHTML[j]);
let frag = node.querySelectorAll('.slide');
let imgNodes = document.querySelector('.all-imgs').appendChild(...frag);
}
}
}
//This part does not work
const slides = document.querySelectorAll('.slide');
console.log(slides);
<div class="all-imgs">
//The div with images gets added here when I run the code (this works), but I cannot use queryselectorAll to get the divs by class
</div>