Conquering The Front with the DOM API
Tags: dom, frontend, javascript, api
Published: 2020-02-20 17:16:18

<h1>The DOM.</h1>

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

<h1>But What Exactly is The DOM?</h1>
The DOM of a web app looks a little something like this...
<img src="https://lh3.googleusercontent.com/proxy/phn-sjhzDpHvj8MZUTwZpbPKR0Nbh0gDEHsGv-jTVQENBNCUzqYmVUe41LkETqbYmmP4wUrXSSGoKHjJG_ZTbyyFfxDjhfFz69FwHqN25M7X">

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 <a href="https://developer.mozilla.org/en-US/docs/Web/API/Node">nodes</a>. 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.

<h1>DOM starter kit</h1>

<h3>Targetting HTML Elements</h3>
```javascript
const container = document.querySelector('.sampleContainer'); 
// By Query
const name = document.getElementbyId('nameTag') 
// By ID Name
cont dob = document.getElementbyClassName('birthDiv')
// By Class Name
```

<h3>Manipulating your CSS with DOM</h3>
```javascript
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

```

<h3>Adding & Removing HTML Elements/Nodes</h3>
```html
<!-- 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.

```
```javascript
// 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 <b>all</b> properties accessible through the DOM, please visit MDN. They have great documentation on <a href="https://developer.mozilla.org/en-US/docs/Web/API/Node">nodes</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model">the DOM API</a>


<h1>DOM in Action !</h1>
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.

```html
<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>
```
```html
   <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>
```

```javascript
// 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"];
    
})

```