Description:
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 classmydivclass
. If it returns0
, 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?