Integrating information from an API into the Document Object Model

const url = `https://catfact.ninja/fact?max_length=140`;

const getFact = () => {
  return fetch('https://catfact.ninja/fact?max_length=140')
  .then(res => res.json())
}

const createFactDiv = (fact) => {
  const factContainer = document.createElement('div')
  const setup = document.createElement('p')

  setup.innerText = fact.fact

  factContainer.append(setup)

  return factContainer
}

const appendFact = (factDiv) => {
  const factContainer = document.getElementById('factContainer')
  factContainer.append(factDiv)
}

document.addEventListener('DOMContentLoaded', () => {

})

getFact().then ((fact) => {
  const FactDiv = createFactDiv(fact)
  appendFact(FactDiv)
})

I've been experimenting with different approaches as I navigate through the complexities of JavaScript, as I am relatively new to it. My goal is to develop an app that showcases interesting cat facts. Initially, I was able to view the DIV containing the FACT accurately in the console.log within the DOM elements, but now it seems to have disappeared and I keep encountering the error: Uncaught (in promise) ReferenceError: append is not defined. Any suggestions on how to proceed would be greatly appreciated!

Answer №1

Ah, the familiar presence of spelling errors! Check out this functional code snippet:


const url = `https://catfact.ninja/fact?max_length=140`;

const fetchFact = () => {
  return fetch('https://catfact.ninja/fact?max_length=140')
  .then(res => res.json())
}

const createFactElement = (fact) => {
  const factContainer = document.createElement('div');
  const display = document.createElement('p');

  display.innerText = fact.fact;

  factContainer.append(display);

  return factContainer
}

const addFactToPage = (factElement) => {
  const factContainer = document.getElementById('factContainer');
  factContainer.append(factElement);
}

//This section is currently not in use
/*
document.addEventListener('DOMContentLoaded', () => {
})
*/

fetchFact().then ((fact) => {
  const factElement = createFactElement(fact);
  addFactToPage(factElement);
})

Consistent camelCase usage is key for smooth coding:

  • In the addFactToPage() function, using FactElement instead of factElement will cause an error.
  • Note from Robin: be cautious of typos like append.fact(FactDiv) instead of appendFact(factDiv).
  • Consider refactoring to appendFact(factElement) following the camelCase convention.
  • Mind your spacing, and adding semicolons at the end of lines can enhance readability!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

what is the method to extract the value of a JSON object nested within another JSON object

Can someone please assist me? "_attachments": { "kiran.jpg": { "content_type": "image/jpeg", "revpos": 6, "digest": "md5-mEsoX4ljN1iJlF2bX1Lw2g==", "length": 4601, "stub": true } } I ...

Capture the onclick attribute with jQuery and then reapply it

I am facing a challenge with a page that has several calendars composed of HTML tables where each day is represented by a td. The td elements have an onClick attribute which I need to manipulate using jQuery. Specifically, I need to remove the onClick attr ...

Exploring the integration of external javascript AMD Modules within Angular2 CLI

During my experience with Angular2 pre-releases, I found myself using systemjs to incorporate external JavaScript libraries like the ESRI ArcGIS JavaScript API, which operates on AMD modules (although typings are available). Now that I am looking to trans ...

Implementing AngularJS drag and drop functionality in a custom directive

I am in search of an example that demonstrates similar functionality to the HTML5 File API using Angular-js. While researching directives for Angular 1.0.4, I found outdated examples that heavily rely on DOM manipulation. Here is a snippet of the pure Ja ...

Is there a way to order the execution of two functions that each produce promises?

With my code, I first check the status of word.statusId to see if it's dirty. If it is, I update the word and then proceed to update wordForms. If it's clean, I simply update wordForms. I'm looking for advice on whether this is the correct a ...

Utilizing HTML5 for page-relative translation

Is there a way to apply a translate to an element so it moves to a specific point on the page instead of relative to its starting position? For instance, in the code snippet below, the "card" elements will move 50, 100 relative to their initial position. ...

Ways to remove any messages containing URLs that are not www.youtube.com or www.twitter.com

Recently, I have encountered a significant issue with Discord Scam Links in my server. I attempted the following approach: if(message.content.includes("discordscam.com")) { message.delete() } However, this method is not effective as it onl ...

Effectively handle multiple connections from nodejs to postgres using the pg library

I need to run a script that performs multiple queries using the pg library for managing connections. However, I am facing an issue where my program stops working when the connection pool is full and does not queue future queries. I have tried setting the p ...

Enhance the functionality of a form by dynamically adding or deleting input rows using

The feature for adding and deleting input rows dynamically seems to be experiencing some issues. While the rows are successfully created using the add function, they are not being deleted properly. It appears that the delete function call is not function ...

Guide for manually initiating the mouseleave event on a smartphone or tablet

Is there a way to change the color of a link to orange when it's hovered over? On mobile devices, the link should turn orange when touched and stay that way until the user clicks away. I'd like to manually trigger the mouseout event to remove th ...

Enhance CSS delivery for the items listed below

Reduce the delay caused by rendering JavaScript and CSS above-the-fold. There are 16 CSS resources currently blocking the rendering of your page. This delay could be affecting the loading time of your content. To improve this issue, consider deferring or ...

Using javascript, retrieve the JSON values for each level

I need help using a recursive function in JavaScript to retrieve the last key value pair from a simple JSON object. Here is an example JSON object: { 'a': { 'b': { 'c': 12, 'd': 'Hello World& ...

Transform a row into a clickable element

I am currently working on a social media platform where users can search for venues stored in the database. In my search.php file, I have implemented a text box that dynamically loads venue names from the database into a venuesearch div as the user types. ...

transferring information to d3.js

I have a json object structured in the following way { "tweet":[ {"text": "hello world"}, {"text": "hello world"} ] } When I check the console output of "data" in my code below, it shows me an Object tweet: Array[131]. However, when I l ...

Ways to display an error notification alongside another message

I have set up a validation directive that requires users to check a box. If the checkbox is left unchecked, an error message will be displayed. However, I am facing an issue where the message overlaps with the checkbox text. https://i.sstatic.net/iTKoo.jp ...

Utilizing AJAX and API calls in Wordpress to display filenames and permissions prior to the JSON response on a Virtual Private Server

I'm currently in the process of transferring a Wordpress website from shared hosting to a VPS. Everything is going smoothly except for AJAX and API calls. Every time an AJAX call is made, it displays some file and folder permissions before the JSON ...

populating a multi-dimensional array using a "for" loop in Javascript

It appears that JavaScript is attempting to optimize code, causing unexpected behavior when filling a multidimensional array (largeArr) with changing values from a one-dimensional array (smallArr) within a loop. Take the following code for example: largeA ...

Preventing React setState from replacing the entire object

When attempting to update a customer's age using setState, the object is altered before calling setState, but the existing object is not updated. customerOnChange(event, field) { //Customer's age currently set at 80 var customer = { ...t ...

Add to the current values of the REACT Form template property

I am new to working with REACT and I have been exploring whether it is possible to append a REACT Form control property value in order to enhance its functionality. To streamline the validation process, I have created a validation template that leverages ...

Clickable link in popup window using fancybox

When I try to use fancybox to open an iframe and scroll to an anchor tag, it works perfectly in IE but not consistently in other browsers. It stops at a different place than the anchor. I suspect the issue may be related to JavaScript based on information ...