Home > Back-end >  How to get REST API JavaScript fetch object value to HTML?
How to get REST API JavaScript fetch object value to HTML?

Time:08-01

How can I get printed console object value to HTML?

I have JavaScript fetch code like this:

const comments = fetch("https://api.github.com/repos/pieceofdiy/comments/issues/1")
  .then((response) => response.json())
  .then((labels) => {
    return labels.comments;
  });

const printComments = () => {
  comments.then((number) => {
    console.log(number);
  });
};
printComments()

printComments() numeric object value shows correct in console, but how to show it in HTML

to <span id="comments">..</span> ?

CodePudding user response:

With JS you can edit the DOM Hierarchy by searching for your desired Element to change.

const commentsEl = document.querySelector('.comments');
commentsEl.innerHTML = printComments();

With document.querySelector(CSS-Selector) you can search the DOM-Tree for a sufficient Element matching your Selector

We store the Element in a variable and change the Content of this Element by saving the comments in the property .innerHTML.

I've added a snippet demonstrating the changes below, and also changed some bits to improve your code.
As the fetch-Method is asynchronous, you’ll see fetching comments ... for a brief moment, as we change the content when the fetch finished and we got the results.

const commentsEl = document.querySelector('.comments');

// We fetch the comments as before
fetch("https://api.github.com/repos/pieceofdiy/comments/issues/1")
  .then((response) => response.json())
  .then((labels) => {
    // But when we get the results, we immedietly change the contents of the comments span.
    commentsEl.innerHTML = labels.comments;
  });
<div >
  <p>Comments:</p>
  <span >Fetching comments ...</span>
</div>

CodePudding user response:

You could try setting a p tag with an id, ex: <p id=“comments”>and then using document.getElementById(“comments”).innerValue = number;

Place that second piece of code into printComments()

CodePudding user response:

First you need to get your span tag in your html document. Then define the innerHtml property of the span element by the value returned by the promise, in this case in your case the value is returned through a callback, so you simply have to perform the process in the scope of the callback.

Here is a snippet to illustrate this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <span id="comments"></span>
    
    <script>
        const span = document.getElementById("comments");

        const comments = fetch("https://api.github.com/repos/pieceofdiy/comments/issues/1")
        .then((response) => response.json())
        .then((labels) => {
            return labels.comments;
        });

        comments
            .then(res => span.innerHTML = res)
            .catch(err => console.log(err));
    </script>
</body>
</html>

But it can be done more cleanly this way:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <ol>
        <li>Comments: <span id="comments1"></span></li>
        <li>Comments: <span id="comments2"></span></li>
        <li>Comments: <span id="comments3"></span></li>
    </ol>

    <script>
        const comments1 = document.getElementById("comments1");
        const comments2 = document.getElementById("comments2");
        const comments3 = document.getElementById("comments3");

        const printComment = async (url, HTMLTag) => {
            try {
                const request = await fetch(url);
                const response = await request.json();
                HTMLTag.innerHTML = response.comments;
            } catch (error) {
                console.log(error);
            }
        };

        printComment("https://api.github.com/repos/pieceofdiy/comments/issues/1", comments1);
        printComment("https://api.github.com/repos/pieceofdiy/comments/issues/1", comments2);
        printComment("https://api.github.com/repos/pieceofdiy/comments/issues/1", comments3);
    </script>
</body>
</html>

Good luck !

  • Related