JavaScript 中的 DOM 操作
DOM 操作 是現代 Web 開發的一個基本面,它允許開發人員動態修改網頁的內容、結構和樣式。文件物件模型 (DOM) 以樹狀格式表示網頁的 HTML 結構。
1.什麼是 DOM?
DOM 是瀏覽器提供的接口,允許 JavaScript 與 HTML 和 CSS 互動。它將頁面表示為節點樹,其中每個元素、屬性或文字都是一個節點。
例子:
對於以下 HTML:
<div> <p>The DOM structure looks like this:</p> <ul> <li>Document <ul> <li>HTML</li> <li>Body <ul> <li>Div (id="container")</li> <li>Paragraph ("Hello, World!")</li> </ul> </li> </ul> </li> </ul> <hr> <h3> <strong>2. Selecting DOM Elements</strong> </h3> <h4> <strong>A. Using getElementById</strong> </h4> <p>Select an element by its ID.<br> </p> <pre class="brush:php;toolbar:false">const container = document.getElementById("container"); console.log(container); // Output: <div> <h4> <strong>B. Using querySelector</strong> </h4> <p>Select the first matching element.<br> </p> <pre class="brush:php;toolbar:false">const paragraph = document.querySelector("p"); console.log(paragraph); // Output: <p>Hello, World!</p>
C.使用 querySelectorAll
選擇所有符合的元素作為 NodeList。
const allParagraphs = document.querySelectorAll("p"); console.log(allParagraphs); // Output: NodeList of <p> elements </p>
3.修改 DOM 元素
A.更改內容
使用textContent或innerHTML屬性來修改內容。
const paragraph = document.querySelector("p"); paragraph.textContent = "Hello, JavaScript!"; // Changes <p>Hello, World!</p> to <p>Hello, JavaScript!</p>
B.更改屬性
使用 setAttribute 或直接屬性賦值。
const image = document.querySelector("img"); image.setAttribute("src", "new-image.jpg"); image.alt = "A descriptive text";
C.改變風格
修改樣式屬性以套用內聯樣式。
const container = document.getElementById("container"); container.style.backgroundColor = "lightblue"; container.style.padding = "20px";
4.新增和刪除元素
A.建立新元素
使用createElement方法。
const newParagraph = document.createElement("p"); newParagraph.textContent = "This is a new paragraph."; document.body.appendChild(newParagraph);
B.刪除元素
使用remove方法或removeChild。
const paragraph = document.querySelector("p"); paragraph.remove(); // Removes the paragraph from the DOM
5.新增事件監聽器到元素
您可以使用事件偵聽器為元素新增互動性。
const button = document.createElement("button"); button.textContent = "Click Me"; button.addEventListener("click", function() { alert("Button clicked!"); }); document.body.appendChild(button);
6.遍歷 DOM
瀏覽父元素、子元素和兄弟元素。
A.家長與孩子
const child = document.querySelector("p"); const parent = child.parentElement; console.log(parent); // Output: Parent element of <p> const children = parent.children; console.log(children); // Output: HTMLCollection of child elements </p>
B.兄弟姊妹
const sibling = child.nextElementSibling; console.log(sibling); // Output: Next sibling element
7.效能最佳化
- 使用 documentFragment 進行批次更新: 透過對 DOM 更新進行分組,最大限度地減少回流和重繪。
const fragment = document.createDocumentFragment(); for (let i = 0; i
最小化直接 DOM 操作:
快取元素並批量修改。使用虛擬 DOM 函式庫:
對於複雜的應用程序,請考慮像 React 或 Vue 這樣的程式庫。
8.實際範例:待辦事項清單
<div> <p>The DOM structure looks like this:</p> <ul> <li>Document <ul> <li>HTML</li> <li>Body <ul> <li>Div (id="container")</li> <li>Paragraph ("Hello, World!")</li> </ul> </li> </ul> </li> </ul> <hr> <h3> <strong>2. Selecting DOM Elements</strong> </h3> <h4> <strong>A. Using getElementById</strong> </h4> <p>Select an element by its ID.<br> </p> <pre class="brush:php;toolbar:false">const container = document.getElementById("container"); console.log(container); // Output: <div> <h4> <strong>B. Using querySelector</strong> </h4> <p>Select the first matching element.<br> </p> <pre class="brush:php;toolbar:false">const paragraph = document.querySelector("p"); console.log(paragraph); // Output: <p>Hello, World!</p>
9.總結
- DOM Manipulation 讓開發者動態修改網頁。
- 使用 getElementById、querySelector 和 createElement 等方法進行有效操作。
- 最小化直接 DOM 操作以獲得更好的效能。
掌握 DOM 操作對於建立動態、互動式和使用者友善的 Web 應用程式至關重要。
嗨,我是 Abhay Singh Kathayat!
我是一名全端開發人員,擁有前端和後端技術的專業知識。我使用各種程式語言和框架來建立高效、可擴展且用戶友好的應用程式。
請隨時透過我的商務電子郵件與我聯繫:kaashshorts28@gmail.com。
以上是掌握 JavaScript 中的 DOM 操作:綜合指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

JavaScript核心數據類型在瀏覽器和Node.js中一致,但處理方式和額外類型有所不同。 1)全局對像在瀏覽器中為window,在Node.js中為global。 2)Node.js獨有Buffer對象,用於處理二進制數據。 3)性能和時間處理在兩者間也有差異,需根據環境調整代碼。

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python和JavaScript的主要區別在於類型系統和應用場景。 1.Python使用動態類型,適合科學計算和數據分析。 2.JavaScript採用弱類型,廣泛用於前端和全棧開發。兩者在異步編程和性能優化上各有優勢,選擇時應根據項目需求決定。

選擇Python還是JavaScript取決於項目類型:1)數據科學和自動化任務選擇Python;2)前端和全棧開發選擇JavaScript。 Python因其在數據處理和自動化方面的強大庫而備受青睞,而JavaScript則因其在網頁交互和全棧開發中的優勢而不可或缺。

Python和JavaScript各有優勢,選擇取決於項目需求和個人偏好。 1.Python易學,語法簡潔,適用於數據科學和後端開發,但執行速度較慢。 2.JavaScript在前端開發中無處不在,異步編程能力強,Node.js使其適用於全棧開發,但語法可能複雜且易出錯。

javascriptisnotbuiltoncorc; sanInterpretedlanguagethatrunsonenginesoftenwritteninc.1)JavascriptwasdesignedAsignedAsalightWeight,drackendedlanguageforwebbrowsers.2)Enginesevolvedfromsimpleterterpretpretpretpretpreterterpretpretpretpretpretpretpretpretpretcompilerers,典型地,替代品。

JavaScript可用於前端和後端開發。前端通過DOM操作增強用戶體驗,後端通過Node.js處理服務器任務。 1.前端示例:改變網頁文本內容。 2.後端示例:創建Node.js服務器。

選擇Python還是JavaScript應基於職業發展、學習曲線和生態系統:1)職業發展:Python適合數據科學和後端開發,JavaScript適合前端和全棧開發。 2)學習曲線:Python語法簡潔,適合初學者;JavaScript語法靈活。 3)生態系統:Python有豐富的科學計算庫,JavaScript有強大的前端框架。


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

Dreamweaver Mac版
視覺化網頁開發工具

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能