DEV Community

Cover image for Manipulating DOM in JavaScript for beginners!
George Ilias
George Ilias

Posted on

Manipulating DOM in JavaScript for beginners!

Hey! πŸ‘‹


~Introduction

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?

~What is the relation between DOM and webpage?

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:

<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

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.

Your HTML it's a template which when a browser reads it, it creates the DOM.

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!

~STEP 1: Access the elements

Here we have our sample 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

// 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)

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

// 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

The text inside any element is stored inside a text node. To access it we use nodeValue property:

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.
// 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).
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.
// 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
// 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");
}

So you can create animations or effects just by adding or removing a class from an element. You can also add inline style:

// 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
// 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");




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.

That's it for now! I'll write another post about events too.

Thank you for your time reading this.

Top comments (0)