I would like to create a very simple library containing only the functions I use most, following an idea similar to the ones in jQuery. For example:
I created the following function to get an element:
var $ = function(el, index){
if(index)
return document.querySelectorAll(el)[index-1];
return document.getElementById(el) || document.querySelector(el);
};
Some tests I did, in the following code snippet:
var $ = function(el, index){
if(index)
return document.querySelectorAll(el)[index-1];
return document.getElementById(el) || document.querySelector(el);
};
$("minha-div-com-id").innerHTML = "pegou pelo ID";
$(".minha-div-com-class").innerHTML = "pegou pela classe";
$(".minhas-divs", 1).innerHTML = "pegou o primeiro elemento com classe '.minha-divs'";
$(".minhas-divs", 3).innerHTML = "pegou o terceiro elemento com classe '.minha-divs'";
<p id="minha-div-com-id"></p> <!-- pelo id -->
<p class="minha-div-com-class"></p> <!-- pela classe -->
<p class="minhas-divs" style='color:blue'></p> <!-- 1 -->
<p class="minhas-divs"></p> <!-- 2 -->
<p class="minhas-divs" style="color:red"></p> <!-- 3 -->
This already meets the basics of what I would like to do. But I wanted to include some functions like jQuery, for example:
$("foo").fazAlgo().eFazMaisAlgumaCoisa().eOutra();
.
I think I'm kind of far from it because my function only returns me an element in the document and what I'm looking for would be a builder . Maybe the term is wrong, but I know this technique by that name in other languages.
I even got something "more or less", but I do not know if it's correct. Here's what I got:
(function(__window){
var lib = {};
__window.minhaBibioteca = lib;
lib.alerta = function(args){
alert(args);
return lib;
};
lib.outroAlerta = function(args){
return lib.alerta(args);
};
})(window);
/**
* Onde consigo usar assim:
*/
minhaBibioteca.alerta("Alerta {1º}")
.outroAlerta("Outro alerta {1º}")
.alerta("Alerta {2º}");
/**
* ... que ainda não é o que estou buscando,
* com o alert é simples, mas quando trata-se de manipular um
* elemento, eu não sei como fazer...
**/
Assuming I have a function called inner(str)
which basically inserts the content / value of str
into the HTML element ( innerHTML
). How would I do to call it like this:
$("foo").inner("Algum Texto");
?