Manipulating DOM in JavaScript for beginners!
Tags: dom, javascript, tutorial, beginners
Published: 2020-04-02 17:27:20

#Hey! 👋 
<code><br></code>
#~Introduction
<p>
JavaScript has many abilities, one of the most useful of them is its ability to manipulate the DOM. Although what exactly is DOM and how we can change it?
</p>
#~What is the relation between DOM and webpage?
<p>
DOM stands for Document Object Model and it's a tree-like representation on a webpage or document. Let's say each node has a relationship with other nodes and that's depending on how they are arranged in the HTML document. Here's some simple HTML code:
</p>

```html
<html>
  <head>
    <meta charset = "utf-8">
    <title></title>
  </head>
  <body>
    <p> This is a paragraph </p>
    <ul>
      <li> Item 1 </li>
      <li> Item 2 </li>
    </ul>
  </body>
</html>
```
Here's what the above HTML looks like as a DOM tree:

![alt text](https://i.imgur.com/NoaU9WT.png)

We frequently referring to the parts of DOM with family relations, for example on the previous image the `<html>` tag is the parent of the `<head>` and the `<body>`. The `<li>` elements are the children of the `<ul>`element. Similarly, the `<li>`s are sibling elements.
<p>Your HTML it's a template which when a browser reads it, it creates the DOM.</p>
<p>When you are creating a site you might want to play with the DOM and be able to change in response to a user action.Every web framework provides a way to adjust the DOM but for start we'll stick with plain JavaScript or, even better, jQuery!</p>

#~STEP 1: Access the elements
<p>Here we have our sample HTML:</p>
```html
<h1 id = "header"> List King </h1>
<h2> Buy groceries </h2>
<ul>
  <li id = "one" class = "hot"> <em> fresh </em> figs </li>
  <li id = "two" class = "hot"> pine nuts </li>
  <li id = "three" class = "hot"> honey </li>
  <li id = "four" class = "hot"> balsamic vinegar </li> 
</ul>
```

####> Select an individual element node
```javascript
// Select the element and store it in a variable
var el = document.getElementById ("one"); // fresh figs

// querySelector() only returns the first match
var el = document.querySelector ("li.hot"); // fresh figs
```

####> Select multiple elements (nodelists)
```javascript
var elements = document.getElementsByClassName ("hot"); // find hot items

if (elements.length > 2) {  // If 3 or more are found
   var el = elements [2];   // Select the third one from the NodeList
   el.className = "cool";   // Change the value of its class atribute
}


var elements = document.getElementsByTagName ("li"); // Find li elements

if (elements.length > 0) {  // If 1 or more are found
   var el = elements [0];   // Select the first one using array syntax
   el.className = "cool";   // Change the value of its class attribute
}


// querySelectorAll() returns a NodeList
var els = document.querySelectorAll ("li.hot");
els [1].className = "cool"; // The second matching element is selected and changed
```

####> Traversing between Element Nodes
```javascript
// PREVIOUS & NEXT SIBLING

// Select the starting point and find its siblings
var startItem = document.getElementById ("two");
var prevItem = startItem.previousSibling;
var nextItem = startItem.nextSibling;


// FIRST & LAST CHILD

// Select the starting point and find its children
var startItem = document.getElementById ("two");
var firstItem = startItem.firstChild;
var lastItem = startItem.lastChild;

```

#~STEP 2: Work with those elements

####> Access & Update Text Nodes
<p>The text inside any element is stored inside a text node. To access it we use nodeValue property:</p>
```javascript
var itemTwo = document.getElementById ("two"); // Get second list item
var elText = itemTwo.firstChild.nodeValue;     // Get its text content
elText = elText.replace ("pine nuts", "kale"); // Change pine nuts to kale
itemTwo.firstChild.nodeValue = elText;         // Update the list item
```

####> Work with HTML content
- Using the `innerHTML` property, you can access and amend the contents of an element including any child elements.

```javascript
// Store the first item in a variable
var firstItem = document.getElementById ("one");
// Get the content of the first list item
var itemContent = firstItem.innerHTML;
// Update the content of the first list item so it is a link 
firstItem.innerHTML = '<a href="http://example.org">' + itemContent + '</a>';
```
- The `textContent` property allows you to collect or update just the text that is in the containing element (and its children).
```javascript
var firstItem = document.getElementById ("one"); // Find the first item
var  showTextContent = firstItem.textContent;    // Get value of textContent
var showInnerText = firstItem.innerText;         // Get value of innerText

// Show the content of these two properties at the end of the list
var msg = "<p>textContent: " + showTextContent + "</p>";
    msg += "<p>innerText: " + showInnerText + "</p>";
var el = document.getElementById ("scriptResults");
el.innerHTML = msg;

firstItem.textContent = "sourdough bread";      // Update the first list item 

```

- Adding elements to the DOM tree.

```javascript
// Create a new element and store it in a variable.
var newEl = document.createElement ("li");

// Create a text node and store it in a variable.
var newText = document.createTextNode ("tea");

// Attach the new text node to the new element.
newEl.appendChild (newText);

// Find the position where the new element should be added.
var position = document.getElementsByTagName ("ul")[0];

// Insert the new element into its position.
position.appendChild (newEl);
```

- Access or Update attribute values

```javascript
// Check and get value
var firstItem = document.getElementById ("one"); // Get first list item

if (firstItem.hasAttribute ("class")) {
  var attr = firstItem.getAttribute("class");
  
  // Add the value of attribute after the list
  var el = document.getElementById ("scriptResults");
  el.innerHTML = "<p> The first item has a class name: " + attr + "</p>";
}

// Create and change 
var fourthItem = document.getElementByTagName ("li").item (3); // Get the fourth item
el2.setAttribute ("class", "cool");                            // Add an attribute to it

// Remove
if (firstItem.hasAttribute ("class")) {
  firstItem.removeAttribute ("class");
}
```
<p> So you can create animations or effects just by adding or removing a class from an element. You can also add inline style:</p>

```javascript
// Adds the indicated style rule
div.style.color = "blue";

// Adds several style rules
div.style.cssText = "color: blue; background: white";

// Adds several style rules
div.setAttribute = ("style", "color: blue; background: white");
```
- Work with classes

```javascript
// Adds class "new" to your new div
div.classList.add ("new");

// Remove "new" class from div
div.classList.remove ("new");

// If div doesn't have class "active" then add it, or if
// it does, then remove it 
div.classList.toggle ("active");
```
####<p>__Important note:__ Usually your JavaScript, is run when the JS file is run, or when the script tag is encountered in the HTML. So if you are including your script tag at the top of your file, many of your methods will not work because the JS code will run before the elements you want to manipulate are created. A simple way to fix this problem is to include your script tags at the bottom of your html, so that it gets run after the elements/nodes are created.</p>
<p>That's it for now! I'll write another post about events too.</p>
<p>Thank you for your time reading this.</p>