11
I would like to create a very simple library containing only the functions I most use, following an idea similar to those 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 on 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 in jQuery, for example:
$("foo").fazAlgo().eFazMaisAlgumaCoisa().eOutra();
.
I think I’m a little far from it because my function only returns me an element in the document and what I’m looking for is 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 don’t know if it’s correct. Follow 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
within the HTML element (innerHTML
). How would I call her that:
$("foo").inner("Algum Texto");
?
I’m going to check :D
– Renan Gomes
+1, is exactly what jQuery does, and includes the mechanism for treating sets of elements.
– bfavaretto