Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

140
Views
How to get a class of dynamically added content via innerhtml

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 :/

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!