0
# DOM Manipulation
1
2
Complete DOM manipulation capabilities including document creation, element manipulation, attribute handling, text content management, and tree traversal following W3C DOM Level 2 Core specification.
3
4
## Capabilities
5
6
### Document Interface
7
8
Core document interface providing factory methods for creating DOM nodes and accessing document structure.
9
10
```javascript { .api }
11
/**
12
* W3C Document interface representing an XML/HTML document
13
*/
14
interface Document extends Node {
15
readonly doctype: DocumentType | null;
16
readonly implementation: DOMImplementation;
17
readonly documentElement: Element | null;
18
documentURI?: string; // xmldom extension
19
20
createElement(tagName: string): Element;
21
createDocumentFragment(): DocumentFragment;
22
createTextNode(data: string): Text;
23
createComment(data: string): Comment;
24
createCDATASection(data: string): CDATASection;
25
createProcessingInstruction(target: string, data: string): ProcessingInstruction;
26
createAttribute(name: string): Attr;
27
createEntityReference(name: string): EntityReference;
28
getElementsByTagName(tagname: string): NodeList;
29
getElementsByClassName(className: string): NodeList;
30
importNode(importedNode: Node, deep: boolean): Node;
31
createElementNS(namespaceURI: string | null, qualifiedName: string): Element;
32
createAttributeNS(namespaceURI: string | null, qualifiedName: string): Attr;
33
getElementsByTagNameNS(namespaceURI: string | null, localName: string): NodeList;
34
getElementById(elementId: string): Element | null;
35
}
36
```
37
38
**Usage Examples:**
39
40
```javascript
41
const { DOMParser } = require('xmldom');
42
const parser = new DOMParser();
43
const doc = parser.parseFromString('<root></root>', 'text/xml');
44
45
// Create different types of nodes
46
const element = doc.createElement('product');
47
const text = doc.createTextNode('Product description');
48
const comment = doc.createComment('This is a comment');
49
const cdata = doc.createCDATASection('<script>alert("test");</script>');
50
const attr = doc.createAttribute('id');
51
attr.value = '123';
52
53
// Build document structure
54
element.appendChild(text);
55
element.setAttributeNode(attr);
56
doc.documentElement.appendChild(element);
57
doc.documentElement.appendChild(comment);
58
59
// Access document properties
60
console.log(doc.documentElement.tagName); // "root"
61
console.log(doc.implementation); // DOMImplementation instance
62
```
63
64
### Element Interface
65
66
Core element interface providing attribute manipulation, child element access, and element-specific operations.
67
68
```javascript { .api }
69
/**
70
* W3C Element interface representing XML/HTML elements
71
*/
72
interface Element extends Node {
73
readonly tagName: string;
74
75
getAttribute(name: string): string;
76
setAttribute(name: string, value: string): void;
77
removeAttribute(name: string): void;
78
getAttributeNode(name: string): Attr | null;
79
setAttributeNode(newAttr: Attr): Attr | null;
80
removeAttributeNode(oldAttr: Attr): Attr;
81
getElementsByTagName(name: string): NodeList;
82
getAttributeNS(namespaceURI: string | null, localName: string): string;
83
setAttributeNS(namespaceURI: string | null, qualifiedName: string, value: string): void;
84
removeAttributeNS(namespaceURI: string | null, localName: string): void;
85
getAttributeNodeNS(namespaceURI: string | null, localName: string): Attr | null;
86
setAttributeNodeNS(newAttr: Attr): Attr | null;
87
getElementsByTagNameNS(namespaceURI: string | null, localName: string): NodeList;
88
hasAttribute(name: string): boolean;
89
hasAttributeNS(namespaceURI: string | null, localName: string): boolean;
90
}
91
```
92
93
**Usage Examples:**
94
95
```javascript
96
const { DOMParser } = require('xmldom');
97
const parser = new DOMParser();
98
const doc = parser.parseFromString('<catalog></catalog>', 'text/xml');
99
100
// Create and configure element
101
const product = doc.createElement('product');
102
product.setAttribute('id', 'P001');
103
product.setAttribute('category', 'electronics');
104
product.setAttribute('price', '299.99');
105
106
// Add text content
107
const name = doc.createElement('name');
108
name.appendChild(doc.createTextNode('Laptop Computer'));
109
product.appendChild(name);
110
111
// Add to document
112
doc.documentElement.appendChild(product);
113
114
// Query and modify attributes
115
console.log(product.getAttribute('price')); // "299.99"
116
product.setAttribute('price', '279.99'); // Update price
117
console.log(product.hasAttribute('discount')); // false
118
119
// Work with attribute nodes
120
const idAttr = product.getAttributeNode('id');
121
console.log(idAttr.name); // "id"
122
console.log(idAttr.value); // "P001"
123
124
// Find child elements
125
const nameElements = product.getElementsByTagName('name');
126
console.log(nameElements.item(0).textContent); // "Laptop Computer"
127
```
128
129
### Node Tree Manipulation
130
131
Core node manipulation methods for building and modifying DOM tree structure.
132
133
```javascript { .api }
134
/**
135
* Base Node interface with tree manipulation methods
136
*/
137
interface Node {
138
readonly nodeName: string;
139
nodeValue: string | null;
140
readonly nodeType: number;
141
readonly parentNode: Node | null;
142
readonly childNodes: NodeList;
143
readonly firstChild: Node | null;
144
readonly lastChild: Node | null;
145
readonly previousSibling: Node | null;
146
readonly nextSibling: Node | null;
147
readonly attributes: NamedNodeMap | null;
148
readonly ownerDocument: Document | null;
149
readonly namespaceURI: string | null;
150
prefix: string | null;
151
readonly localName: string | null;
152
textContent: string | null;
153
154
insertBefore(newChild: Node, refChild: Node | null): Node;
155
replaceChild(newChild: Node, oldChild: Node): Node;
156
removeChild(oldChild: Node): Node;
157
appendChild(newChild: Node): Node;
158
hasChildNodes(): boolean;
159
cloneNode(deep: boolean): Node;
160
normalize(): void;
161
isSupported(feature: string, version: string): boolean;
162
hasAttributes(): boolean;
163
isDefaultNamespace(namespaceURI: string | null): boolean;
164
lookupNamespaceURI(prefix: string | null): string | null;
165
}
166
```
167
168
**Usage Examples:**
169
170
```javascript
171
const { DOMParser } = require('xmldom');
172
const parser = new DOMParser();
173
const doc = parser.parseFromString('<items></items>', 'text/xml');
174
175
// Build tree structure
176
const container = doc.documentElement;
177
const item1 = doc.createElement('item');
178
const item2 = doc.createElement('item');
179
const item3 = doc.createElement('item');
180
181
item1.appendChild(doc.createTextNode('First item'));
182
item2.appendChild(doc.createTextNode('Second item'));
183
item3.appendChild(doc.createTextNode('Third item'));
184
185
// Add children in order
186
container.appendChild(item1);
187
container.appendChild(item2);
188
container.appendChild(item3);
189
190
// Insert new item at beginning
191
const newFirst = doc.createElement('item');
192
newFirst.appendChild(doc.createTextNode('New first item'));
193
container.insertBefore(newFirst, container.firstChild);
194
195
// Replace middle item
196
const replacement = doc.createElement('item');
197
replacement.appendChild(doc.createTextNode('Replacement item'));
198
container.replaceChild(replacement, item2);
199
200
// Remove last item
201
container.removeChild(item3);
202
203
// Clone structure
204
const clonedContainer = container.cloneNode(true);
205
console.log(clonedContainer.childNodes.length); // Same as original
206
207
// Tree traversal
208
let current = container.firstChild;
209
while (current) {
210
console.log(current.textContent);
211
current = current.nextSibling;
212
}
213
```
214
215
### Text Content Management
216
217
Methods for managing text content within elements and text nodes.
218
219
```javascript { .api }
220
/**
221
* CharacterData interface for text-containing nodes
222
*/
223
interface CharacterData extends Node {
224
data: string;
225
readonly length: number;
226
227
substringData(offset: number, count: number): string;
228
appendData(arg: string): void;
229
insertData(offset: number, arg: string): void;
230
deleteData(offset: number, count: number): void;
231
replaceData(offset: number, count: number, arg: string): void;
232
}
233
234
/**
235
* Text interface for text nodes
236
*/
237
interface Text extends CharacterData {
238
splitText(offset: number): Text;
239
}
240
241
/**
242
* Comment interface for comment nodes
243
*/
244
interface Comment extends CharacterData {
245
}
246
247
/**
248
* CDATASection interface for CDATA sections
249
*/
250
interface CDATASection extends Text {
251
}
252
```
253
254
**Usage Examples:**
255
256
```javascript
257
const { DOMParser } = require('xmldom');
258
const parser = new DOMParser();
259
const doc = parser.parseFromString('<article></article>', 'text/xml');
260
261
// Create and manipulate text content
262
const paragraph = doc.createElement('p');
263
const text = doc.createTextNode('This is the initial text content.');
264
paragraph.appendChild(text);
265
266
// Use CharacterData methods
267
console.log(text.length); // 33
268
console.log(text.substringData(12, 7)); // "initial"
269
270
text.appendData(' More text added.');
271
text.insertData(33, ' Additional content.');
272
text.replaceData(0, 4, 'That');
273
274
console.log(text.data); // Modified text content
275
276
// Split text node
277
const secondText = text.splitText(20);
278
console.log(paragraph.childNodes.length); // 2 text nodes
279
280
// Work with CDATA sections
281
const cdata = doc.createCDATASection('<script>alert("Hello");</script>');
282
paragraph.appendChild(cdata);
283
console.log(cdata.data); // Script content preserved
284
285
// Use textContent property (DOM Level 3)
286
paragraph.textContent = 'Replaced all content';
287
console.log(paragraph.childNodes.length); // 1 text node
288
289
// Comments
290
const comment = doc.createComment('This is a comment');
291
doc.documentElement.appendChild(comment);
292
comment.data = 'Updated comment text';
293
```
294
295
### Attribute Management
296
297
Comprehensive attribute handling including both simple attribute methods and attribute node manipulation.
298
299
```javascript { .api }
300
/**
301
* Attr interface representing element attributes
302
*/
303
interface Attr extends Node {
304
readonly name: string;
305
readonly specified: boolean;
306
value: string;
307
readonly ownerElement: Element | null;
308
}
309
310
/**
311
* NamedNodeMap interface for attribute collections
312
*/
313
interface NamedNodeMap {
314
readonly length: number;
315
getNamedItem(name: string): Node | null;
316
setNamedItem(arg: Node): Node | null;
317
removeNamedItem(name: string): Node;
318
item(index: number): Node | null;
319
getNamedItemNS(namespaceURI: string | null, localName: string): Node | null;
320
setNamedItemNS(arg: Node): Node | null;
321
removeNamedItemNS(namespaceURI: string | null, localName: string): Node;
322
}
323
```
324
325
**Usage Examples:**
326
327
```javascript
328
const { DOMParser } = require('xmldom');
329
const parser = new DOMParser();
330
const doc = parser.parseFromString('<products></products>', 'text/xml');
331
332
const product = doc.createElement('product');
333
334
// Simple attribute operations
335
product.setAttribute('id', 'P123');
336
product.setAttribute('name', 'Widget');
337
product.setAttribute('price', '29.99');
338
339
console.log(product.getAttribute('name')); // "Widget"
340
console.log(product.hasAttribute('discount')); // false
341
342
// Attribute node operations
343
const idAttr = doc.createAttribute('sku');
344
idAttr.value = 'W-001';
345
const oldAttr = product.setAttributeNode(idAttr);
346
console.log(oldAttr); // null (no previous attribute)
347
348
// Access attribute through NamedNodeMap
349
const attrs = product.attributes;
350
console.log(attrs.length); // 4 attributes
351
const priceAttr = attrs.getNamedItem('price');
352
priceAttr.value = '24.99'; // Modify through attribute node
353
354
// Iterate through attributes
355
for (let i = 0; i < attrs.length; i++) {
356
const attr = attrs.item(i);
357
console.log(`${attr.name}: ${attr.value}`);
358
}
359
360
// Remove attributes
361
product.removeAttribute('sku');
362
const removedAttr = product.removeAttributeNode(product.getAttributeNode('price'));
363
console.log(removedAttr.value); // "24.99"
364
```
365
366
### Document Fragment Operations
367
368
Work with document fragments for efficient DOM manipulation and temporary node storage.
369
370
```javascript { .api }
371
/**
372
* DocumentFragment interface for lightweight document containers
373
*/
374
interface DocumentFragment extends Node {
375
// Inherits all Node methods
376
// When appended to another node, its children are moved, not the fragment itself
377
}
378
```
379
380
**Usage Examples:**
381
382
```javascript
383
const { DOMParser } = require('xmldom');
384
const parser = new DOMParser();
385
const doc = parser.parseFromString('<container></container>', 'text/xml');
386
387
// Create document fragment for batch operations
388
const fragment = doc.createDocumentFragment();
389
390
// Build content in fragment
391
for (let i = 1; i <= 5; i++) {
392
const item = doc.createElement('item');
393
item.setAttribute('id', i.toString());
394
item.appendChild(doc.createTextNode(`Item ${i}`));
395
fragment.appendChild(item);
396
}
397
398
console.log(fragment.childNodes.length); // 5 items
399
400
// Append fragment to document (moves all children)
401
doc.documentElement.appendChild(fragment);
402
console.log(fragment.childNodes.length); // 0 (children moved)
403
console.log(doc.documentElement.childNodes.length); // 5 items
404
```