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?
A website consists of HTML and CSS at its most basic level. Document Object Model (DOM) is what the browser creates as a representation of the document. The documents in this section enable Javascript to manipulate a website’s elements and styles. This is achieved through the use of objects in a tree model.
- HTML elements as objects
- Properties and events of the HTML elements
- Methods to access the HTML elements
DOM Document
All other objects on your website are owned by the DOM Document. This means you must always start at the document in order to access any object on your webpage. As well as properties and methods that enable us to access and modify our website, it contains many other useful properties and methods.
Finding HTML Elements
As we now know what DOM documents are, we can begin to construct our first HTML elements. You can use the Javascript DOM to accomplish this in many different ways. Here are some of the most common:
Get element by ID
A single element is retrieved by its id using the getElementById() method. The following example shows how to retrieve a single element:
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
The getElementsByClassName() method returns a list of all the elements found in an object using an array.
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
By using the getElementsByTagName() method, we can also get our elements 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
When a CSS selector is specified, the querySelector() method returns the first matching element. Thus, you can get elements according to their ids, classes, tags, and all other valid CSS selectors. These are only a few of the most commonly used selectors.
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
With querySelectorAll(), all elements that fit the CSS Selector are returned instead of only those that match querySelector().
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
By changing the HTML element’s properties, we are able to modify its content and appearance.
Changing the HTML
Changes can be made to the content of an HTML element by using the innerHTML property.
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
It is also possible to modify the value of an attribute using the DOM.
document.getElementsByTag(“img”).src = “test.jpg”;
Throughout this example, all *img/> tags point to test.jpg as the src.
Changing the style
Our HTML elements’ style property needs to be changed in order to change their style. We can do this with the following example syntax:
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
The next step will be to learn how we can add new elements and delete existing ones.
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
Let’s examine how we can replace items now.
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
The write() method also allows us to write HTML expressions and Javascript directly into the HTML 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
HTML DOM events can also be reacted to by Javascript. To summarize them, here are a few examples:
mouse click
page load
mouse move
input field change
Assign Events
Using the attributes on your tags, you can create events directly in HTML code. For example, here is an example of an onclick event:
<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
In the next section, we’ll take a look at assigning event listeners to HTML elements.
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
A DOM Document has a hierarchical relationship between its nodes. A tree-like structure can be seen in this arrangement. A node’s relationship to its child, siblings, and parent is often described using the terms parent, sibling, and child.
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
Nodes can be navigated using these properties:
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
Congratulations on making it all the way to the end! I hope this article helped you better understand how to manipulate elements on your website using Javascript DOM.
Contact me via Linkedin or leave a comment below if you have any questions or feedback…Thanks!