Completely experimental and only for learning I am trying to reinvent the wheel, a wheel called jquery. The original purpose of doing that was to understand chainable functions. So I wrote a function which is doing this, and very well as far as I can see, like so: (a bit shortened)
var $ = function(s) {
var el = document.querySelectorAll(s);
var myobj = {
addClass(className) {
el.forEach(elem => {elem.classList.add(className)});
return this;
},
toggleClass(className) {
el.forEach(elem => {elem.classList.toggle(className)});
return this;
},
removeClass(className) {
el.forEach(elem => {elem.classList.remove(className)});
return this;
},
html(html) {
if (typeof html == 'string') {
el.forEach(elem => {elem.innerHTML = html});
return this;
} else {
return el[0].innerHTML;
}
}
};
return myobj;
};
(this is really a working example) Now I can use jquery-like syntax for manipulate classes and html of an element (or a node list of elements) like so: $('#test').html('new html content');
or chained like $('a').html('my new link').addClass('newclassname');
, which is really cool.
For those who are interested, here's the complete script snapshot of today including css()
and attr()
, and including the missing jquery function id()
.
My questions are:
[RESOLVED] How can I get this function to return jquery-like just the element itself like
var elm = $('div#test');
, now I am getting back the entire object.[RESOLVED] (plz. see comments below) How can I write a fallback function, to prevent getting error message like
$(...).animate is not a function
, if I am using a method which is currently not covered in this function, like$('div#test').addClass('newclass').animate({top:'2.3em',background:'red'});
, sinceanimate()
isn't implemented at the moment. Inphp
there is a__get()
function, is there something similar in javascript ?
Please don't ask me for why I am doing this all, as I mentioned it's for learning and understanding
Thanks.