Skip to content
Advertisement

Issue with createElement() don’t change data when I call new data

When I press on div “User” bring me posts for this user but when I change to another user imposed deletes autmicaly for old user posts and bring to me posts for a new user, unfortunately, it shows posts for new user bottom of the posts for old user.

Deleted old posts and bring to me new posts on the same div.

This function for create elements posts:

 function getPost(userID){
         fetch('https://jsonplaceholder.typicode.com/posts?userId='+ userID)
         .then((response) =>{
            if (response.ok) {
               return response.json() 
            }
         
         })
         .then((posts) => {
            for(let post of posts){
               const parentPosts = document.querySelector(".infos")
               const orginalPost = document.querySelector("#demo")
               console.log(orginalPost);
               // orginalPost.style.display="none";
            //     //orginalPost.innerHTML='';  
                let newPost = document.createElement('div')
                newPost.innerHTML = orginalPost.innerHTML;
                newPost.classList.remove("orginal")
                newPost.className = 'info';
            // //    //console.log('new post ',newPost);
                let postHead = document.querySelector(".postHead")
                let postP = document.querySelector(".postP")
                     postHead.innerHTML = post.title;
                     postP.innerHTML = post.body;
            // //    //const parentPosts = document.querySelector(".infos")
                     parentPosts.appendChild(newPost)
                    remove(parentPosts)
            }
                         return
         });
      }

This function is supposed to remove old posts

 function remove(element) {
         let elementLength = element.children.length;
         console.log("element.children.length >> "+elementLength)
         if (element > 0) {
            element.firstChild.remove()
            //element.removeChild(element.lastChild);
            console.log("element.children.length from loop >> "+ elementLength)
}
  }

This all code

<html>
   <head>
      <style>
body{
   background: linear-gradient(120DEG,#c0a397,#ebe6b4);
}
         .conterner{
         width: 100%;
         display: flex;
         flex-direction: row;
         }
         .users{
            margin: 2px;
            background: white;
            width: 30%;
            height: 100%;
         }
         .infos{
            margin: 2px;
            background: white;
            width: 70%;
         }
         .user{
            border-radius: 65px;
            background-color: rgba(187, 200, 200, 0.315);
            margin: 0 auto;
            cursor: pointer;
         }

         .user:hover,
         :active{
            border: rgb(224, 152, 132) 2px solid;
         }
         h3{
            padding: 1px;
            margin-left: 25px;
         }
         .info{
            border-radius: 23px;
            background-color: rgba(187, 200, 200, 0.331);
            margin: 8px;
            padding: 2px ;
            padding-left: 20px;
         }
         .line{
            width: 97%;
            margin:0;
            padding: 0;
            border-bottom: 1px solid black;
            /* position: relative; */
            }
            .dispaly{
               display: none;
            }
            .orginal{
               display: none;
            }
      </style>
   </head>

   <body>
      <main>
         <div class="conterner">

            <div class="users " >
               <div style="margin: 0 a;" id="parUser">
                  <div class="user" id="user" >
                     <h3 id="name"> Ahmed </h3>
                     <h3 id="email"> Ahmed.ali@gmail.com </h3>
                  </div>
               </div>
                
            </div>
            <div class="info orginal" id="demo">
               <h5 class="postHead" > post post postpost</h5>
               <div class="line"></div>
               <p class="postP"> post post postpost</p>
            </div>
            
            <div class="infos">
               <div class="info">
                  <h5 class="postHead" > post post postpost</h5>
                  <div class="line"></div>
                  <p class="postP"> post post postpost</p>
               </div>
            </div>
         </div>
        
      </main>
      <script>
         

         function getUsers(userID){

       fetch('https://jsonplaceholder.typicode.com/users')
         .then((response) =>{
            if (response.ok) {
               return response.json() 
            }
         
         })
         .then((users) => {
            for(let user of users){
               // console.log(user)
               const orginalDiv = document.querySelector("#user");
               orginalDiv.style.display ='none';
               const newDiv = document.createElement('div')
               newDiv.innerHTML= orginalDiv.innerHTML;
               newDiv.className="user";
               const nameH = document.querySelector('#name')
               nameH.innerHTML = user.name;
               const emailH = document.querySelector('#email')
               emailH.innerHTML = user.email;
               const parentDiv = document.getElementById("parUser")
               parentDiv.appendChild(newDiv);
               console.log(newDiv);
               newDiv.addEventListener("click", ()=>userEvent(user.id)) 
               console.log(user.id)
               const parentPosts = document.querySelector(".infos")
            }
            
                     return
         })
        // orderElement(user)
      }
      function getPost(userID){
         fetch('https://jsonplaceholder.typicode.com/posts?userId='+ userID)
         .then((response) =>{
            if (response.ok) {
               return response.json() 
            }
         
         })
         .then((posts) => {
            for(let post of posts){
               const parentPosts = document.querySelector(".infos")
               const orginalPost = document.querySelector("#demo")
               console.log(orginalPost);
               // orginalPost.style.display="none";
            //     //orginalPost.innerHTML='';  
                let newPost = document.createElement('div')
                newPost.innerHTML = orginalPost.innerHTML;
                newPost.classList.remove("orginal")
                newPost.className = 'info';
            // //    //console.log('new post ',newPost);
                let postHead = document.querySelector(".postHead")
                let postP = document.querySelector(".postP")
                     postHead.innerHTML = post.title;
                     postP.innerHTML = post.body;
            // //    //const parentPosts = document.querySelector(".infos")
                     parentPosts.appendChild(newPost)
                    remove(parentPosts)
            }
                         return
         });
      }
      
      function remove(element) {
         let elementLength = element.children.length;
         console.log("element.children.length >> "+elementLength)
         if (element > 0) {
            element.firstChild.remove()
            //element.removeChild(element.lastChild);
            console.log("element.children.length from loop >> "+ elementLength)
}
  }
     getUsers()
      
     getPost()

      function userEvent(id) {
         getPost(id);
        
      }

      </script>
      
   </body>
</html>


Advertisement

Answer

This function supposed to work for the remove old posts

The function remove contains this block:

if(element > 0){
    element.firstChild.remove()
    console.log("element.children.length from loop >> "+ elementLength)
}

Given that element is likely a HTMLElement, it is never going to be true, even if it is null.

console.log(null > 0)
console.log(document.createElement('div') > 0)

You should use the length variable elementLength, which you prepared before and contains an integer:

if(elementLength > 0){
    element.firstChild.remove()
    console.log("element.children.length from loop >> "+ elementLength)
}

While this concludes why your elements never were removed, I suggest to remove the content of parentPosts before adding newPost.

/***
* Removes all children from element
*/
function remove(element){
  if(element){
    while(element.firstChild) element.firstChild.remove()
  }

  /*
  let elementLength = element.children.length;
  console.log("element.children.length >> "+elementLength)
  if (element > 0) {
    element.firstChild.remove()
    console.log("element.children.length from loop >> "+ elementLength)
  }
  */
}

Here is an adjusted snippet.

function getUsers(userID){
  fetch('https://jsonplaceholder.typicode.com/users')
   .then((response) => {
      if(response.ok){
         return response.json() 
      }
   })
   .then((users) => {
      for(let user of users){
         // console.log(user)
         const orginalDiv = document.querySelector("#user");
         orginalDiv.style.display ='none';
         
         const newDiv = document.createElement('div')
         newDiv.innerHTML= orginalDiv.innerHTML;
         newDiv.className="user";
         newDiv.addEventListener("click", () => userEvent(user.id)) ;
         
         const nameH = document.querySelector('#name')
         nameH.innerHTML = user.name;
         
         const emailH = document.querySelector('#email')
         emailH.innerHTML = user.email;
         
         const parentDiv = document.getElementById("parUser")
         parentDiv.appendChild(newDiv);
                  
         //REM: Not required
         //console.log(newDiv);
         //console.log(user.id)
         //const parentPosts = document.querySelector(".infos")
      }

  return
 })
};

function getPost(userID){
  fetch('https://jsonplaceholder.typicode.com/posts?userId='+ userID)
  .then((response) => {
    if(response.ok){
       return response.json() 
    }
 })
 .then((posts) => {
    //REM: These wont change inside the loop
    const orginalPost = document.querySelector("#demo");
    const parentPosts = document.querySelector(".infos");
 
    //REM: Clear the current content
    remove(parentPosts);

    //REM: Add new content
    for(let post of posts){
      //console.log(orginalPost);

      const newPost = document.createElement('div');
      newPost.innerHTML = orginalPost.innerHTML;
      
      //REM: Setting className below, removed all other classes anyway
      //newPost.classList.remove("orginal")
      newPost.className = 'info';

      const postHead = newPost.querySelector(".postHead");
      postHead.innerHTML = post.title;
      
      const postP = newPost.querySelector(".postP");
      postP.innerHTML = post.body;
      
      parentPosts.appendChild(newPost)
    };
    
    return
  })
};

function remove(element){
  if(element){
    while(element.firstChild) element.firstChild.remove()
  }
};

function userEvent(id){
  getPost(id);
};

getUsers()
getPost()
body{
  background: linear-gradient(120DEG,#c0a397,#ebe6b4);
}
.conterner{
  width: 100%;
  display: flex;
  flex-direction: row;
}
.users{
  margin: 2px;
  background: white;
  width: 30%;
  height: 100%;
}
.infos{
  margin: 2px;
  background: white;
  width: 70%;
}
.user{
  border-radius: 65px;
  background-color: rgba(187, 200, 200, 0.315);
  margin: 0 auto;
  cursor: pointer;
}

.user:hover,
:active{
  border: rgb(224, 152, 132) 2px solid;
}
h3{
  padding: 1px;
  margin-left: 25px;
}
.info{
  border-radius: 23px;
  background-color: rgba(187, 200, 200, 0.331);
  margin: 8px;
  padding: 2px ;
  padding-left: 20px;
}
.line{
  width: 97%;
  margin:0;
  padding: 0;
  border-bottom: 1px solid black;
  /* position: relative; */
  }
  .dispaly{
     display: none;
  }
  .orginal{
     display: none;
  }
<main>
   <div class="conterner">
      <div class="users " >
         <div style="margin: 0 a;" id="parUser">
            <div class="user" id="user" >
               <h3 id="name"> Ahmed </h3>
               <h3 id="email"> Ahmed.ali@gmail.com </h3>
            </div>
         </div>
      </div>
      
      <div class="info orginal" id="demo">
         <h5 class="postHead" > post post postpost</h5>
         <div class="line"></div>
         <p class="postP"> post post postpost</p>
      </div>

      <div class="infos">
         <div class="info">
            <h5 class="postHead" > post post postpost</h5>
            <div class="line"></div>
            <p class="postP"> post post postpost</p>
         </div>
      </div>
   </div>
</main>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement