jQuery Empty Result Warning - AddOn
* jQuery Add On to warn, if a selection returns empty.
* @author Daniel Suess
* @version 0.1 alpha
HTML
<script src="https://code.jquery.com/ui/1.11.3/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
<div id="existing-id">Existing Block</div>
<div id="existing-id-2">Another Existing Block</div>
<br/>
<br/>sample jQuery UI component to prove, it does not interfere with other plugins:
<div id="datepicker"></div>
<div id="console">Console:
<br/>(should show 3 warnings)</div>
CSS
#console {
font-family: monospace;
background-color: #efefef;
margin-top: 3em;
padding: 0.5em;
border: 1px solid grey;
}
.log {
color: green;
}
.warn {
color: red;
}
.green-bg {
background-color: #89FF65;
}
#existing-id, #existing-id-2 {
border: 1px dashed black;
min-height: 2em;
}
JavaScript
// just for jsFiddle and console.warn to work
window.console = {
log: function (text) {
var msg = document.createElement('div');
msg.innerHTML = 'LOG ' + text;
msg.className = 'log';
document.getElementById('console').appendChild(msg);
},
warn: function (text) {
var msg = document.createElement('div');
msg.innerHTML = 'WARN ' + text;
msg.className = 'warn';
document.getElementById('console').appendChild(msg);
}
};
/*
* jQuery Empty Result Warning - AddOn
* Add On to warn, if a selection returns empty.
* @author Daniel Suess
* @version 0.1 alpha
*/
(function (jQuery) {
"use strict";
if (jQuery && window.console && window.console.log && window.console.warn) {
console.log('### Loading jQuery Empty Result Warning - AddOn');
// backup
var initOri = jQuery.fn.init;
// replace
$.fn.init = function (sel, ctx, rootjQuery) {
var result = initOri.apply(this, arguments);
//var result = initOri(sel);
if (sel === undefined) {
// avoid warnings for undefined
return null;
}
if (result.length === 0) {
console.warn('empty result: $(\'' + sel + '\')');
}
return result;
};
// reset prototype for $ constructor
jQuery.fn.init.prototype = jQuery.fn;
}
}($));
// test cases
$(); // do it
$('#existing-id').addClass('green-bg'); // do it
$('#existing-id-2').addClass('green-bg'); // do it
$('#non-existing-id').addClass('green-bg'); // should warn
$('#existing-id-2').removeClass('green-bg'); // do it
$('.XXXX').removeClass('green-bg'); // should warn
$("#datepicker").datepicker(); // do it, but show warning too as it checks for nested IDs