Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Comments aren't properly displaying under post (using jsonplaceholder)

When I’m clicking on comment icon comments are displaying only on the first card. Also comments’ appearance only changing on the first card. Everything else seems to be working fine. I want every card to show and delete its’ own comment separately. You can see my issue with snippet code. Tanks in advance.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <script src="https://kit.fontawesome.com/a89a4ef5c6.js" crossorigin="anonymous"></script>
    <title>lab</title>
</head>
<body>
<div class="container">
    <div class="row">
        <button type="button" id="btn" class="mt-3 mx-auto btn btn-primary">Get Posts</button>
    </div>
    <div style="padding-top: 100px" class="row" id="cardDiv">
    </div>
</div>

<script>

    let ton = 0;
    let div = document.getElementById('cardDiv');
    const btn = document.getElementById('btn').addEventListener("click", getPosts);

    function getPosts(){
        fetch("https://jsonplaceholder.typicode.com/posts")
        .then((response)=>{
            return response.json();
        })
        .then((resp)=>{
           console.log(resp)
            resp.forEach(
                elem=>{
                    div.innerHTML += `
                       <div class="card" style="width: 18rem;">
                           <div class="card-body">
                           <div>${elem.id}</div>
                               <h5 class="card-title">${elem.title}</h5>
                               <p class="card-text">${elem.body}</p>
                                <i id="myClick" onclick="showComments(${elem.id})" class="far fa-comment"></i>
                           <div class="zxc" id="hello"></div>
                         </div>
                       </div>`
                }
            )
        })
    }

    function showComments(q){
        let commentPlace = document.getElementById('hello');
        let inp = document.getElementById('myClick');

        if (inp.classList.contains("far")) {
            fetch("https://jsonplaceholder.typicode.com/comments")
                .then((resp)=>{
                    return resp.json();
                })
                .then((post)=>{
                        for (let index=0; index < post.length; index++){
                            if (post[ton].postId === q){
                                commentPlace.innerHTML += `<p>${post[ton].body}</p>`
                            }
                            ton = ton+1;
                        }
                        ton = 0;
                    }
                )
            inp.classList.remove("far");
            inp.classList.add("fas");

        }else {
            inp.classList.remove("fas");
            inp.classList.add("far");
            commentPlace.innerHTML = "";
        }
    }
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>
</body>
</html>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The reason your comments are not displayed properly is because creating the cards through a forloop which assigns every card the same id hello and myClick

I have edited your code and it will work now –

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <script src="https://kit.fontawesome.com/a89a4ef5c6.js" crossorigin="anonymous"></script>
    <title>lab</title>
</head>
<body>
<div class="container">
    <div class="row">
        <button type="button" id="btn" class="mt-3 mx-auto btn btn-primary">Get Posts</button>
    </div>
    <div style="padding-top: 100px" class="row" id="cardDiv">
    </div>
</div>

<script>

    let ton = 0;
    let div = document.getElementById('cardDiv');
    const btn = document.getElementById('btn').addEventListener("click", getPosts);

    function getPosts(){
        fetch("https://jsonplaceholder.typicode.com/posts")
        .then((response)=>{
            return response.json();
        })
        .then((resp)=>{
           console.log(resp)
            resp.forEach(
                elem=>{
                    div.innerHTML += `
                       <div class="card" style="width: 18rem;">
                           <div class="card-body">
                           <div>${elem.id}</div>
                               <h5 class="card-title">${elem.title}</h5>
                               <p class="card-text">${elem.body}</p>
                                <i id="myClick-${elem.id}" onclick="showComments(${elem.id})" class="far fa-comment"></i>
                           <div class="zxc" id="hello-${elem.id}"></div>
                         </div>
                       </div>`
                }
            )
        })
    }

    function showComments(q){
        let commentPlace = document.getElementById(`hello-${q}`);
        let inp = document.getElementById(`myClick-${q}`);

        if (inp.classList.contains("far")) {
            fetch("https://jsonplaceholder.typicode.com/comments")
                .then((resp)=>{
                    return resp.json();
                })
                .then((post)=>{
                        for (let index=0; index < post.length; index++){
                            if (post[ton].postId === q){
                                commentPlace.innerHTML += `<p>${post[ton].body}</p>`
                            }
                            ton = ton+1;
                        }
                        ton = 0;
                    }
                )
            inp.classList.remove("far");
            inp.classList.add("fas");

        }else {
            inp.classList.remove("fas");
            inp.classList.add("far");
            commentPlace.innerHTML = "";
        }
    }
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>
</body>
</html>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading