JAVASCRIPT
// This code sample simply give you a very basic concept of jQuery (and other JavaScript libraries).
// From this you can learn about how to make the chainning methods, the CSS selectors etc.
// There aren’t any HTML collection loop because here I use `document.querySelector()` and
// not `document.querySelectorAll()` for selecting the DOM, so that the code snippet will be easier to learn.
// **DEMO:** <https://codepad.co/snippet/rrOIewk9/edit>
(function() {
// the real constructor
var _init = function(selector) { // `selector` → for `document.querySelector()`
// prevent broken scope of the `_init`’s `this` keyword
// by caching the `this` to a variable named as `base`
var base = this;
// `$('#foo').element` to get the `#foo`
base.element = document.querySelector(selector);
// `$('#foo').length` to get the `#foo` length in document
base.length = base.element.length;
// `$('#foo').html('<b>test</b>')`
base.html = function(s) {
base.element.innerHTML = s;
return base; // make it chainable …
};
// `$('#foo').css( ... )`
base.css = function(prop, val) {
// `$('#foo').css({'color': '#000'})`
if (typeof prop === "object") {
for (var i in prop) {
base.element.style[i] = prop[i];
}
// `$('#foo').css('color', '#000')`
} else {
base.element.style[prop] = val;
}
return base; // make it chainable …
};
// etc …
base.addClass = function(s) {
base.element.classList.add(s);
return base;
};
base.removeClass = function(s) {
base.element.classList.remove(s);
return base;
};
base.toggleClass = function(s) {
base.element.classList.toggle(s);
return base;
};
}; // end constructor
// create the magic `$(selector)` function
var $ = function(selector) {
return new _init(selector);
};
// others …
$.ajax = function() {};
$.get = function() {};
$.post = function() {};
window.$ = $;
})();
// test the script!
$('h1').html('Lorem ipsum <em>dolor</em> sit amet!').css({
'color': 'red',
'background': 'yellow'
}).css('border', '4px solid green');