JavaScript Document createExpression() Method

Beginner
⏱️ 11 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Baseline Widely available
Instance method

What You’ll Learn

document.createExpression() is an instance method that compiles an XPath string into an XPathExpression you can evaluate again and again (see MDN Document: createExpression()). Learn how it differs from a one-shot document.evaluate(), how to reuse expressions on different contexts, optional namespace mapping, and five try-it labs.

01

Kind

Instance method

02

Input

XPath string

03

Returns

XPathExpression

04

Next

.evaluate()

05

Best for

Reuse

06

Status

Baseline

Introduction

XPath is a query language for selecting nodes in an XML/HTML tree — similar in spirit to CSS selectors, but with a different syntax and more power for some document shapes.

document.createExpression(xpathText) does not run the query yet. It compiles the path into an XPathExpression. Then you call xpathExpr.evaluate(contextNode) to get an XPathResult. MDN highlights that the compiled expression can be reused for repeated evaluations.

💡
Compile once, evaluate many times

MDN sample: create //div once, evaluate against document, then again against a nav context node.

MDN also requires: call createExpression on the same document you will evaluate against.

Related tutorials: createElement(), createEvent().

Understanding document.createExpression()

An instance method on the page’s document object (part of the XPathEvaluatorBase API on Document; MDN).

  • xpathText — string containing the XPath expression to compile (MDN).
  • namespaceURLMapper — optional function mapping a prefix to a namespace URL, or null (MDN).
  • Return value — a compiled XPathExpression.
  • EvaluatexpathExpr.evaluate(context) returns an XPathResult (MDN).
  • Same document — create and run against the same document (MDN).
  • Reuse — keep the expression object and evaluate it on different contexts.

📝 Syntax

General form of Document.createExpression (MDN):

JavaScript
createExpression(xpathText, namespaceURLMapper)

Parameters

  • xpathText — string; the XPath expression to compile (MDN).
  • namespaceURLMapper — function that maps a namespace prefix to a namespace URL, or null if none is needed (MDN). Typical signature: (prefix) => namespaceURI | null.

Return value

An XPathExpression ready for evaluate().

MDN basic pattern

JavaScript
const xpathExpr = document.createExpression("//div");
const xpathResult = xpathExpr.evaluate(document); // XPathResult
const nodeContext = document.querySelector("nav");
// Re-using the XPathExpression "xpathExpr"
const otherResult = xpathExpr.evaluate(nodeContext); // XPathResult

🔍 Tiny XPath cheat sheet for beginners

Enough XPath to understand the examples on this page:

XPathMeaning
//divAll div elements in the tree
//p[@class="note"]p elements with class="note"
.//lili descendants of the context node
count(//button)Number of button elements
string(//h1)String value of the first matching h1

⚡ Quick Reference

GoalCode
Compiledocument.createExpression("//div")
Evaluate on documentexpr.evaluate(document)
Evaluate on a nodeexpr.evaluate(nav)
Iterate nodesresult.iterateNext() (ordered node iterator)
Namespace mappercreateExpression(xpath, (p) => map[p] || null)
MDN statusBaseline Widely available

🔍 At a Glance

Four facts about document.createExpression().

Returns
XPathExpression

compiled

Runs via
.evaluate()

XPathResult

Reuse
yes

MDN focus

Status
Baseline

since 2015

📋 Compile + evaluate vs one-shot evaluate

StepcreateExpression pathdocument.evaluate path
1. PreparecreateExpression("//div")Pass xpath string each time
2. Runexpr.evaluate(ctx)document.evaluate(xpath, ctx, ...)
3. Second runReuse exprPass the string again
Best forLoops / multiple contextsSingle lookup

Examples Gallery

Examples follow MDN Document: createExpression() and practical reuse patterns for beginners.

📚 Getting Started

Compile an expression and evaluate it more than once.

Example 1 — MDN: compile once, evaluate twice

Official reuse pattern: same expression, different contexts.

JavaScript
const xpathExpr = document.createExpression("//div");
const xpathResult = xpathExpr.evaluate(document); // XPathResult
const nodeContext = document.querySelector("nav");
const otherResult = xpathExpr.evaluate(nodeContext); // XPathResult

console.log(xpathExpr instanceof XPathExpression); // true
console.log(xpathResult.resultType); // number (result type constant)
Try It Yourself

How It Works

Compilation happens once. Each evaluate call returns a fresh XPathResult for that context.

Example 2 — Iterate matching nodes

Request an ordered node iterator and walk matches with iterateNext().

JavaScript
const expr = document.createExpression("//li");
const result = expr.evaluate(
  document,
  XPathResult.ORDERED_NODE_ITERATOR_TYPE
);

const texts = [];
let node = result.iterateNext();
while (node) {
  texts.push(node.textContent.trim());
  node = result.iterateNext();
}
console.log(texts);
Try It Yourself

How It Works

The second argument to evaluate selects the result type. ORDERED_NODE_ITERATOR_TYPE is friendly for looping node by node.

📈 Practical Patterns

Scoped contexts, numeric XPath, and namespace prefixes.

Example 3 — Scope with a context node

Evaluate .//span relative to a section, not the whole document.

JavaScript
const section = document.getElementById("panel");
const expr = document.createExpression(".//span");
const result = expr.evaluate(
  section,
  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE
);

console.log(result.snapshotLength);
for (let i = 0; i < result.snapshotLength; i++) {
  console.log(result.snapshotItem(i).textContent);
}
Try It Yourself

How It Works

A leading . makes the path relative to the context node you pass to evaluate — the same idea as MDN’s nav example.

Example 4 — Numeric result with count()

XPath can return numbers, not only nodes.

JavaScript
const expr = document.createExpression("count(//button)");
const result = expr.evaluate(
  document,
  XPathResult.NUMBER_TYPE
);

console.log(result.numberValue);
Try It Yourself

How It Works

With NUMBER_TYPE, read result.numberValue. String and boolean result types work similarly with stringValue / booleanValue.

Example 5 — Optional namespaceURLMapper

Map prefixes when querying namespaced markup (for example SVG).

JavaScript
const svgNS = "http://www.w3.org/2000/svg";

function nsResolver(prefix) {
  const map = { svg: svgNS };
  return map[prefix] || null;
}

// Example: count svg:circle elements when prefixes are used in the XPath
const expr = document.createExpression("count(//svg:circle)", nsResolver);
const result = expr.evaluate(document, XPathResult.NUMBER_TYPE);
console.log(result.numberValue);
Try It Yourself

How It Works

MDN: the mapper turns a prefix into a namespace URL (or null). For plain HTML without prefixes, pass null or omit the need for mapping.

🚀 Common Use Cases

  • Repeated XPath scans — compile once, evaluate in a loop (MDN).
  • Scoped searches — same expression against different panels or list roots.
  • XML / mixed documents — query with namespace-aware paths.
  • Complex node tests — when CSS selectors are awkward or incomplete.
  • Not every UI query — prefer querySelector for simple HTML selection.
  • One-off lookupsdocument.evaluate may be simpler.

🧠 How createExpression() Works

1

Pass an XPath string

MDN: xpathText is compiled; optional mapper resolves prefixes.

Input
2

Get XPathExpression

The browser returns a reusable compiled expression object.

Compile
3

Call evaluate(context)

Pass the document or a context node; choose a result type as needed.

Run
4

Read XPathResult

Iterate nodes or read number/string/boolean values, then reuse the expression.

📝 Notes

  • MDN: Baseline Widely available since July 2015.
  • MDN: call createExpression on the same document you evaluate against.
  • Compilation alone does not select nodes — you must call evaluate.
  • Pass null for namespaceURLMapper when prefixes are not used (MDN).
  • For everyday HTML, CSS selectors are often clearer than XPath.
  • Related: createElement(), createEvent(), createDocumentFragment().

Browser Support

Document.createExpression() is Baseline Widely available on MDN (since July 2015). Logos use the shared browser-image-sprite.png sprite from this project.

Baseline Widely available

Document.createExpression()

Compile reusable XPathExpression objects across all major browsers.

Baseline Widely available
Google Chrome Supported
Yes
Mozilla Firefox Supported
Yes
Apple Safari Supported
Yes
Microsoft Edge Supported
Yes
Opera Supported
Yes
Internet Explorer Supported (legacy)
Yes
createExpression() Wide

Bottom line: Compile with createExpression when you reuse XPath. For simple HTML selection, prefer querySelector / querySelectorAll.

Conclusion

document.createExpression(xpathText) compiles an XPath string into a reusable XPathExpression. Evaluate it against the document or a smaller context node whenever you need the same query more than once — exactly the pattern MDN demonstrates.

Continue with createEvent(), createNodeIterator(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Compile once when evaluating the same path repeatedly
  • Create the expression on the same document you query (MDN)
  • Pass a context node to narrow the search
  • Choose an explicit XPathResult type for clear reads
  • Use a namespace mapper when XPath prefixes are required

❌ Don’t

  • Expect createExpression alone to return matching nodes
  • Cross documents with a compiled expression from elsewhere (MDN)
  • Reach for XPath when a simple CSS selector is enough
  • Forget null / a mapper when prefixes appear in the path
  • Mutate the DOM mid-iteration without knowing iterator invalidation rules

Key Takeaways

Knowledge Unlocked

Five things to remember about createExpression()

Compile XPath once; evaluate it many times.

5
Core concepts
🔄02

Reuse

evaluate again

key idea
📄03

Same doc

required

MDN
04

Alt

document.evaluate

one-shot
🛡05

Status

Baseline

2015

❓ Frequently Asked Questions

MDN: Document.createExpression() compiles an XPathExpression from an XPath string. You can then call evaluate() on that compiled expression — including repeatedly against different contexts.
No. MDN marks Document.createExpression() as Baseline Widely available (since July 2015). It is not Deprecated, Experimental, or Non-standard.
An XPathExpression object. Call xpathExpr.evaluate(contextNode) to get an XPathResult (MDN example).
Yes. MDN: you must call createExpression on the same document that you run the expression against.
Use createExpression when you will run the same XPath many times (MDN highlights reuse). For a one-off query, document.evaluate(xpath, context, ...) is often enough.
MDN: an optional function that maps a namespace prefix to a namespace URL, or null if none is needed. Use it when your XPath uses prefixes for XML/SVG namespaces.
Did you know?

XPath and CSS selectors both ask “which nodes?”, but XPath can return numbers, strings, and booleans too — for example count(//button). That is why XPathResult has numberValue and friends, not only node iterators.

Next: createNodeIterator()

Learn how to walk a DOM subtree with NodeIterator, whatToShow, and filters.

createNodeIterator() →

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.

7 people found this page helpful