Using Web Standards in your Web Pages

  • Revision slug: Using_Web_Standards_in_your_Web_Pages
  • Revision title: Using Web Standards in your Web Pages
  • Revision id: 37064
  • Created:
  • Creator: GT
  • Is current revision? No
  • Comment

Revision Content

"Browser makers are no longer the problem. The problem lies with designers and developers chained to the browser-quirk-oriented markup of the 1990s-often because they don't realize it is possible to support current standards while accommodating old browsers."

This article provides an overview of the process for upgrading the content of your web pages to conform to the World Wide Web Consortium (W3C) web standards. The first 2 sections address exclusively validation issues, benefits of validation, deprecated elements, deprecated attributes. How to upgrade a webpage markup code to pass validation and how to implement CSS are addressed by providing recommendations, tutorials and references.

The other sections address DOM and DHTML coding practices which are at odds with the W3C web standards and suggest replacements. Every proposed W3C web standards replacement in this article is working without a problem in modern browsers like MSIE 7, Firefox 2, Opera 9, Safari 2, Konqueror 3.5+, Icab 3, etc. The final section, Summary of Changes, outlines all the changes described in this article.


Benefits of using web standards

The benefits of using web standards (W3C recommendations and language specifications regarding webpage authoring) are numerous, important, often underestimated and often misunderstood.

The benefits for valid markup code are

  • consistent cross-browser rendering
  • markup code is forward-compatible (future-proof)
  • webpage is more accessible
  • problems with a webpage are easier to identify, to debug and to fix when it uses valid markup code
  • webpages are faster to develop and easier to maintain

Valid markup code is important to achieve because of one particular reason which is often ignored: there is no error correction mechanism provided by the HTML 4.01 specification.

HTML 4.01, Section B.1 Notes on invalid documents states:
"This {{mediawiki.external('HTML 4.01')}} specification does not define how conforming user agents handle general error conditions, including how user agents behave when they encounter elements, attributes, attribute values, or entities not specified in this document."

So when a browser encounters a particular error in the markup code, the browser has no specific, predefined mechanism (or response) provided by the HTML 4.01 specification: the error part will be rendered in various ways by different browsers. Invalid markup code is outside the HTML 4.01 specification and is therefore rendered entirely thanks to non-standard browser interpretation. This phenomenon is particularly true for syntaxical errors such as:

  • missing end quote in attribute values: "There's also the missing quotes problem, e.g., leaving a close quote off a link href. Browsers employ complicated heuristics to try to match up unclosed quotes that depend on the number of quotes in the document, their positions, and other factors" from David Hyatt's blog
  • Incorrect nesting of elements

    Elements must close in the right order; elements must not overlap each other.

The following code example is invalid syntax because of incorrect nesting of elements:

<p>These are 2 <strong>strong words. </p></strong>

This type of markup error happens often to beginners and to unaware web authors; it is detected and reported by HTML validators. An HTML validator will report this typical error message:
"end tag for 'STRONG' omitted, but its declaration does not permit this. (...) you used something inside this tag that was not allowed, and the validator is complaining that the tag should be closed before such content can be allowed. (...)"


The following code example is valid syntax and correct nesting of elements:

<p>These are 2 <strong> strong words </strong>.</p>

More info:
incorrect nesting of elements explained at WDG
Tag Soup: How UAs handle <x> <y> </x> </y> by Ian Hickson

  • misused or misplaced elements:

    Another frequently encountered markup error is to have a block-level element (e.g. <p>, <div>, <table>) nested inside an inline element (e.g. <span>, <strong>, <big>).

The following markup code example is invalid syntax because an inline element (<b>) wraps a block-level element (<p>):

<b><p>This is a bold paragraph.</p></b>

This type of markup error happens often to beginners and to unaware web authors; it is detected and reported by HTML validators. An HTML validator will report this typical error message:
"document type does not allow element 'B' here (...) One possible cause for this message is that you have attempted to put a block-level element (such as '<p>' or '<table>') inside an inline element (such as '<a>', '<span>')."


The following code example is valid markup syntax because the inline element (<b>) is nested inside the block-level element (<p>):

<p><b>This is a bold paragraph. </b></p>

More info:
Tag Soup: Blocks-in-inlines by Ian Hickson

By avoiding invalid markup code, a web author reduces risks of causing overlapping elements, misaligned or misplaced elements or strange layout problems. In some cases, a browser may even crash when encountering malformed markup code.

First example of malformed markup code causing crash:
The importance of human-readable markup (May 2003) by Mark Pilgrim
Second example example of malformed markup code causing crash:
IE vertical-align:top vulnerability (October 2003) by Jehiah Czebotar

More reading on markup validation:

The benefits for clear separation of content from presentation aspects (font, color, padding, margin, border, etc.) thanks to CSS implementation are

  • smaller files and faster download (Note 1)
  • better layout control
  • better interoperability across platforms, devices and media (Note 2)
  • easier maintenance and increased opportunities

Note 1: Why use CSS to separate content from presentation? from MaxDesign
What is the separation of content and presentation? Why is it important? from maccaws.org
Note 2: HTML 4.01, Section 2.4.1 Separate structure and presentation:
"Experience has shown that separating the structure of a document from its presentational aspects reduces the cost of serving a wide range of platforms, media, etc., and facilitates document revisions."

Explaining in detail how to implement CSS in webpages would go beyond the scope of this article. For people wishing to implement CSS into their webpages, we recommend the following tutorials:

The benefits for using valid CSS code are

  • consistent cross-browser rendering
  • problems with a webpage, in particular a DHTML-driven webpage, are easier to identify, to debug and to fix when it uses valid CSS code

Reduced browser incompatibilities

In the last 5 years, browser vendors and web-aware software manufacturers have provided accessible bug reporting systems and have been consistently improving and correcting their HTML and CSS rendering engines when a webpage triggers standards compliant rendering mode. That is particularly true for Opera browser, Safari browser, Icab browser and Mozilla-based browsers. So with time, newer versions of browsers have lesser incompatibilities as they comply more closely to W3C specifications.

2 risks regarding editing with a WYSIWYG HTML editor

Many web author amateurs create their webpages with a WYSIWYG HTML editor, ie a graphical HTML editor like MS-Front Page, Nvu, DreamWeaver, KompoZer, etc. One risk involved with this kind of edition is that edition relies too much on the visual feedback of the editor. There are many web browsers and web-aware softwares that access webpages, not just 1. What the web author sees (while editing his webpage with such kind of software) may not be what his visitors will see because of different browsers (or different browser versions of the same browser name) involved, different configurations of the same browser, different media, different devices, different contexts in use. WYSIWYG webpage editors often lead web authors to the mistaken belief that what they see (while editing their webpage) is/should be good enough for everyone else. Unless a web author can test his webpages in multiple browsers, in multiple environments, media, with various devices, etc, the only realistic test and valuable, recommendable checking is to validate the markup code (and CSS code) of a webpage with a HTML validator (and a CSS validator). Markup validation is not browser dependent or browser specific; all graphical HTML editors are browser dependent and browser specific.

Another risk with WYSIWYG HTML editors is that these softwares have a tendency to add superfluous code (like many <br> and &nbsp;) in order to position or to fix elements within the webpage or within the viewport. So even though the markup code may be valid, the end result is a non-scalable, rigid (screen resolution dependent) webpage filled with spacer.gif, <br> and &nbsp; which bloat the markup code. This goes against the purpose of a clean, lean, streamlined markup code. In this context, spacer.gif, <br> and &nbsp; can be replaced most of the time by a wise usage of CSS properties like padding, margin or clear. It is beyond the scope of this article to elaborate on this issue but we wish to indicate that many <br> and &nbsp; is often the sign of bloated markup code and of a non-scalable webpage.

References on benefits of using web standards

Making your page using web standards: how to

Step 1: Choosing a doctype declaration referring to a strict DTD

Here is a list of possible doctype declarations:
http://www.w3.org/TR/html4/struct/global.html#version-info

We recommend you use a doctype declaration which indicates a strict Document Type Definition (DTD); we recommend HTML 4.01 strict.

Unless you know you need to serve a document as content-type application/xhtml+xml, you should use HTML 4.01 strict: there is no known, significant benefit of using an XHTML doctype declaration if your webpage is to be served as content-type text/html. Explaining in detail this issue goes beyond the scope of this article. The reader is invited to read:

In HTML 4.01 strict, elements and attributes which are dedicated to presentation are excluded, deprecated in favor of CSS. In that sense, HTML 4.01 strict helps to achieve a clear separation of structure from presentational aspects. Also because of the deprecation of some elements and attributes, HTML 4.01 strict is a trimmed version of HTML 4.01 and therefore is likely to be better supported by a larger number of user agents and media.

"Doctype switching"

HTML 4.01 strict brings other benefits. Modern browsers can render webpages in 2 different rendering modes: backward-compatible rendering mode (also called "quirks mode") and standards compliant rendering mode (also called "standards mode" and sometimes called "strict mode"). Modern browsers will choose one of these 2 rendering mode based on the doctype declaration in use in a webpage: this feature is referred as the "doctype switching" or "doctype sniffing". When choosing a doctype declaration (like HTML 4.01 strict) which triggers standards compliant rendering mode, modern browsers conform more closely to the specification of web languages (HTML 4 and CSS), in particular in their implementation of what is known as the "CSS 1 box model". So, the webpage code needs less browser forks and less workarounds: this is furthermore true when the most recent browser versions are involved (Opera 9, Safari 2.x, Icab 3, MSIE 7, Firefox 2, Camino 1, Seamonkey 1, Konqueror 3.5+, etc.). Choosing to trigger standards compliant rendering mode is a safe and sound decision as a wide majority of browsers in use today support the "doctype switching" feature.

More on "doctype switching":

Step 2: Validate your HTML 4 code

Next step is to validate your HTML 4 code. Validation is a process by which the web author checks that the syntax, grammar of his webpage conforms to the formal rules of the DTD. Web authors should be particularly attentive to errors reported by HTML validators.

Where can I validate my webpages? How to validate webpages?

Free online services:

Free offline extension:

Shareware offline HTML validator:

  • "A real validator" from WDG is an HTML validator for Windows; the registration cost for this shareware is $25. US. It can validate several HTML documents at once and it comes with a complete HTML 4.01 reference. Such reference is quite handy as it provides examples, explanations and useful information.

Top 5 most frequently encountered validation errors and how to fix them

Ampersands (&'s) in URLs from WDG
Ampersands, PHP Sessions and Valid HTML from W3C Quality tip for webmaster

The alt attribute must be a textual replacement, a text rendering equivalent if/when, for some reason (network problem, user agent, user preference setting), the image can not be rendered. When one thinks of the alt attribute of an image, one should think of what he would say of such image if he was to describe it on the telephone. More info on alt attribute:
W3C Quality Assurance Tip for Webmasters: Use the alt attribute to describe the function of each visual

An useful tutorial on correcting the most frequently encountered validation errors is: Liberty! Equality! Validity! from Eric A. Meyer.

How to upgrade markup code in some frequently encountered cases: <font>, <center>, bgcolor

I use <font>. How to define or to replace <font> with CSS?

The purpose of the deprecated FONT element is to specify typeface, color and size of the enclosed text. This functionality has been offloaded from HTML to CSS. The FONT element can be directly replaced with a SPAN element that includes the same style information:

<p><font color="blue" face="Helvetica">
A really <font size="+1">big</font> shoe.
</font></p>

... becomes:

<p><span style="color: blue; font-family: Helvetica, sans-serif;">
A really <span style="font-size: larger;">big</span> shoe.
</span></p>

... or even more concisely:

<p style="color: blue; font-family: Helvetica, sans-serif;">
A really <span style="font-size: larger;">big</span> shoe.</p>

This is appropriate usage for a local change to the font. However, this is not the best use of styles; the strength of CSS lies in the ability to gather text and other styling into logical groupings that can be applied across a document, without repeating the specific styling on every element that requires it.

More on conversion of <FONT>: W3C Quality Assurance tip for webmaster: Care With Font Size, Forget <font> and use CSS

I use <center> or align="center". How to align with CSS?

The CSS1 text-align property specifies how text or inline elements (like an image) are aligned within an element.

<p style="text-align: center;"><img src="..." width="..."
height="..." alt="..."></p>
// will center the image inside the <p> element

CSS margin-left: auto; margin-right: auto; properties will center a block-level element within its containing block. Defining margin-left and margin-right is for block-level elements. When both margin-left and margin-right are auto, they are set to equal values, thus centering a block-level element within its parent.
CSS1 horizontal formating
Worth mentioning is the excellent tutorial:
Centring using CSS by D. Dorward
Also Interactive demo on CSS horizontal alignment and horizontal formating

How to replace bgcolor? How to colorize background with CSS?

The bgcolor attribute can be replaced with CSS1 background-color property.

If you have

<td bgcolor="green" width="150">
... content here ...
</td>

... can replace it with:

<td style="background-color: green;" width="150">
... content here ...
</td>

How to upgrade markup code in specific cases: <embed>, <applet>, <marquee>, <bgsound>

What if I use <embed> for flash or for a video?

Explaining in details how to do this would go beyond the scope of this article. Nevertheless, we recommend the following articles so that you can have flash or a video in your webpage and, at the same time, have your page validate.

What if I use <applet>?

We recommend these resources:

Worth mentioning here: Java Upgrade Guide: Migrating From the Microsoft VM for Java to the Sun JRE http://java.sun.com/j2se/1.4.2/docs/guide/deployment/deployment-guide/upgrade-guide/index.html "after December, 2007, Microsoft will no longer support or provide a Java implementation with any of its products. (...) Those running applets in the Internet Explorer web browser will need to download and install an alternate VM."

What if I use <marquee>?

Marquee can be replaced with content string inside a <div> or <span> rotating over time with Javascript and DOM level 1. It must be said that this sort of effect is discouraged. Studies have shown that constantly moving objects or moving text disturb reading and weakens peripherical vision. DHTML marquee also greatly consumes user system resources (cpu, RAM) on tested browsers and will put modest systems under considerable stress. If after webpage assessment and consideration, you still want to include a marquee effect in your page, then you can use the following recommendable tutorials:
Cross-browser and web standard compliant Stock Ticker example by D. Rosenberg
Comprehensive web standard compliant alternative to <marquee> by D. Rosenberg
Mozilla 1.4+, NS 7.2 and Firefox 1.x support the non-standard <marquee> element. On the other hand, users can disable such support using this tip

What if I have <bgsound>?

Then use HTML 4.01 OBJECT, e.g.:
<OBJECT data="audiofile.wav" type="audio/wav" ...></OBJECT>
See this DevEdge article for information on rendering a sound OBJECT invisible within the page.
Web page background sound often slows down considerably web page loading; like the text effects above, music or sound accompanying a page is seldom appreciated. According to the survey page What we really hate on the web, 41.9% of survey respondents will avoid sites that automatically play music; 71.1% strongly dislike sites that automatically play music.
Why Playing Music on your Web Site is a Bad Idea by A. Gulez

Step 3: Validate your CSS code

Where can I validate my CSS code?

Free Online CSS validation services:

Built-in report of CSS parsing errors in modern browsers:

  • Error console in Firefox 2. From the menu, Tools/Error console; the error console reports CSS parsing errors.
  • Error console in Opera 9. From the menu, Tools/Advanced/Error console; the error console reports CSS parsing errors.
  • Error console in Icab 3. From the menu, Preferences/Show All/Other/Error report: the error console reports CSS parsing errors.

Using the W3C DOM

The document objects for some browsers have properties for accessing arrays of elements and types of elements. document.all[], for example, is used by Internet Explorer to access particular elements within the document. Many of these arrays were not made a part of the W3C specification for the Document Object Model and will cause JavaScript errors in standards-compliant browsers like Firefox, Seamonkey and Netscape 7+.

The W3C Document Object Model exposes almost all of the elements in an HTML page as scriptable objects. In general the attributes and methods of the W3C DOM are more powerful than the proprietary object models used in DHTML programming. The attributes and methods of the W3C DOM are overall well supported by modern browsers like MSIE 7, Opera 9, Safari 2, Konqueror 3.x and Mozilla-based browsers (Firefox, Seamonkey, Netscape 7+, Camino): so there is no gain from relying on proprietary object models.

Unsupported DOM-related Properties

The following document object properties are not supported in the W3C Document Object Model:

  • document.layers[]
  • id_attribute_value
  • document.all
  • document.all.id_attribute_value
  • document.all{{mediawiki.external('id_attribute_value')}}

The following form related properties (originally from Internet Explorer) are not supported in the W3C Document Object Model:

  • FormName.InputName.value
  • InputName.value
  • FormCtrlName
  • document.forms(0)

Scripts that use these properties will not execute in Firefox, Mozilla and Netscape 7+ or other standards-compliant browsers. Instead, use the W3C DOM access attributes and access methods described in the next section; since these are supported by Internet Explorer too, then there is no need to use MSIE-specific attributes and methods.

Accessing Elements with the W3C DOM

The best and most supported practice for getting scriptable access to an element in an HTML page is to use document.getElementById(id). A very wide majority of browsers (MSIE 5+, Firefox, NS 7+, Seamonkey, Opera 6+, Safari 1.x, Konqueror 3.x, etc.) support document.getElementById(id). This method returns a reference to the uniquely identified element, which can then be used to script that element. For example, the following short sample dynamically sets the left margin of a div element with an id of "inset" to half an inch:

// in the HTML: <div id="inset">Sample Text</div>
document.getElementById("inset").style.marginLeft = ".5in";
IE-specific ways to access elements W3C web standards replacements
id_attribute_valuedocument.getElementById(id_attribute_value)
document.all.id_attribute_valuedocument.getElementById(id_attribute_value)
document.all{{mediawiki.external('id_attribute_value')}}document.getElementById(id_attribute_value)
FormName.InputName.valuedocument.forms{{mediawiki.external('\"FormName\"')}}.InputName.value or
document.forms{{mediawiki.external('\"FormName\"')}}.elements{{mediawiki.external('\"InputName\"')}}.value
InputName.valuedocument.forms{{mediawiki.external('\"FormName\"')}}.InputName.value or
document.forms{{mediawiki.external('\"FormName\"')}}.elements{{mediawiki.external('\"InputName\"')}}.value
FormCtrlNamedocument.forms{{mediawiki.external('\"FormName\"')}}.FormCtrlName or
document.forms{{mediawiki.external('\"FormName\"')}}.elements{{mediawiki.external('\"FormCtrlName\"')}}
document.forms(0)document.forms{{mediawiki.external(0)}}

More on accessing forms and form elements:
Referencing Forms and Form Controls by comp.lang.javascript newsgroup FAQ notes
DOM 2 specification on accessing forms and form elements

For accessing a group of elements, the DOM specification also includes getElementsByTagName, which returns a list of all the elements with the given tag name in the order they appear in the document:

var arrCollection_Of_Anchors = document.getElementsByTagName("a");
var objFirst_Anchor = arrCollection_Of_Anchors[0];
alert("The url of the first link is " + objFirst_Anchor.href);

In addition to these access methods, the W3C DOM2 specifications provide methods for creating new elements and inserting them in a document, for creating attributes, new content, for traversing the content tree and for handling events raised as the user interacts with the document itself.

Manipulating Document Style and Content

Changing an Element's Style Using the DOM

The following table describes standards-based methods for accessing and updating style rules defined for various HTML elements in a web page. See the W3C DOM2 Recommendation, CSS2 Extended Interface.

DOM level 2 provides for the assignment of new values to the CSS properties of an element using the ElemRef.style object reference. You can get a reference to the element to which that style corresponds by using the DOM's getElementById or one of the other methods described in the DOM access section above.

Deprecated coding practices Appropriate DOM 2 replacements
IE5+: ElemRef.style.pixelLeft DOM level 2: parseInt(ElemRef.style.left, 10)
IE5+: ElemRef.style.pixelTop DOM level 2: parseInt(ElemRef.style.top, 10)
IE5+: ElemRef.style.pixelLeft = x;
ElemRef.style.pixelTop = y;
DOM level 2:

ElemRef.style.left = x + "px";

ElemRef.style.top = y + "px";
W3C DOM2 Reflection of an Element's CSS Properties

Keep in mind that according to the W3C Recommendation, the values returned by the style property of an element reflect static settings in the element's STYLE attribute only, not the total "computed style" that includes any inherited style settings from parent elements. Therefore, if you wish to read and write these properties from JavaScript through the DOM2, use one of these two approaches:

  • Place all of the element's static CSS declarations (if it has any) in the element's STYLE attribute.
  • Use no static CSS declarations for the element and initialize its CSS properties from JavaScript through the DOM.
W3C DOM2 Reflection of an Element's CSS Positioning Properties

The values returned by the W3C DOM2 style.left and style.top properties are strings that include the CSS unit suffix (such as "px"), whereas IE5+ ElemRef.style.pixelLeft (and the corresponding properties for top) return an integer. So, if you want to get the element's inline STYLE settings for left and top as integers, parse the integer from the string by using parseInt(). Conversely, if you want to set the element's inline STYLE settings for left and top, make sure to construct a string that includes the unit (such as "140px") by appending the unit string to the integer value.

CSS 1 and CSS 2.x specifications require that non-zero values must be specified with a length unit; otherwise, the css declaration will be ignored. Mozilla-based browsers, MSIE 6+, Opera 7+ and other W3C standards-compliant browsers enforce such handling of parsing error.
CSS 1 Forward-compatible parsing
CSS 2.1 Rules for handling parsing errors

Changing an Element's Text Using the DOM

Changing the actual text content of an element has changed substantially compared to the normal means of operation. Each element's content is broken up into a set of child nodes, consisting of plain text and sub-elements. In order to change the text of the element, the script operates on the node.

The node structure and supporting methods are defined in the W3C DOM level 1 recommendation.

If the element has no sub-elements, just text, then it (normally) has one child node, accessed as ElemRef.childNodes{{mediawiki.external(0)}}. In such precise case, the W3C web standards equivalent of ElemRef.innerText is ElemRef.childNodes{{mediawiki.external(0)}}.nodeValue.

We could introduce DOM 3 Core textContent attribute here which is supported by Mozilla 1.5+, Safari 2.x, Opera 9.x and is a perfect equivalent to MSIE's innerText. http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#Node3-textContent

The following examples show how to modify the text of a SPAN element that already exists in the HTML file.

<body>
  <P>Papa's got <SPAN id="dynatext">a lot of nerve</SPAN>!</P>

  <script type="text/javascript">
<span class="remark">// get reference to the SPAN element</span>
var SpanElemRef = document.getElementById("dynatext");

<span class="remark">// implement SpanElemRef.innerText = "a brand new bag"</span>
var new_txt = document.createTextNode("a brand new bag");
SpanElemRef.replaceChild(new_txt, SpanElemRef.childNodes[0]);

<span class="remark">// alternate, slightly more dangerous implementation
//(will not work if childNodes[0] is not a text node)</span>
SpanElemRef.childNodes[0].nodeValue = "a brand new bag";

<span class="remark">// implement SpanElemRef.innerHTML = "a brand <b>new</b> bag"</span>
var new_el = document.createElement(SpanElemRef.nodeName);
new_el.appendChild(document.createTextNode("a brand "));
var bold_el = document.createElement("B");
bold_el.appendChild(document.createTextNode("new"));
new_el.appendChild(bold_el);
new_el.appendChild(document.createTextNode(" bag"));
span_el.parentNode.replaceChild(new_el, SpanElemRef);
  </script>
</body>

The first example shows the relatively simple method of replacing the text in the SPAN by substituting a new text node for the original. The assumption here is that the SPAN has a single, text child; the code would work even if that were not true, but the results might be unexpected.

The second example shows a more concise but brute-force technique of accomplishing the same thing. As noted, if the first child node is not a text node, this action will not work: although sub-element nodes have a nodeValue, the contents of that field are not displayed in the document.

The final example shows a technique equivalent to setting innerHTML. First, it constructs a new element, created as the same type (SPAN) as the original. Next it adds three nodes: an initial text node, a B element with its own text node, and a final text node. The script then accesses the SPAN element's parent (the P element), and substitutes the new element for the original SPAN in the parent's list of child nodes.

It should be clear that translating scripts to modify document content is not a trivial undertaking. The benefit of such a conversion is that the script will work in modern, W3C DOM-compliant browsers such as Netscape 7 and other Gecko-based programs. Requirements of backward compatibility, however, will not only prolong but worsen the difficulties of dealing with multiple platforms.

Developing Cross Browser/Cross Platform Pages

An important practice when doing cross-browser, cross-platform pages and DHTML development involves the ability to determine the capabilities of the browser which loads your web page. As a web author, you understandably want to avoid script errors and page layout problems and you may want to ensure your scripts reach as wide an audience as possible. There are 2 known approaches for such goals: the browser identification approach (also known as userAgent string detection and often referred as "browser sniffing") and the Object/Feature support detection approach. The browser identification approach is now known to be complicated, unreliable and difficult to maintain.

Browser identification approach (aka "browser sniffing"): not best, not reliable approach

This approach, still commonly used nowadays, attempts to identify the browser and makes the web author at design time decide what that implies in terms of capabilities of the visiting browser. Such approach is fraught with problems and difficulties. It requires from the web author to have knowledge of the capabilities of all current browsers that may visit the page and then to code appropriately for these. It requires from the web author to make assumptions about what will happen with future browsers or to decide to provide future browsers a safe fallback service. It assumes that web authors are able to correctly identify browsers and browser versions in the first place... which is far from being a reliable and easy task to achieve.

The browser identification approach relies on functions that check the browser type string value and browser version string value and that search for certains characters or sub-strings in the navigator.userAgent property string. Once "detected", the web author then uses different functions (aka code branching) or points the user to different pages (aka site branching) or web content. Site branching can be particularly dangerous as people may enter a page through a link, bookmark, search engine or cache with a "wrong" browser.

Let's see a basic example of this approach.

if (navigator.appVersion.charAt(0) = "8")
{
  if (navigator.appName = "Netscape")
  {
    isNS8 = true;
    alert("NS8");
  };
}
else if (navigator.appVersion.indexOf("MSIE") != -1)
{
  isIE = true;
  alert("IE");
};

While this kind of checking in the above code can work in a crude sense, sharp readers may wonder what happens when IE 8 is released or when an Opera 8.x user visits the page or even when an user with any non-Netscape browser starting with a "8" character in the appVersion string visits that page. As new browsers are released, it becomes necessary to make updates to such code which attempts to narrow down the browser and browser version and to make the appropriate switches.

Another major problem with this approach is that the browser identity can be "spoofed" because, in many modern browsers, the navigator.appVersion and navigator.userAgent string properties are user configurable strings. For example,

  • Firefox 1.x users and users of any/all Mozilla-based browsers can customize the "general.useragent.*" string properties to any value.
  • Opera 6+ allows users to set the browser identification string via a menu
  • MSIE uses the Windows registry
  • Safari and Icab browsers mask their browser identity under Internet Explorer or Netscape labels

A user or browser distributor can put what they want in the navigator.userAgent string and this may trick your code into executing a "wrong" block of code. Moreover, there are many cases where even the accurately-identified browser does not perform as it is reputed/expected to.

So if "browser sniffing" is unreliable and difficult, how do you code safely for different browsers and different browser versions? ...

Using Object/Feature support detection approach: best and overall most reliable

When you use object/feature support detection, you only implement those features whose support you have first tested and verified on the visiting browser. This method has the advantage of not requiring you to test for anything except whether the particular features you code are supported in the visiting browser.

Let's see a basic, simple object support detection example.

function hideElement(id_attribute_value)
{
if (document.getElementById &&
    document.getElementById(id_attribute_value) &&
    document.getElementById(id_attribute_value).style)
 {
 document.getElementById(id_attribute_value).style.visibility="hidden";
 };
}

// example:
// <button type="button" onclick="hideElement('d1');">hide div</button>
// <div id="d1">Some text</div>

These repeated calls to document.getElementById are not the most efficient way to check for the existence of particular objects or features in the browser's DOM implementation, but they serve to illustrate clearly how object support detection works.

The top-level if clause looks to see if there is support for a method called getElementById on the document object, which is the one of the most basic levels of support for the DOM in a browser. If there is, the code sees if document.getElementById(id_attribute_value) returns a reference to an existing element, which it then checks for a style object. If the style object exists on the element, then it sets that object's visibility property. The browser will not error if you set this unimplemented property, so you do not need to check that the visiblity property itself exists.

So, instead of needing to know which browsers and browser versions support a particular DOM method (or DOM attribute or DOM feature), you can verify the support for that particular method in the visiting browser. With this approach, you ensure that all browsers -- including future releases and browsers whose userAgent strings you do not know about -- will continue working with your code.

More on object/feature support detection:
A Strategy That Works: Object/Feature Detecting by comp.lang.javascript newsgroup FAQ notes
Browser detection - No; Object detection - Yes by Peter-Paul Koch

Also good http://developer.mozilla.org/en/docs/Browser_Detection_and_Cross_Browser_Support but outdated in my opinion

Using XMLHttpRequest

Microsoft first introduced the XMLHttpRequest object in Internet Explorer 5.0 as an ActiveX control. However, in IE7 and other browsers XMLHttpRequest is a native scripting object. Thus, the most widely-supported way of including an XMLHttpRequest is to use the native object if possible, and fall back on the ActiveX control, like this:

if (window.XMLHttpRequest)
{
    //Firefox, Opera, IE7, and other browsers will use the native object
    var request = new XMLHttpRequest();
}
else
{
    //IE 5 and 6 will use the ActiveX control
    var request = new ActiveXObject("Microsoft.XMLHTTP");
}

If support for IE 5 and 6 is not a concern, then this next approach will work fine and is much more concise:

var request = new XMLHttpRequest()

More on XMLHttpRequest:

Summary of Changes

This section outlines all of the element and practice updates described in this article. For a complete discussion of these items, see the sections in which they are described.

Proprietary or Deprecated Feature W3C Feature or Recommended Replacement
deprecated FONT HTML 4.01 SPAN plus
CSS1 color: ; font-family: ; font-size: ;
deprecated CENTER or align="center" CSS1 text-align: center; for in-line elements like text or image
deprecated CENTER or align="center" CSS1 margin-left: auto; margin-right: auto;
for block-level elements
deprecated bgcolor CSS1 background-color: ;
non-standard EMBED HTML 4.01 OBJECT
deprecated APPLET HTML 4.01 OBJECT
non-standard MARQUEE HTML 4.01 DIV plus scripting
non-standard BGSOUND HTML 4.01 OBJECT
Proprietary or Deprecated Feature W3C Feature or Recommended Replacement
IE5+

id_attribute_value
document.all.id_attribute_value

document.all{{mediawiki.external('<var>id_attribute_value</var>')}}
DOM level 2:
document.getElementById(id_attribute_value)
IE5+ FormName.InputName.value DOM level 1:

document.forms{{mediawiki.external('\"<var>FormName</var>\"')}}.InputName.value

IE5+ InputName.value DOM level 1:

document.forms{{mediawiki.external('\"<var>FormName</var>\"')}}.InputName.value

IE5+ FormCtrlName DOM level 1:

document.forms{{mediawiki.external('\"<var>FormName</var>\"')}}.FormCtrlName

IE5+ document.forms(0) DOM level 1:

document.forms{{mediawiki.external(0)}}

IE ElemRef.innerText DOM Level 1 (Core) interface

We could introduce DOM 3 Core textContent attribute here which is supported by Mozilla 1.5+ and is a perfect equivalent to innerText. http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#Node3-textContent

IE5+ ElemRef.style.pixelTop DOM level 2: parseInt(ElemRef.style.top, 10)
IE5+ ElemRef.style.pixelLeft = x; ElemRef.style.pixelTop = y; DOM level 2: ElemRef.style.left = x + "px"; ElemRef.style.top = y + "px";
IE5+ new ActiveXObject("Microsoft.XMLHTTP") new XMLHttpRequest()
Proprietary or Deprecated Feature W3C Feature or Recommended Replacement

References

You can learn more on using web standards from these sites:


Original Document Information

  • Author(s): Mike Cowperthwaite, Marcio Galli, Jim Ley, Ian Oeschger, Simon Paquet, Gérard Talbot
  • Last Updated Date: December 24, 2006
  • Copyright Information: Portions of this content are © 1998–2006 by individual mozilla.org contributors; content available under a Creative Commons license | Details.
{{ wiki.languages( { "ja": "ja/Using_Web_Standards_in_your_Web_Pages" } ) }}

Revision Source

<p>
</p>
<blockquote>"Browser makers are no longer the problem. The problem lies with designers and developers chained to the browser-quirk-oriented markup of the 1990s-often because they don't realize it is possible to support current standards while accommodating old browsers."<div style="text-align: right;"><a class="external" href="http://webstandards.org/about/history/">-Web Standards Project</a></div></blockquote>
<p>This article provides an overview of the process for upgrading the content of your web pages to conform to the <a class="external" href="http://www.w3.org/">World Wide Web Consortium (W3C)</a> web standards. The first 2 sections 
address exclusively validation issues, benefits of validation, deprecated elements, deprecated attributes. How to upgrade a webpage markup code to pass validation and how to implement CSS are addressed by providing recommendations, tutorials and references.</p>
<p>The other sections address <abbr title="Document Object Model">DOM</abbr> and <abbr title="Dynamic HyperText Markup Language">DHTML</abbr> coding practices which are at odds with the <abbr title="World Wide Web Consortium">W3C</abbr> web standards and suggest replacements. <strong>Every proposed W3C web standards replacement in this article is working without a problem 
in modern browsers like MSIE 7, Firefox 2, Opera 9, Safari 2, Konqueror 3.5+, Icab 3, etc.</strong> The final section, 
<a href="#Summary_of_Changes">Summary of Changes</a>, outlines all the changes described in this article.</p>
<p><br>
</p>
<h2 name="Benefits_of_using_web_standards"> Benefits of using web standards </h2>
<p>The benefits of using web standards (W3C recommendations and language specifications regarding webpage authoring) are numerous, important, often underestimated and often misunderstood.</p>
<h3 name="The_benefits_for_valid_markup_code_are"> The benefits for valid markup code are </h3>
<ul><li> consistent cross-browser rendering
</li><li> markup code is forward-compatible (future-proof)
</li><li> webpage is more accessible
</li><li> problems with a webpage are easier to identify, to debug and to fix when it uses valid markup code
</li><li> webpages are faster to develop and easier to maintain
</li></ul>
<p>Valid markup code is important to achieve because of one particular reason which is often ignored: there is no error correction mechanism provided by the HTML 4.01 specification.</p>
<p><a class="external" href="http://www.w3.org/TR/html4/appendix/notes.html#h-B.1">HTML 4.01, Section B.1 Notes on invalid documents</a> states:<br>
"This {{mediawiki.external('HTML 4.01')}} specification does not define how conforming user agents handle general error conditions, including how user agents behave when they encounter elements, attributes, attribute values, or entities not specified in this document."</p>
<p>So when a browser encounters a particular error in the markup code, the browser has no specific, predefined mechanism (or response) provided by the HTML 4.01 specification: the error part will be rendered in various ways by different browsers. Invalid markup code is outside the HTML 4.01 specification and is therefore rendered entirely thanks to non-standard browser interpretation. This phenomenon is particularly true for syntaxical errors such as:</p>
<ul><li> missing end quote in attribute values: "There's also the missing quotes problem, e.g., leaving a close quote off a link href. Browsers employ complicated heuristics to try to match up unclosed quotes that depend on the number of quotes in the document, their positions, and other factors" from <a class="external" href="http://weblogs.mozillazine.org/hyatt/archives/2004_01.html#004702">David Hyatt's blog</a>
</li><li> Incorrect nesting of elements <p id="incorrectnesting">Elements must close in the right order; elements <strong>must not overlap</strong> each other.</p>
</li></ul>
<div class="bad">
<p>The following code example is invalid syntax because of incorrect nesting of elements:</p>
<pre>&lt;p&gt;These are 2 &lt;strong&gt;strong words. &lt;/p&gt;&lt;/strong&gt;
</pre>
<p>This type of markup error happens often to beginners and to unaware web authors; it is detected and reported by HTML validators. An HTML validator will report <a class="external" href="http://validator.w3.org/docs/errors.html#ve-73">this typical error message</a>:<br>
"end tag for 'STRONG' omitted, but its declaration does not permit this. (...) you used something inside this tag that was not allowed, and the validator is complaining that the tag should be closed before such content can be allowed. (...)"</p>
</div>
<p><br>
</p>
<div class="good">
<p>The following code example is valid syntax and correct nesting of elements:</p>
<pre>&lt;p&gt;These are 2 &lt;strong&gt; strong words &lt;/strong&gt;.&lt;/p&gt;
</pre>
</div>
<p>More info:<br>
<a class="external" href="http://www.htmlhelp.org/tools/validator/problems.html.en#nesting">incorrect nesting of elements</a> explained at <abbr title="Web Design Group">WDG</abbr><br>
<a class="external" href="http://ln.hixie.ch/?start=1037910467&amp;count=1">Tag Soup: How UAs handle &lt;x&gt; &lt;y&gt; &lt;/x&gt; &lt;/y&gt;</a> by Ian Hickson</p>
<ul><li> misused or misplaced elements: <p>Another frequently encountered markup error is to have a block-level element (e.g. <code>&lt;p&gt;</code>, <code>&lt;div&gt;</code>, <code>&lt;table&gt;</code>) nested inside an inline element (e.g. <code>&lt;span&gt;</code>, <code>&lt;strong&gt;</code>, <code>&lt;big&gt;</code>).</p>
</li></ul>
<div class="bad" id="blocknestedininline">
<p>The following markup code example is invalid syntax because an inline element (<code>&lt;b&gt;</code>) wraps a block-level element (<code>&lt;p&gt;</code>):</p>
<pre>&lt;b&gt;&lt;p&gt;This is a bold paragraph.&lt;/p&gt;&lt;/b&gt;
</pre>
<p>This type of markup error happens often to beginners and to unaware web authors; it is detected and reported by HTML validators. An HTML validator will report <a class="external" href="http://validator.w3.org/docs/errors.html#ve-65">this typical error message</a>:<br>
"document type does not allow element 'B' here (...) One possible cause for this message is that you have attempted to put a block-level element (such as '<code>&lt;p&gt;</code>' or '<code>&lt;table&gt;</code>') inside an inline element (such as
'<code>&lt;a&gt;</code>', '<code>&lt;span&gt;</code>')."</p>
</div>
<p><br>
</p>
<div class="good">
<p>The following code example is valid markup syntax because the inline element (<code>&lt;b&gt;</code>) is nested inside the block-level element (<code>&lt;p&gt;</code>):</p>
<pre>&lt;p&gt;&lt;b&gt;This is a bold paragraph. &lt;/b&gt;&lt;/p&gt;
</pre>
</div>
<p>More info:<br>
<a class="external" href="http://ln.hixie.ch/?start=1138169545&amp;count=1">Tag Soup: Blocks-in-inlines</a> by Ian Hickson</p>
<p>By avoiding invalid markup code, a web author reduces risks of causing overlapping elements, misaligned or misplaced elements or strange layout problems. In some cases, a <strong>browser may even crash</strong> when encountering malformed markup code.</p>
<p>First example of malformed markup code causing crash:<br>
<a class="external" href="http://diveintomark.org/archives/2003/05/03/the_importance_of_humanreadable_markup">The importance of human-readable markup (May 2003)</a> by Mark Pilgrim<br>
Second example example of malformed markup code causing crash:<br>
<a class="external" href="http://jehiah.com/archive/ie-vertical-align-top-vulnerability">IE vertical-align:top vulnerability (October 2003)</a> by Jehiah Czebotar</p>
<p>More reading on markup validation:</p>
<ul><li> <a class="external" href="http://webtips.dan.info/validators.html">Validators -- checking the correctness of your documents</a> by Daniel Tobias
</li><li> <a class="external" href="http://karlcore.com/articles/article.php?id=9">The Importance Of Standards Compliance and The Process of Validation</a> by Karl Core
</li><li> <a class="external" href="http://weblogs.mozillazine.org/hyatt/archives/2004_01.html#004702">Error Handling in Web Browsers</a> by David Hyatt
</li></ul>
<h3 name="The_benefits_for_clear_separation_of_content_from_presentation_aspects_.28font.2C_color.2C_padding.2C_margin.2C_border.2C_etc..29_thanks_to_CSS_implementation_are"> The benefits for clear separation of content from presentation aspects (font, color, padding, margin, border, etc.) thanks to CSS implementation are </h3>
<ul><li> smaller files and faster download (Note 1)
</li><li> better layout control
</li><li> better interoperability across platforms, devices and media (Note 2)
</li><li> easier maintenance and increased opportunities
</li></ul>
<p>Note 1: <a class="external" href="http://www.maxdesign.com.au/presentation/benefits/index07.htm">Why use CSS to separate content from presentation?</a> from MaxDesign<br>
<a class="external" href="http://www.maccaws.org/kit/primer/">What is the separation of content and presentation? Why is it important?</a> from maccaws.org<br>
Note 2: <a class="external" href="http://www.w3.org/TR/html4/intro/intro.html#h-2.4.1">HTML 4.01, Section 2.4.1 Separate structure and presentation</a>:<br>
"Experience has shown that separating the structure of a document from its presentational aspects reduces the cost of serving a wide range of platforms, media, etc., and facilitates document revisions."</p>
<p>Explaining in detail how to implement CSS in webpages would go beyond the scope of this article. For people wishing to implement CSS into their webpages, we recommend the following tutorials:</p>
<ul><li> <a class="external" href="http://developer.mozilla.org/en/docs/CSS:Getting_Started">Getting Started: a 14 parts step-by-step guide on CSS</a> at Mozilla Developer Center
</li><li> <a class="external" href="http://www.htmlhelp.com/reference/css/quick-tutorial.html">CSS tutorials from <abbr title="Web Design Group">WDG</abbr></a> (for beginners)
</li><li> <a class="external" href="http://tutorials.alsacreations.com/">Creating websites with CSS and (X)HTML</a>: tutorials and lessons at alsacreations.com for beginners, intermediate and advanced users
</li><li> <a class="external" href="http://www.westciv.com/style_master/academy/css_tutorial/">Complete CSS Guide</a> at WestCiv
</li><li> <a class="external" href="http://www.htmldog.com/">CSS lessons and tutorials</a> at HTML Dog for beginners, intermediate and advanced users
</li><li> <a class="external" href="http://www.456bereastreet.com/lab/developing_with_web_standards/css/#css">Tips and resources on CSS</a> for intermediate and advanced users
</li></ul>
<h3 name="The_benefits_for_using_valid_CSS_code_are"> The benefits for using valid CSS code are </h3>
<ul><li> consistent cross-browser rendering
</li><li> problems with a webpage, in particular a <abbr title="Dynamic Hyper Text Markup Language">DHTML</abbr>-driven webpage, are easier to identify, to debug and to fix when it uses valid CSS code
</li></ul>
<h3 name="Reduced_browser_incompatibilities"> Reduced browser incompatibilities </h3>
<p>In the last 5 years, browser vendors and web-aware software manufacturers have provided accessible bug reporting systems and have been consistently improving and correcting their HTML and CSS rendering engines when a webpage triggers standards compliant rendering mode. That is particularly true for Opera browser, Safari browser, Icab browser and Mozilla-based browsers. So with time, newer versions of browsers have lesser incompatibilities as they comply more closely to W3C specifications.</p>
<h3 name="2_risks_regarding_editing_with_a_WYSIWYG_HTML_editor"> 2 risks regarding editing with a WYSIWYG HTML editor </h3>
<p>Many web author amateurs create their webpages with a <abbr title="What-You-See-Is-What-You-Get">WYSIWYG</abbr> HTML editor, ie a graphical HTML editor like MS-Front Page, <a class="external" href="http://www.nvu.com/index.php">Nvu</a>, DreamWeaver, <a class="external" href="http://kompozer.net/">KompoZer</a>, etc. One risk involved with this kind of edition is that edition relies too much on the visual feedback of the editor. There are many web browsers and web-aware softwares that access webpages, not just 1. What the web author sees (while editing his webpage with such kind of software) may not be what his visitors will see because of different browsers (or different browser versions of the same browser name) involved, different configurations of the same browser, different media, different devices, different contexts in use. <abbr title="What-You-See-Is-What-You-Get">WYSIWYG</abbr> webpage editors often lead web authors to the mistaken belief that what they see (while editing their webpage) is/should be good enough for everyone else. Unless a web author can test his webpages in multiple browsers, in multiple environments, media, with various devices, etc, <strong>the only realistic test and valuable, recommendable checking is to validate the markup code (and CSS code)</strong> of a webpage with a HTML validator (and a CSS validator). Markup validation is not browser dependent or browser specific; all graphical HTML editors are browser dependent and browser specific.</p>
<p>Another risk with <abbr title="What-You-See-Is-What-You-Get">WYSIWYG</abbr> HTML editors is that these softwares have a tendency to add superfluous code (like many <code>&lt;br&gt;</code> and <code>&amp;nbsp;</code>) in order to position or to fix elements within the webpage or within the viewport. So even though the markup code may be valid, the end result is a non-scalable, rigid (screen resolution dependent) webpage filled with <code>spacer.gif</code>, <code>&lt;br&gt;</code> and <code>&amp;nbsp;</code> which bloat the markup code. This goes against the purpose of a clean, lean, streamlined markup code. In this context, <code>spacer.gif</code>, <code>&lt;br&gt;</code> and <code>&amp;nbsp;</code> can be replaced most of the time by a wise usage of CSS properties like padding, margin or clear. It is beyond the scope of this article to elaborate on this issue but we wish to indicate that many <code>&lt;br&gt;</code> and <code>&amp;nbsp;</code> is often the sign of bloated markup code and of a non-scalable webpage.</p>
<h3 name="References_on_benefits_of_using_web_standards"> References on benefits of using web standards </h3>
<ul><li> <a class="external" href="http://www.maxdesign.com.au/presentation/benefits/index.htm">The benefits of Web Standards to your visitors, your clients and you!</a> an excellent slide show from MaxDesign
</li><li> <a class="external" href="http://diveintomark.org/archives/2003/05/05/why_we_wont_help_you">Why we won't help you</a> by Mark Pilgrim
</li><li> <a class="external" href="http://www.dillo.org/help/bug_meter.html#standards">Why are standards so important?</a> from Dillo project
</li><li> <a class="external" href="http://www.adaptivepath.com/publications/essays/archives/000266.php">The Business Value of Web Standards</a> by Jeffrey Veen
</li><li> <a class="external" href="http://www.maccaws.org/kit/primer/">What Every Web Site Owner Should Know About Standards</a> from maccaws.org
</li></ul>
<h2 name="Making_your_page_using_web_standards:_how_to"> Making your page using web standards: how to </h2>
<h3 name="Step_1:_Choosing_a_doctype_declaration_referring_to_a_strict_DTD"> Step 1: Choosing a doctype declaration referring to a strict <abbr title="Document Type Definition">DTD</abbr> </h3>
<p>Here is a list of possible doctype declarations:<br>
http://www.w3.org/TR/html4/struct/global.html#version-info</p>
<p>We recommend you use a doctype declaration which indicates a
strict Document Type Definition (DTD); <strong>we recommend HTML 4.01 strict</strong>.</p>
<p>Unless <strong>you know you need</strong> to serve a document
as content-type <code>application/xhtml+xml</code>, you should use HTML 4.01 strict: there is no known, significant benefit of using an XHTML doctype declaration if your webpage is to be served as content-type <code>text/html</code>. Explaining in detail this issue goes beyond the scope of this article. The reader is invited to read:</p>
<ul><li> <a class="external" href="http://www.spartanicus.utvinternet.ie/no-xhtml.htm">No to XHTML</a> an excellent article from Spartanicus
</li><li> <a class="external" href="http://www.webdevout.net/articles/beware_of_xhtml.php">Beware of XHTML</a> by David Hammond
</li><li> <a class="external" href="http://www.hixie.ch/advocacy/xhtml">Sending XHTML as text/html Considered Harmful</a> by Ian Hickson
</li><li> <a class="external" href="http://www.xml.com/pub/a/2003/03/19/dive-into-xml.html">XHTML's Dirty Little Secret</a> by Mark Pilgrim
</li><li> <a class="external" href="http://www.autisticcuckoo.net/archive.php?id=2005/03/14/xhtml-is-dead">XHTML Is Dead</a> by Tommy Olsson
</li><li> <a class="external" href="http://hsivonen.iki.fi/xhtml-the-point/">XHTML - What's the Point?</a> by Henri Sivonen
</li></ul>
<p>In HTML 4.01 strict, elements and attributes which are dedicated to presentation are excluded, deprecated in favor of CSS. In that sense, HTML 4.01 strict helps to achieve a clear separation of structure from presentational aspects. Also because of the deprecation of some elements and attributes, HTML 4.01 strict is a trimmed version of HTML 4.01 and therefore is likely to be better supported by a larger number of user agents and media.</p>
<h4 name=".22Doctype_switching.22"> "Doctype switching" </h4>
<p>HTML 4.01 strict brings other benefits. Modern browsers can render webpages in 2 different rendering modes: backward-compatible rendering mode (also called "quirks mode") and standards compliant rendering mode (also called "standards mode" and sometimes called "strict mode"). Modern browsers will choose one of these 2 rendering mode based on the doctype declaration in use in a webpage: this feature is referred as the "doctype switching" or "doctype sniffing".
<strong>When choosing a doctype declaration (like HTML 4.01 strict) which triggers standards compliant rendering mode, modern browsers conform more closely to the specification of web languages (HTML 4 and CSS), in particular in their implementation of what is known as the "CSS 1 box model"</strong>. So, the webpage code needs less browser forks and less workarounds: this is furthermore true when the <strong>most recent browser versions</strong> are involved (Opera 9, Safari 2.x, Icab 3, MSIE 7, Firefox 2, Camino 1, Seamonkey 1, Konqueror 3.5+, etc.). Choosing to trigger standards compliant rendering mode is a safe and sound decision as a wide majority of browsers in use today support the "doctype switching" feature.</p>
<p>More on "doctype switching":</p>
<ul><li> <a class="external" href="http://developer.mozilla.org/en/docs/Mozilla%27s_DOCTYPE_sniffing">Mozilla's DOCTYPE sniffing</a> at Mozilla Developer Center
</li><li> <a class="external" href="http://hsivonen.iki.fi/doctype/">Activating the Right Layout Mode Using the Doctype Declaration</a> by Henri Sivonen
</li><li> <a class="external" href="http://gutfeldt.ch/matthias/articles/doctypeswitch.html">Doctype switching and standards compliance: An overview</a> by Matthias Gutfeldt
</li><li> <a class="external" href="http://www.webdevout.net/doctype_switching.php#rules">Doctype switching rules chart for popular web browsers</a> by David Hammond
</li></ul>
<h3 name="Step_2:_Validate_your_HTML_4_code"> Step 2: Validate your HTML 4 code </h3>
<p>Next step is to validate your HTML 4 code. Validation is a process by which the web author checks that the syntax, grammar of his webpage conforms to the formal rules of the <abbr title="Document Type Definition">DTD</abbr>. Web authors should be particularly attentive to errors reported by HTML validators.</p>
<h4 name="Where_can_I_validate_my_webpages.3F_How_to_validate_webpages.3F"> Where can I validate my webpages? How to validate webpages? </h4>
<p>Free online services:</p>
<ul><li> <a class="external" href="http://validator.w3.org/">W3C markup validation service</a> from the World Wide Web Consortium
</li><li> <a class="external" href="http://www.htmlhelp.com/tools/validator/"><abbr title="Web Design Group">WDG</abbr> HTML Validator</a>
</li><li> <a class="external" href="http://www.validome.org/">Validome validation services</a>: Validome validator is multi-lingual (English, Français, Русская версия and Deutch) and its report is <a class="external" href="http://www.validome.org/lang/en/errors/ALL">more complete, more accurate as it is able to report more errors</a>
</li></ul>
<p>Free offline extension:</p>
<ul><li> <a class="external" href="http://users.skynet.be/mgueury/mozilla/index.html">HTML validator as a Firefox extension working offline (SGML parser)</a>: Marc Gueury's Firefox extension (currently at version 0.8.3.4, still in beta) when using the SGML parser will report the same errors as the W3C markup validator.
</li></ul>
<p>Shareware offline HTML validator:</p>
<ul><li> <a class="external" href="http://arealvalidator.com/">"A real validator" from <abbr title="Web Design Group">WDG</abbr></a> is an HTML validator for Windows; the registration cost for this shareware is $25. US. It can validate several HTML documents at once and it comes with a complete HTML 4.01 reference. Such reference is quite handy as it provides examples, explanations and useful information.
</li></ul>
<h4 name="Top_5_most_frequently_encountered_validation_errors_and_how_to_fix_them"> Top 5 most frequently encountered validation errors and how to fix them </h4>
<ul><li> <a href="#incorrectnesting">incorrect nesting of elements</a>
</li><li> unescaped ampersands in URLs: ampersands (&amp;'s) in an URL must be escaped, must be replaced with &amp;amp;<br>
</li></ul>
<p><a class="external" href="http://www.htmlhelp.org/tools/validator/problems.html.en#amp">Ampersands (&amp;'s) in URLs</a> from <abbr title="Web Design Group">WDG</abbr><br> 
<a class="external" href="http://www.w3.org/QA/2005/04/php-session">Ampersands, PHP Sessions and Valid HTML</a> from W3C Quality tip for webmaster
</p>
<ul><li> misplaced elements (eg <a href="#blocknestedininline">block-level element nested within inline element</a>)
</li><li> missing elements (eg missing &lt;title&gt; in &lt;head&gt; section)
</li><li> missing alt attribute in &lt;img&gt;<br>
</li></ul>
<p>The alt attribute must be a textual replacement, a text rendering equivalent if/when, for some reason (network problem, user agent, user preference setting), the image can not be rendered. When one thinks of the alt attribute of an image, one should think of what he would say of such image if he was to describe it on the telephone. More info on alt attribute:<br>
<a class="external" href="http://www.w3.org/QA/Tips/altAttribute">W3C Quality Assurance Tip for Webmasters: Use the alt attribute to describe the function of each visual</a>
</p>
<p>An useful tutorial on correcting the most frequently encountered validation errors is: <a class="external" href="http://developer.mozilla.org/en/docs/Liberty%21_Equality%21_Validity%21">Liberty! Equality! Validity!</a> from Eric A. Meyer.</p>
<h4 name="How_to_upgrade_markup_code_in_some_frequently_encountered_cases:_.3Cfont.3E.2C_.3Ccenter.3E.2C_bgcolor"> How to upgrade markup code in some frequently encountered cases: <code>&lt;font&gt;</code>, <code>&lt;center&gt;</code>, <code>bgcolor</code> </h4>
<h5 name="I_use_.3Cfont.3E._How_to_define_or_to_replace_.3Cfont.3E_with_CSS.3F"> I use <code>&lt;font&gt;</code>. How to define or to replace <code>&lt;font&gt;</code> with CSS? </h5>
<p id="deprecated_font">The purpose of the deprecated <code>FONT</code> element is to specify typeface, color and size of the enclosed text. This functionality has been offloaded from HTML to CSS. The FONT element can be directly replaced with a <code>SPAN</code> element that includes the same style information:</p>
<pre>&lt;p&gt;&lt;font color="blue" face="Helvetica"&gt;
A really &lt;font size="+1"&gt;big&lt;/font&gt; shoe.
&lt;/font&gt;&lt;/p&gt;</pre>
<p>... becomes:</p>
<pre>&lt;p&gt;&lt;span style="color: blue; font-family: Helvetica, sans-serif;"&gt;
A really &lt;span style="font-size: larger;"&gt;big&lt;/span&gt; shoe.
&lt;/span&gt;&lt;/p&gt;</pre>
<p>... or even more concisely:</p>
<pre>&lt;p style="color: blue; font-family: Helvetica, sans-serif;"&gt;
A really &lt;span style="font-size: larger;"&gt;big&lt;/span&gt; shoe.&lt;/p&gt;</pre>
<p>This is appropriate usage for a local change to the font. However, this is not the best use of styles; the strength of CSS lies in the ability to gather text and other styling into logical groupings that can be applied across a document, without repeating the specific styling on every element that requires it.</p>
<p>More on conversion of &lt;FONT&gt;: 
<a class="external" href="http://www.w3.org/QA/Tips/font-size#css">W3C Quality Assurance tip for webmaster: Care With Font Size, Forget &lt;font&gt; and use CSS</a>
</p>
<h5 name="I_use_.3Ccenter.3E_or_align.3D.22center.22._How_to_align_with_CSS.3F"> I use <code>&lt;center&gt;</code> or <code>align="center"</code>. How to align with CSS? </h5>
<p id="center">The <a class="external" href="http://www.w3.org/TR/REC-CSS1#text-align">CSS1 text-align property</a> specifies how text or inline elements (like an image) are aligned within an element.</p>
<pre>&lt;p style="text-align: center;"&gt;&lt;img src="..." width="..."
height="..." alt="..."&gt;&lt;/p&gt;
// will center the image inside the &lt;p&gt; element</pre>
<p>CSS <code>margin-left: auto; margin-right: auto;</code> properties will center a block-level element within its containing block. Defining margin-left and margin-right is for block-level elements. When both <code>margin-left</code> and <code>margin-right</code> are <code>auto</code>, they are set to equal values, thus centering a block-level element within its parent.<br>
<a class="external" href="http://www.w3.org/TR/REC-CSS1#horizontal-formatting">CSS1 horizontal formating</a><br>
Worth mentioning is the excellent tutorial:<br>
<a class="external" href="http://dorward.me.uk/www/centre/">Centring using CSS</a> by D. Dorward<br>
Also <a class="external" href="http://www.gtalbot.org/NvuSection/NvuWebDesignTips/HorizontalAlignment.html">Interactive demo on CSS horizontal alignment and horizontal formating</a></p>
<h5 name="How_to_replace_bgcolor.3F_How_to_colorize_background_with_CSS.3F"> How to replace <code>bgcolor</code>? How to colorize background with CSS? </h5>
<p id="bgcolor">The <code>bgcolor</code> attribute can be replaced with <a class="external" href="http://www.w3.org/TR/CSS1#background-color">CSS1 background-color property</a>.</p>
<p>If you have</p>
<pre>&lt;td bgcolor="green" width="150"&gt;
... content here ...
&lt;/td&gt;</pre>
<p>... can replace it with:</p>
<pre>&lt;td style="background-color: green;" width="150"&gt;
... content here ...
&lt;/td&gt;</pre>
<h4 name="How_to_upgrade_markup_code_in_specific_cases:_.3Cembed.3E.2C_.3Capplet.3E.2C_.3Cmarquee.3E.2C_.3Cbgsound.3E"> How to upgrade markup code in specific cases: <code>&lt;embed&gt;</code>, <code>&lt;applet&gt;</code>, <code>&lt;marquee&gt;</code>, <code>&lt;bgsound&gt;</code> </h4>
<h5 name="What_if_I_use_.3Cembed.3E_for_flash_or_for_a_video.3F"> What if I use <code>&lt;embed&gt;</code> for flash or for a video? </h5>
<p id="embed">Explaining in details how to do this would go beyond the scope of this article. Nevertheless, we recommend the following articles so that you can have flash or a video in your webpage and, at the same time, have your page validate.</p>
<ul><li> <a class="external" href="http://www.alistapart.com/articles/flashsatay">Embedding Flash While Supporting Standards</a>
</li><li> <a class="external" href="http://www.alistapart.com/articles/byebyeembed">Bye Bye Embed: Embedding a video</a>
</li><li> <a class="external" href="http://wiki.dreamhost.com/index.php/Object_Embedding">Embedding Object with valid code</a>
</li></ul>
<h5 name="What_if_I_use_.3Capplet.3E.3F"> What if I use <code>&lt;applet&gt;</code>? </h5>
<p id="applet">We recommend these resources:</p>
<ul><li> <a class="external" href="http://ww2.cs.fsu.edu/%7Esteele/XHTML/appletObject.html">Java applet using &lt;object&gt; tag</a> by Shayne Steele
</li><li> <a class="external" href="http://www.w3.org/TR/html401/struct/objects.html#edef-APPLET">HTML 4.01 on Including an applet</a>
</li><li> <a class="external" href="http://www.w3.org/TR/html401/struct/objects.html#edef-OBJECT">HTML 4.01 on Including an object</a>
</li></ul>
<p><span class="comment">Worth mentioning here: Java Upgrade Guide: Migrating From the Microsoft VM for Java to the Sun JRE http://java.sun.com/j2se/1.4.2/docs/guide/deployment/deployment-guide/upgrade-guide/index.html "after December, 2007, Microsoft will no longer support or provide a Java implementation with any of its products. (...) Those running applets in the Internet Explorer web browser will need to download and install an alternate VM."</span>
</p>
<h5 name="What_if_I_use_.3Cmarquee.3E.3F"> What if I use <code>&lt;marquee&gt;</code>? </h5>
<p id="marquee">Marquee can be replaced with content string inside a <code>&lt;div&gt;</code> or <code>&lt;span&gt;</code> rotating over time with Javascript and DOM level 1. It must be said that this sort of effect is discouraged. Studies have shown that constantly moving objects or moving text disturb reading and weakens peripherical vision. DHTML marquee also greatly consumes user system resources (cpu, RAM) on tested browsers and will put modest systems under considerable stress. If after webpage assessment and consideration, you still want to include a marquee effect in your page, then you can use the following recommendable tutorials:<br>
<a class="external" href="http://developer.mozilla.org/en/docs/DHTML_Demonstrations_Using_DOM/Style:Stock_Ticker">Cross-browser and web standard compliant Stock Ticker example</a> by D. Rosenberg<br>
<a class="external" href="http://devedge-temp.mozilla.org/toolbox/examples/2002/xb/xbMarquee/index_en.html">Comprehensive web standard compliant alternative to &lt;marquee&gt;</a> by D. Rosenberg<br>
Mozilla 1.4+, NS 7.2 and Firefox 1.x support the non-standard <code>&lt;marquee&gt;</code> element. On the other hand, users can disable such support using <a class="external" href="http://www.mozilla.org/support/firefox/tips#lay_marquee">this tip</a></p>
<h5 name="What_if_I_have_.3Cbgsound.3E.3F"> What if I have <code>&lt;bgsound&gt;</code>? </h5>
<p id="bgsound">Then use HTML 4.01 <code>OBJECT</code>, e.g.:<br>
<code>&lt;OBJECT data="audiofile.wav" type="audio/wav" ...&gt;&lt;/OBJECT&gt;</code><br>
See <a class="external" href="http://devedge-temp.mozilla.org/library/manuals/2002/plugin/1.0/intro.html#1003240">this DevEdge article</a> for information on rendering a sound OBJECT invisible within the page.<br>
Web page background sound often slows down considerably web page loading; like the text effects above, music or sound accompanying a page is seldom appreciated. According to the survey page <a class="external" href="http://www.lowendmac.com/musings/02/0528.html">What we really hate on the web</a>, 41.9% of survey respondents will avoid sites that automatically play music; 71.1% strongly dislike sites that automatically play music.<br>
<a class="external" href="http://www.wowwebdesigns.com/power_guides/music_off.php">Why Playing Music on your Web Site is a Bad Idea</a> by A. Gulez</p>
<h3 name="Step_3:_Validate_your_CSS_code"> Step 3: Validate your CSS code </h3>
<h4 name="Where_can_I_validate_my_CSS_code.3F"> Where can I validate my CSS code? </h4>
<p>Free Online CSS validation services:</p>
<ul><li> <a class="external" href="http://jigsaw.w3.org/css-validator/">W3C CSS Validation Service</a>
</li><li> <a class="external" href="http://www.htmlhelp.org/tools/csscheck/"><abbr title="Web Design Group">WDG</abbr> CSS checker</a>
</li></ul>
<p>Built-in report of CSS parsing errors in modern browsers:</p>
<ul><li> Error console in Firefox 2. From the menu, Tools/Error console; the error console reports CSS parsing errors.
</li><li> Error console in Opera 9. From the menu, Tools/Advanced/Error console; the error console reports CSS parsing errors.
</li><li> Error console in Icab 3. From the menu, Preferences/Show All/Other/Error report: the error console reports CSS parsing errors.
</li></ul>
<h2 name="Using_the_W3C_DOM"> Using the <abbr title="World Wide Web Consortium">W3C</abbr> DOM </h2>
<p>The <code>document</code> objects for some browsers have properties for accessing arrays of elements and types of elements. <code>document.all[]</code>, for example, is used by Internet Explorer to access particular elements within the document. Many of these arrays were not made a part of the <abbr title="World Wide Web Consortium">W3C</abbr> specification for the Document Object Model and will cause JavaScript errors in standards-compliant browsers like Firefox, Seamonkey and Netscape 7+.</p>
<p>The <a class="external" href="http://www.w3.org/DOM/DOMTR"><abbr title="World Wide Web Consortium">W3C</abbr> Document Object Model</a> exposes almost all of the elements in an HTML page as scriptable objects. In general the attributes and methods of the <abbr title="World Wide Web Consortium">W3C</abbr> DOM are more powerful than the proprietary object models used in DHTML programming. <strong>The attributes and methods of the <abbr title="World Wide Web Consortium">W3C</abbr> DOM are overall well supported by modern browsers like MSIE 7, Opera 9, Safari 2, Konqueror 3.x and Mozilla-based browsers (Firefox, Seamonkey, Netscape 7+, Camino): so there is no gain from relying on proprietary object models</strong>.</p>
<h3 name="Unsupported_DOM-related_Properties"> Unsupported DOM-related Properties </h3>
<p>The following <code>document</code> object properties are not supported in the <abbr title="World Wide Web Consortium">W3C</abbr> Document Object Model:</p>
<ul><li> <code>document.layers[]</code>
</li><li> <code>id_attribute_value</code>
</li><li> <code>document.all</code>
</li><li> <code>document.all.id_attribute_value</code>
</li><li> <code>document.all{{mediawiki.external('id_attribute_value')}}</code>
</li></ul>
<p>The following form related properties (originally from Internet Explorer) are not supported in the <abbr title="World Wide Web Consortium">W3C</abbr> Document Object Model:</p>
<ul><li> <code>FormName.InputName.value</code>
</li><li> <code>InputName.value</code>
</li><li> <code>FormCtrlName</code>
</li><li> <code>document.forms(0)</code>
</li></ul>
<p>Scripts that use these properties will not execute in Firefox, Mozilla and Netscape 7+ or other standards-compliant browsers. <strong>Instead, use the <abbr title="World Wide Web Consortium">W3C</abbr> DOM access attributes and access methods described in the next section; since these are supported by Internet Explorer too, then there is no need to use MSIE-specific attributes and methods.</strong></p>
<h3 name="Accessing_Elements_with_the_W3C_DOM"> Accessing Elements with the <abbr title="World Wide Web Consortium">W3C</abbr> DOM </h3>
<p><strong>The best and most supported practice for getting scriptable access to an element in an HTML page is to use <code>document.getElementById(<var>id</var>)</code>.</strong> A very wide majority of browsers (MSIE 5+, Firefox, NS 7+, Seamonkey, Opera 6+, Safari 1.x, Konqueror 3.x, etc.) support document.getElementById(<var>id</var>). This method returns <strong>a reference to the uniquely identified element</strong>, which can then be used to script that element. For example, the following short sample dynamically sets the left margin of a <code>div</code> element with an <code>id</code> of "inset" to half an inch:</p>
<pre>// in the HTML: &lt;div id="inset"&gt;Sample Text&lt;/div&gt;
document.getElementById("inset").style.marginLeft = ".5in";</pre>
<table cellpadding="4" class="standard-table" id="dom_access" summary="List of Internet Explorer specific ways to access elements in a document or form elements (1st, left column) and their respective W3C web standards replacements (2nd, right column)">

  <tbody><tr style="text-align: center;"><th scope="col">IE-specific ways to access elements</th><th scope="col">
  <abbr title="World Wide Web Consortium">W3C</abbr> web standards replacements</th></tr>
  <tr><td>id_attribute_value</td><td>document.getElementById(id_attribute_value)</td></tr>
  <tr><td>document.all.id_attribute_value</td><td>document.getElementById(id_attribute_value)</td></tr>
  <tr><td>document.all{{mediawiki.external('id_attribute_value')}}</td><td>document.getElementById(id_attribute_value)</td></tr>
  <tr><td>FormName.InputName.value</td><td>document.forms{{mediawiki.external('\"FormName\"')}}.InputName.value or<br>
  document.forms{{mediawiki.external('\"FormName\"')}}.elements{{mediawiki.external('\"InputName\"')}}.value</td></tr>
  <tr><td>InputName.value</td><td>document.forms{{mediawiki.external('\"FormName\"')}}.InputName.value or<br>
  document.forms{{mediawiki.external('\"FormName\"')}}.elements{{mediawiki.external('\"InputName\"')}}.value</td></tr>
  <tr><td>FormCtrlName</td><td>document.forms{{mediawiki.external('\"FormName\"')}}.FormCtrlName or<br>
  document.forms{{mediawiki.external('\"FormName\"')}}.elements{{mediawiki.external('\"FormCtrlName\"')}}</td></tr>
  <tr><td>document.forms(0)</td><td>document.forms{{mediawiki.external(0)}}</td></tr>
 </tbody></table>
<p>More on accessing forms and form elements:<br>
<a class="external" href="http://jibbering.com/faq/faq_notes/form_access.html">Referencing Forms and Form Controls</a> by comp.lang.javascript newsgroup FAQ notes<br>
<a class="external" href="http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-40002357">DOM 2 specification on accessing forms and form elements</a></p>
<p>For accessing a group of elements, the DOM specification also includes <code>getElementsByTagName</code>, which returns a list of all the elements with the given tag name in the order they appear in the document:</p>
<pre>var arrCollection_Of_Anchors = document.getElementsByTagName("a");
var objFirst_Anchor = arrCollection_Of_Anchors[0];
alert("The url of the first link is " + objFirst_Anchor.href);</pre>
<p>In addition to these access methods, the <abbr title="World Wide Web Consortium">W3C</abbr> DOM2 specifications provide methods for creating new elements and inserting them in a document, for creating attributes, new content, for traversing the content tree and for handling events raised as the user interacts with the document itself.</p>
<h3 name="Manipulating_Document_Style_and_Content"> Manipulating Document Style and Content </h3>
<h4 name="Changing_an_Element.27s_Style_Using_the_DOM"> Changing an Element's Style Using the DOM </h4>
<p id="dom_manip">The following table describes standards-based methods for accessing and updating style rules defined for various HTML elements in a web page. See the <abbr title="World Wide Web Consortium">W3C</abbr> DOM2 Recommendation, <a class="external" href="http://www.w3.org/TR/2000/REC-DOM-Level-2-Style-20001113/css.html#CSS-extended">CSS2 Extended Interface</a>.</p>
<p>DOM level 2 provides for the assignment of new values to the CSS properties of an element using the <code><var>ElemRef</var>.style</code> object reference. You can get a reference to the element to which that style corresponds by using the DOM's <code>getElementById</code> or one of the other methods described in the <a href="#dom_access">DOM access section</a> above.</p>
<table cellpadding="4" class="standard-table" summary="List of some non-standard ways to modify the style of an element (1st, left column) and their respective standard compliant replacement (2nd, right column)">

<tbody><tr style="text-align: center;">
<th scope="col">Deprecated coding practices</th>
<th scope="col">Appropriate DOM 2 replacements</th>
</tr>

<tr>
<td>IE5+: <code><var>ElemRef</var>.style.pixelLeft</code></td>
<td>DOM level 2: <code>parseInt(<var>ElemRef</var>.style.left, 10)</code></td>
</tr>

<tr>
<td>IE5+: <code><var>ElemRef</var>.style.pixelTop</code></td>
<td>DOM level 2: <code>parseInt(<var>ElemRef</var>.style.top, 10)</code></td>
</tr>

<tr>
<td>IE5+: <code><var>ElemRef</var>.style.pixelLeft = <var>x</var>;<br>
<var>ElemRef</var>.style.pixelTop = <var>y</var>;</code></td>
<td>DOM level 2:<br>
<p><code><var>ElemRef</var>.style.left = <var>x</var> + "px";</code><br>
</p>
<code><var>ElemRef</var>.style.top = <var>y</var> + "px";</code></td>
</tr>

</tbody></table>
<h5 name="W3C_DOM2_Reflection_of_an_Element.27s_CSS_Properties"> <abbr title="World Wide Web Consortium">W3C</abbr> DOM2 Reflection of an Element's CSS Properties </h5>
<p>Keep in mind that according to the <abbr title="World Wide Web Consortium">W3C</abbr> Recommendation, the values returned by the style property of an element reflect static settings in the element's <code>STYLE</code> attribute only, not the total "computed style" that includes any inherited style settings from parent elements. Therefore, if you wish to read and write these properties from JavaScript through the DOM2, use one of these two approaches:</p>
<ul><li> Place all of the element's static CSS declarations (if it has any) in the element's <code>STYLE</code> attribute.
</li><li> Use no static CSS declarations for the element and initialize its CSS properties from JavaScript through the DOM.
</li></ul>
<h5 name="W3C_DOM2_Reflection_of_an_Element.27s_CSS_Positioning_Properties"> <abbr title="World Wide Web Consortium">W3C</abbr> DOM2 Reflection of an Element's CSS Positioning Properties </h5>
<p>The values returned by the <abbr title="World Wide Web Consortium">W3C</abbr> DOM2 <code>style.left</code> and <code>style.top</code> properties are strings that include the CSS unit suffix (such as "px"), whereas IE5+ <code><var>ElemRef</var>.style.pixelLeft</code> (and the corresponding properties for top) return an integer. So, if you want to get the element's inline <code>STYLE</code> settings for left and top as integers, parse the integer from the string by using <code>parseInt()</code>. Conversely, if you want to set the element's inline <code>STYLE</code> settings for left and top, make sure to construct a string that includes the unit (such as "140px") by appending the unit string to the integer value.</p>
<p><strong>CSS 1 and CSS 2.x specifications require that non-zero values must be specified with a length unit; otherwise, the css declaration will be ignored.</strong> Mozilla-based browsers, MSIE 6+, Opera 7+ and other W3C standards-compliant browsers enforce such handling of parsing error.<br>
<a class="external" href="http://www.w3.org/TR/REC-CSS1#forward-compatible-parsing">CSS 1 Forward-compatible parsing</a><br>
<a class="external" href="http://www.w3.org/TR/CSS21/syndata.html#parsing-errors">CSS 2.1 Rules for handling parsing errors</a></p>
<h4 name="Changing_an_Element.27s_Text_Using_the_DOM"> Changing an Element's Text Using the DOM </h4>
<p>Changing the actual text content of an element has changed substantially compared to the normal means of operation. Each element's content is broken up into a set of child nodes, consisting of plain text and sub-elements. In order to change the text of the element, the script operates on the node.</p>
<p>The node structure and supporting methods are defined in the <abbr title="World Wide Web Consortium">W3C</abbr> <a class="external" href="http://www.w3.org/TR/REC-DOM-Level-1/">DOM level 1</a> recommendation.</p>
<p>If the element has no sub-elements, just text, then it (normally) has one child node, accessed as <code>ElemRef.childNodes{{mediawiki.external(0)}}</code>. In such precise case, the W3C web standards equivalent of <code>ElemRef.innerText</code> is <code>ElemRef.childNodes{{mediawiki.external(0)}}.nodeValue</code>.</p>
<p><span class="comment">We could introduce DOM 3 Core textContent attribute here which is supported by Mozilla 1.5+, Safari 2.x, Opera 9.x and is a perfect equivalent to MSIE's innerText. http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#Node3-textContent</span>
</p>
<p>The following examples show how to modify the text of a <code>SPAN</code> element that already exists in the HTML file.</p>
<pre>&lt;body&gt;
  &lt;P&gt;Papa's got &lt;SPAN id="dynatext"&gt;a lot of nerve&lt;/SPAN&gt;!&lt;/P&gt;

  &lt;script type="text/javascript"&gt;
&lt;span class="remark"&gt;// get reference to the SPAN element&lt;/span&gt;
var SpanElemRef = document.getElementById("dynatext");

&lt;span class="remark"&gt;// implement SpanElemRef.innerText = "a brand new bag"&lt;/span&gt;
var new_txt = document.createTextNode("a brand new bag");
SpanElemRef.replaceChild(new_txt, SpanElemRef.childNodes[0]);

&lt;span class="remark"&gt;// alternate, slightly more dangerous implementation
//(will not work if childNodes[0] is not a text node)&lt;/span&gt;
SpanElemRef.childNodes[0].nodeValue = "a brand new bag";

&lt;span class="remark"&gt;// implement SpanElemRef.innerHTML = "a brand &lt;b&gt;new&lt;/b&gt; bag"&lt;/span&gt;
var new_el = document.createElement(SpanElemRef.nodeName);
new_el.appendChild(document.createTextNode("a brand "));
var bold_el = document.createElement("B");
bold_el.appendChild(document.createTextNode("new"));
new_el.appendChild(bold_el);
new_el.appendChild(document.createTextNode(" bag"));
span_el.parentNode.replaceChild(new_el, SpanElemRef);
  &lt;/script&gt;
&lt;/body&gt;
</pre>
<p>The first example shows the relatively simple method of replacing the text in the <code>SPAN</code> by substituting a new text node for the original. The assumption here is that the <code>SPAN</code> has a single, text child; the code would work even if that were not true, but the results might be unexpected.</p>
<p>The second example shows a more concise but brute-force technique of accomplishing the same thing. As noted, if the first child node is not a text node, this action will not work: although sub-element nodes have a <code>nodeValue</code>, the contents of that field are not displayed in the document.</p>
<p>The final example shows a technique equivalent to setting <code>innerHTML</code>. First, it constructs a new element, created as the same type (<code>SPAN</code>) as the original. Next it adds three nodes: an initial text node, a <code>B</code> element with its own text node, and a final text node. The script then accesses the <code>SPAN</code> element's parent (the <code>P</code> element), and substitutes the new element for the original <code>SPAN</code> in the parent's list of child nodes.</p>
<p>It should be clear that translating scripts to modify document content is not a trivial undertaking. The benefit of such a conversion is that the script will work in modern, <abbr title="World Wide Web Consortium">W3C</abbr> DOM-compliant browsers such as Netscape 7 and other Gecko-based programs. Requirements of backward compatibility, however, will not only prolong but worsen the difficulties of dealing with multiple platforms.</p>
<h2 name="Developing_Cross_Browser.2FCross_Platform_Pages"> Developing Cross Browser/Cross Platform Pages </h2>
<p>An important practice when doing cross-browser, cross-platform pages and DHTML development involves the ability to determine the capabilities of the browser which loads your web page. As a web author, you understandably want to avoid script errors and page layout problems and you may want to ensure your scripts reach as wide an audience as possible. There are 2 known approaches for such goals: the browser identification approach (also known as userAgent string detection and often referred as "browser sniffing") and the Object/Feature support detection approach. The browser identification approach is now known to be complicated, unreliable and difficult to maintain.</p>
<h3 name="Browser_identification_approach_.28aka_.22browser_sniffing.22.29:_not_best.2C_not_reliable_approach"> Browser identification approach (aka "browser sniffing"): not best, not reliable approach </h3>
<p>This approach, still commonly used nowadays, attempts to identify the browser and makes the web author at design time decide what that implies in terms of capabilities of the visiting browser. Such approach is fraught with problems and difficulties. It requires from the web author to have knowledge of the capabilities of all current browsers that may visit the page and then to code appropriately for these. It requires from the web author to make assumptions about what will happen with future browsers or to decide to provide future browsers a safe fallback service. It assumes that web authors are able to correctly identify browsers and browser versions in the first place... which is far from being a reliable and easy task to achieve.</p>
<p>The browser identification approach relies on functions that check the browser type string value and browser version string value and that search for certains characters or sub-strings in the <code>navigator.userAgent</code> property string. Once "detected", the web author then uses different functions (aka code branching) or points the user to different pages (aka site branching) or web content. Site branching can be particularly dangerous as people may enter a page through a link, bookmark, search engine or cache with a "wrong" browser.</p>
<p>Let's see a basic example of this approach.</p>
<div class="bad example">
<pre>if (navigator.appVersion.charAt(0) = "8")
{
  if (navigator.appName = "Netscape")
  {
    isNS8 = true;
    alert("NS8");
  };
}
else if (navigator.appVersion.indexOf("MSIE") != -1)
{
  isIE = true;
  alert("IE");
};</pre>
<p>While this kind of checking in the above code can work in a crude sense, sharp readers may wonder what happens when IE 8 is released or when an Opera 8.x user visits the page or even when an user with any non-Netscape browser starting with a "8" character in the appVersion string visits that page. As new browsers are released, it becomes necessary to make updates to such code which attempts to narrow down the browser and browser version and to make the appropriate switches.</p>
</div>
<p>Another major problem with this approach is that the browser identity can be "spoofed" because, in many modern browsers, the <strong><code>navigator.appVersion</code> and <code>navigator.userAgent</code> string properties are user configurable strings</strong>. For example,</p>
<ul><li> Firefox 1.x users and users of any/all Mozilla-based browsers can customize the "general.useragent.*" string properties to any value.
</li><li> Opera 6+ allows users to set the browser identification string via a menu
</li><li> MSIE uses the Windows registry
</li><li> Safari and Icab browsers mask their browser identity under Internet Explorer or Netscape labels
</li></ul>
<p><strong>A user or browser distributor can put what they want in the <code>navigator.userAgent</code> string</strong> and this may trick your code into executing a "wrong" block of code. Moreover, there are many cases where even the accurately-identified browser does not perform as it is reputed/expected to.</p>
<p>So if "browser sniffing" is unreliable and difficult, how do you code safely for different browsers and different browser versions? ... </p>
<h3 name="Using_Object.2FFeature_support_detection_approach:_best_and_overall_most_reliable"> Using Object/Feature support detection approach: best and overall most reliable </h3>
<p>When you use object/feature support detection, you only implement those features whose support you have first tested and verified on the visiting browser. This method has the advantage of not requiring you to test for anything except whether the particular features you code are supported in the visiting browser.</p>
<p>Let's see a basic, simple object support detection example.</p>
<div class="good example">
<pre>function hideElement(id_attribute_value)
{
if (document.getElementById &amp;&amp;
    document.getElementById(id_attribute_value) &amp;&amp;
    document.getElementById(id_attribute_value).style)
 {
 document.getElementById(id_attribute_value).style.visibility="hidden";
 };
}

// example:
// &lt;button type="button" onclick="hideElement('d1');"&gt;hide div&lt;/button&gt;
// &lt;div id="d1"&gt;Some text&lt;/div&gt;</pre>
<p>These repeated calls to document.getElementById are not the most efficient way to check for the existence of particular objects or features in the browser's DOM implementation, but they serve to illustrate clearly how object support detection works.</p>
<p>The top-level if clause looks to see if there is support for a method called getElementById on the document object, which is the one of the most basic levels of support for the DOM in a browser. If there is, the code sees if document.getElementById(id_attribute_value) returns a reference to an existing element, which it then checks for a style object. If the style object exists on the element, then it sets that object's visibility property. The browser will not error if you set this unimplemented property, so you do not need to check that the visiblity property itself exists.</p>
</div>
<p>So, instead of needing to know which browsers and browser versions support a particular DOM method (or DOM attribute or DOM feature), you can verify the support for that particular method in the visiting browser. With this approach, you ensure that all browsers -- including future releases and browsers whose userAgent strings you do not know about -- will continue working with your code.</p>
<p>More on object/feature support detection:<br>
<a class="external" href="http://jibbering.com/faq/faq_notes/not_browser_detect.html#bdFD">A Strategy That Works: Object/Feature Detecting</a> by comp.lang.javascript newsgroup FAQ notes<br>
<a class="external" href="http://www.quirksmode.org/js/support.html">Browser detection - No; Object detection - Yes</a> by Peter-Paul Koch</p>
<p><span class="comment">Also good http://developer.mozilla.org/en/docs/Browser_Detection_and_Cross_Browser_Support but outdated in my opinion</span>
</p>
<h2 name="Using_XMLHttpRequest"> Using XMLHttpRequest </h2>
<p>Microsoft first introduced the XMLHttpRequest object in Internet Explorer 5.0 as an ActiveX control. However, in IE7 and other browsers XMLHttpRequest is a native scripting object. Thus, the most widely-supported way of including an XMLHttpRequest is to use the native object if possible, and fall back on the ActiveX control, like this:
</p>
<pre>if (window.XMLHttpRequest)
{
    //Firefox, Opera, IE7, and other browsers will use the native object
    var request = new XMLHttpRequest();
}
else
{
    //IE 5 and 6 will use the ActiveX control
    var request = new ActiveXObject("Microsoft.XMLHTTP");
}
</pre>
<p>If support for IE 5 and 6 is not a concern, then this next approach will work fine and is much more concise:
</p>
<pre>var request = new XMLHttpRequest()
</pre>
<p>More on XMLHttpRequest:
</p>
<ul><li> <a class="external" href="http://www.w3.org/TR/XMLHttpRequest/">The XMLHttpRequest Object: W3C Working Draft 27 September 2006</a>
</li></ul>
<h2 name="Summary_of_Changes"> Summary of Changes </h2>
<p>This section outlines all of the element and practice updates described in this article. For a complete discussion of these items, see the sections in which they are described.</p>
<table cellpadding="4" class="toc" rules="all" summary="List of non-standard or deprecated feature (1st, left column) discussed in this document with its respective W3C recommended replacement (2nd, right column)">

<tbody><tr style="text-align: center;">
<th scope="col">Proprietary or Deprecated Feature</th>
<th scope="col"><abbr title="World Wide Web Consortium">W3C</abbr> Feature or Recommended Replacement</th></tr>
<tr><td>deprecated <code>FONT</code></td>
<td>HTML 4.01 <a href="#deprecated_font"><code>SPAN</code> plus<br>
CSS1 <code>color: ; font-family: ; font-size: ;</code></a></td></tr>
<tr><td>deprecated <code>CENTER</code> or <code>align="center"</code></td>
<td>CSS1 <a href="#center"><code>text-align: center;</code> for
in-line elements like text or image</a></td></tr>
<tr><td>deprecated <code>CENTER</code> or <code>align="center"</code></td>
<td>CSS1 <a href="#center"><code>margin-left: auto; margin-right: auto;</code><br>
for block-level elements</a></td></tr>
<tr><td>deprecated <code>bgcolor</code></td>
<td>CSS1 <a href="#bgcolor"><code>background-color: ;</code></a></td></tr>
<tr><td>non-standard <code>EMBED</code></td>
<td>HTML 4.01 <a href="#embed"><code>OBJECT</code></a></td></tr>
<tr><td>deprecated <code>APPLET</code></td>
<td>HTML 4.01 <a href="#applet"><code>OBJECT</code></a></td></tr>
<tr><td>non-standard <code>MARQUEE</code></td>
<td>HTML 4.01 <a href="#marquee"><code>DIV</code> plus scripting</a></td></tr>
<tr><td>non-standard <code>BGSOUND</code></td>
<td>HTML 4.01 <a href="#bgsound"><code>OBJECT</code></a></td></tr>
<tr style="text-align: center;"><th>Proprietary or Deprecated Feature</th>
<th><abbr title="World Wide Web Consortium">W3C</abbr> Feature or Recommended Replacement</th></tr>
<tr><td>IE5+<br>
<p><code><var>id_attribute_value</var></code><br>
<code>document.all.<var>id_attribute_value</var></code><br>
</p>
<code>document.all{{mediawiki.external('&lt;var&gt;id_attribute_value&lt;/var&gt;')}}</code></td>
<td>DOM level 2:<br>
<a href="#dom_access"><code>document.getElementById(<var>id_attribute_value</var>)</code></a></td></tr>

<tr><td>IE5+ <code><var>FormName</var>.<var>InputName</var>.value</code></td>
<td>DOM level 1:<br>
<p><a href="#dom_access"><code>document.forms{{mediawiki.external('\"&lt;var&gt;FormName&lt;/var&gt;\"')}}.<var>InputName</var>.value</code></a>
</p>
</td></tr>

<tr><td>IE5+ <code><var>InputName</var>.value</code></td>
<td>DOM level 1:<br>
<p><a href="#dom_access"><code>document.forms{{mediawiki.external('\"&lt;var&gt;FormName&lt;/var&gt;\"')}}.<var>InputName</var>.value</code></a>
</p>
</td></tr>

<tr><td>IE5+ <code><var>FormCtrlName</var></code></td>
<td>DOM level 1:<br>
<p><a href="#dom_access"><code>document.forms{{mediawiki.external('\"&lt;var&gt;FormName&lt;/var&gt;\"')}}.<var>FormCtrlName</var></code></a>
</p>
</td></tr>

<tr><td>IE5+ <code>document.forms(0)</code></td>
<td>DOM level 1:<br>
<p><a href="#dom_access"><code>document.forms{{mediawiki.external(0)}}</code></a>
</p>
</td></tr>

<tr><td>IE <code><var>ElemRef</var>.innerText</code></td>
<td><a href="#dom_manip">DOM Level 1 (Core) interface</a>
<p><span class="comment">We could introduce DOM 3 Core textContent attribute here which is supported by Mozilla 1.5+ and is a perfect equivalent to innerText. http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#Node3-textContent</span>
</p>
</td></tr>

<tr><td>IE5+ <code><var>ElemRef</var>.style.pixelTop</code></td>
<td>DOM level 2: <a href="#dom_manip"><code>parseInt(<var>ElemRef</var>.style.top, 10)</code>
</a></td></tr>
<tr><td>IE5+ <code><var>ElemRef</var>.style.pixelLeft = <var>x</var>;
<var>ElemRef</var>.style.pixelTop = <var>y</var>;</code></td>
<td>DOM level 2: <a href="#dom_manip"><code><var>ElemRef</var>.style.left = <var>x</var> + "px"; 
<var>ElemRef</var>.style.top = <var>y</var> + "px";</code></a></td></tr>
<tr>
  <td>IE5+ new ActiveXObject("Microsoft.XMLHTTP")</td>
  <td>new XMLHttpRequest()</td>
</tr>

<tr style="text-align: center;"><th>Proprietary or Deprecated Feature</th>
<th><abbr title="World Wide Web Consortium">W3C</abbr> Feature or Recommended Replacement</th></tr>
</tbody></table>
<h2 name="References"> References </h2>
<p>You can learn more on using web standards from these sites:</p>
<ul><li> <a class="external" href="http://webstandards.org/learn/faq/#p3">What are web standards and why should I use them? What are the advantages of using web standards?</a> from <a class="external" href="http://webstandards.org/">Web Standards Project</a>
</li></ul>
<ul><li> <a class="external" href="http://www.w3.org/QA/2002/04/Web-Quality">Web Quality Assurance tips for webmasters: My Web site is standard! And yours?</a> from <a class="external" href="http://www.w3.org/QA/Tips/"><abbr title="World Wide Web Consortium">W3C</abbr> Quality Assurance</a>
</li></ul>
<ul><li> <a class="external" href="http://maccaws.org/">Making A Commercial Case for Adopting Web Standards</a>
</li></ul>
<ul><li> <a class="external" href="http://devedge-temp.mozilla.org/viewsource/2003/media-farm/index_en.html">Case Study in a Successful Standards-Based Migration</a>
</li></ul>
<ul><li> <a class="external" href="http://webstandardsgroup.org/standards/">Web Standards Group</a>
</li></ul>
<ul><li> <a class="external" href="http://developer.apple.com/internet/webcontent/bestwebdev.html">Web Page Development: Best Practices</a>
</li></ul>
<ul><li> <a class="external" href="http://www.mozilla.org/docs/web-developer/faq.html">Mozilla Web Author <abbr title="Frequently Asked Questions">FAQ</abbr></a>
</li></ul>
<ul><li> <a class="external" href="http://www.reloco.com.ar/mozilla/compat.html">Making your web page compatible with Mozilla</a>
</li></ul>
<ul><li> <a class="external" href="http://www.westciv.com/style_master/academy/css_tutorial/">Complete CSS Guide</a>
</li></ul>
<ul><li> <a class="external" href="http://tutorials.alsacreations.com/">CSS lessons and tutorials</a>
</li></ul>
<ul><li> <a class="external" href="http://www.htmldog.com/">HTML and CSS lessons and tutorials</a>
</li></ul>
<ul><li> <a class="external" href="http://www.digital-web.com/articles/preparing_for_standard_compliant_browsers_part1/">Preparing for standard-compliant browsers, Part 1</a>
</li></ul>
<ul><li> <a class="external" href="http://www.digital-web.com/articles/preparing_for_standard_compliant_browsers_part2/">Preparing for standard-compliant browsers, Part 2</a>
</li></ul>
<hr>
<div class="originaldocinfo">
<h2 name="Original_Document_Information"> Original Document Information </h2>
<ul><li> Author(s): Mike Cowperthwaite, Marcio Galli, Jim Ley, Ian Oeschger, Simon Paquet, Gérard Talbot
</li><li> Last Updated Date: December 24, 2006
</li><li> Copyright Information: Portions of this content are © 1998–2006 by individual mozilla.org contributors; content available under a Creative Commons license | <a class="external" href="http://www.mozilla.org/foundation/licensing/website-content.html">Details</a>.
</li></ul>
</div>
{{ wiki.languages( { "ja": "ja/Using_Web_Standards_in_your_Web_Pages" } ) }}
Revert to this revision