Why i am geeting empty node list for buttons?

https://github.com/kedaragate/webDev

I have created html elements using javascript, i have given class name for user button element as “.card-btn” and unique id for each button as per user id, but when i do document.querySelectorAll for button, I get empty node list. how to tackle this problem.?

hey @kedar.agate Try these consoles on displayCards function

      let displayCards = function (users) {
        console.time();
        
        users.forEach((user) => {
          const userCard = createUserCard(user);
          usersDiv.appendChild(userCard);
        });

        console.timeEnd();
      };

and add one more console right after you query for all buttons

//user modal
      userButton = document.querySelectorAll(".card-btn");
      console.log("query complete");

You gonna find out what’s happening.

It’s because it takes time to process request to the api
while rest of the JS code runs so fast

log

1 Like

Do u mean to say, setTimeOut() or async await to be used, if so where to use it?

You can define the onclick function right at the time of adding it to the DOM.

   let createUserCard = function (user) {
       
        let userButton = document.createElement("button");
        userButton.className = "card-btn";
        userButton.id = user.id;
        userButton.textContent = "See More Details";
       
 
        userButton.onclick  =  function (e) {
          console.log(user.id);
        };

        userDiv.appendChild(userButton);
        return userDiv;
      };

another good practice would be doing this

  function printUser(u) {
        console.log(u);
      }

      let createUserCard = function (user) {
     // rest of the code
     
     userButton.onclick = () => printUser(user);
    }

solution:

      function printUser(u) {
        fetch(`https://dummyapi.io/data/v1/user/${u.id}`, {
          method: "GET",
          headers: {
            "app-id": "62c3859db3b09459b4b1f8a0",
          },
        })
          .then((response) => response.json())
          .then((data) => {
            const userData = data.data;
            console.log(userData);
          });
      }

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.