Reputation: 57921
First, I'm a bit confused that I can't find the answer at once on SO. The question is about the codestyle.
Consider an example:
$('input[type=text]').on('click', doSomething);
What happens if there are no inputs on the page? The result of this selector appears to be null
and we get an error.
So, we have to make the code bigger and uglier:
var inputs = $('input[type=text]');
if (inputs) {
inputs.on('click', doSomething);
}
I love jQuery and am expecting a more elegant and short form of this solution.
UPDATE
The reason of this problem was prototype.js
included by the 3-party script on a page. Apologises, I should have tested the problem in a sandbox before posting on SO
Upvotes: 0
Views: 590
Reputation: 1
I hope this works...
$('input[type="text"]').on('click', doSomething);
Upvotes: 0
Reputation: 3059
The selector actually does not return null
if it doesn't find a match and this is intentional, so that chaining does not break. This is in line with jQuery's "write less, do more" motto.
I made a jsFiddle to illustrate this. Open up the developer tools on your browser and look at the console.
var doSomething = function(){};
$('input[type=text]').on('click', doSomething); //No error
//...because this:
var obj = $('input[type=text]'); //is a jQuery object, even
//though there are no <input> elements
console.dir(obj); //Inspect the console. you get: jQuery.fn.jQuery.init[0]
I hope that makes sense. You can simply do the former in your example:
$('input[type=text]').on('click', doSomething);
Upvotes: 2
Reputation: 2647
there's no error, just an empty object. you can go with
$('input[type=text]').on('click', doSomething);
Upvotes: 1
Reputation: 150283
a jQuery selector will always return a jQuery object, you will never get null.
$('#Not exist!').attr('foo', 'foo'); //no error, returns jQuery
unlike document.getElementById
:
document.getElementById('Not exist!') == null
Upvotes: 7