1

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>
I Love Code
  • 420
  • 1
  • 5
  • 26
  • 1
    You xhr request is async, so your `document.querySelectorAll` runs **before** the HTTP request returns – Liam May 21 '20 at 14:42
  • Does this answer your question? [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Liam May 21 '20 at 14:42
  • @Liam thank you, I have something to look at to try now, I will respond if I didn't come right. – I Love Code May 21 '20 at 15:01

0 Answers0