Skip to content

Instantly share code, notes, and snippets.

@manuelbieh
Last active August 29, 2015 14:01
Show Gist options
  • Save manuelbieh/7755710428d0212aabf9 to your computer and use it in GitHub Desktop.
Save manuelbieh/7755710428d0212aabf9 to your computer and use it in GitHub Desktop.
Might be useful for debugging ("where is this f*ing margin coming from?!?").
/*! document.getElementsByStyle()
*
* Returns an array (not a NodeList!!) containing all elements matching certain
* computed style rules.
*
* Usage:
* var blockElements = document.getElementsByStyle('display: block');
*
* PS: I know it might not be the best idea to extend HTMLElement/HTMLDocument since it
* returns an array not a NodeList (like getElementsByTagName). But I recommend to use
* it for debugging purposes only, it's slow!
*
* @author Manuel Bieh
* @url http://www.manuelbieh.com/
* @version 1.0.0
* @license MIT
*
*/
;(function(window) {
var getElementsByStyle = function(style) {
var elements = this.querySelectorAll('*');
var matched = [];
style = style.split(':');
var prop = style.splice(0,1)[0];
var value = style.join(':').replace(/^\s*/g,'').replace(/(\s|;)*$/g, '');
for(var i = 0; i < elements.length; i++) {
var el = elements[i];
var propVal = window.getComputedStyle(el).getPropertyValue(prop);
if(propVal === value) {
matched.push(el);
}
}
return matched;
}
var extend = [HTMLDocument, HTMLElement];
extend.forEach(function(obj) {
obj.prototype.getElementsByStyle = getElementsByStyle;
});
}(this));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment