jQuery .contents() Method

Beginner
6 min read
Updated: Oct 2026
5 examples
Live preview

What Is .contents()?

.contents() (since jQuery 1.2) returns the direct child nodes of each matched element — including text and comment nodes. It is like .children(), but broader. Since 3.2 it also returns contents of <template> elements.

Remember
$("p").contents();                    // elements + text + comments
$("p").children();                    // elements only

// Official pattern — wrap non-element nodes
$("p").contents()
  .filter(function () { return this.nodeType !== 1; })
  .wrap("<b>");

// Same-origin iframe document
$("#frame").contents().find("a");
NeedUse
Children + text/comments$el.contents()
Element children only.children()
Any-depth elements.find()
Filter the result.filter()
Wrap matched nodes.wrap()

How to Use .contents()

Select a parent, call .contents(), then filter by node type if needed.

  1. Select the parent(s) — e.g. $("p") or $(".container").
  2. Call .contents() (no arguments) for every direct child node.
  3. Filter when needed: nodeType === 3 for text, !== 1 for non-elements.
  4. Chain safe methods — .wrap(), .each(), .remove() on elements.
  5. For iframes, use only same-origin frames, then .find() inside.
PieceRequired?Role
Matched setYesParents whose child nodes you want
ArgumentsNone.contents() takes no parameters
nodeType filterOftenIsolate text (3), comment (8), or element (1)
Depth—Always exactly one level

Pseudocode

Pseudocode
call $(parents).contents()

result = empty set
for each parent in the matched set:
    for each direct child node of parent:
        add node to result
        (element, text, or comment)

return result as a new jQuery object

optional next step:
    filter by nodeType before wrap / style

Cheat Sheet

Keep these facts next to .children().

TopicDetail
Syntax.contents()
SincejQuery 1.2 (<template> since 3.2)
DepthOne level only
NodesElements + text + comments
vs .children()Elements only
nodeType1 = element, 3 = text, 8 = comment
iframeSame-origin document access
DOM change?No by itself — query only

Live Preview

Compare .contents() with .children(), or wrap text nodes.

Sample paragraph mixes text and a span. Text nodes appear in .contents() only.

Hello John, how are you?

Result
Ready — pick an action and click Run.

jQuery Examples

Short, copy-ready snippets. Use Try It Yourself for a live editor.

Example 1 — Official Wrap Text in <b>

Wrap non-element child nodes inside a paragraph (official demo idea).

jQuery
$("p")
  .contents()
  .filter(function () {
    return this.nodeType !== 1;
  })
  .wrap("<b>");
Try It Yourself

How It Works

  1. Contents. Collect every direct child node of p.
  2. Filter. Keep nodes that are not elements (nodeType !== 1).
  3. Wrap. Each remaining text node gets a <b> parent.
  4. Skip. The span stays as-is.

Example 2 — Text Chunks to Paragraphs

Official idea: wrap text nodes in <p> and remove <br> separators.

jQuery
$(".container")
  .contents()
  .filter(function () { return this.nodeType === 3; })
  .wrap("<p>")
  .end()
  .filter("br")
  .remove();
Try It Yourself

How It Works

  1. Contents. Read every direct child of the container.
  2. Text only. nodeType === 3 keeps text chunks.
  3. Wrap. Each chunk becomes a paragraph.
  4. Cleanup. .end() then .filter("br").remove() drops breaks.

Example 3 — .contents() vs .children()

Same parent — compare how many nodes each method returns.

jQuery
var $box = $("#mixed");
$("#out").text(
  "contents: " + $box.contents().length +
  "\nchildren: " + $box.children().length
);
Try It Yourself

How It Works

  1. Markup. Text, a span, more text, a p, more text.
  2. contents. Counts every direct node (text + elements).
  3. children. Counts only the span and p.
  4. Pick. Use .contents() when text nodes matter.

Example 4 — Inspect Each Child nodeType

Label direct children as element, text, or comment.

jQuery
var labels = { 1: "element", 3: "text", 8: "comment" };
var lines = [];
$("#inspect").contents().each(function () {
  lines.push(labels[this.nodeType] || "other");
});
$("#out").text(lines.join(", "));
Try It Yourself

How It Works

  1. Walk. .each() visits every direct child node.
  2. Read. this.nodeType identifies the kind of node.
  3. Map. 1 → element, 3 → text, 8 → comment.
  4. Learn. Useful before choosing a filter for wrap/remove.

Example 5 — Links Inside a Same-Origin iframe

Official idea: reach into an iframe document, then find anchors (CSS-free).

jQuery
$("#frameDemo").on("load", function () {
  $(this).contents().find("a").text(function (i, t) {
    return "[link] " + t;
  });
});
Try It Yourself

How It Works

  1. Load. Wait for the iframe to finish loading.
  2. Document. .contents() returns the iframe document.
  3. Find. .find("a") selects links inside that document.
  4. Limit. Cross-origin iframes block this access.

Edge Cases & Pitfalls

Check these when .contents() looks empty or fails to style.

methods

Most jQuery APIs need elements

Calling .css() or .addClass() on text nodes is unreliable. Filter to elements, or use methods that support text nodes (like .wrap()).

depth

One level only

Text inside a child element is not returned. Call .contents() on that child, or use .find() for element descendants.

iframe

Same-origin only

Cross-origin iframes throw a security error. Wait for load before reading .contents().

whitespace

Whitespace is a text node

Newlines and spaces between tags count as text nodes. Filter empty text if you only want visible content.

Browser Support

.contents() is a core jQuery traversing method since 1.2. It works in every browser that runs your loaded jQuery version. <template> contents are included since 3.2.

✓ Stable · jQuery 1.2+

jQuery .contents()

Universal across jQuery-supported browsers. iframe access still depends on same-origin policy.

1.2+ jQuery since
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
.contents() Universal

Bottom line: Safe for everyday use. Filter by nodeType before styling text, and keep iframe demos same-origin.

Performance Notes

ApproachCostBest for
$("#box").contents()CheapLocal parent, few child nodes
$("p").contents() then filterCheap–moderateText-node edits across many paragraphs
$("div").contents() page-wideModerateAvoid — too broad; scope first

Scope to a known parent. Prefer .children() when you only need elements — it skips text/comment work you do not need.

Key Takeaways

  • Role: get direct child nodes, including text and comments.
  • vs .children(): broader set — elements plus non-elements.
  • Filter: use nodeType before wrap/style on text nodes.
  • iframe: same-origin only; wait for load first.

One line: .contents() is one-level children plus text/comments — filter by nodeType before most jQuery actions.

Frequently Asked Questions

.contents() returns a new jQuery object with all direct child nodes of each matched element — elements, text nodes, and comments. Like .children(), it goes one level down, but it also includes non-element nodes.
.children() returns only direct child elements. .contents() also includes text and comment nodes. Use .contents() when you need text nodes; use .children() for element-only queries.
Most jQuery methods expect element nodes. Text nodes use nodeType 3, comments use 8, elements use 1. Filter after .contents() before wrapping or styling text.
Yes, when the iframe is same-origin. $('#frame').contents() returns the iframe document so you can chain .find(). Cross-origin iframes are blocked for security.
No. It only inspects direct child nodes one level down. Nested text inside a child element is not included — go into that child first, or use .find() for element descendants.
No. .contents() accepts no parameters. Filter afterward with .filter() if you need only text nodes or only elements.

Next: .each() method

Iterate over a jQuery set with a callback for each element.

.each() 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.

8 people found this page helpful