# jQuery Quick Reference

*Selectors, DOM, events, AJAX, effects, traversal*

> Source: jQuery Documentation (api.jquery.com) · MIT

## Selectors

### Basic Selectors

```
$("p")               // all <p> elements
$(".btn")            // class selector
$("#main")           // ID selector
$("ul > li")         // direct children
$("input[type='text']") // attribute selector
```

### Common Selectors

| Command | Description |
|---------|-------------|
| `$('*')` | All elements |
| `$('a, span')` | Multiple selectors |
| `$(':first')` | First matched element |
| `$(':last')` | Last matched element |
| `$(':even') / $(':odd')` | Even/odd indexed elements |
| `$(':visible') / $(':hidden')` | Visibility filters |
| `$(':contains(text)')` | Elements containing text |
| `$(':has(selector)')` | Elements containing selector match |

## DOM Manipulation

### Content & Structure

```
$("#el").html("<b>Bold</b>");   // set inner HTML
$("#el").text("Plain text");     // set text content
$("ul").append("<li>New</li>");  // add at end
$("ul").prepend("<li>First</li>"); // add at start
```

### Insert & Remove

```
$("<p>Hello</p>").insertAfter("#el");  // insert after
$("<p>Hi</p>").insertBefore("#el");     // insert before
$("#el").remove();     // remove element from DOM
$("#el").empty();      // remove all children
```

### Methods

| Command | Description |
|---------|-------------|
| `.html()` | Get/set inner HTML |
| `.text()` | Get/set text content |
| `.append() / .prepend()` | Add child at end/start |
| `.after() / .before()` | Insert sibling after/before |
| `.wrap()` | Wrap element with new parent |
| `.clone()` | Deep copy element |
| `.replaceWith()` | Replace element |

## Events

### Binding Events

```
$(".btn").on("click", function () {
  $(this).toggleClass("active");
});
$(document).on("click", ".dynamic", handler); // delegation
$(".btn").off("click"); // remove handler
```

### Shorthand Methods

| Command | Description |
|---------|-------------|
| `.click(fn)` | Click handler |
| `.hover(fnIn, fnOut)` | Mouse enter/leave |
| `.focus() / .blur()` | Focus gained/lost |
| `.change(fn)` | Value changed (input/select) |
| `.submit(fn)` | Form submission |
| `.keydown() / .keyup()` | Keyboard events |

### Document Ready

```
$(document).ready(function () { /* DOM loaded */ });
$(function () { /* shorthand */ });
```

## Effects & Animation

### Show / Hide / Toggle

```
$("#el").hide(400);          // hide with animation
$("#el").show(400);          // show with animation
$("#el").toggle();           // toggle visibility
$("#el").fadeIn(600);        // fade in
$("#el").slideDown(400);     // slide down
```

### Custom Animation

```
$("#el").animate({
  opacity: 0.5,
  left: "+=50px",
  height: "toggle"
}, 1000, function () { /* complete */ });
```

### Effect Methods

| Command | Description |
|---------|-------------|
| `.fadeIn() / .fadeOut()` | Animate opacity |
| `.fadeToggle()` | Toggle with fade |
| `.slideDown() / .slideUp()` | Animate height |
| `.animate(props, ms)` | Custom CSS animation |
| `.stop()` | Stop current animation |
| `.delay(ms)` | Delay next queued effect |

## AJAX

### Shorthand Methods

```
$.get("/api/data", function (data) { console.log(data); });
$.post("/api/data", { name: "Alice" }, function (res) {});
$.getJSON("/api/items", function (json) {});
$("#el").load("/fragment.html"); // load HTML into element
```

### Full $.ajax

```
$.ajax({
  url: "/api/data",
  method: "POST",
  data: JSON.stringify({ key: "val" }),
  contentType: "application/json",
  success: (res) => console.log(res),
  error: (xhr) => console.error(xhr.status)
});
```

### AJAX Options

| Command | Description |
|---------|-------------|
| `url` | Request URL |
| `method` | HTTP method (GET, POST, ...) |
| `data` | Data to send |
| `dataType` | Expected response type |
| `contentType` | Request content type |
| `success / error` | Callback functions |
| `headers` | Custom request headers |

## Traversal

### Tree Navigation

```
$("li").parent();           // direct parent
$("li").parents("ul");      // all matching ancestors
$("ul").children("li");     // direct children
$("ul").find(".active");    // all matching descendants
$("li").siblings();         // sibling elements
```

### Traversal Methods

| Command | Description |
|---------|-------------|
| `.parent() / .parents()` | Direct parent / all ancestors |
| `.children() / .find()` | Direct children / all descendants |
| `.siblings()` | All sibling elements |
| `.next() / .prev()` | Next/previous sibling |
| `.closest(sel)` | Nearest ancestor matching selector |
| `.first() / .last()` | First/last in matched set |
| `.eq(index)` | Element at index |
| `.filter(sel)` | Reduce to matching elements |

## Attributes & CSS

### Attributes

```
$("img").attr("src");              // get attribute
$("img").attr("src", "new.jpg");   // set attribute
$("img").removeAttr("title");      // remove attribute
$("input").prop("checked", true);  // set property
```

### CSS & Classes

```
$(".box").css("color", "red");     // set single style
$(".box").css({ color: "red", fontSize: "14px" }); // multi
$("p").addClass("highlight");
$("p").removeClass("highlight");
$("p").toggleClass("active");
$("p").hasClass("active");         // returns boolean
```

## Forms

### Values & Serialization

```
$("input").val();              // get value
$("input").val("new value");   // set value
$("form").serialize();         // "name=Alice&age=30"
$("form").serializeArray();    // [{name, value}, ...]
```

### Form Selectors

| Command | Description |
|---------|-------------|
| `$(":input")` | All form elements |
| `$(":checked")` | Checked checkboxes/radios |
| `$(":selected")` | Selected option elements |
| `$(":disabled")` | Disabled elements |
| `$(":text")` | Text inputs |

## Utilities

### Array & Object Helpers

```
$.each([1, 2, 3], function (i, val) { /* iterate */ });
$.each(obj, function (key, val) { /* iterate object */ });
$.extend({}, defaults, options); // merge objects
$.inArray("b", ["a", "b", "c"]); // returns 1 (index)
```

### Utility Methods

| Command | Description |
|---------|-------------|
| `$.each(arr, fn)` | Iterate array or object |
| `$.extend(target, ...)` | Merge objects (shallow) |
| `$.inArray(val, arr)` | Index of value (-1 if missing) |
| `$.isArray(obj)` | Check if array |
| `$.trim(str)` | Remove leading/trailing whitespace |
| `$.parseJSON(str)` | Parse JSON string |
| `$.map(arr, fn)` | Transform array elements |

## Common Patterns

### Chaining

```
$("ul")
  .find("li")
  .addClass("item")
  .first()
  .css("font-weight", "bold");
```

### Plugin Pattern

```
$.fn.highlight = function (color) {
  return this.each(function () {
    $(this).css("background", color || "yellow");
  });
};
$("p").highlight("pink");
```

### Conflict Resolution

```
// Avoid $ conflicts with other libraries
jQuery.noConflict();
jQuery(document).ready(function ($) {
  $(".btn").click(handler); // $ safe inside
});
```
