jQuery Traversing

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 32 Tutorials
DOM collections

What You’ll Learn

A jQuery selection is a collection of DOM elements, not a single node. Traversing methods let you grow, shrink, or navigate those collections before you style or manipulate them. Start with .add() to union sets — this hub links to 32 traversing method tutorials (more coming soon).

01

Collections

Matched sets

02

.add()

Union sets

03

Selectors

Match more

04

Chaining

Stack & .end()

05

Deduped

Unique nodes

06

32 guides

Full index

Introduction

When you write $("li.active"), jQuery stores every matching list item in an internal array-like object. Often you need to include more elements — siblings, headings, footer links — without running a second query and merging results yourself.

What Is jQuery Traversing?

Traversing covers methods that operate on jQuery collections: combining sets with .add(), filtering with .not(), walking the tree with .parent() and .find(), and returning to earlier selections with .end(). These methods answer “which elements am I working with?” — not “how do I change the HTML?”

💡
Beginner Tip

Think of a jQuery object as a basket of DOM nodes. .add() puts more items in the basket; .not() removes some; .end() swaps back to the basket you had before the last filter.

Key Features

  • Non-destructive — Traversing returns new jQuery objects; earlier selections stay on the internal stack.
  • Flexible arguments.add() accepts selectors, DOM nodes, HTML strings, or other jQuery objects.
  • Automatic deduplication — The same element never appears twice in one collection.
  • Chain-friendly — Combine traversing with manipulation: $("h2").add("p").css("color", "navy").

📝 Syntax

Minimal .add() workflow:

jQuery
// Start with list items, add every paragraph
const $combined = $("li").add("p");

$combined.addClass("highlight");

Method groups

GroupExamplesPurpose
Collection building.add()Union the current set with more matched elements
Filtering.not(), .filter()Remove or keep elements in the current set
Tree walking.parent(), .children(), .find()Move to related nodes in the DOM
Stack navigation.end()Return to the previous jQuery object on the chain stack

This hub currently documents .add() in depth. Additional traversing tutorials will appear in the index as they are published.

⚡ Quick Reference

GoalMethod
Add elements by selector$("li").add("p")
Add a DOM element$("li").add(document.getElementById("footer"))
Add parsed HTML$("li").add("<span class='badge'>new</span>")
Union two jQuery objects$("h2").add($("h3"))
Scope selector to a context$("li").add("p", "#sidebar")
Undo last filter (stack)$("div").find("p").end() → back to div

When to Use Traversing

  • Batch styling — Highlight headings and paragraphs together with one .add() chain.
  • Form validation — Collect inputs, labels, and error messages into one set before toggling classes.
  • Event handlers — Attach one listener to multiple unrelated element groups.
  • Avoid duplicate queries — Merge selections instead of looping two separate jQuery objects.
  • Progressive tutorials — Learn collection building with .add() before filters and tree walkers.

👀 .add() vs .addBack() vs .end()

Four traversing ideas beginners often mix up — all work on collections, not DOM insertion:

.add() → union current set + matched elements → grows with new selector/DOM input .addBack() → union current set + previous stack set → merges after .find(), .nextAll(), etc. .end() → return previous stack set only → discards current selection .not() → remove matching elements from set → shrinks the collection Example: $("li.third-item").nextAll().addBack() // item 3 + following siblings Example: $("li").add("p") // all li PLUS all p $("div").find("p").addBack() // div AND its p children $("div").find("span").end() // back to $("div") only

Traversing Method Tutorial Index

Search by method name or browse by category. Each tutorial includes syntax, try-it examples, and FAQs.

Collection Building

1 tutorial

Expand the current matched set by combining additional elements.

MethodDescriptionTutorial
.add()Create a new jQuery object from the union of the current set and additional elements matched by selector, DOM node, HTML, or jQuery object.Open

Selection Stack

4 tutorials

Merge or restore previous matched sets from jQuery's internal traversal stack.

MethodDescriptionTutorial
.addBack()Add the previous set of elements on the traversal stack to the current set, optionally filtered by a selector.Open
.andSelf()Legacy name for the same stack merge as .addBack() — deprecated in jQuery 1.8, removed in jQuery 3.0.Open
.end()End the most recent filtering operation and return the matched set to its previous state on the internal stack.Open
.pushStack()Push an array of DOM elements onto jQuery’s selection stack as a new set — enables .end() for plugins and custom traversal.Open

Tree Traversal

15 tutorials

Move through the DOM tree — descendants, children, ancestors, and node collections.

MethodDescriptionTutorial
.children()Get direct child elements one level down from each matched parent, optionally filtered by a selector.Open
.parent()Get the immediate parent element of each matched node — one level up the DOM tree, optionally filtered by a selector.Open
.parents()Get every ancestor of each matched element — walking up the DOM tree toward html, optionally filtered by a selector.Open
.parentsUntil()Get ancestors of each element up to but not including a stop selector, DOM node, or jQuery object — optionally filtered by a second selector.Open
.closest()Walk up the DOM tree from each element (including self) and return the first ancestor that matches a selector.Open
.offsetParent()Get the closest ancestor element that is positioned — CSS position relative, absolute, or fixed.Open
.contents()Get all direct child nodes — elements, text, and comments — one level down from each matched parent.Open
.find()Get descendants of each element in the current set, filtered by a selector, jQuery object, or DOM element.Open
.next()Get the immediately following sibling of each element in the current set, optionally filtered by a selector.Open
.nextAll()Get all following siblings of each element in the current set, optionally filtered by a selector.Open
.nextUntil()Get all following siblings of each element up to but not including the element matched by a selector, DOM node, or jQuery object.Open
.prev()Get the immediately preceding sibling of each element in the current set, optionally filtered by a selector.Open
.prevAll()Get all preceding siblings of each element in the current set, optionally filtered by a selector — in reverse document order.Open
.prevUntil()Get preceding siblings of each element up to but not including a stop selector, DOM node, or jQuery object — optionally filtered by a second selector.Open
.siblings()Get all siblings of each element in the current set — every element at the same parent level except the element itself, optionally filtered by a selector.Open

Collection Iteration

2 tutorials

Loop over matched elements — side effects with .each() or transform and collect return values with .map().

MethodDescriptionTutorial
.each()Iterate over each element in the matched set, executing a callback with the index and DOM element.Open
.map()Pass each element through a callback and build a new jQuery object from the return values.Open

Set Filtering

10 tutorials

Narrow or test a matched collection — boolean checks, first or last element, descendant containment, by index, even or odd positions, selector, or callback tests.

MethodDescriptionTutorial
.eq()Reduce the matched set to the single element at the specified zero-based index, counting from the end when negative.Open
.slice()Reduce the matched set to a subset specified by a start index and optional end index — like Array.prototype.slice, with negative indices from the end.Open
.even()Reduce the matched set to elements at even zero-based indexes — 0, 2, 4, and so on.Open
.odd()Reduce the matched set to elements at odd zero-based indexes — 1, 3, 5, and so on.Open
.filter()Reduce the matched set to elements that match a selector, pass a callback test, or appear in a given jQuery object or DOM element.Open
.not()Remove elements from the matched set — keep elements that do not match a selector, fail a callback test, or match a provided DOM element or jQuery object.Open
.first()Reduce the matched set to the first element in the set — equivalent to .eq(0).Open
.has()Reduce the matched set to elements that have a descendant matching a selector or DOM element.Open
.is()Check whether at least one element in the matched set matches a selector, callback, jQuery object, or DOM element — returns true or false.Open
.last()Reduce the matched set to the final element in the set — equivalent to .eq(-1).Open

Examples Gallery

Include jQuery 3.7+ and open DevTools Console (F12) to run each snippet. Assume basic HTML with <li>, <p>, and <h2> elements on the page.

📚 Combining Sets

Core .add() patterns for growing a collection.

Example 1 — Add Elements by Selector

Select all list items, then union every paragraph into the same collection.

jQuery
const $items = $("li").add("p");

console.log("Count:", $items.length);
$items.css("outline", "2px solid #7c3aed");
.add() Tutorial

How It Works

.add("p") searches the document for paragraphs and merges them with the existing li set. The result is a new jQuery object — the original $("li") is unchanged.

Example 2 — Add a DOM Element Directly

Pass a raw DOM node when you already have a reference from vanilla JavaScript.

jQuery
const footer = document.getElementById("footer");
const $withFooter = $("h2").add(footer);

console.log("Includes footer:", $withFooter.is(footer)); // → true

How It Works

jQuery accepts Element nodes alongside selectors. Useful when an API returns a native DOM reference you want in an existing chain.

Example 3 — Union Two jQuery Objects

Merge two independent queries without re-running a complex selector.

jQuery
const $headings = $("h2, h3");
const $emphasis = $("strong, em");
const $all = $headings.add($emphasis);

$all.addClass("text-accent");

How It Works

When the same node appears in both collections, jQuery keeps one copy. Duplicates are removed automatically.

Example 4 — Add with a Context Element

The optional second argument limits where the selector runs — like a scoped $("p", context).

jQuery
const $navLinks = $("#nav a");
const $sidebarLinks = $navLinks.add("a", "#sidebar");

console.log("Sidebar links included:", $sidebarLinks.length);

How It Works

Without context, .add("a") would match every anchor on the page. The second argument restricts the search to #sidebar only.

💡 Best Practices

✅ Do

  • Use .add() to batch actions on unrelated groups
  • Pass a context when the selector would otherwise be too broad
  • Chain .add() before one .css() or .on() call
  • Store merged collections in a variable for reuse
  • Use .end() to return after .find() or .filter()

❌ Don’t

  • Confuse .add() with .append() or .after()
  • Expect .add() to insert HTML into the document tree
  • Re-query the DOM when you can union existing jQuery objects
  • Forget that results are deduplicated — order may differ from input
  • Skip the method tutorial when you need edge-case syntax

Key Takeaways

Knowledge Unlocked

Four things to remember about Traversing

Your starting point for 32 method tutorials.

4
Core concepts
02

.not()

Filter out

Shrink
03

.end()

Go back

Stack
32 04

Index

Search all

Ref

❓ Frequently Asked Questions

Traversing methods work on jQuery collections — they move between elements, filter sets, or combine matched nodes without inserting HTML into the DOM. .add() is a collection-building method that unions the current set with more elements.
.add(selector) returns a new jQuery object containing every element in the current set plus any elements matched by the argument. You can pass a CSS selector, DOM element, HTML string, or another jQuery object.
.add() combines two groups of elements into one jQuery collection for further chaining — it does not insert nodes into the DOM. .append() is a manipulation method that inserts content as a child of matched elements.
No. Like most jQuery methods, .add() returns a new jQuery object. The previous selection remains available — use .end() after a chain of filters to pop back to an earlier set on the internal stack.
Yes. $("li").add($("p")) unions both collections. jQuery deduplicates elements so the same node is not listed twice in the result.
Read the overview, study the add vs not vs end comparison, try the hub examples, then open the .add() tutorial for full syntax, five try-it labs, and method-specific FAQs.
Did you know?

jQuery keeps an internal stack of collections as you chain traversing methods. After $("div").find("p").add("span"), calling .end() twice walks back through find and returns you to the original $("div") set.

🎉 Conclusion

jQuery Traversing helps you shape which elements you operate on before changing content or styles. Start with .add() to union collections, keep .not() and .end() in mind for filtering and stack navigation, and use the searchable index as more method tutorials go live.

Open the .add() tutorial next for full syntax, interactive labs, and method-specific FAQs.

Start with .add()

Learn how to combine the current jQuery set with additional matched elements.

.add() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

4 people found this page helpful