По многочисленным просьбам перенес в отдельную тему
отсюда.
jQuery style JavaScript library (chaining, prototyping, addoning)
/* API
Constructor:
$(...) see .init(...)
Utilities:
$.slice(array #target, number #begin, number #end)
$.push(array #target, array #source)
$.each(array #target, function #callback, object #context)
$.find(string #selector, element #context)
$.now()*
Properties:
.nodes = []
Methods:
.init(string #selector[, element #context = document])
.slice(number #begin[, number #end = this.nodes.length])
.push(array #source)
.each(function #callback[, object #context = this])
.find(string #selector)
.text([string #text])*
.html([string #html])*
Examples:
$('div').text('T1').init('p',$('#id').nodes[0]).html('<b>T2</b><b>T3</b>')
.find('b').slice(0,1).push($('.class').nodes).text('T5')
.each(function(node, index, nodes){alert(this.text(index).html())})
.init('body').find('*').text('T6');
*/
// Core:
(function() {
// constructor
function $(selector, context) {
return new $.fn.init(selector, context);
}
// library prototype alias
$.fn = $.prototype;
// array prototype alias
var array = Array.prototype;
// utilities:
$.slice = function(target, begin, end) {
return array.slice.call(target, begin, end);
};
$.push = function(target, source) {
array.push.apply(target, source);
return target;
};
$.each = function(target, callback, context) {
array.forEach.call(target, callback, context);
return target;
};
$.find = function(selector, context) {
var nodes = context.querySelectorAll(selector);
return $.slice(nodes, 0, nodes.length);
};
// methods:
$.fn.init = function(selector, context) {
this.nodes = $.find(selector, context || document);
return this;
};
$.fn.slice = function(begin, end) {
this.nodes = $.slice(this.nodes, begin, end || this.nodes.length);
return this;
};
$.fn.push = function(source) {
$.push(this.nodes, source);
return this;
};
$.fn.each = function(callback, context) {
$.each(this.nodes, callback, context || this);
return this;
};
$.fn.find = function(selector) {
var nodes = [];
$.each(this.nodes, function(node) {
$.push(nodes, $.find(selector, node));
});
this.nodes = nodes;
return this;
};
// instance prototype
$.fn.init.prototype = $.fn;
// library alias
window.$ = $;
}());
// *Addons:
$.now = function() {
return new Date().getTime();
};
$.fn.text = function(text) {
if (text === undefined) {
text = [];
this.each(function(node) {
text.push(node.textContent);
});
return text.join(' ');
} else {
return this.each(function(node) {
node.textContent = text;
});
}
};
$.fn.html = function(html) {
if (html === undefined) {
return this.nodes.length ?
this.nodes[0].innerHTML : undefined;
} else {
return this.each(function(node) {
node.innerHTML = html;
});
}
};
UPD:
- переименовано
window._ в
window.$,
function Lib в
function $,
var method в
var array,
.method в
.fn.
- перенесено описание типов параметров методов из кода отдельно.