PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 15, 2022

[FIXED] How to refresh just one DOM element using JS vanilla

 October 15, 2022     dom, javascript     No comments   

Issue

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!");
        });
    });

Solution

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.



Answered By - connexo
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing