Understanding the JavaScript DOM Manipulations

8063 VIEWS

·

DOM stands for document object model and it can be represented as a tree of elements created by the browser. DOM manipulation is the interaction of the JavaScript DOM API to modify or change the HTML document. With DOM manipulation, you can create, modify, style, or delete elements without a refresh. It also promotes user interactivity with browsers.

You can use different programming languages to manipulate the DOM. This particular article will focus on how to use the JavaScript language to manipulate DOM.

Let’s Get Started with JavaScript DOM Manipulations

What is DOM? DOM stands for document object model. It is represented hierarchically using a tree of nodes or elements by the browser. Javascript can manipulate these nodes present on the DOM. Javascript is able to do this because the DOM is object oriented, meaning it has a set of properties and methods that you can change, add or create. 

The browser is made up of the window object, which has the document object as the first node. The root element, which is the HTML element, is the next node. The HTML element is further divided into the head tag and body tag. The head tag has children elements such as the meta tags and title tags. The body also has children elements such as header tags and link tags.

https://www.w3.org/TR/WD-DOM/introduction.html for more information on DOM.

JavaScript DOM Elements

You can access these elements from the DOM and manipulate them using JavaScript to give a desired result.

Selecting Elements from the DOM

You can use different JavaScript DOM selectors to select various elements. These DOM selectors are document object methods; they pull the element that you need to access. You can change, alter, replace or style the accessed elements based on your preference.

Some JavaScript DOM selectors are:

  1. getElementById() – Here, selection is based on the id name. This selector returns only the first matched element.
  2. getElementByClassName() – This method returns all elements that match a specified class name.
  3. getElementByTagName() – This method returns all the elements that match a specific tag name.
  4. querySelector() – This method returns the first element that matches a specific CSS selector in the document.
  5. querySelectorAll() – It returns all elements that match the specified css selector in the document.

Let’s get this more exciting by trying some examples:

<div id = “test”> Hello world </div>
<script >
console.log(document.getElementById("test"));
</script>

In this example, we used the getElementById method to access a div with the ID name ‘test’ and log it into the console. You can style this element based on your preference using the style property.

 //styling the accessed element
document.getElementById('test').style.color = "pink";

This automatically changes the text color to pink.

What if you want to change not just the text color, but the text content? You can use various properties to do this, here is one:

//changing the text content
document.getElementById("test").textContent=" Have a great day!";

We accessed the element in the examples above by using the getElementById() method, now let’s change the background color, using the querySelector() method:

document.querySelector("div").style.backgroundColor='blue';

For more information on DOM selectors: https://developer.mozilla.org/en-US/docs/Web/API/Document_object_model/Locating_DOM_elements_using_selectors 

Traversing the DOM

The DOM tree is a collection of nodes and elements, having a parent-child or a sibling relationship. Traversing basically means moving up and down the DOM and accessing and altering either parent or child of specific nodes or elements.

Properties used in traversing the DOM are the previous sibling, next sibling, child nodes, first child, and last child.

Let’s work with an example:

<div>
    <ul class="list">
        <li  class="list-item">first child</li>
        <li class="list-item">second child</li>
    </ul>
</div>
script>
  let list = document.querySelector("ul");
  let parentElement =list.parentNode;
  console.log(parentElement);
</script>

The console will return the div tag, because it is the parent element of the ul. We can add the style property to the parent element.

list.parentNode.style.color='yellow';

Check out this, for more information on traversing the DOM: https://www.w3.org/wiki/Traversing_the_DOM

Creating and Removing Elements from the DOM

You can create elements and insert them into the DOM, as well as remove them from the DOM. How about trying out a simple example?

In this example, the ul has two list items, we will create another list item and insert it into the ul.

<div>
    <ul class="list">
        <li  class="list-item">first child</li>
        <li class="list-item">second child</li>
    </ul>
</div>
<script>
//create an element
let li = document.createElement("li");
//give it an id 
li.id = "item";
//set the attribute
li.setAttribute('title','new div');
//create a textNode
let textNode = document.createTextNode('third child');
//append textNode to li
li. appendChild(textNode);
//append li to ul 
document.querySelector('ul').appendChild(li);
</script>

This creates a new list item and throws it into the DOM.

Now that you know how to create list items, it is equally important to know how to remove elements. You can remove elements using different methods. Here is one:

//this will remove the first li element
let li = document.querySelectorAll('li');
li[0].remove();

This will remove the first li element.

 You can also remove all the list items. Here is an example below:

//this will remove all li elements
let li = document.querySelectorAll('li');
let ul = document.querySelector('ul');
ul.remove(li);

Conclusion

CSS lets us style a page, JavaScript allows us to change the behavior of the page, while DOM glues everything together by giving us access to the elements we want to work on. Thank you for reading. Happy coding.


Faith Njah is a front-end developer, with experience in building dynamic websites using web technologies like HTML, CSS, JavaScript, and A-frame VR. She is also passionate about learning.


Discussion

Leave a Comment

Your email address will not be published. Required fields are marked *

Menu
Skip to toolbar