Last updated on

Bad news.

There isn’t a jQuery if statement.

But then how do you write conditional statements with jQuery?

Well, you might be forgetting that jQuery is just a JavaScript library.  It’s merely an extension on top of the native JavaScript language.

Therefore, you can simply use JavaScript’s built in if statement syntax to create a jQuery if statement.

Quick Example

var $myElement = $('#myElem');
if($myElement.val().length > 0){
  // Do something now that there is some value in the element
}

The above quick example shows that creating a jQuery if statement is exactly the same as using the native JavaScript if. The only difference is that the condition you are checking (the bit inside the parentheses) contains a jQuery reference (the $myElement variable) rather than plain JavaScript variable.

The above example demonstrates a particular case where you might want to select an element on the page (with the id ‘myElem’) and then checks if the length of the value of the element is bigger than 0.  In other words, it’s an input field element that has a value entered in to it.

What kinds of expressions can be used in a jQuery if statement

Once you have jQuery installed, anything that’s a valid jQuery expression is fine to use inside a jQuery if statement.

You can make use of the full range of jQuery’s functions and properties to make complex expressions inside of the if statement’s parentheses.

A common thing to do might be to count the number of elements on a page that match a particular CSS selector.

For example:

var numberOfDivs = $('div').length;
if(numberOfDivs === 0){
  alert('Wow, there are no divs on your page!');
}

So it makes sense to store your reference to a jQuery condition in a variable and just plug that straight in to a standard JavaScript if statement.

If jQuery statement with else clause

Of course it’s simple to extend the if statement to include an else clause too.

if($('#username').val() === 'james'){
  alert('Hi James');
} else {
  alert('Hi someone else');
}

Again, it doesn’t matter what the jQuery code is you use in the if statement as long as it evaluates to a condition that is either true or false.

Conclusion

That’s it – no jQuery if statement is available but you can easily use a native JavaScript if statement alongside your jQuery code.