W3C DOM Level 1 提供跨語言存取文件結構的方式。在 HTML 中,每個標籤、文字與屬性都可視為節點,程式可以讀取、修改、新增或刪除。
例如一個 p 元素包含文字節點;若文字中又有 b 元素,就會形成父子關係。屬性節點通常不放在 childNodes 中。
可用 parentNode、childNodes、firstChild、lastChild 遍歷,也可用 getElementsByTagName 或 getElementById 快速取得目標。getElementById 是最穩定的方式。
文字節點可用 nodeValue 修改;屬性可用 setAttribute。新增元素可用 createElement,插入可用 appendChild 或 insertBefore,刪除可用 removeChild。
var x = document.createElement('hr');
document.getElementById('inserthere').appendChild(x);
建立文字節點則使用 createTextNode。熟練這些操作後,就能在不重新載入頁面的情況下更新內容。