JavaScript Document createProcessingInstruction() Method

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

What You’ll Learn

document.createProcessingInstruction() is an instance method that builds a ProcessingInstruction node (see MDN Document: createProcessingInstruction()). Learn target and data, the MDN xml-stylesheet example, validation exceptions, how to insert and serialize the node, and five try-it labs.

01

Kind

Instance method

02

Args

target, data

03

Returns

ProcessingInstruction

04

Looks like

<?target data?>

05

Best in

XML docs

06

Status

Baseline

Introduction

In XML, a processing instruction (PI) is a special node that carries a message to an application. Serialized, it looks like <?xml-stylesheet href="mycss.css"?> — not an element, not a comment.

doc.createProcessingInstruction(target, data) creates that node in memory. MDN notes you usually insert it into an XML document (for example with insertBefore) so serializers and tools can see it.

💡
Create → insert → serialize

1) const pi = doc.createProcessingInstruction(target, data)
2) doc.insertBefore(pi, doc.firstChild)
3) Inspect with XMLSerializer (MDN pattern)

Everyday HTML pages rarely need PIs. This API shines when you build or edit XML documents (often from DOMParser).

Related tutorials: createComment(), createCDATASection(), createElement().

Understanding document.createProcessingInstruction()

An instance method on a Document (call it on the XML document you will mutate; MDN).

  • target — first part of the PI (for example xml-stylesheet) (MDN).
  • data — remaining information after the target; must not contain ?> (MDN).
  • Return value — a new ProcessingInstruction node.
  • Properties — read pi.target and pi.data.
  • nodeTypeNode.PROCESSING_INSTRUCTION_NODE (7).
  • Attach — insert into the XML tree before the node is useful in output (MDN).

📝 Syntax

General form of Document.createProcessingInstruction (MDN):

JavaScript
createProcessingInstruction(target, data)

Parameters

  • target — string for the PI target (the name after <?) (MDN). Must be a valid XML name.
  • data — string of information after the target (MDN). Cannot include the closing sequence ?>.

Return value

A new ProcessingInstruction node (ready to insert into an XML document).

Exceptions

  • InvalidCharacterError — MDN: thrown if target is not a valid XML name, or if data contains ?>.

MDN example

JavaScript
const doc = new DOMParser().parseFromString("<foo />", "application/xml");
const pi = doc.createProcessingInstruction(
  "xml-stylesheet",
  'href="mycss.css" type="text/css"',
);

doc.insertBefore(pi, doc.firstChild);

console.log(new XMLSerializer().serializeToString(doc));
// <?xml-stylesheet href="mycss.css" type="text/css"?><foo/>

⚡ Quick Reference

GoalCode
Create PIdoc.createProcessingInstruction("xml-stylesheet", 'href="a.css"')
Read target / datapi.target / pi.data
Insert at topdoc.insertBefore(pi, doc.firstChild)
Serializenew XMLSerializer().serializeToString(doc)
nodeTypeNode.PROCESSING_INSTRUCTION_NODE (7)
MDN statusBaseline Widely available

🔍 At a Glance

Four facts about document.createProcessingInstruction().

Returns
ProcessingInstruction

node

Parts
target + data

MDN

Forbidden
?> in data

throws

Status
Baseline

since 2015

📋 Detached PI vs inserted PI

After createProcessingInstructionAfter insertBefore
In document tree?No (detached)Yes
Visible in serialize?Only if you serialize the node aloneAppears in document output
Typical next stepConfigure / inspectUse XMLSerializer / save XML

Examples Gallery

Examples follow MDN Document: createProcessingInstruction() and practical XML PI patterns.

📚 Getting Started

Build an xml-stylesheet PI and inspect its properties.

Example 1 — MDN: xml-stylesheet PI

Parse XML, create a PI, insert it before the root element, serialize.

JavaScript
const doc = new DOMParser().parseFromString("<foo />", "application/xml");
const pi = doc.createProcessingInstruction(
  "xml-stylesheet",
  'href="mycss.css" type="text/css"',
);

doc.insertBefore(pi, doc.firstChild);

console.log(new XMLSerializer().serializeToString(doc));
// <?xml-stylesheet href="mycss.css" type="text/css"?><foo/>
Try It Yourself

How It Works

The PI is created on the same doc you insert into. insertBefore(pi, doc.firstChild) places it ahead of <foo/>.

Example 2 — Read target and data

Inspect the two halves of a processing instruction.

JavaScript
const doc = new DOMParser().parseFromString("<root/>", "application/xml");
const pi = doc.createProcessingInstruction("php", 'echo "hi";');

console.log(pi.target); // "php"
console.log(pi.data);   // 'echo "hi";'
console.log(pi.nodeName); // "php" (same as target for PI nodes)
Try It Yourself

How It Works

target is the instruction name; data is the free-form payload after it (MDN).

📈 Practical Patterns

Validation errors and node typing.

Example 3 — ?> in data throws (MDN)

The closing sequence cannot appear inside data.

JavaScript
const doc = new DOMParser().parseFromString("<root/>", "application/xml");

try {
  doc.createProcessingInstruction("note", "oops ?> still open");
} catch (err) {
  console.log(err.name); // "InvalidCharacterError"
}
Try It Yourself

How It Works

MDN: including ?> in data throws InvalidCharacterError because that sequence ends a PI.

Example 4 — Invalid target name

Targets must be valid XML names (MDN).

JavaScript
const doc = new DOMParser().parseFromString("<root/>", "application/xml");

try {
  doc.createProcessingInstruction("1bad", "data");
} catch (err) {
  console.log(err.name); // "InvalidCharacterError"
}

const ok = doc.createProcessingInstruction("xml-stylesheet", 'href="a.css"');
console.log(ok.target); // "xml-stylesheet"
Try It Yourself

How It Works

Names starting with a digit (or other illegal XML name forms) are rejected (MDN).

Example 5 — nodeType is 7

Confirm the node kind before inserting.

JavaScript
const doc = new DOMParser().parseFromString("<root/>", "application/xml");
const pi = doc.createProcessingInstruction("app", "mode=debug");

console.log(pi.nodeType); // 7
console.log(pi.nodeType === Node.PROCESSING_INSTRUCTION_NODE); // true
console.log(pi instanceof ProcessingInstruction); // true
Try It Yourself

How It Works

Processing instructions share the node tree with elements and text, but they are identified by PROCESSING_INSTRUCTION_NODE.

🚀 Common Use Cases

  • xml-stylesheet links — associate CSS/XSLT with XML (MDN example).
  • XML tool pipelines — inject PIs that downstream processors understand.
  • Serializing XML — round-trip documents with XMLSerializer.
  • Teaching XML node types — contrast PIs with comments and elements.
  • Not for typical HTML UI — prefer elements, comments, or metadata tags in HTML.
  • Validation-aware builders — catch illegal targets / ?> early.

🧠 How createProcessingInstruction() Works

1

Pass target + data

MDN: two strings; data must not contain ?>.

Input
2

Validate names

Invalid XML target names or illegal data throw InvalidCharacterError.

Check
3

Get a PI node

A detached ProcessingInstruction with target and data.

Create
4

Insert into XML

Use insertBefore / appendChild, then serialize if needed.

📝 Notes

  • MDN: Baseline Widely available since July 2015.
  • Usually used with XML documents; insert before the node is useful (MDN).
  • Data must not contain ?>; target must be a valid XML name (MDN).
  • Call the method on the same document you plan to insert into.
  • Related: createComment(), createCDATASection(), nodeType.

Browser Support

Document.createProcessingInstruction() 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.createProcessingInstruction()

Create ProcessingInstruction nodes for XML documents 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
createProcessingInstruction() Wide

Bottom line: Use createProcessingInstruction for XML PIs such as xml-stylesheet. Insert the node into the XML document, then serialize when you need markup.

Conclusion

document.createProcessingInstruction(target, data) builds an XML processing instruction node. Validate the target name, keep ?> out of the data, insert the node into an XML document, and serialize when you need the <?target data?> form — just like MDN’s stylesheet example.

Continue with createComment(), createRange(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Create PIs on the XML document you will mutate
  • Use valid XML names for target
  • Insert with insertBefore / appendChild
  • Serialize with XMLSerializer to verify output
  • Prefer this API for XML tooling, not everyday HTML UI

❌ Don’t

  • Put ?> inside data (MDN)
  • Use illegal targets like names starting with a digit (MDN)
  • Expect the detached PI to appear in the document without inserting it
  • Confuse PIs with HTML comments or elements
  • Assume HTML authors commonly need processing instructions

Key Takeaways

Knowledge Unlocked

Five things to remember about createProcessingInstruction()

Build XML <?target data?> nodes in the DOM.

5
Core concepts
📄02

Parts

target + data

two args
⚠️03

Ban

?> in data

throws
04

Insert

into XML

MDN
🛡05

Status

Baseline

2015

❓ Frequently Asked Questions

It creates a new ProcessingInstruction node from a target string and a data string (MDN). You usually insert it into an XML document — for example with insertBefore.
No. MDN marks Document.createProcessingInstruction() as Baseline Widely available (since July 2015). It is not Deprecated, Experimental, or Non-standard.
A ProcessingInstruction node. Read pi.target and pi.data (or nodeValue / textContent for the data).
Serialized form is <?target data?>. MDN’s example builds <?xml-stylesheet href="mycss.css"?> before the document element.
MDN: InvalidCharacterError if target is not a valid XML name, or if data contains the closing sequence ?>.
Processing instructions are an XML concept. MDN shows creating them on an XML Document from DOMParser (application/xml). Everyday HTML UIs rarely need them.
Did you know?

The XML declaration <?xml version="1.0"?> looks like a processing instruction, but it is special syntax handled by parsers — you do not create it with createProcessingInstruction("xml", ...) in the same way you create an xml-stylesheet PI for application use.

Next: createRange()

Learn how to create Range objects and set start/end boundaries for DOM selection and editing.

createRange() →

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