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.
>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`);