JavaScript’s Document Object Model (DOM)

AJ Auntor

Developers can manipulate a website’s content, structure, and style using the Javascript DOM (Document Object Model). The purpose of this article is to introduce you to the DOM and teach you how to manipulate it using Javascript. In addition to providing basic DOM operations, this article is also a useful reference.

What is the DOM?

  • HTML elements as objects
  • Properties and events of the HTML elements
  • Methods to access the HTML elements

DOM Document

Finding HTML Elements

Get element by ID

var items = document.getElementsByClassName(‘list-items’);

We are going to save the variable header title with the element with the id of the header title.

Get elements by class name

var items = document.getElementsByClassName(‘list-items’);

We are getting all the items with class list-items and storing them in a variable.

Get element by tag name

var listItems = document.getElementsByTagName(‘li’);

Our HTML document contains all li elements, so we are going to get them as variables.

Queryselector

Get by id:

var header = document.querySelector(‘#header’)

Get by class:

var items = document.querySelector(‘.list-items’)

Get by tag:

var headings = document.querySelector(‘h1’);

Get more specific elements:

Selectors allow us to access more specific elements as well.

document.querySelector(“h1.heading”);

Here, we are looking for both a tag and its class simultaneously, and returning the first element that passes the CSS Selector.

Queryselectorall

var heading = document.querySelectorAll(‘h1.heading’);

An array of h1 tags with a heading class is created by putting them all in this example.

Changing HTML Elements

Changing the HTML

document.getElementById(“#header”).innerHTML = “Hello World!”;

Our example gets the element with the id header and sets the inner content to “Hello World””.

Another way to use InnerHTML is to put tags inside another tag.

document.getElementsByTagName("div").innerHTML = "<h1>Hello World!</h1>"

All already existing div tags are given a h1 tag.

Changing a value of an attribute

document.getElementsByTag(“img”).src = “test.jpg”;

Throughout this example, all *img/> tags point to test.jpg as the src.

Changing the style

document.getElementById(id).style.property = new style

We can now test the example by changing the bottom border of an element to a solid black line:

document.getElementsByTag(“h1”).style.borderBottom = “solid 3px #000”;

In place of the normal CSS property names, the CSS properties should be written in camelcase. For instance, borderBottom should be written instead of border-bottom.

Adding and deleting elements

Adding elements

var div = document.createElement(‘div’);

With this method, we simply create a div element using a tagname instead of passing it through the createElement() method. Afterward, we just need to insert it into our DOM document and give it some content.

var newContent = document.createTextNode("Hello World!"); 
div.appendChild(newContent);
document.body.insertBefore(div, currentDiv);

The content is created with a String parameter with the createTextNode() method and then an element is added before an existing div.

Deleting elements

var elem = document.querySelector('#header');
elem.parentNode.removeChild(elem);

The removeChild() method is used to delete an element.

Replace elements

var div = document.querySelector('#div');
var newDiv = document.createElement(‘div’);
newDiv.innerHTML = "Hello World2"
div.parentNode.replaceChild(newDiv, div);

The replaceChild() method is used to replace an element. There are two arguments in the above code, the first representing the new element and the second representing the element we wish to replace.

Directly writing HTML output into the output stream

document.write(“<h1>Hello World!</h1><p>This is a paragraph!</p>”);

JavaScript expressions, such as dates, can also be passed.

document.write(Date());

In addition to taking multiple arguments, the write() method will append them in order of occurrence to the document.

Event Handlers

mouse click

page load

mouse move

input field change

Assign Events

<h1 onclick=”this.innerHTML = ‘Hello!’”>Click me!</h1>

In the example given, the *h1/> text changes to “Hello””“Hello””“Hello”” as soon as you click the button.

As you can see in the next example, you can also call functions when an event occurs.

<h1 onclick=”changeText(this)”>Click me!</h1>

As soon as the button is clicked, we call the changeText() method with the element passed as an attribute.

Assigning the same events in JavaScript is also possible.

document.getElementById(“btn”).onclick = changeText();

Assign Events Listeners

document.getElementById(“btn”)addEventListener('click', runEvent);

Our btn element is simply associated with a clickevent that triggers the runEvent method when clicked.

An element can also have multiple events assigned to it:

document.getElementById(“btn”)addEventListener('mouseover', runEvent);

Node Relationships

There is only one node with no parent at the top of the graph, which is called the root. HTML documents usually have a root tag called *html/>, since it has no children and is the top tag of the document.

Navigating Between Nodes

parentNode

childNodes

firstChild

lastChild

nextSibling

The following example shows how you can get the parent element of an h1.

var parent = document.getElementById(“heading”).parentNode

Finally, my conclusion

Contact me via Linkedin or leave a comment below if you have any questions or feedback…Thanks!

Software Engineer (Front End)