skip to Main Content

How can I make my own JS library parts or functions like my examples below?

How do I take a variable and add something like this to it:


let x = document.createElement("p");

x.pickle(); 

//let's say ".pickle" turns the text green. I do not want to use a normal function to do this like `setAtrribute` I want to do it through my own custom thing like ".pickle"

let x = new Something().color("green");

//How Can I create a new addition or something like libraries? Potentially Chainable Methods.

How do I do this as JS libraries do? Even if my example needs to be changed to make it work.

2

Answers


  1. There’s a textContent property that you can get and set.

    JavaScript also allows you to add members to any object. So you could create a new member called "add" that has behavior you want.

    In theory, you can even use .prototype to make all the objects of a given type have new behavior.

    However, adding properties to objects your code doesn’t "own" is not usually a great idea. It’s usually better to create your own function/object/class with its own behaviors that you can use to change the values of other objects. That’s why libraries like Prototype.js fell out of favor and were replaced by jQuery (prior to SPA frameworks taking over the world).

    const div = document.querySelector(".example");
    
    div.textContent += " | New Text";
    
    div.add = (moreText) => div.textContent += " | " + moreText;
    
    div.add("hi");
    div.add("there");
    
    HTMLElement.prototype.pickle = function() { this.textContent += "| I'm a pickle" };
    div.pickle();
    <div class="example">Original Text</div>
    Login or Signup to reply.
  2. It looks like you want to have your own class with methods that set attributes, properties, CSS, …etc of a DOM element. You could have that class also create the DOM element, and make methods chainable.

    Maybe something like this:

    // Custom class that has methods that allow chaining.
    class Element {
        constructor(type) {
            this.elem = document.createElement(type);
        }
        text(text) {
            if (arguments.length) {
                this.elem.textContent = text; // set
                return this; // <-- make chainable
            } else {
                return this.elem.textContent; // get
            }
        }
        append(...elems) {
            this.elem.append(...elems.map(obj => obj.elem));
            return this;
        }
        attr(name, value) {
            if (arguments.length) {
                this.elem.setAttribute(name, value); // set
                return this;
            } else {
                return this.elem.getAttribute(name); // get
            }
        }
        css(obj) {
            Object.assign(this.elem.style, obj);
            return this;
        }
        appendTo(target) {
            document.querySelector(target).append(this.elem);
            return this;
        }
        // ...add more methods...
        static find(selector) {
            const instance = Object.create(Element.prototype);
            instance.elem = document.querySelector(selector);
            return instance;
        }
    }
    
    // Example use
    const div = new Element("div").text("hello").css({background: "yellow"}).appendTo("body");
    console.log(`the div has '${div.text()}' as text`);
    const find = Element.find("div"); // Can I get it?
    console.log(`found div. '${find.text()}'`);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search