Reputation: 12846
I was trying to find out a method to check whether an element with specific class exists.
Then I encountered this code:
if ($(".mydivclass")[0])
{
// Do something if class exists
}
else
{
// Do something if class does not exist
}
Which states that if there is a true value at the first ([0])
index, then assume class exists.
Now again I can find another solution like:
if ($(".mydivclass").size())
{
// code here
}
The size()
method just returns the number of elements that the jQuery selector selects - in this case the number of elements with the class mydivclass
. If it returns 0
, the expression is false, and therefore there are none, and if it returns any other number, the divs must exist.
So my question lies, which one of these two is the faster one?
Upvotes: 0
Views: 229
Reputation: 1709
So I am curious also, and I did some test for following 5 methods:
my scripts:
var testCount = 100000;
var cn = 'container';
var cns = '.'+cn;
console.time('[0]');
for(var i=testCount;i>0;i--){
if($(cns)[0]){};
}
console.timeEnd('[0]');
console.time('.size');
for(var i=testCount;i>0;i--){
if($(cns).size()){};
}
console.timeEnd('.size');
console.time('.length');
for(var i=testCount;i>0;i--){
if($(cns).length){};
}
console.timeEnd('.length');
console.time('querySelector');
for(var i=testCount;i>0;i--){
if(document.querySelector(cns)){};
}
console.timeEnd('querySelector');
console.time('classname');
for(var i=testCount;i>0;i--){
if(document.getElementsByClassName(cn)[0]){};
}
console.timeEnd('classname');
I do the test in this page, just pasting the code and run it in chrome console. And it turns out that the first 3 methods have similar performance, only difference by <100 ms.
querySelector method is fast when the class exist but slowest when class is not exist...Don't know why it is like this.
The getElementsByClassName method are fastest, only takes 1/10 time of the first 3 method.
this is one of the result:
[0]: 2168.198ms
.size: 1951.075ms
.length: 1936.117ms
querySelector: 672.186ms
classname: 242.048ms
and to answer your question, I think the two do not really have a faster one, both slow for this purpose...
Upvotes: 0
Reputation: 8047
$('.mydivclass')[0]
is the fastest way.
Sources:
Performance test:
http://jsperf.com/check-if-div-exists
Related question:
Check if div with certain class name exists
Upvotes: 2