Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
jQuery log selector: See what your selectors are selecting!
/*!
* jQuery log selector - v0.1pre - 6/2/2011
* http://benalman.com/
*
* Copyright (c) 2011 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
// Log the selector used to select elements to each selected element,
// otherwise to the body. Hover over logged selectors to highlight
// stuff all fancy-like.
(function($) {
// A class name "base" that should be fairly unique.
var base = 'selector-cb-omg-unique';
// A (future) reference to a style element.
var style;
// The styles that will go in that style element.
var styles = ('.%-phover {background: #afa;}'
+ '.% {padding: 1px; display: block; color: #0a0; font-weight: 700;}'
+ '.%-fail {color: #f00; font-style: italic;}'
+ '.%-hover {color: #fff; background: #0a0;}').replace(/%/g, base);
$.fn.logSelector = function() {
// Get all elements that match the given selector, but that are NOT our
// custom log elements.
var elems = this.not('.' + base);
// Create a span with a className that can be filtered out, and content in
// the format: selector [#matches]
var spans = $('<span/>', {
className: base,
html: this.selector + ' [' + elems.length + ']'
});
// If this is the first run, create a style element containing the
// relevant CSS rules.
if ( !style ) {
style = $('<style>' + styles + '</style>').appendTo('head');
}
if ( elems.length ) {
// If elements were selected, bind a hover event handler to each span.
spans.hover(function(e) {
var state = e.type == 'mouseenter';
elems.toggleClass(base + '-phover', state);
spans.toggleClass(base + '-hover', state);
});
} else {
// If no elements were selected, add a fail class to each span.
spans.addClass(base + '-fail');
// The span elements will be appended to the body.
elems = $('body');
}
// Note: spans MUST be re-set here, in cases where elems has a length > 1!
spans = spans.appendTo(elems);
// Make this method chainable.
return this;
};
})(jQuery);
@cowboy

This comment has been minimized.

Copy link
Owner Author

@cowboy cowboy commented Oct 22, 2010

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment