DEV Community

Cover image for Conquering The Front with the DOM API
Peter Rose
Peter Rose

Posted on

Conquering The Front with the DOM API

The DOM.

For some, it might be a tricky subject but once figured out, it becomes a game-changer. No, rather it becomes the game-changer. You might think this is an overstatement but the DOM might the most essential component of web development.

But What Exactly is The DOM?

The DOM of a web app looks a little something like this...

Looks a lot like your average HTML skeleton, no? But alas! they're really not one and the same. The DOM is a virtual representation of your HTML skeleton. It is better to visualize the DOM as a tree of nodes. It allows us to manipulate our HTML from the JavaScript document, itself. This is because the DOM interprets all of the tags within our HTML document a collection of node objects. This can be useful since this allows us to target specific nodes by using the respective method to search by class name, ID, or tag name. Once we have access to them, manipulating its properties and/or styles becomes as easy as console logging. At that point, the world is yours.

DOM starter kit

Targetting HTML Elements

const container = document.querySelector('.sampleContainer'); 
// By Query
const name = document.getElementbyId('nameTag') 
// By ID Name
cont dob = document.getElementbyClassName('birthDiv')
// By Class Name

Manipulating your CSS with DOM

const photo = document.querySelector('.photo');
photo.style.cssText = ''.concat(
    'width       : 400px;',
    'color       : #f0f0f0;',
    'margin-top  : 10px;'
);

// Concat CSS Styles

photo.style.width = '400px';
photo.style.color = '#f0f0f0';

// Target Individual Styles

Adding & Removing HTML Elements/Nodes

<!-- Here, we have a list and two buttons that remove and add to the list respectively.
This is done through the DOM and does not require a page refresh. -->

<ul id="myList">
   <li>Coffee</li>
   <li>Tea</li>
   <li>Milk</li>
</ul>

<p>Click the button to remove the first item from the list.</p>

<button onclick="removeNode()">Delete Top Item</button>

<input id="addNodeInput" value="">
<button onclick="addNode()">Add to List</button>
// You can also use event listeners, if you'd rather not use onclick.

// Connect our nodes to the JavaScript file.
const list = document.getElementById("myList");
const input = document.getElementById("addNodeInput");

// Remove Node Function.
function removeNode() {
  list.removeChild(list.childNodes[0]);
}
// Syntax: ParentNode.removeChild(childNode)


// Add Node Function
function addNode() {
   newItem = document.createElement("<li>") // Make New element.
   newItem.innerHTML = input.value // Assign the innerHTML of the new 
   item to the current value of the input tag.
   list.appendChild(newItem) // Add it to the list.
}

For a more in-depth rundown of all properties accessible through the DOM, please visit MDN. They have great documentation on nodes and the DOM API

DOM in Action !

This is Monumentous when used in conjunction with event listeners. Having the HTML document change upon user events is the definition of interaction. Let's simulate a real-world example of how you would use the DOM. Let's say you had some data you got from a server and wanted it displayed to your webpage. We'll style the page quickly and jump into how DOM enables us to accomplish this task.

<style>
    body { /* Flex your document body*/
       display: flex;
       justify-content: center;
       align-items: center;
       flex-direction: column;
    }
    #userContainer { /* Simple styling  */
       height: 500px; 
       width: 400px; 
       background-color: darkslategrey;
       display: flex; 
       justify-content: space-around;
       align-items: center;
       flex-direction: column;
       font-size: 24px;
       border-radius: 18px;
}
    #userContainer img { /* Make image a circle */
        border-radius: 50%;
    }
</style>
   <section id="userContainer">
        <img id="userPhoto" src="https://via.placeholder.com/150/09f/fff.png"></img>
        <p id="userName">name</p>
        <p id="userAge">age</p>
        <p id="userPhone">phone</p>
    </section> 
    <button id="button"> Fill Data </button>
// The Data you obtained
const userData = JSON.parse('{"name": "Michelle","age": 23,"photo":"https://2ithep36u4oimr3rn1a214zj-wpengine.netdna-ssl.com/wp-content/uploads/2018/09/alissa-davies-headshot-150x150.jpg","address": {"streetAddress": "88 8nd Street","city": "New York"},"phoneNumber": [{"type": "home","number": "347 123-5555"},{"type": "fax","number": "222 222-2222"}]}');

// Connect all your nodes/html elements that you want.
const userName = document.getElementById("userName")
const userPhoto = document.getElementById("userPhoto")
const userAge = document.getElementById("userAge")
const userPhone = document.getElementById("userPhone")

// Add Event Listener & assign each section to the desired property on the object.
document.getElementById("button").addEventListener("click", function(e) {
    userPhoto.src = userData["photo"]; // Assign every Section to respective data from objects.
    userName.innerText = userData["name"];
    userPhone.innerText = userData.phoneNumber[0].number;
    userAge.innerText = userData["age"];

})

Top comments (0)