搜尋
首頁web前端js教程探索前端開發的基本 DOM 方法

由 Chimezie Innocent 撰寫✏️

在使用者瀏覽自己喜歡的線上商店或其他網站時,流暢的網頁可以根據使用者的操作動態運行,這是提供最佳體驗的關鍵。但是,什麼是用戶按需存取所有這些重要內容的基礎呢?

使用 HTML 編寫的文字檔案指示 Web 瀏覽器如何顯示使用者期望的動態內容,而存取和修改網頁內容的方式稱為文件物件模型或 DOM:

Exploring essential DOM methods for frontend development

DOM 彌合了 HTML 結構和 JavaScript 之間的差距,讓您動態修改網頁並與之互動。可以採用一些方法來修改 DOM 並與 DOM 交互,這些方法稱為 DOM 方法。 DOM 方法對於前端開發至關重要,因為它們可以實現與網頁的動態交互,從而為使用者提供更流暢的網頁瀏覽體驗。

掌握本文中提供的特定 DOM 方法將使您能夠打造豐富的使用者體驗。 DOM 方法有很多,但本文將只探討前端開發的基本 DOM 方法及其相關用例。此外,我在文章底部提供了一個表格,其中包含此處介紹的 DOM 方法的名稱、語法和功能。

一些 DOM 方法用於類似的任務,因此將它們分組在一起將有助於我們更好地理解它們的作用。我們還將研究這些 DOM 方法的用例,以了解如何最好地使用它們。

探索查詢或選擇 DOM 方法

這些 DOM 方法用於尋找和存取 DOM 樹或 HTML 中的特定元素。

查詢選擇器()

查詢方法清單中第一個是querySelector。此方法選擇與指定 CSS 選擇器或選擇器組相符的第一個元素。如果未找到符合項,則傳回 null。它使用所有有效的 CSS 選擇器來尋找元素。

讓我們來看下面的範例:

// index.html



  
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
  
  
    <h1 id="Hello-World">Hello World</h1>
    <div class="first">
      <p>This is a paragraph</p>
    </div>
    <div class="first">
      <p>This is a paragraph</p>
    </div>
    <div id="second">
      <p>Another paragraph</p>
    </div>
  
  <script src="/script.js"></script>

上面的程式碼渲染了一個帶有 h1 標籤、三個 div 元素和三個段落 p 標籤的頁面。我們將在大多數範例用例中使用此範例程式碼。

如果您注意到,其中兩個 div 具有類別屬性和相同的類別名,而另一個具有 ID 屬性。

如我們先前所解釋的,querySelector 會找出第一個與 CSS 選擇器相符的元素。這意味著我們可以利用類別、ID 甚至它們的標籤來透過此方法尋找元素。見下圖:

// script.js

const element = document.querySelector("h1").textContent;
console.log(element);

const element2 = document.querySelector(".first").innerHTML;
console.log(element2);

const element3 = document.querySelector("#second").innerHTML;
console.log(element3);

從上面的內容中,我們使用標籤名稱、類別和 ID 屬性來尋找元素。控制台上的結果輸出將是:Exploring essential DOM methods for frontend development

我們只得到了“Hello World”,因為我們正在記錄文字內容,如上所示,同時取得 div 的完整innerHTML。另外,我們有兩個具有相同類別名稱的 div,但控制台日誌中只顯示一個。這是因為 querySelector 僅檢索具有指定 CSS 選擇器的第一個元素。

還有一件事:我們可以更進一步,透過 querySelector 方法使用複雜的選擇器。由於所有 CSS 選擇器字串都是有效的,我們甚至可以使用否定選擇器。請參閱以下用例,以了解如何對 HTML 進行細微更改:

// index.html



  
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
  
  
    <h1 id="Hello-World">Hello World</h1>

    <div class="first">
      <p class="paragraph main">This is a paragraph</p>
    </div>
    <div class="first">
      <p class="paragraph">This is a second paragraph</p>
    </div>
    <div id="second">
      <p>Another paragraph</p>
    </div>
  
  <script src="/script.js"></script>

我們在第一個 div 中的 p 標籤中新增了一個 class 屬性段落,並在第一個 p 標籤中新增了一個 class main :

// script.js

const element = document.querySelector("div p").textContent;
console.log(element);

const element2 = document.querySelector("div.first .paragraph:not(.main)").textContent;
console.log(element2);

這是結果輸出: Exploring essential DOM methods for frontend development 由於我們可以透過先指定父元素然後深入DOM 層次結構來存取DOM 子元素,所以我們可以使用div p 存取第一段,其中div 是父節點p 是子節點。

此外,在第二個查詢中,我們這次得到了第二段而不是第一段。這是因為在我們的 CSS 選擇器中,我們取得的第一個元素不是主類別。

查詢選擇器全部()

查詢方法清單中的第二個是querySelectorAll。此 DOM 方法取得或傳回靜態 NodeList,其中包含與指定選擇器或選擇器群組相符的所有 DOM 元素。此方法對於選擇或查詢同一類別的多個元素非常有用。

注意:NodeList 只是節點的集合。 querySelectorAll() 傳回靜態 NodeList,這表示 DOM 中的任何變更都不會影響集合的內容。

看下面的用例:

// script.js

const element = document.querySelectorAll("div");
console.log(element);

const element2 = document.querySelectorAll(".first");
console.log(element2);

console.log(typeof element)

As explained, querySelectorAll() will return a node list of all the divs. Additionally, we are checking what type of primitive the returned element is, and as expected, when we console log the element’s type, it returns an object: Exploring essential DOM methods for frontend development After getting the node list, we can loop through the elements using any of the loops like map, forEach, and so on to make whatever changes we want:

// script.js

const element = document.querySelectorAll(".first");
element.forEach(paragraph => paragraph.innerHTML="This is great")

The below image shows how we are just changing the text content of the p tags — nothing fancy: Exploring essential DOM methods for frontend development  

getElementById()

This DOM method retrieves the element with a specific ID. This is best used when you need to select a single unique element quickly since IDs are required to be unique if specified. Unlike the querySelector and querySelectorAll, you don’t need to add the # selector when using the getElementById() method:

// script.js

const element = document.getElementById("second").textContent;
console.log(element);

This will return the element with the ID specified. The output of the console will be: Exploring essential DOM methods for frontend development  

getElementsByClassName()

This DOM method returns an array-like object containing all the child elements with the specified class names. Each element in the object can be accessed by its index:

// script.js

const element = document.getElementsByClassName("first");
console.log(element)

This will return all elements with the class name first. The output on the console will be: Exploring essential DOM methods for frontend development   Similar to the querySelectorAll, this method is useful when you want to apply changes to multiple elements with the same class name. Let’s change the color:

// script.js

const element = document.getElementsByClassName("first");
Array.from(element).map((el) => (el.style.color = "red"));

In your webpage, the output becomes: Exploring essential DOM methods for frontend development  

getElementsByTagName()

This method is ideal for operations on a specific element as it returns an HTML collection of elements with specified tag names.

// script.js

const element = document.getElementsByTagName("p");
console.log(element)

On the console, the output will be logged as the following: Exploring essential DOM methods for frontend development   Also, since element returns an array-like object, you can perform multiple changes at once by using any of the loop operators. Each element can also be accessed by its index, which starts at 0.

// script.js

const element = document.getElementsByTagName("p");
Array.from(element).map((el) => (el.style.color = "red"));

const last_item = element[2].textContent
console.log(last_item); // Another paragraph

The output results in the below: Exploring essential DOM methods for frontend development  

Methods for getting and setting content

These DOM methods accomplish two uses — they help us retrieve information from elements and allow us set the content dynamically.

innerHTML

This method retrieves and sets the HTML content of an element. It specifically retrieves the HTML inside the element, including text and tags, and can also replace the HTML.

Let’s employ one h1 tag for this use case:


  
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
  
  
    <h1 id="Hello-World">Hello World</h1>
  
  <script src="/script.js"></script>

Next, we’ll write the following in our script:

// script.js

const element = document.getElementById("h1");
console.log(element.innerHTML);

element.innerHTML = "<h5 id="New-Content">New Content</h5>";
console.log(element.innerHTML);

In our console, we will get the “Hello World” since we are retrieving the HTML content. Next, we’ll change the HTML tag to an h5 tag with new content. When we retrieve the new element, we see it has changed: Exploring essential DOM methods for frontend development  

textContent

As the name implies, this method gets and sets the text content of the node and its descendants. The best use case for this method is for getting and replacing the text content of an element without the HTML tags.

Let’s look at the use case below:


  
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
  
  
    <h1 id="This-is-span-some-span-text">This is <span>some</span> text!</h1>
  
  <script src="/script.js"></script>

The above code renders a h1 tag with the text: “This is some text”

// script.js

const element = document.getElementById("h1");
console.log(element.textContent);

// change the content
element.textContent = "This is a new text";
console.log(element.textContent);

In our script.js file, we use the query method getElementById to retrieve the h1 tag. Next, we use the textContent method to change the content of our h1 text to “This is a new text”.

The output becomes the following: Exploring essential DOM methods for frontend development  

Attribute and style manipulation methods

This group includes methods that allow you to modify DOM elements' attributes, properties, and content.

add

This method adds a specified class to an element’s class list. You can use the add method to toggle CSS classes to change an element’s appearance.

In our HTML, let’s add a style:


  
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
      .newClass {
        color: green;
      }
    </style>
  
  
    <h1 id="This-is-span-some-span-text">This is <span>some</span> text!</h1>
  
  <script src="/script.js"></script>

The result is just a class with a green text color. Nothing happens when we load our page because we haven’t assigned the style to any element yet. Next, let’s assign the style to our h1 element using the add method:

// script.js

let element = document.getElementById('h1');
element.classList.add('newClass');

Reload your page and you will see that the header’s color has changed: Exploring essential DOM methods for frontend development  

remove

This method removes a specified class from an element’s class list. The remove method takes out a CSS class to change the element’s appearance back to default.

// script.js

let element = document.getElementById('h1');
element.classList.remove('newClass');

createElement

This method creates a new HTML element with the specified tag name (e.g., div, p) and is essential for dynamically building elements on the page. You can create new paragraphs, buttons, or any other HTML element as needed:

// script.js

let newDiv = document.createElement('div');

appendChild

This method inserts a child element as the last child of a parent element and adds newly created elements (with the createElement method) to an existing element in the DOM; this allows us to build complex structures dynamically. After a child element or node has been created, use appendChild to add the new element to the end of the list of children of the specified node.

See example below:


  
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
  
  
    <h1 id="This-is-span-some-span-text">This is <span>some</span> text!</h1>
    <div id="div"></div>
  
  <script src="/script.js"></script>

This is what we have before we append any new element: Exploring essential DOM methods for frontend development   Next, let’s create a new element and add it to the empty div above.

// script.js

const parentNode = document.getElementById("div");
const textElement = document.createTextNode("This is a text node");
const pTag = document.createElement("p");
const newElement = pTag.appendChild(textElement);
parentNode.appendChild(newElement);

We included a text node and appended it to a p tag that we created using the createElement method. Next, we append the p tag to our div, which we have targeted using the getElementById method. The output then shows on our page as seen below: Exploring essential DOM methods for frontend development  

setProperty

This method sets a specific style property on an element (e.g., color, font-size) and provides granular control over element styles. This lets you dynamically change the appearance of elements based on user interactions and other conditions.

The syntax of the setProperty method is:

element.style.setProperty(propertyName, value)

Where propertyName is the CSS property we want to target, and value indicates the values of the CSS property.

Look at the example below:

// script.js

const element = document.getElementById("h1");
element.style.setProperty("color", "red");

In the code above, we retrieve our element using its id: h1. Next, we use our setProperty method to change or set the color of the text content to red.

On our page, the output of the code is as shown: Exploring essential DOM methods for frontend development  

Event or event handling methods

Event methods handle and manipulate events, enabling interactivity in webpages. The essential methods under this category include addEventListener() and removeEventListener().

addEventListener()

This is one of the most important DOM methods that you will use. The method attaches an event listener to an element, allowing the element to respond to specific user interactions. An event is anything that happens in your system, program, or webpage. An event could be a click, a load, a focus, a keydown, or keyup event, and so on.

The addEventListener attaches to an element, a listener that listens to any of these events, and when the events happen, the listener triggers a specified interaction with that element.

The syntax for the addEventListener is the following:

addEventListener(type, listener)

Where type is the type of event you want to listen to, listener is the object that receives a notification or implements the event you want.

In our HTML, let’s add a button element:


  
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
  
  

    <button>Click Me!</button>
  
  <script src="/script.js"></script>

In our JavaScript file, let’s add a listener that shows a “Hello World” alert whenever the button is clicked:

// script.js

const buttonElement = document.querySelector("button");
buttonElement.addEventListener("click", () => {
  alert("Hello World");
});

Using the querySelector, we get the button element. Then, we attach a click event to it. Whenever the button is clicked, our listener function is executed:

The output becomes:

Webpage with ‘Hello World’ heading, three paragraphs, a ‘Click Me!’ button, and an alert box saying ‘Hello World’.  

removeEventListener()

Similar to the addEventListener, this method removes an event listener from an element.

The syntax for this method is below:

removeEventListener(type, listener)

Where type is the type of event you are listening to and listener is the function that implements the event you want.

Let’s see a real-world use case to see this method in action. Copy and replace your HTML with the code below:


  
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
  
  
    <h1 id="Canvas-Drawing">Canvas Drawing</h1>
    <canvas id="drawingCanvas" width="500" height="500" style="border: 2px solid black"></canvas>
    <div>
      <button id="startDrawingBtn">Start Drawing</button>
      <button id="stopDrawingBtn">Stop Drawing</button>
    </div>
  
  <script src="/script.js"></script>

It’s nothing fancy — we have a canvas element we can draw on and two buttons that allow us to draw on the canvas or not. The main interactivity comes in our JavaScript below:

// script.js

let startButton = document.getElementById("startDrawingBtn");
let stopButton = document.getElementById("stopDrawingBtn");
let canvas = document.getElementById("drawingCanvas");
let ctx = canvas.getContext("2d");
let drawing = false;

// draw function
function draw(event) {
  if (!drawing) return;
  ctx.lineWidth = 5;
  ctx.lineCap = "round";
  ctx.strokeStyle = "blue";
  ctx.lineTo(
    event.clientX - canvas.offsetLeft,
    event.clientY - canvas.offsetTop
  );
  ctx.stroke();
  ctx.beginPath();
  ctx.moveTo(
    event.clientX - canvas.offsetLeft,
    event.clientY - canvas.offsetTop
  );
}

// mousedown handler
function handleMouseDown(event) {
  drawing = true;
  ctx.beginPath();
  canvas.addEventListener("mousemove", draw);
}

// mouseup handler
function handleMouseUp() {
  drawing = false;
  ctx.beginPath();
  canvas.removeEventListener("mousemove", draw);
}

// Function to start drawing
function startDrawing() {
  canvas.addEventListener("mousedown", handleMouseDown);
  canvas.addEventListener("mouseup", handleMouseUp);
}

// Function to stop drawing
function stopDrawing() {
  drawing = false;
  canvas.removeEventListener("mousedown", handleMouseDown);
  canvas.removeEventListener("mouseup", handleMouseUp);
}

// Our event listeners
startButton.addEventListener("click", startDrawing);
stopButton.addEventListener("click", stopDrawing);

We get our button and canvas elements using the getElementById method. Next, we have three events: mouseup, mousedown, and mousemove. These events will be used for our canvas drawing.

We define two functions to handle our drawing state:

  • In the startDrawing function, we attach mousedown and mouseup events to the canvas to enable drawing when the mouse is held down and dragged. mousemove is used within mousedown to draw as the mouse moves
  • In the stopDrawing function, we remove the mousedown, mouseup, and mousemove events to stop drawing using the removeEventListener method

Finally, we attach click events to our buttons to trigger startDrawing or stopDrawing event functions when clicked.

The output becomes the following: Exploring essential DOM methods for frontend development  

DOM methods cheat sheet

Below is a summary of the different DOM methods we have seen so far in this article. The table includes the syntax and function of each method:

Name Syntax Function
Query or Select methods document.querySelector(selector) Selects the first element that matches the specified CSS selector.
document.querySelectorAll(selector) Selects all element that matches the specified CSS selector. Returns a `NodeList`.
document.getElementById(id) Selects an element by its ID.
document.getElementsByClassName(className) Selects all elements that have the specified class name. Returns an HTMLCollection.
document.getElementsByTagName(tagName) Selects all elements that have the specified tag name. Returns an HTMLCollection.
Get Content Methods element.innerHTML Gets or sets the HTML content of an element.
element.textContent Gets or sets the text content of an element.
Attribute and Style Manipulation Methods element.classList.add(className) Adds a class to the class list of an element.
element.classList.remove(className) Removes a class from the class list of an element.
document.createElement(tagName) Creates a new element with the specified tag name.
element.appendChild(childNode) Adds or inserts a child element/node as the last child of a parent element.
element.style.setProperty(propertyName, value) Sets a new value to a specific style property on an element.
Event Handling methods element.addEventListener(event, handleFunction) Attaches an event listener to an element, allowing the element to respond to specific user interactions.
element.removeEventListener(event, handleFunction) Removes an event handler that has been attached to an element.

結論

我們已經研究了基本的 DOM 方法並了解了每種方法的用例。掌握這些 DOM 方法不僅對於任何前端開發人員至關重要,而且還使您能夠創建動態和互動式 Web 應用程式。查詢 DOM 元素、操作內容和屬性以及處理事件和樣式都提供了有效控制和增強使用者體驗的基礎工具。

LogRocket:透過了解上下文更輕鬆地調試 JavaScript 錯誤

偵錯程式碼總是一項乏味的任務。但你越了解自己的錯誤,就越容易糾正它們。

LogRocket 讓您以新的、獨特的方式理解這些錯誤。我們的前端監控解決方案追蹤使用者與 JavaScript 前端的互動,使您能夠準確查看使用者的操作導致了錯誤。

Exploring essential DOM methods for frontend development

LogRocket 記錄控制台日誌、頁面載入時間、堆疊追蹤、帶有標頭 + 正文的慢速網路請求/回應、瀏覽器元資料和自訂日誌。了解 JavaScript 程式碼的影響從未如此簡單!

免費試用。

以上是探索前端開發的基本 DOM 方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
在JavaScript中替換字符串字符在JavaScript中替換字符串字符Mar 11, 2025 am 12:07 AM

JavaScript字符串替換方法詳解及常見問題解答 本文將探討兩種在JavaScript中替換字符串字符的方法:在JavaScript代碼內部替換和在網頁HTML內部替換。 在JavaScript代碼內部替換字符串 最直接的方法是使用replace()方法: str = str.replace("find","replace"); 該方法僅替換第一個匹配項。要替換所有匹配項,需使用正則表達式並添加全局標誌g: str = str.replace(/fi

構建您自己的Ajax Web應用程序構建您自己的Ajax Web應用程序Mar 09, 2025 am 12:11 AM

因此,在這裡,您準備好了解所有稱為Ajax的東西。但是,到底是什麼? AJAX一詞是指用於創建動態,交互式Web內容的一系列寬鬆的技術。 Ajax一詞,最初由Jesse J創造

如何創建和發布自己的JavaScript庫?如何創建和發布自己的JavaScript庫?Mar 18, 2025 pm 03:12 PM

文章討論了創建,發布和維護JavaScript庫,專注於計劃,開發,測試,文檔和促銷策略。

如何在瀏覽器中優化JavaScript代碼以進行性能?如何在瀏覽器中優化JavaScript代碼以進行性能?Mar 18, 2025 pm 03:14 PM

本文討論了在瀏覽器中優化JavaScript性能的策略,重點是減少執行時間並最大程度地減少對頁面負載速度的影響。

如何使用瀏覽器開發人員工具有效調試JavaScript代碼?如何使用瀏覽器開發人員工具有效調試JavaScript代碼?Mar 18, 2025 pm 03:16 PM

本文討論了使用瀏覽器開發人員工具的有效JavaScript調試,專注於設置斷點,使用控制台和分析性能。

jQuery矩陣效果jQuery矩陣效果Mar 10, 2025 am 12:52 AM

將矩陣電影特效帶入你的網頁!這是一個基於著名電影《黑客帝國》的酷炫jQuery插件。該插件模擬了電影中經典的綠色字符特效,只需選擇一張圖片,插件就會將其轉換為充滿數字字符的矩陣風格畫面。快來試試吧,非常有趣! 工作原理 插件將圖片加載到畫布上,讀取像素和顏色值: data = ctx.getImageData(x, y, settings.grainSize, settings.grainSize).data 插件巧妙地讀取圖片的矩形區域,並利用jQuery計算每個區域的平均顏色。然後,使用

如何構建簡單的jQuery滑塊如何構建簡單的jQuery滑塊Mar 11, 2025 am 12:19 AM

本文將引導您使用jQuery庫創建一個簡單的圖片輪播。我們將使用bxSlider庫,它基於jQuery構建,並提供許多配置選項來設置輪播。 如今,圖片輪播已成為網站必備功能——一圖胜千言! 決定使用圖片輪播後,下一個問題是如何創建它。首先,您需要收集高質量、高分辨率的圖片。 接下來,您需要使用HTML和一些JavaScript代碼來創建圖片輪播。網絡上有很多庫可以幫助您以不同的方式創建輪播。我們將使用開源的bxSlider庫。 bxSlider庫支持響應式設計,因此使用此庫構建的輪播可以適應任何

如何使用Angular上傳和下載CSV文件如何使用Angular上傳和下載CSV文件Mar 10, 2025 am 01:01 AM

數據集對於構建API模型和各種業務流程至關重要。這就是為什麼導入和導出CSV是經常需要的功能。在本教程中,您將學習如何在Angular中下載和導入CSV文件

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版