Hopping over to our ‘app.js’ file, lets use a fetch call to my favorite API — PokeAPI.co, (for this demonstration we will only pull information about the first “Pokemon” in the API— “Bulbasaur”) which will give us back a single parsed JSON object that we can work with. Then we will ‘console.log’ this to make sure everything is hooked up, and we are getting the object back that we requested from the fetch call:
In your terminal, from the root directory of the project, run command ‘lite-server’ (or however you run your local server) to serve up your web page. Here is the object you’ll see in your browser’s dev tools console if everything is done correctly:
Beneath our fetch call is where we are going to create the function that will dynamically add things to the DOM. In this case, we’ll be creating a webpage that takes values from the “PokeAPI” fetch call, and dynamically adds information about “Bulbasaur” to the web page, without hardcoding this info in our ‘index.html’ file. So let’s name our function ‘displayBulbasaurInfo’, and inside of our new function, we should grab the elements from ‘index.html’ we plan to manipulate:
In order for our new function to receive the object from our fetch call, we need to replace the ‘console.log’ in line 3 with the function name:
Finally! We are set up to begin the 3 main steps to DOM manipulation!
Step 1 : Create Elements
Continuing inside of our ‘displayBulbasaurInfo’ function, we must now create HTML elements that will eventually be “changed” (step 2), and lastly be “appended” (step 3) to the DOM. In the case of our header, we will create an ‘h1’ element to append to it later that will serve as our page’s title. For our section element, which will hold all attributes we want other than “Bulbasaur’s” name, we will create ‘h3’ elements to append to it later:
Step 2: Change the Elements
Below our newly created blank ‘h1’, and ‘h3’ elements, we will now change the inner text by adding information from our “Bulbasaur” object:
Step 3: Append the Elements
Lastly, beneath the lines we just wrote that changed our elements to include “Bulbasaur” info, we now need to append these finished elements to the elements we initially grabbed from our ‘index.html’ file in line 6 and 7 below:
Final Result of our DOM Manipulation:
You can now see the ‘h1’ and ‘h3’ elements were created, changed, and appended appropriately to our header and section elements. With that, we have successfully manipulated the DOM!
This has been a very simple example of DOM manipulation, which is a way to add elements dynamically to our existing HTML from our JS file, except before we added (append) the elements, we “changed” their inner info using an API we retrieved info from in our JS file. I hope this article taught you how to apply DOM manipulation to your project and make it more dynamic. Thanks for reading!