JavaScript DOM

Tram Ho

JavaScript series

This chapter deals with the DOM – a way for JS to access elements on a web page.

A. DOM Introduction

1. Introduction

The DOM (Document Object Model) is an entity created by the browser when loading a web page. DOM consists of many elements, organized hierarchically in the form of trees, so called DOM trees. The DOM tree structure is quite similar to the element structure in HTML documents, the nested tags are modeled accordingly in the DOM.

The example starts with the following HTML.

When the HTML page above is loaded, a corresponding DOM object is created by the browser. The DOM object has a similar hierarchy as the elements in the above HTML page.

The browser will render the web page based on the DOM structure as above, and it also provides API for JS to access, thus JS has the ability to access the elements on the website (through the DOM) and create the Interactive.

Thanks to the DOM, JS can perform the following actions:

  • Read the data and change the elements
  • Change CSS style for element
  • Add, delete element or its properties
  • Event handling for elements

There are 3 types of DOM, including Core DOM, XML DOM and HTML DOM. This section only covers HTML DOM. And simply understood, the DOM is an interface, including standard objects, methods, … that is provided by the browser for languages ​​like JS to be accessible, thereby performing behaviors on the web.

B. DOM element

1. Finding elements

To perform actions on a web page, we first need to “select” the necessary elements, then perform actions such as reading, changing content, … on the selected element.

For optimal performance, it is not advisable to access the DOM too much, because the manipulation of the DOM is quite slow. Therefore, when “selecting” an element that needs to perform many actions, it should be stored in a variable. For example.

The document object provides many methods to perform “selecting” elements:

  • Search by id, class or tag
  • Search with string CSS selector
  • Find elements that belong to existing collections

Note, this is a fairly basic error. The methods used to select an element can select one or more elements. Note that methods that select multiple elements will have an additional s in the method name, for example.

Search by ID, class, tag name

Returns an element with a specified id, otherwise it returns null.

Search by class name or tag name. Unlike searching by ID that only returns an element, these two methods return an array (actually just a bit like an array rather than an array). Therefore, being able to access each specific element is similar to accessing the elements of the array.

Search by CSS selector string

Returns the first element found, which is a Node object that matches the sequence selector. If not found method returns null.

Returns a NodeList of found elements. NodeList structure uses similar arrays.

The above two methods throw SYNTAX_ERR error if the selector string is wrong.

Search in available collections

In the DOM there are a number of built-in collections, which contain groups of commonly used elements such as forms, links, images, … throughout the document.

HTMLcollection is quite similar to NodeList, both of which are used similarly to arrays. This section will be discussed in more detail in the following section.

2. Access elements

With the DOM, you can access any element on a web page, to read data and change its content, properties or styles.

Element content

To access the element text content, use the innerHTML property. The attribute contains the content string (does not contain the code tag) and can assign a new value.

There are elements without content, such as img, …

There are also two similar innerText and textContent properties.

HTML attributes

Because the DOM models elements into objects, HTML attributes are also coded into properties of the DOM object.

Note, in HTML, attributes are attributes, but in DOM, they are called properties. Attribute is understood as additional information for element, while property emphasizes the property of element when in object form.

Property name is similar to attribute name so it’s easy to get used to.

To access the property, you need to call the object name and dot, followed by the property name as above.

There are also two methods, getAttribute() and setAttribute() , which help read and change HTML attributes (again, HTML attributes rather than CSS properties).

CSS style

Styles are given in an object attribute by the DOM, named style. Therefore, we need to call the property in the property as in the example code below.

CSS properties use hyphens, but in JS it is changed back to camelCase. And the shorthand properties are written in the same string format in CSS as above.

3. Traversing

Because the elements in the DOM are hierarchically organized and related to each other, from an element we can find related elements based on the relationship between them.

From here I will use the word node to call the element. Node will be discussed later, but basically every element is a node.

The DOM provides us with several properties to search for nodes related to the selected node.

These properties return a reference to another related node object.

C. DOM node

1. Node interface

Node is the most basic object in DOM, everything in document, element is also node. Node is essentially an interface, every object in the DOM implements this interface, so every object in the DOM can be considered as a node. Therefore, they have common properties and methods.

Node can be element, can be attribute (HTML attribute), text (text node), comment (comment node). There are also many other types such as entity, notation, document type, … but we do not need to care too much.

Node members

The nodeType property returns a number, representing the node type. For example, element node (1), attribute node (2), text node (3), comment node (8), etc.

An element is actually created by multiple nodes, so when creating the element, it is necessary to create multiple child nodes and merge them into a complete element. For example an a tag as follows.

It will consist of 3 basic nodes.

Each node will have an attribute called nodeValue , containing the value of the node.

Root nodes

Object document contains two nodes especially document.head , document.body and document.documentElement . JS can access these two nodes, thereby accessing the entire object on the site.

2. Create element

To create an element in the DOM, there are 4 steps:

  • Create node element
  • Create text nodes, child attribute nodes
  • Add the above child nodes to the element node
  • Add element node to a certain position

For example, to add the link element as above, we use the following code.

The above code only creates a link, but it doesn’t appear yet. You need to add it to an element with the following two methods.

In addition to creating the element with each child node, we can do it using some of the available methods of the element. For example, instead of creating node tr and td to insert rows into a table, just select that table and then call its insertRow() method.

However, this method requires you to remember the methods specific to each particular element type, so it is seldom used.

3. Remove, replace element

Remove method

Use the remove() method of the element to delete itself.

RemoveChild method

Sometimes because the browser doesn’t support the remove() method may not work. Then, we can delete it indirectly through its parentNode, and delete it using the removeChild() method.

ReplaceChild method

Use the replaceChild method to replace a node with a new node.

The above method takes two params, the first param is the new element, param 2 is the old one that needs replacing.

4. HTMLcollection & NodeList

HTMLcollection & NodeList

As mentioned above, some of the methods used to find multiple elements like getElementsByTagName() , getElementsByClassName() , querySelectorAll() return structures that are like arrays, but not arrays, are HTMLcollection and NodeList.

As follows:

  • getElementsByTagName() returns HTMLcollection
  • getElementsByClassName() , querySelectorAll() return NodeList
  • The childNodes property of any node is also a NodeList

Compare to array

Although HTMLcollection and NodeList are accessible via an index similar to an array, with a length attribute to get lengths, they are actually not arrays.

They do not have array methods like pop() , push() , shift() , etc.

HTMLcollection vs NodeList

HTMLcollection only contains node elements, while NodeList contains all types of nodes.

HTMLcollection is accessible only by name, id or index, while NodeList is only accessible via index.

Above are the two differences between HTMLcollection and NodeList.

Built in HTMLcollections

There are several built-in HTMLcollection as follows.

For example, get HTMLcollection document.forms . Because HTMLcollection is accessible via both name and index, we can retrieve any form on the web page.

D. DOM event

1. Overview

We are familiar with the event in the previous chapters. The event is basically an event that occurs at a certain time, or satisfies certain conditions, and can be assigned a code to it. When the event happens (fire – shoots out), the code attached to the event will be executed.

In an event HTML is an element’s property, whose value is the JS code to execute when the event occurs.

Instead of attaching the event directly in the HTML document when writing the code, we can attach or modify the event right at the runtime through the DOM.

The above example defines the closeApp() function, and uses the DOM to attach it to the onclick event of the element (whose id is closeButton). When clicking on this element, the onclick event is fired, and the closeApp() function is executed.

2. Event listener

The event listener listens for specific events of an element, and when that event occurs, it calls a specified method. The methods attached to the event listener are called event handlers.

The event listener can listen for events from every DOM object, not just visual elements on the web page.

Benefits of event listener:

  • Easy to add and remove: Normally, event handlers have to change the HTML code to do this, but with the event listener, it can be done at runtime.
  • There may be multiple event handlers: The normal event has only one event handler, but with the event listener it is possible to add multiple event handlers for one event.
  • Separating JS code from HTML: Organizing source code better, and not depending on the inherent and constant HTML document.

Add event listener

To add an event listener for a specific event of the selected element, call the addEventListener() method for that event. It is possible to add multiple event handlers at the same time, or multiple event types to the same element.

Method of getting two required arguments:

  • Param 1: sequence of event names, corresponding to events in HTML but without the word “on” at the beginning.
  • Param 2: The function will run when the event occurs.

There is also an optional param 3 that is a boolean useCapture (default is false). If this parameter is true, then the event will use capturing, otherwise bubbling.

  • Bubbling: going from the selected element to the ancestors. For example, clicking on the button then the onclick of the button is done first, then the parent’s onclick and up again.
  • Capturing: In contrast to bubbling, goes from the ancestor element first to the last current element.

The concept is called event propagation.

Remove event listener

Use delete event listener for element.

Note that the event name and the name of the called function must be the same as when adding, and only remove for the event handler of function call (anonymous function will not work).

IE 8 support

The IE 8 version of the browser does not support the above two methods, so it should be replaced by attachEvent() and detachEvent() .

You can use the following code to check, if the addEventListener() method is used, if not then use attachEvent() instead.

The remove() method is similar.

Share the news now

Source : Viblo