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

How to get REST API JavaScript fetch object value to HTML?

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

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

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

>Solution :

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 class="container">
  <p>Comments:</p>
  <span class="comments">Fetching comments ...</span>
</div>
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