How to implement such a record? Let's say there is a function, while returning an element:

var $ = function (id) { if (id[0] == '#') { id = id.slice(1); } return document.getElementById (id); }; 

And there is a function that does something with this element:

 var function bg (elem, color) { elem.style.backgroundColor = color; }; 

They are used like this:

 bg($("id"), "цвет"); 

How to change these functions so that they work like in jquery:

 $("id").bg("цвет"); 

I would also like to know how to make the ability to write a color change many times on the same element:

 $("id").bg("цвет1").bg("цвет2").bg("цвет3") ...; 
  • @Stanislav Dalinin, If you are given an exhaustive answer, mark it as correct (click on the check mark next to the selected answer). - Vitalina

1 answer 1

 var MyObj = function(obj) { this.obj = obj; }; MyObj.prototype.bg = function (color) { var id = this.obj; if (id[0] == '#') { id = id.slice(1); } var a = document.getElementById(id); a.innerText = color; return this; }; var $ = function (id) { return new MyObj(id); }; $('#test').bg('0xFF0000').bg('green'); 

html:

 <p id="test">test</p> 

link

Further refine your requirements.

  • And that such a record will work `$ (" id "). Bg (" color1 "). Bg (" color2 "). Bg (" color3 ")`? - Stanislav Dalinin
  • Updated example. - KoVadim