Last active
December 17, 2015 04:58
-
-
Save bergantine/5554117 to your computer and use it in GitHub Desktop.
Dolla javascript selector. From http://flippinawesome.org/2013/05/06/5-things-you-should-stop-doing-with-jquery/. #javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div class="container"> | |
<ul> | |
<li id="pink">Pink</li> | |
<li id="salmon">Salmon</li> | |
<li id="blue">Blue</li> | |
<li id="green">Green</li> | |
<li id="red">Red</li> | |
</ul> | |
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// custom lightweight selector implementation | |
// nickname: dolla | |
window.$ = function(selector) { | |
return document.querySelector(selector); | |
}; | |
window.$$ = function(selector) { | |
var items = {}, | |
results = [], | |
length = 0, | |
i = 0; | |
// this doesn't work on IE 8- and Blackberry Browser | |
results = Array.prototype.slice.call(document.querySelectorAll(selector)); | |
length = results.length; | |
// add the results to the items object | |
for ( ; i < length; ) { | |
items[i] = results[i]; | |
i++; | |
} | |
// add some additional properties to this items object to | |
// make it look like an array | |
items.length = length; | |
items.splice = [].splice(); | |
// add an 'each' method to the items | |
items.each = function(callback) { | |
var i = 0; | |
for ( ; i < length; ) { | |
callback.call(items[i]); | |
i++; | |
} | |
} | |
return items; | |
}; | |
// end custom selector API | |
(function() { | |
// select the green item and crank up the font size | |
$("#green").style.fontSize = "2em"; | |
// select item1 by id and change it's background color to salmon | |
$$("li").each(function() { | |
this.style.backgroundColor = this.id; | |
}); | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment