Need to change this JQuery code to check for element existence prior to processing [duplicate]

First, as @Archer pointed out in the comments above, this plugin is not coded properly. The idiomatic jQuery plugin will fail silently when its method is invoked on a jQuery object with no elements.

As seen from the code here, this plugin either runs the console.log() or an alert() if the console doesn’t exist when there’s no element:

if ($(this).length == 0) {
    if (window.console && window.console.log) {
        window.console.log('Element does not exist in DOM!');
    } else {
        alert('Element does not exist in DOM!');    
    }
    return false;
}

This is pretty bad. The plugin does have a debugMode that can be disabled, but it wouldn’t help because that flag isn’t used here. To modify the source, you could change the first line above:

if (opts.debugMode && $(this).length == 0) {

And then be sure to set debugMode:false in your settings.

But how this ultimately affects IE is that it doesn’t have a console object defined when the dev tools are closed (and never in IE6/7), so a simple solution would be to make sure that object is defined with a NO-OP function.

if (!window.console) {
    window.console = {
        log: function() {}
    };
}

Now it will find the console and invoke the empty function in IE instead of firing the alert().

There are other methods on the console object that should probably be filled in too, but the log() is the most common.


If you’re so inclined, it may not be a bad idea to file a bug report with the developer. It seems that the project hasn’t been updated in the last 2 years, so I don’t know if it’ll help, but it couldn’t hurt.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)