How to Test if an Element is an XML Node in jQuery

This article explains how to determine whether a specific element or document is an XML node using the jQuery utility function $.isXMLDoc(). You will learn the correct syntax, how to properly pass native DOM elements versus jQuery collections, practical code examples, and common pitfalls to avoid when performing this validation.

Understanding jQuery.isXMLDoc()

The $.isXMLDoc() method evaluates whether an object is an XML document or a node within one. It returns a boolean: true if the passed argument is an XML node or document, and false if it is an HTML node, another JavaScript object, or null/undefined.

The syntax is straightforward:

jQuery.isXMLDoc( node )

Passing Native DOM Elements

The most critical aspect of $.isXMLDoc() is that it expects a native DOM node, not a wrapped jQuery collection. Passing a jQuery object directly to the function will cause it to return false, because the jQuery wrapper object does not possess the native DOM properties the method checks.

If you have a jQuery object, you must unwrap it to access the underlying DOM node using either bracket notation ([0]) or the .get(0) method:

// Correct: passing the raw DOM element
var isXml = $.isXMLDoc($("#myElement")[0]);

// Incorrect: passing the jQuery wrapper object
var isXmlWrong = $.isXMLDoc($("#myElement")); // Always returns false

Code Examples

1. Testing an XML Node

When parsing a standard XML string into a document, you can test both the document root and its child elements:

// Parse an XML string into an XML Document
var xmlData = "<bookstore><book><title>Everyday Italian</title></book></bookstore>";
var xmlDoc = $.parseXML(xmlData);

// 1. Test the root XML document
console.log($.isXMLDoc(xmlDoc)); // Output: true

// 2. Locate an element and extract the native node
var bookNode = $(xmlDoc).find("book")[0];

// Test the XML element
console.log($.isXMLDoc(bookNode)); // Output: true

2. Testing an HTML Node

When tested against standard HTML elements or the global HTML document, $.isXMLDoc() returns false:

// Test the current HTML document
console.log($.isXMLDoc(document)); // Output: false

// Test a regular HTML element
var htmlDiv = document.createElement("div");
console.log($.isXMLDoc(htmlDiv)); // Output: false

Handling Non-Element Inputs

If the input is not a valid DOM node, $.isXMLDoc() safely returns false without throwing an error:

$.isXMLDoc(null);       // Output: false
$.isXMLDoc(undefined);  // Output: false
$.isXMLDoc({});         // Output: false

Ensure that your selector has found at least one element before referencing index [0]. Passing undefined resulting from an empty selection ($('#nonExistent')[0]) will simply return false.