Skip to content

Instantly share code, notes, and snippets.

@HarishChaudhari
Created December 7, 2022 05:06
Show Gist options
  • Save HarishChaudhari/a100b20fd8dda14c8f81d859ff62aff1 to your computer and use it in GitHub Desktop.
Save HarishChaudhari/a100b20fd8dda14c8f81d859ff62aff1 to your computer and use it in GitHub Desktop.
JavaScript DOM Manipulator
const manipulator = new DOMManipulator();
// Create a new div element with an ID of "myDiv", a class of "myClass", and some content
const myDiv = manipulator.createElement('div', 'myDiv', 'myClass', 'Hello, world!', {
'data-id': 123,
'data-name': 'John Doe'
});
// Modify the div element to update its class and content, and add a new attribute
manipulator.modifyElement(myDiv, null, 'myOtherClass', 'Hello, world! How are you?', {
'data-age': 28
});
// Delete the div element
manipulator.deleteElement(myDiv);
class DOMManipulator {
// Method to create an HTML element
createElement(elementType, elementId, elementClass, elementContent, attributes) {
// Create the element
const element = document.createElement(elementType);
// Set the element's ID
if (elementId) {
element.id = elementId;
}
// Set the element's class
if (elementClass) {
element.className = elementClass;
}
// Set the element's content
if (elementContent) {
element.innerHTML = elementContent;
}
// Set the element's attributes
if (attributes) {
for (let attribute in attributes) {
element.setAttribute(attribute, attributes[attribute]);
}
}
// Return the element
return element;
}
// Method to modify an HTML element
modifyElement(element, elementId, elementClass, elementContent, attributes) {
// Set the element's ID
if (elementId) {
element.id = elementId;
}
// Set the element's class
if (elementClass) {
element.className = elementClass;
}
// Set the element's content
if (elementContent) {
element.innerHTML = elementContent;
}
// Set the element's attributes
if (attributes) {
for (let attribute in attributes) {
element.setAttribute(attribute, attributes[attribute]);
}
}
}
// Method to delete an HTML element
deleteElement(element) {
// Remove the element from the DOM
element.parentNode.removeChild(element);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment