How to code document.querySelector('.class').doSomeThing()
with native JavaScript like jQuery methode
exp: $('.class').doSomeThing();
How to code document.querySelector('.class').doSomeThing()
with native JavaScript like jQuery methode
exp: $('.class').doSomeThing();
Element.protototype.doSomething = function( passedFunction ){
passedFunction.call( this );
return this;
}
To work with querySelectorAll
as well, you would need to assign the function to NodeList.prototype.doSomething
too.
Implement a prototype
of the Element
object.
Element.prototype.doSomething = function(){
// do something
}
If I understood right:
<!DOCTYPE html>
<html lang="en">
<head>
<title> Bla! </title>
<script type='text/javascript'>
function SayB1(data) {
alert (data);
}
function Init() {
var buttons = document.getElementsByClassName('button1');
for (var i in buttons) {
buttons[i].onclick = function() {
SayB1(this.innerHTML);
};
}
}
</script>
</head>
<body onload='Init();'>
<button class='button1'> B1 -1 </button>
<button class='button1'> B1 -2 </button>
<button class='button2'> B2 -1 </button>
<button class='button2'> B2 -2 </button>
<button class='button1'> B1 -3 </button>
</body>
</html>
There is multiple way of doing a jQuery like plugin. Here one way i like :
(function(scope, name, undefined){
scope[name] = function(selector){
return new Plugin(selector);
}
function Plugin(selector){
buildArrayLike(this, selector)
}
function buildArrayLike(obj, selector){
var el = document.querySelectorAll(selector);
for(var c = 0; c < el.length; c++) obj[c] = el[c];
obj.length = el.length;
}
Plugin.prototype = {
constructor : Plugin,
method : function(){
alert(this.length);
return this; //For chaining;
}
}
})(window, '$')
console.log($('div'));
$('div').method();
Fiddle : http://jsfiddle.net/Rw5BJ/