jQuery If Statement Examples

Tech reviewed: Deepak Prasad
jQuery If Statement Examples

jQuery does not add a new if keyword, but it is often used inside jQuery code to control what happens after a selection, event, or AJAX response. The real value is in combining jQuery selections with normal JavaScript conditionals.

That pattern is useful when you need to check element count, visibility, or data before applying jQuery hide() or another DOM action.

Tested on: Node.js v20.18.2. A short note after each runnable snippet describes what you should see in the console.


Method 1: Use if with a jQuery selection

A common check is whether the selection matched any elements.

javascript
const count = 1;

if (count > 0) {
  console.log("jquery-if:", "matched");
}
Output

Expected output:

You should see one line logging jquery-if: matched.

Use this pattern before you call a method on a collection that might be empty.


Method 2: Use else if and else for branch logic

You can branch your code based on the state of the page or the selected element.

javascript
const status = "hidden";

if (status === "visible") {
  console.log("jquery-status:", "show");
} else if (status === "hidden") {
  console.log("jquery-status:", "hide");
} else {
  console.log("jquery-status:", "toggle");
}
Output

Expected output:

You should see one line logging jquery-status: hide.

This style is common when you are deciding whether to hide, show, or toggle an element.


Method 3: Combine conditional checks with jQuery methods

Check the state first, then call the effect or DOM method.

javascript
const visible = false;

if (visible) {
  console.log("action:", "show");
} else {
  console.log("action:", "hide");
}
Output

Expected output:

You should see one line logging action: hide.

That pattern keeps jQuery code predictable and easy to maintain.


Summary

A jQuery if statement is really normal JavaScript condition logic used around jQuery selections and events. Use it to check state, branch cleanly, and decide whether to show, hide, or update an element.


Official documentation

Olorunfemi Akinlua

Boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs user-friendly interfaces to enhance digital …

  • JavaScript
  • Web Design