Javascript is a programming language commonly used in Browsers, and thus play quite the role in web applications: Javascript interacts with HTML documents and specific syntax involved, to create what we call ‘the magic’ of websites. And in order to interact with these HTML cards, Javascript will first have to go through the Document Object Model or DOM.

In this article, we will learn what DOM is, as well as DOM methods using JavaScript.

1. What is DOM?

DOM is short for Document Object Model, particularly for HTML documents. In each HTML card, there are properties and parent-child segmentations with others. These segmentations and properties in an HTML card is called a selector, and DOM will be responsible for tasks like changing card properties, changing HTML structure… DOM is also used for extracting documents in HTML and XML formats – creating trees of objects, which are often independent from the operation system, and utilizes object-oriented programming to describe documents.

For a clear understanding of DOM, refer to the below illustration.

We can see that all HTML cards will be managed in document, with the highest being html, followed by the branches body and head: Head includes cards like styletitle, and so on, while body contains myriads of other cards. Therefore, in order to interact with these HTML cards using Javascript we first have to go through document. Example:

The example includes a javascript processing code as below:

The code means to find card with id=”main-content” then attach the HTML inside the card with “Welcome to the online programming learning website codelearn.io “.

With DOM, JavaScript will have all the necessary capabilities for creating dynamic HTML:

  • JavaScript can change all in-page HTML elements.
  • JavaScript can change all in-page HTML properties.
  • JavaScript can change all in-page CSS styles.
  • JavaScript can eliminate all HTML elements and current properties.
  • JavaScript can add new HTML elements and properties.
  • JavaScript react to all in-page HTML events.
  • JavaScript can create new in-page HTML events.
2. What is HTML DOM?

HTML DOM is an object model and programming interface for HTML, with:

  • HTML elements as objects.
  • Properties for all HTML elements.
  • Methods for all HTML elements.
  • Events for all HTML elements.

HTML DOM is a standard that allows all operations on a website, including getting, changing, adding, or deleting all HTML elements.

3. DOM Tree of Objects

3.1. Nodes

In HTML DOM, the DOM Tree structure means that each element is regarded as a node, represented on a tree. There are different kinds of nodes for different elements, with the major ones being: document node, element node, and text node.

  • Document node: The HTML document itself, often represented by the <html> card.
  • Element node: Represents on HTML element.
  • Text node: each text snippet in an HTML document, inside an HTML card, is a text node. It can be a website name in the <title> card, the heading name in the <h1> card, or a paragraph in the <p> card.
  • There are also the attribute node and the comment node.

3.2. Node relationships

  • The document node is always the first node.
  • All non-document nodes only have one parent node.
  • A node can have none or many child nodes.
  • Nodes with the same parent are called siblings.
  • Among child nodes, the first one is called firstChild, and the las one is the lastChild.

In the DOM Tree of Objects below, we can see that:

  • The document node is <html>.
  • <head> and <body> are siblings, as they both have <html> as parent.
  • <body> has three children, <h1> being the firstChild and the second <p> being the lastChild.
  • The element node <a> has 2 children, including 1 text node and 1 attribute node.
4. How to use DOM

DOM can give you this “world-changing” power, seeing that all contents can be dynamically updated via DOM’s many attributes and methods. Everything can be done, from changing text formats, contents, to changing node structure and adding new nodes. Therefore, it is important to understand how to use DOM and the meaning of each attribute and method, in order to create good content.

4.1. Common Attributes and Methods

Attributes

  • id: Identity – exclusive to each element, and thus is often used to directly and quickly access DOM.
  • className: also used for direct access like in id, but 1 className can be used for many elements.
  • tagName: Name of HTML card.
  • innerHTML: Return to HTML code of the current element. This HTML code will be a sequence of characters with all inner elements, including element nodes and text nodes.
  • outerHTML: Return to HTML code of the current element. In other words, outerHTML = tagName + innerHTML.
  • textContent: Return to 1 sequence that includes the content of all text nodes inside the current element.
  • attributes: A set of attributes like id, name, class, href, title…
  • style: A set of styles for current elements.
  • value: Turn the value of a selected element into a variable.
  • Lấy giá trị của thành phần được chọn thành một biến.

4.2. Methods

  • getElementById(id): Refer to one single node with id attribute similar to the id required.
  • getElementsByTagName(tagname): Refer to all nodes with tagName attributes similar to the required card. Or in other words, searching for all DOM elements with the same type of HTML cards. To access all cards inside the HTML document, use document.getElementsByTagName (‘*’).
  • getElementsByName(name): Refer to all nodes with name attribute similar to the name required.
  • getAttribute(attributeName): Get the value of an attribute.
  • setAttribute(attributeName, value): Reset the value of an attribute.
  • appendChild(node): Add a child node to the current node.
  • removeChild(node): Remove a child node to the current node.

On the other hand, all DOM attributes are nodes on the DOM Tree of Objects, and therefore obtain relationship attributes to represent their dependence among on another. Due to these relation attributes, we can indirectly access DOM via attribute relationships and positions.

4.3. Relationship attributes

  • parentNode
  • childNodes
  • firstChild
  • lastChild
  • nextSibling
  • previousSibling

The full list can be viewed at W3SCHOOLS

5. DOM access

5.1. Indirect access

Each node on the DOM Tree of Objects has 6 relationship attributes, from which you can access indirectly per their positions:

  • Node.parentNode: Refer to the single parent Node of the current Node. This exclusivity means that to find the original of a node, you will have to connect attributes more than once, for example, Node.parentNode.parentNode.
  • Node.childNodes: Refer to direct childNodes of the current node, which results in a set of nodes. It is important to note that childNodes cannot be identified by node type, and the result returned may include many different types of node.
  • Node.firstChild: Refer to the firstChild node of the current node, similar to calling Node.childNodes[0].
  • Node.lastChild: Refer to the last Child node of the current node, similar to calling i Node.childNodes[Element.childNodes.length-1].
  • Node.nextSibling: Refer to a siblingNode directly next to the current node.
  • Node.previousSibling: Refer to a siblingNode directly previous to the current node.

5.2. Direct access

Direct access will be much faster and simpler, as you do not need to know about node relationships and positions. There are 3 methods for directly access, supported in all browsers:

  • document.getElementById(‘required_id)
  • document.getElementsByTagName(‘div’)
  • document.getElementsByName(‘required_name’)
6. Creating, adding, removing, and replacing HTML elements with JS

6.1. Creating a HTML element

To create a new HTML element, we can:

  • document.createElement(tag_name): Create an element with tag_name as a, p, div,…
  • element.cloneNode(): Create an element by cloning another element.
  • document.createTextNode(text): Create a text node.

The above example will create a text node, but this will not yet be displayed until you attach it to the HTML document. It will then become child to some parent node, and there are several ways to attach this new element from Javascript into DOM HTML.

  • element.appendChild(newNode): Add the newNode element into the set element, it will become the lastChild .
  • element.insertBefore(newNode, node2): Insert the newNode element before  node2.
  • element.replaceChild(newNode, oldNode): Replace the oldNode with the newNode element.

The following example will create a p (paragraph) element, then insert it to the existing div element in DOM HTML.

6.2. Removing a HTML element

To remove a HTML element, select the parent element then use removeChild(node)

The above example will remove the p1 element.

You can also try getting the parentNode by its properties to skip having to find it in DOM: child.parentNode.removeChild(child);

6.3. Replacing a HTML element

To replace an element with another, use element.replaceChild(newNode, oldNode). Here, element represents the parent node.

7. Conclusion

Via the article, we had learned basic DOM concepts and methods. While this is mostly on the surface, we can still see the importance and prowess of DOM. Please leave constructive comments so that we can further improve in the future. Thank you!

Khoaa
CodeLearn

Related posts: