Click here to Skip to main content
15,892,768 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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?

JavaScript
<pre>    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);



What I have tried:

I have tried .getElementByClassName, but it also doesn't work :/
Posted
Updated 28-Mar-22 4:32am

1 solution

I deleted my previous comment after reading the question again. The function you're using is correct, but I think you're using it in the wrong location. The fetch() function returns a Promise<> which is a fancy way of saying "this will produce something either now, or later on".

You've put your code for selecting the buttons outside of the then() function, which means that it will probably execute before the Promise<> has had chance to complete. You need to select the elements only once they've been appended to the HTML body:

JavaScript
    document.querySelector('.movieList').appendChild(div)


    const btns = document.querySelectorAll(".delete");
    console.log(btns);
  }
});
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900