DOM (Document Object Model)

Francabel
3 min readJun 3, 2020

According to MDN, DOM connects web pages to scripts by representing the structure of a document, such as the HTML representing a web page — in memory. In other words, DOM is an application programming interface which allows users interact with web pages. Also, it allows you change the page’s content without changing HTML.

How do you interact with the Page?

Let’s begin from how to choose the node or element you want.

To interact with web pages, we have to get the node of each element. The following is the example of how to get the nodes and modify them.

picture 2
picture 3

getElementbyID

If we like to get the parent (myId) and style it, we can use getElementbyID and then change its style. You can see the red background on the picture 3.

getElementbyClassName(return array-like list)

getElementByTagName(return array-like list)

getElementbyClassName and getElementByTagName will return an array-like list. So, if you like to use it to select your element, you need to add the element’s index as shown on the picture 2.

guerySelector

It is really powerful that you can choose the element using CSS-selector way. For example, if you want to choose myId, you just need to write const myId = document.querySelector(“#myId”).

classList.add()

classList.remove()

You can edit (add or remove) your class name by classList.

classList.toggle()

Toggle means change the status of your element. For example, there is a button. If you don’t press, the element’s background-color is black. If you press it, its background color becomes red.

innerHTML() and innerText

What is the difference of these two function? innerText is only for the text of your content, however, innerHTML includes the tag of your content.

appendChild()

From the above picture, you might see the last line of appendChild(). What does that mean? It means that you can put something after the element you specify. So in this example, I would like to add par2 after the first element under the parent element.

DOM allows you to have more interaction with a web application. Learning DOM is the very first step for build a interactive web. The next article will focus on how the web responses the event.

Thank you for your time. If you like my article, please share your comment below and email me at garnett284@gmail.com.

--

--

Francabel

從業務轉換跑道,目前正朝著前端工程師邁進,寫code是生活,是工作,也是態度。轉職是一段旅行,享受旅行的過程,並指引到夢想處