Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Variables with something.someFunc

I cant find how to do this or know the terminology so excuse me if this may be a duplicate.

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"

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 allows 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...
}

// Example use
const div = new Element("div").text("hello").css({background: "yellow"}).appendTo("body");
console.log(`the div has '${div.text()}' as text`);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading