DOM 操作是前端開發的基礎。透過 document 物件,可以尋找元素、讀寫內容、操作屬性、修改樣式,也能新增或刪除節點。
常見方法包含 getElementById、getElementsByName、getElementsByTagName 與 getElementsByClassName。getElementById 會回傳單一元素,其他多數會回傳集合。
非表單元素可使用 innerHTML 取得或設定標籤內的 HTML;innerText 只處理文字;outerHTML 則包含元素本身。

若設定 innerHTML,原本內容會被取代;若設定 innerText,則會原樣呈現文字。

表單元素可透過 document.formName.elementName 或 getElementById 取得。文字輸入框使用 value 取得或設定內容,textarea 則可用 innerHTML 或 value。
表單按鈕若設定 onclick="return false",可阻止預設行為,例如避免表單提交或連結跳轉。
可使用 setAttribute 設定屬性、getAttribute 取得屬性、removeAttribute 移除屬性。常見應用包含檢查答案、倒數計時後啟用按鈕等。

例如將 disabled 屬性移除後,原本不可用的按鈕就會變成可提交。

可透過 element.style 直接修改單一樣式,也可用 className 一次套用多個 class。常見應用包含背景圖片輪播、顯示隱藏、字體顏色與排版切換。

nextSibling、previousSibling、parentNode、childNodes、firstChild、lastChild 可用來操作相關節點。createElement 可建立元素,appendChild 可加入子元素,removeChild 可刪除子元素。
此外,熟悉字串操作、Date 物件與 Math 函式,也能讓 DOM 開發更完整。