Learn how to do ‘if’ statements with jQuery.
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
}
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){