jQuery and .length>0
var sd = jQuery(".bla");
if (sd.length>0){
}
Is there any cooler way to write that code? I want some code to execute only if there are some classes named bla
. I do know I can use the each, b开发者_如何学JAVAut I do not want to and I do know I can do stuff like sd.action()
, but I do not want to.
I'm not sure how much 'cooler' this is, but just:
if ($('.bla').length) {
// Do stuff
}
Will do the trick.
Edit: If you need to re-use the selector after the check, you can still use the same syntax:
var sd = $(".bla");
if (sd.length) {
// Do stuff
}
To make the code look a little "cooler" if you don't want to use length etc..
jQuery.fn.extend({
exists: function() {
return this.length !== 0;
}
});
if (jQuery(".bla").exists()) {
console.log('found');
}
Honestly, this is a perfectly acceptable and fast way (no function calls) to do what you want. I do similar things all the time. Even using $().each
is a little slower because it requires a function call, even though it won't actually do anything.
Regarding the other answer here, which is also correct: Doing $('.bla')
more than once will also be slower. If you think you may use $('.bla')
later, it's better to store it in a variable like you have in your code. This avoids another jQuery call and lets the browser take care of the garbage collection.
Hope this makes sense! :)
The "coolest" way to make that look (in my opinion) is
if ( $('.bla').length > 0 ) {
// ...
}
You can use .size()
$(".blah").size() > 0
http://api.jquery.com/size/
Nope.
I dont think there is anything cooler. (SO wouldnt let me just answer the question with No )
精彩评论