Introduction to the DOM
What is the DOM?
DOM is an acronym for Document Object Model which refers to a logical representation of a document (HTML or XML) and it's contents on the web. The representation is a tree structure showing the document in the browser from the root to all branches.
The DOM represents the document as nodes and objects. Each node in the tree is an object representing a part of the document.
For example, this HTML document;
<title>Title of document</title>
<h1 style='color: red'>
The DOM for this would be;
All element, properties and events on HTML elements are organized into objects by the DOM.
How to Access the DOM
window.alert("Welcome to my page")
In this case, when the page is fetched, we get an alert box (the style of the alert box is dependent on the browser) showing the text - "Welcome to my page.".
Let's perfom some DOM manipulations.
The API provides us with different methods which we can use to manipulate the DOM. We'll look at few of those.
This method allows us to select an element from the DOM with the id attribute. The argument passed to the method is the id of the element. For example;
let elem = document.getElementById("header")
elem.align = "right"
elem.style.color = "pink"
The script is placed after the elements to ensure that all elements have loaded. You won't be able to manipulate an incomplete DOM right?
We then get our header element. We then manipulate the
align attribute by assigning a value of right. The
style attribute is also manipulated. Remember the the value of the style attribute comes in form of an object, i.e
<tag style="property: value; property2: value">
With this, we are also able to manipulate the color property of the element with CSS.
2. createElement(), createTextNode(), appendChild()
The first method allows us to create a new element by its tag name, the second allows us to create text (remember the text label in the DOM above?) while the third allows us to append an element to a previous element. Let's see this in practice by creating a new link.
<h1>A new element</h1>
let newElement = document.createElement("a")
let newElementText = document.createTextNode("Google")
newElement.href = "https://google.com"
newElement.style.fontSize = "30px"
After creating the element, we appending a text ('Google') to it, set the href, specify the font size and then append it to the body.
For more information on DOM, check out this documentations on MDN;
If you have any questions or contributions regarding this article, kindly reach Dillion Megida (@iamdillion) or visit us on twitter - @thewebfor5