Skip to content

Instantly share code, notes, and snippets.

@HarishChaudhari
Created December 7, 2022 05:06

Revisions

  1. HarishChaudhari created this gist Dec 7, 2022.
    15 changes: 15 additions & 0 deletions call-dom-manipulator.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,15 @@
    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);
    63 changes: 63 additions & 0 deletions class-dom-manipulator.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,63 @@
    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);
    }
    }