Using the W3C DOM

我们的志愿者还没有将这篇文章翻译为 中文 (简体) 。加入我们帮助完成翻译!

The Document object has properties for accessing collections of elements, such as document.images and document.forms. Some browsers have non-standard properties, such as Internet Explorer's document.all[], that are not part of the W3C Document Object Model (DOM) standards and may cause JavaScript errors in standards-compliant browsers.

The W3C Document Object Model provides interfaces DOM elements to scriptable objects. W3C DOM standards are well supported by modern browsers, however the standards are moving target so support for newer features should be tested before use. Using W3C standards means that code will run in compliant browsers with minimal need for cross-browser support, whereas code based on proprietary standards requires much more effort to be compatible with multiple user agents.

The following IE proprietary 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[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) (Note: document.forms[0] (using square brackets) uses the DOM standard Forms collection)

Scripts that use these properties will throw errors in most standards-compliant browsers. Instead, use the W3C DOM properties and methods (examples in the next section). These are supported by Internet Explorer too so there is no need to use MSIE-specific attributes and methods.

Accessing Elements with the W3C DOM

The basic method for referencing elements in an HTML page is document.getElementById(). All modern browsers support it. The method returns a reference to the uniquely identified element, which can then be used to script the 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";
Note: Internet Explorer 5 through 7 have a flawed implementation of getElementById(), which returns the first element with a matching NAME or ID (Id versus name when using getElementById, MSDN: getElementById Method).
IE-specific ways to access elements W3C web standards replacements
id_attribute_value document.getElementById()
document.all.id_attribute_value document.getElementById()
document.all[id_attribute_value] document.getElementById()
FormName.InputName.value document.forms["FormName"].InputName.value or
document.forms["FormName"].elements["InputName"].value
InputName.value document.forms["FormName"].InputName.value or
document.forms["FormName"].elements["InputName"].value
FormCtrlName document.forms["FormName"].FormCtrlName or
document.forms["FormName"].elements["FormCtrlName"]
document.forms(0) document.forms[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
Referencing Forms and Form elements correctly, Javascript Best Practices, by Matt Kruse

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

var arrCollection_Of_Pargs = document.getElementsByTagName("p");
var objFirst_Parg = arrCollection_Of_Pargs[0];
// objFirst_Parg will reference the first paragraph in the document
objFirst_Parg.style.border = "2px solid green";
// and now, the first paragraph in the document 
// gets a 2px solid green border.

In addition to these access methods, the W3C DOM 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 dispatched 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 DOM 2 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

The text of an element is available as the textContent or innerText property (some browsers support both).  The textContent property was introduced in the W3C DOM 3 Core, innerText has been an IE method since IE 4 and has been standardised in HTML5.

Both properties can be read or set. Reading the property returns the text of an element with all the element content removed. Setting the property replaces all the element's content with a single text node with the assigned text.

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">
// get a reference to the SPAN element
var spanEl = document.getElementById("dynatext");

// Detect whether the browser supports textContent or innerText
if (typeof spanEl.textContent == 'string') {
  spanEl.textContent = 'some gall';
} else if (typeof spanEl.innerText == 'string') {
  spanEl.innerText = 'some gall';
  
// If neither are supported, use other DOM methods
} else {
  while (spanEl.firstChild) {
    spanEl.removeChild(spanEl.firstChild);
  }
  spanEl.appendChild(document.createTextNode('some gall'));
}
  </script>
</body>

The first part of the code gets a reference to the element. It then tests for support for textContent, then innerText and uses which ever is supported. If neither is supported, it assumes support for basic DOM 1 methods and uses those.

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 W3C DOM-compliant browsers.

Useful references on changing an element's text using the DOM


<- Previous section: Using web standards: how

Next section: Developing Cross-browser pages ->

Document Tags and Contributors

最后编辑者: manish.jethani,