• Skip to main content
  • Select language
  • Skip to search
MDN Web Docs
  • Technologies
    • HTML
    • CSS
    • JavaScript
    • Graphics
    • HTTP
    • APIs / DOM
    • WebExtensions
    • MathML
  • References & Guides
    • Learn web development
    • Tutorials
    • References
    • Developer Guides
    • Accessibility
    • Game development
    • ...more docs
Archive of obsolete content
  1. MDN
  2. Archive of obsolete content
  3. Archived open Web documentation
  4. Writing JavaScript for XHTML

Writing JavaScript for XHTML

In This Article
    1. Problem: Nothing Works
      1. Solution: The CDATA Trick
    2. Problem: Names in XHTML and HTML are represented in different cases
    3. Solution: Use or convert to lower case
    4. Problem: My Cookie Isn't Saved!
      1. Solution: Use the Storage Object
    5. Problem: I Can't Use document.write()
      1. Solution: Use DOM Methods
    6. Problem: I want to remain forward compatible!
    7. Solution: Avoid HTML-specific DOM
    8. Problem: My Favourite JS Library still Breaks
    9. I Read about E4X. Now, This Is Perfect, Isn't It?
    10. Finally: Content Negotiation
    11. Further Reading
    12.  See also

In practise, very few XHTML documents are served over the Web with the correct MIME media type, application/xhtml+xml. Whilst authored to the stricter rules of XML, they are sent with the media type for HTML (text/html). The receiving browser considers the content to be HTML, and does not utilise its XML parser.

There are a number of reasons for this. Partially it is because, prior to version 9, Internet Explorer was incapable of handling XHTML sent with the official XHTML media type at all. (Rather than displaying content, it would present the user with a file download dialog.) But it is also founded in the experience that JavaScript, authored carefully for HTML, can break when placed with an XML environment.

This article shows some of the reasons alongside with strategies to remedy the problems. It will encourage web authors to use more XML features and make their JavaScript interoperable with real XHTML applications.

(Note that XHTML documents which behave correctly in both application/xhtml+xml and text/html environments are sometimes known as 'polyglot' documents.)

To test the following examples locally, use Firefox's extension switch. Just write an ordinary (X)HTML file and save it once as test.html and once as test.xhtml.

Problem: Nothing Works

After switching the MIME type suddenly no inline script works anymore. Even the plain old alert() method is gone. The code looks something like this:

<script type="text/javascript">
   //<!--
   window.alert("Hello World!");
   //-->
 </script>

Solution: The CDATA Trick

This problem usually arises, when inline scripts are included in comments. This was common practice in HTML, to hide the scripts from browsers not capable of JS. In the age of XML comments are what they were intended: comments. Before processing the file, all comments will be stripped from the document, so enclosing your script in them is like throwing your lunch in a Piranha pool. Moreover, there's really no point to commenting out your scripts -- no browser written in the last ten years will display your code on the page.

The easy solution is to do away with the commenting entirely:

<script type="text/javascript">
   window.alert("Hello World!");
 </script>

This will work so long as your code doesn't contain characters which are "special" in XML, which usually means < and &. If your code contains either of these, you can work around this with CDATA sections:

<script type="text/javascript">
 <![CDATA[
   // is the variable a non-negative integer less than 10?
   if (variable < 10 && variable >= 0)
     action();
 ]]>
 </script>

Note that the CDATA section is only necessary because of the < in the code; otherwise you could have ignored it.

A third solution is to use only external scripts, neatly sidestepping the special-character problem.

Alternatively, the CDATA section can be couched within comments so as to be able to work in either application/xhtml+xml or text/html:

<script type="text/javascript">
//<![CDATA[
        ...
//]]>
</script>
<!-- (For styles, it is different) -->
<style type="text/css">
/*<![CDATA[*/
        ...
/*]]>*/
</style>

And if you really need compatibility with very old browsers that do not recognize the script or style tags resulting in their contents displayed on the page, you can use this:

<script type="text/javascript"><!--//--><![CDATA[//><!--
        ...
//--><!]]></script>
<!-- (For styles, it is different) -->
<style type="text/css"><!--/*--><![CDATA[/*><!--*/
        ...
/*]]>*/--></style>

See this document for more on the issues related to application/xhtml+xml and text/html (at least as far as XHTML 1.* and HTML 4; HTML5 addresses many of these problems).

Problem: Names in XHTML and HTML are represented in different cases

Scripts that used getElementsByTagName() with an upper case HTML name no longer work, and attributes like nodeName or tagName return upper case in HTML and lower case in XHTML.

Solution: Use or convert to lower case

For methods like getElementsByTagName(), passing the name in lower case will work in both HTML and XHTML. For name comparisons, first convert to lower case before doing the comparison (e.g., "el.nodeName.toLowerCase() === 'html'"). This will ensure that documents in HTML will compare correctly and will do no harm in XHTML where the names are already lower case.

Problem: My Cookie Isn't Saved!

We found out already, that the document object in XML files is different from the ones in HTML files. Now we take a look at one widly used property that is missing in XML files. In XML documents there is no document.cookie. That is, you can write something like

document.cookie = "key=value";

in XML as well, but nothing is saved in cookie storage.

Solution: Use the Storage Object

With Firefox 2 there was a new feature enabled, the HTML 5 Storage object. Although this feature is not free of critics, you can use it to bypass the non-existing cookie, if your document is of type XML. Again, you will have to write your own wrapper to respect any given combination of MIME type and browser.

Problem: I Can't Use document.write()

This problem has the same cause as the one above. This method does not exist in XMLDocuments anymore. There are reasons why this decision was made, one being that a string of invalid markup will instantly break the whole document.

Solution: Use DOM Methods

Many people avoided DOM methods because of the typing to create one simple element, when document.write() worked. Now you can't do this as easily as before. Use DOM methods to create all of your elements, attributes and other nodes. This is XML proof, as long as you keep the namespace problem in focus (e.g., there is a document.createElementNS method).

Of course, you can still use strings like in document.write(), but it takes a little more effort. For example:

var string = '<div xmlns="http://www.w3.org/999/xhtml"><h1>Hello World!</h1></div>';
var parser = new DOMParser();
var documentFragment = parser.parseFromString(string, "text/xml");
body.appendChild(documentFragment); // assuming 'body' is the body element

But be aware that if your string is not well-formed XML (e.g., you have an & where it should not be), then this method will crash, leaving you with a parser error.

Problem: I want to remain forward compatible!

Given the direction away from formatting attributes and the possibility of XHTML becoming eventually more prominent (or at least the document author having the possibility of later wanting to make documents available in XHTML for browsers that support it), one may wish to avoid features which are not likely to stay compatible into the future.

Solution: Avoid HTML-specific DOM

The HTML DOM , even though it is compatible with XHTML 1.0, is not guaranteed to work with future versions of XHTML (perhaps especially the formatting properties which have been deprecated as element attributes). The regular XML DOM provides sufficient methods via the Element interface for getting/setting/removing attributes.

Problem: My Favourite JS Library still Breaks

If you use JavaScript libraries like the famous prototype.js or Yahoo's one, there is bad news for you: As long as the developers don't apply the fixes mentioned above, you won't be able to use them in your XML-XHTML applications.

Two possible ways still are there, but neither is very promissing: Take the library, recode it and publish it or e-mail the developers, e-mail your friends to e-mail the developers and e-mail your customers to e-mail the developers. If they get the hint and are not too annoyed, perhaps they start to implement XML features in their libraries.

I Read about E4X. Now, This Is Perfect, Isn't It?

As a matter of fact, it isn't. E4X is a new method of using and manipulating XML in JavaScript. But, standardized by ECMA, they neglected to implement an interface to let E4X objects interact with DOM objects our document consists of. So, with every advantage E4X has, without a DOM interface you can't use it productively to manipulate your document. However, it can be used for data, and be converted into a string which can then be converted into a DOM object. DOM objects can similarly be converted into strings which can then be converted into E4X.

Finally: Content Negotiation

Now, how do we decide, when to serve XHTML as XML? We can do this on server side by evaluating the HTTP request header. Every browser sends with its request a list of MIME types it understands, as part of the HTTP content negotiation mechanism. So if the browser tells our server, that it can handle XHTML as XML, that is, the Accept: field in the HTTP head contains application/xhtml+xml somewhere, we are safe to send the content as XML.

In PHP, for example, you would write something like this:

if( strpos( $_SERVER['HTTP_ACCEPT'], "application/xhtml+xml" ) ) {
  header( "Content-type: application/xhtml+xml" );
  echo '<?xml version="1.0" ?>'."\n";
} else {
  header( "Content-type: text/html" );
}

This distinction also sends the XML declaration, which is strongly recommended, when the document is an XML file. If the content is sent as HTML, an XML declaration would break IE's Doctype switch, so we don't want it there.

For completeness here is the Accept field, that Firefox 2.0.0.9 sends with its requests:

Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5

Further Reading

You will find several useful articles in the developer wiki:

  • XML in Mozilla
  • DOM
  • XML Introduction
  • XML Extras

DOM 2 methods you will need are:

  • DOM:document.createElementNS
  • DOM:document.getElementsByTagNameNS

 See also

  • Properly Using CSS and JavaScript in XHTML Documents

Document Tags and Contributors

Tags: 
  • JavaScript
  • XHTML
  • XML
 Contributors to this page: jswisher, Wilfred, kscarfone, dddh, dhodder, teoli, Sheppy, Neil, Brettz9, jake33, Yuhong, Fidlej, Manuel Strehl, Waldo
 Last updated by: jswisher, Feb 9, 2016, 10:56:35 AM

  1. .htaccess ( hypertext access )
  2. <input> archive
  3. Add-ons
    1. Add-ons
    2. Firefox addons developer guide
    3. Interaction between privileged and non-privileged pages
    4. Tabbed browser
    5. bookmarks.export()
    6. bookmarks.import()
  4. Adding preferences to an extension
  5. An Interview With Douglas Bowman of Wired News
  6. Apps
    1. Apps
    2. App Development API Reference
    3. Designing Open Web Apps
    4. Graphics and UX
    5. Open web app architecture
    6. Tools and frameworks
    7. Validating web apps with the App Validator
  7. Archived Mozilla and build documentation
    1. Archived Mozilla and build documentation
    2. ActiveX Control for Hosting Netscape Plug-ins in IE
    3. Archived SpiderMonkey docs
    4. Autodial for Windows NT
    5. Automated testing tips and tricks
    6. Automatic Mozilla Configurator
    7. Automatically Handle Failed Asserts in Debug Builds
    8. BlackConnect
    9. Blackwood
    10. Bonsai
    11. Bookmark Keywords
    12. Building TransforMiiX standalone
    13. Chromeless
    14. Creating a Firefox sidebar extension
    15. Creating a Microsummary
    16. Creating a Mozilla Extension
    17. Creating a Release Tag
    18. Creating a Skin for Firefox/Getting Started
    19. Creating a Skin for Mozilla
    20. Creating a Skin for SeaMonkey 2.x
    21. Creating a hybrid CD
    22. Creating regular expressions for a microsummary generator
    23. DTrace
    24. Dehydra
    25. Developing New Mozilla Features
    26. Devmo 1.0 Launch Roadmap
    27. Download Manager improvements in Firefox 3
    28. Download Manager preferences
    29. Drag and Drop
    30. Embedding FAQ
    31. Embedding Mozilla in a Java Application using JavaXPCOM
    32. Error Console
    33. Exception logging in JavaScript
    34. Existing Content
    35. Extension Frequently Asked Questions
    36. Fighting Junk Mail with Netscape 7.1
    37. Firefox Sync
    38. Force RTL
    39. GRE
    40. Gecko Coding Help Wanted
    41. HTTP Class Overview
    42. Hacking wiki
    43. Help Viewer
    44. Helper Apps (and a bit of Save As)
    45. Hidden prefs
    46. How to Write and Land Nanojit Patches
    47. Introducing the Audio API extension
    48. Java in Firefox Extensions
    49. JavaScript crypto
    50. Jetpack
    51. Litmus tests
    52. Makefile.mozextension.2
    53. Microsummary topics
    54. Migrate apps from Internet Explorer to Mozilla
    55. Monitoring downloads
    56. Mozilla Application Framework
    57. Mozilla Crypto FAQ
    58. Mozilla Modules and Module Ownership
    59. Mozprocess
    60. Mozprofile
    61. Mozrunner
    62. Nanojit
    63. New Skin Notes
    64. Persona
    65. Plug-n-Hack
    66. Plugin Architecture
    67. Porting NSPR to Unix Platforms
    68. Priority Content
    69. Prism
    70. Proxy UI
    71. Remote XUL
    72. SXSW 2007 presentations
    73. Space Manager Detailed Design
    74. Space Manager High Level Design
    75. Standalone XPCOM
    76. Stress testing
    77. Structure of an installable bundle
    78. Supporting private browsing mode
    79. Table Cellmap
    80. Table Cellmap - Border Collapse
    81. Table Layout Regression Tests
    82. Table Layout Strategy
    83. Tamarin
    84. The Download Manager schema
    85. The life of an HTML HTTP request
    86. The new nsString class implementation (1999)
    87. TraceVis
    88. Treehydra
    89. URIScheme
    90. URIs and URLs
    91. Using Monotone With Mozilla CVS
    92. Using SVK With Mozilla CVS
    93. Using addresses of stack variables with NSPR threads on win16
    94. Venkman
    95. Video presentations
    96. Why Embed Gecko
    97. XML in Mozilla
    98. XPInstall
    99. XPJS Components Proposal
    100. XRE
    101. XTech 2005 Presentations
    102. XTech 2006 Presentations
    103. XUL Explorer
    104. XULRunner
    105. ant script to assemble an extension
    106. calICalendarView
    107. calICalendarViewController
    108. calIFileType
    109. xbDesignMode.js
  8. Archived open Web documentation
    1. Archived open Web documentation
    2. Browser Detection and Cross Browser Support
    3. Browser Feature Detection
    4. Displaying notifications (deprecated)
    5. E4X
    6. E4X Tutorial
    7. LiveConnect
    8. MSX Emulator (jsMSX)
    9. Old Proxy API
    10. Properly Using CSS and JavaScript in XHTML Documents
    11. Reference
    12. Scope Cheatsheet
    13. Server-Side JavaScript
    14. Sharp variables in JavaScript
    15. Standards-Compliant Authoring Tools
    16. Using JavaScript Generators in Firefox
    17. Window.importDialog()
    18. Writing JavaScript for XHTML
    19. XForms
    20. background-size
    21. forEach
  9. B2G OS
    1. B2G OS
    2. Automated Testing of B2G OS
    3. B2G OS APIs
    4. B2G OS add-ons
    5. B2G OS architecture
    6. B2G OS build prerequisites
    7. B2G OS phone guide
    8. Building B2G OS
    9. Building and installing B2G OS
    10. Building the B2G OS Simulator
    11. Choosing how to run Gaia or B2G
    12. Customization with the .userconfig file
    13. Debugging on Firefox OS
    14. Developer Mode
    15. Developing Firefox OS
    16. Firefox OS Simulator
    17. Firefox OS apps
    18. Firefox OS board guide
    19. Firefox OS developer release notes
    20. Firefox OS security
    21. Firefox OS usage tips
    22. Gaia
    23. Installing B2G OS on a mobile device
    24. Introduction to Firefox OS
    25. Mulet
    26. Open web apps quickstart
    27. Pandaboard
    28. PasscodeHelper Internals
    29. Porting B2G OS
    30. Preparing for your first B2G build
    31. Resources
    32. Running tests on Firefox OS: A guide for developers
    33. The B2G OS platform
    34. Troubleshooting B2G OS
    35. Using the App Manager
    36. Using the B2G emulators
    37. Web Bluetooth API (Firefox OS)
    38. Web Telephony API
    39. Web applications
  10. Beginner tutorials
    1. Beginner tutorials
    2. Creating reusable content with CSS and XBL
    3. Underscores in class and ID Names
    4. XML data
    5. XUL user interfaces
  11. Case Sensitivity in class and id Names
  12. Creating a dynamic status bar extension
  13. Creating a status bar extension
  14. Gecko Compatibility Handbook
  15. Getting the page URL in NPAPI plugin
  16. Index
  17. Inner-browsing extending the browser navigation paradigm
  18. Install.js
  19. JXON
  20. List of Former Mozilla-Based Applications
  21. List of Mozilla-Based Applications
  22. Localizing an extension
  23. MDN
    1. MDN
    2. Content kits
  24. MDN "meta-documentation" archive
    1. MDN "meta-documentation" archive
    2. Article page layout guide
    3. Blog posts to integrate into documentation
    4. Current events
    5. Custom CSS classes for MDN
    6. Design Document
    7. DevEdge
    8. Developer documentation process
    9. Disambiguation
    10. Documentation Wishlist
    11. Documentation planning and tracking
    12. Editing MDN pages
    13. Examples
    14. Existing Content/DOM in Mozilla
    15. External Redirects
    16. Finding the right place to document bugs
    17. Getting started as a new MDN contributor
    18. Landing page layout guide
    19. MDN content on WebPlatform.org
    20. MDN page layout guide
    21. MDN subproject list
    22. Needs Redirect
    23. Page types
    24. RecRoom documentation plan
    25. Remove in-content iframes
    26. Team status board
    27. Trello
    28. Using the Mozilla Developer Center
    29. Welcome to the Mozilla Developer Network
    30. Writing chrome code documentation plan
    31. Writing content
  25. MMgc
  26. Makefile - .mk files
  27. Marketplace
    1. Marketplace
    2. API
    3. Monetization
    4. Options
    5. Publishing
  28. Mozilla release FAQ
  29. Newsgroup summaries
    1. Newsgroup summaries
    2. Format
    3. Mozilla.dev.apps.firefox-2006-09-29
    4. Mozilla.dev.apps.firefox-2006-10-06
    5. mozilla-dev-accessibility
    6. mozilla-dev-apps-calendar
    7. mozilla-dev-apps-firefox
    8. mozilla-dev-apps-thunderbird
    9. mozilla-dev-builds
    10. mozilla-dev-embedding
    11. mozilla-dev-extensions
    12. mozilla-dev-i18n
    13. mozilla-dev-l10n
    14. mozilla-dev-planning
    15. mozilla-dev-platform
    16. mozilla-dev-quality
    17. mozilla-dev-security
    18. mozilla-dev-tech-js-engine
    19. mozilla-dev-tech-layout
    20. mozilla-dev-tech-xpcom
    21. mozilla-dev-tech-xul
    22. mozilla.dev.apps.calendar
    23. mozilla.dev.tech.js-engine
  30. Obsolete: XPCOM-based scripting for NPAPI plugins
  31. Plugins
    1. Plugins
    2. Adobe Flash
    3. External resources for plugin creation
    4. Logging Multi-Process Plugins
    5. Monitoring plugins
    6. Multi-process plugin architecture
    7. NPAPI plugin developer guide
    8. NPAPI plugin reference
    9. Samples and Test Cases
    10. Shipping a plugin as a Toolkit bundle
    11. Supporting private browsing in plugins
    12. The First Install Problem
    13. Writing a plugin for Mac OS X
    14. XEmbed Extension for Mozilla Plugins
  32. SAX
  33. Security
    1. Security
    2. Digital Signatures
    3. Encryption and Decryption
    4. Introduction to Public-Key Cryptography
    5. Introduction to SSL
    6. NSPR Release Engineering Guide
    7. SSL and TLS
  34. Solaris 10 Build Prerequisites
  35. Sunbird Theme Tutorial
  36. Table Reflow Internals
  37. Tamarin Tracing Build Documentation
  38. The Basics of Web Services
  39. Themes
    1. Themes
    2. Building a Theme
    3. Common Firefox theme issues and solutions
    4. Creating a Skin for Firefox
    5. Making sure your theme works with RTL locales
    6. Theme changes in Firefox 2
    7. Theme changes in Firefox 3
    8. Theme changes in Firefox 3.5
    9. Theme changes in Firefox 4
  40. Updating an extension to support multiple Mozilla applications
  41. Using IO Timeout And Interrupt On NT
  42. Using SSH to connect to CVS
  43. Using workers in extensions
  44. WebVR
    1. WebVR
    2. WebVR environment setup
  45. XQuery
  46. XUL Booster
  47. XUL Parser in Python