The 3 Main Steps to DOM Manipulation Using JavaScript

During the past week, I spent 3–4 days building a full-stack web application using Ruby on Rails (back end) and JavaScript (front end). One of my biggest takeaways from this project was DOM manipulation with JavaScript. The DOM (Document Object Model) is the representation of your project’s HTML after the browser has read it, and includes the changes to this HTML after manipulating it with your JavaScript file as well. Below the initial setup, I’ll be explaining the 3 main steps to DOM manipulation, and demonstrate an example of what this might be used for.

Initial Setup:

Hopping over to our ‘app.js’ file, lets use a fetch call to my favorite API —, (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:

(Note: This fetch call returns a single object, if your project’s fetch call returns more than one object, you will need to use the ‘forEach’ applicative in order to be working with individual objects.)

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

Each one is a different attribute we want to display, as you can see by my convention of naming the constants

Step 2: Change the Elements

I added string interpolation with back-ticks on lines 15–17 to properly label the info we are displaying

Step 3: Append the Elements

Final Result of our DOM Manipulation:

In Conclusion:

Full Stack Web Developer && Creative Thinker && Flatiron School Grad && Continuous Learner