0
# Attributes & Properties
1
2
Comprehensive attribute manipulation and property access with support for both raw and decoded attribute values, class management, and element property inspection.
3
4
## Capabilities
5
6
### Attribute Access Methods
7
8
Methods for getting, setting, and checking HTML attributes with proper encoding/decoding.
9
10
```typescript { .api }
11
/**
12
* Get decoded attribute value
13
* @param key - Attribute name (case insensitive)
14
* @returns Decoded attribute value or undefined if not present
15
*/
16
getAttribute(key: string): string | undefined;
17
18
/**
19
* Set attribute value
20
* @param key - Attribute name
21
* @param value - Attribute value to set
22
* @returns HTMLElement for method chaining
23
*/
24
setAttribute(key: string, value: string): HTMLElement;
25
26
/**
27
* Remove attribute
28
* @param key - Attribute name to remove
29
* @returns HTMLElement for method chaining
30
*/
31
removeAttribute(key: string): HTMLElement;
32
33
/**
34
* Check if attribute exists
35
* @param key - Attribute name to check (case insensitive)
36
* @returns true if attribute exists, false otherwise
37
*/
38
hasAttribute(key: string): boolean;
39
40
/**
41
* Replace all attributes with new set
42
* @param attributes - Object containing new attributes
43
* @returns HTMLElement for method chaining
44
*/
45
setAttributes(attributes: Attributes): HTMLElement;
46
```
47
48
**Usage Examples:**
49
50
```typescript
51
import { parse } from "node-html-parser";
52
53
const element = parse('<div class="container" data-id="123">Content</div>');
54
55
// Get attributes
56
console.log(element.getAttribute('class')); // "container"
57
console.log(element.getAttribute('data-id')); // "123"
58
console.log(element.getAttribute('missing')); // undefined
59
60
// Check attributes
61
console.log(element.hasAttribute('class')); // true
62
console.log(element.hasAttribute('id')); // false
63
64
// Set attributes
65
element.setAttribute('id', 'main-div');
66
element.setAttribute('role', 'main');
67
console.log(element.getAttribute('id')); // "main-div"
68
69
// Remove attributes
70
element.removeAttribute('data-id');
71
console.log(element.hasAttribute('data-id')); // false
72
73
// Replace all attributes
74
element.setAttributes({
75
'class': 'new-class',
76
'title': 'New title',
77
'tabindex': '0'
78
});
79
80
console.log(element.toString());
81
// <div class="new-class" title="New title" tabindex="0">Content</div>
82
```
83
84
### Attribute Properties
85
86
Properties for accessing raw and processed attribute collections.
87
88
```typescript { .api }
89
/** Get all attributes as decoded key-value pairs */
90
get attributes(): Record<string, string>;
91
92
/** Get all raw attributes with original encoding */
93
get rawAttributes(): RawAttributes;
94
95
/** Get parsed and decoded attributes (alias for attributes) */
96
get attrs(): Attributes;
97
98
/** Get raw attribute string as it appears in HTML */
99
rawAttrs: string;
100
```
101
102
**Usage Examples:**
103
104
```typescript
105
const element = parse('<div class="test" data-value="hello & world" title="tooltip">Content</div>');
106
107
// Get all attributes (decoded)
108
console.log(element.attributes);
109
// { class: "test", "data-value": "hello & world", title: "tooltip" }
110
111
// Get raw attributes (with original encoding)
112
console.log(element.rawAttributes);
113
// { class: "test", "data-value": "hello & world", title: "tooltip" }
114
115
// Get raw attribute string
116
console.log(element.rawAttrs);
117
// 'class="test" data-value="hello & world" title="tooltip"'
118
119
// Iterate over attributes
120
Object.entries(element.attributes).forEach(([key, value]) => {
121
console.log(`${key}: ${value}`);
122
});
123
```
124
125
### Class Management
126
127
DOMTokenList class providing standard DOM APIs for managing CSS classes.
128
129
```typescript { .api }
130
/** Class list management object */
131
get classList(): DOMTokenList;
132
133
/** Get class names as space-separated string */
134
get classNames(): string;
135
136
interface DOMTokenList {
137
/** Number of classes */
138
get length(): number;
139
140
/** Array of class names */
141
get value(): string[];
142
143
/** Add class (throws error if class contains whitespace) */
144
add(className: string): void;
145
146
/** Remove class */
147
remove(className: string): void;
148
149
/** Replace one class with another */
150
replace(oldClass: string, newClass: string): void;
151
152
/** Toggle class presence */
153
toggle(className: string): void;
154
155
/** Check if class exists */
156
contains(className: string): boolean;
157
158
/** Get iterator for class names */
159
values(): IterableIterator<string>;
160
161
/** Convert to space-separated string */
162
toString(): string;
163
}
164
```
165
166
**Usage Examples:**
167
168
```typescript
169
const element = parse('<div class="container active">Content</div>');
170
171
// Access classList
172
const classes = element.classList;
173
console.log(classes.length); // 2
174
console.log(classes.value); // ["container", "active"]
175
console.log(classes.toString()); // "container active"
176
177
// Check classes
178
console.log(classes.contains('active')); // true
179
console.log(classes.contains('hidden')); // false
180
181
// Modify classes
182
classes.add('new-class');
183
classes.remove('active');
184
classes.toggle('highlighted');
185
186
console.log(element.className); // "container new-class highlighted"
187
188
// Replace class
189
classes.replace('container', 'wrapper');
190
console.log(classes.toString()); // "wrapper new-class highlighted"
191
192
// Iterate over classes
193
for (const className of classes.values()) {
194
console.log(`Class: ${className}`);
195
}
196
197
// Error handling
198
try {
199
classes.add('invalid class'); // Throws error - contains space
200
} catch (error) {
201
console.error(error.message);
202
}
203
```
204
205
### Element Properties
206
207
Direct access to key element properties and identifiers.
208
209
```typescript { .api }
210
/** Element ID attribute value */
211
id: string;
212
213
/** Element tag name in uppercase */
214
get tagName(): string;
215
set tagName(name: string): void;
216
217
/** Element tag name in lowercase */
218
get localName(): string;
219
220
/** Raw tag name preserving original case */
221
rawTagName: string;
222
```
223
224
**Usage Examples:**
225
226
```typescript
227
const element = parse('<DIV id="main-content" class="wrapper">Content</DIV>');
228
229
// Access properties
230
console.log(element.id); // "main-content"
231
console.log(element.tagName); // "DIV"
232
console.log(element.localName); // "div"
233
console.log(element.rawTagName); // "DIV"
234
235
// Modify properties
236
element.id = "new-id";
237
element.tagName = "section";
238
239
console.log(element.toString());
240
// <section id="new-id" class="wrapper">Content</section>
241
242
// ID changes update attribute
243
console.log(element.getAttribute('id')); // "new-id"
244
```
245
246
## Advanced Attribute Patterns
247
248
### Working with Data Attributes
249
250
Handle HTML5 data attributes with proper naming conventions:
251
252
```typescript
253
const element = parse('<div data-user-id="123" data-active="true">User</div>');
254
255
// Access data attributes
256
const userId = element.getAttribute('data-user-id');
257
const isActive = element.getAttribute('data-active') === 'true';
258
259
// Set data attributes
260
element.setAttribute('data-role', 'admin');
261
element.setAttribute('data-created', new Date().toISOString());
262
263
// Remove data attributes
264
element.removeAttribute('data-active');
265
```
266
267
### Handling Special Characters
268
269
Work with attributes containing special characters and HTML entities:
270
271
```typescript
272
const element = parse('<div title="hello "world"" data-json="{"key":"value"}">Content</div>');
273
274
// Get decoded values
275
console.log(element.getAttribute('title')); // 'hello "world"'
276
console.log(element.getAttribute('data-json')); // '{"key":"value"}'
277
278
// Set values with special characters (automatically encoded)
279
element.setAttribute('description', 'Text with "quotes" & symbols');
280
element.setAttribute('data-config', JSON.stringify({ active: true }));
281
```
282
283
### Bulk Attribute Operations
284
285
Efficiently manage multiple attributes:
286
287
```typescript
288
const element = parse('<div>Content</div>');
289
290
// Set multiple attributes at once
291
element.setAttributes({
292
'id': 'bulk-example',
293
'class': 'demo-element',
294
'data-version': '2.0',
295
'role': 'button',
296
'tabindex': '0',
297
'aria-label': 'Demo button'
298
});
299
300
// Copy attributes from another element
301
const source = parse('<span id="source" class="copy-me" title="tooltip">Source</span>');
302
const target = parse('<div>Target</div>');
303
304
// Copy all attributes except tag-specific ones
305
const attributesToCopy = { ...source.attributes };
306
delete attributesToCopy.id; // Don't copy ID to avoid duplicates
307
target.setAttributes(attributesToCopy);
308
309
// Conditional attribute setting
310
const config = {
311
shouldHaveId: true,
312
isActive: false,
313
role: 'button'
314
};
315
316
if (config.shouldHaveId) {
317
element.setAttribute('id', 'conditional-id');
318
}
319
320
if (config.isActive) {
321
element.classList.add('active');
322
}
323
324
element.setAttribute('role', config.role);
325
```
326
327
### Attribute Validation and Sanitization
328
329
Validate and sanitize attribute values before setting:
330
331
```typescript
332
function setValidatedAttribute(element: HTMLElement, key: string, value: string) {
333
// Basic validation
334
if (!key || key.includes(' ')) {
335
throw new Error('Invalid attribute name');
336
}
337
338
// Sanitize value
339
const sanitizedValue = value.trim();
340
341
if (sanitizedValue) {
342
element.setAttribute(key, sanitizedValue);
343
} else {
344
element.removeAttribute(key);
345
}
346
}
347
348
// Safe attribute operations
349
const element = parse('<div>Content</div>');
350
351
try {
352
setValidatedAttribute(element, 'title', ' Valid title ');
353
setValidatedAttribute(element, 'data-empty', ' '); // Removes empty attribute
354
355
console.log(element.toString());
356
} catch (error) {
357
console.error('Validation failed:', error.message);
358
}
359
```
360
361
## Type Definitions
362
363
```typescript { .api }
364
interface Attributes {
365
[key: string]: string;
366
}
367
368
interface RawAttributes {
369
[key: string]: string;
370
}
371
372
interface KeyAttributes {
373
id?: string;
374
class?: string;
375
}
376
```