Home > Enterprise >  How to refresh just one DOM element using JS vanilla
How to refresh just one DOM element using JS vanilla

Time:09-23

I'm using DOM to create an element for me that shows the amount of likes a specific comment has received. When someone likes the button that data gets pushed to the API. However, in order to see the number of likes increase I have to manually reload the page.

Is there a way to automatically refresh that specific DOM element so that when a user clicks the like button the amount of likes will automatically increase (so refresh) without having to manually reload the website?

    // shows the amount of likes
    const likeCounter = document.createElement("p");
    likeCounter.classList.add("comments__container-content-like-counter");
    functionsDiv.appendChild(likeCounter);
    likeCounter.innerText = commentData.likes;


    // likes a comment and adds it to the api
    commentLike.addEventListener("click", () => {
        const addLike = commentData.id;

        axios.put(`${baseURL}comments/${addLike}/like?api_key=${apiKEY}`).then(() => {
            console.log("Like has been added!");
        });
    });

CodePudding user response:

Here you go:

 // shows the amount of likes

const likeCounter = document.createElement("p");
likeCounter.classList.add("comments__container-content-like-counter");
functionsDiv.appendChild(likeCounter);
likeCounter.innerText = commentData.likes;


// likes a comment and adds it to the api
commentLike.addEventListener("click", () => {
    const addLike = commentData.id;

    axios.put(`${baseURL}comments/${addLike}/like?api_key=${apiKEY}`).then(() => {
        console.log("Like has been added!");
        likeCounter.textContent = Number(likeCounter.textContent) 1
    });
});

Just add the line

likeCounter.textContent = Number(likeCounter.textContent) 1

to the promise chain.

  • Related