-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
42 lines (40 loc) · 1.55 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* Class for managing HTML elements with specific attributes.
*/
class HtmlAttributeManager {
/**
* Creates an instance of HtmlAttributeManager.
* @param {string} attributeName - The name of the HTML attribute to search for.
* @param {string} functionName - The name of the function to call for each matching element.
*/
constructor(attributeName, functionName) {
this.attributeName = attributeName;
this.functionName = functionName;
this.handleEvent = this.handleEvent.bind(this);
document.addEventListener('DOMContentLoaded', this.handleEvent);
}
/**
* Finds HTML elements with the specified attribute and calls the corresponding function.
*/
handleEvent() {
try {
const elements = document.querySelectorAll(`[${this.attributeName}]`);
elements.forEach(element => {
const attributeValue = element.getAttribute(this.attributeName);
if (typeof window[this.functionName] === 'function') {
window[this.functionName](element, attributeValue);
} else {
console.error(`Function '${this.functionName}' not found or not a function.`);
}
});
} catch (error) {
console.error('An error occurred while processing HTML attributes:', error);
}
}
/**
* Removes the event listener when the instance is no longer needed.
*/
destroy() {
document.removeEventListener('DOMContentLoaded', this.handleEvent);
}
}