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
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).
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: