Приглашаем посетить
Достоевский (dostoevskiy-lit.ru)

Accessing an Element's Attributes

Accessing an Element's Attributes

Every element object exposes its attributes, style, and contents to scripting languages. This information is obtained from the underlying source code for the document. This section shows how attributes are exposed. Chapter 11, "Dynamic Styles," discusses accessing an element's style, and Chapter 13, "Dynamic Contents," discusses accessing an element's contents.

Data Types

In HTML, an attribute always takes one of the following data types: number, string, string from a predefined list, or compact value. (Compact values are values that are true or false.) The DTD (document type definition) specifies the data type for each attribute.

In the Dynamic HTML object model, each attribute is exposed as a property. Such a property has one of the following four data types:

The script in the following HTML document uses the four data types:

<HTML>
   <HEAD>
      <TITLE>Programming Attributes--Data Types</TITLE>
   </HEAD>
   <BODY>
      <INPUT TYPE=TEXT SIZE=35 ID="txt1" DISABLED>
      <H1 ALIGN="Left" ID="hd1" ONCLICK="alert(`Clicked!')">
         This is a left-aligned header.
      </H1>
      <SCRIPT LANGUAGE="JavaScript">
         alert(document.all.txt1.disabled); // Boolean true
         alert(document.all.hd1.align);     // String left
         alert(document.all.txt1.size);     // 32-bit integer 35
         alert(document.all.hd1.onclick);   // Function pointer
      </SCRIPT>
   </BODY>
</HTML>

A property is exposed for every defined attribute in HTML, even if the attribute is not explicitly defined in the document. For example, the Input element in the preceding code does not have the VALUE attribute specified, but in the object model all Input elements always expose the value property. The value of a property corresponding to an unspecified attribute depends on its data type. String properties contain empty strings; number properties contain the default values for the corresponding attributes; compact properties contain false; and function pointers contain null.

An event attribute contains code that executes as the result of a specified action. When the code string is parsed, a function object is created. Rather than expose the string defining the function, a property representing such an event contains a pointer to the function.

If you try to assign a value of one data type to a property of another, the results will vary depending on the scripting language. Either the value will be coerced into the property's data type or an error will occur. For example, if you assign a number to a string property in JavaScript, the interpreter will translate the number into its string representation before making the assignment. If the language supports explicit casting from one type to another, you should explicitly cast values to ensure predictable results. The parseInt function in JavaScript, for example, changes a string representation of a number into an actual number:

document.myText.size = parseInt("100");  // 100

Naming Conventions

While HTML allows attributes to be defined insensitive of case, JavaScript is case sensitive. To simplify programming with case-sensitive languages, the object model defines all properties using a consistent naming convention, which allows you to determine the property name for any existing attribute without having to look it up in a reference.

Following this naming convention, all properties—not just properties representing attributes—have names beginning in lowercase; each appended keyword begins with a capital letter—for example, tagName. Because most attributes consist of a single keyword, the corresponding properties are generally all lowercase.

For each attribute, the corresponding property has the same name as the attribute, except in two cases: the className property represents the CLASS attribute, and the htmlFor property represents the FOR attribute (used with Label and Script elements). These exceptions are necessary because for and class are reserved words in many programming languages.

Access to Original Values

Because HTML is text based, there are times when an attribute might contain a value that is not compatible with the data type of the exposed property. For example, the SIZE attribute represents the integer size of a text box. However, if the HTML source contains a string rather than a number, the size property still returns the default size because the data type for the value is predetermined. The Dynamic HTML object model is designed to ensure that even invalid attributes and values are accessible to scripts. All elements expose the following methods to provide access to the untouched value from the original document.

The getAttribute method takes the property name as a string and returns the value as it appears in the source code. If the source file sets the SIZE attribute to the string big, for example, the size property returns the default size 20. But getAttribute("size") returns the string big because the getAttribute method always returns the untouched value from the source code.

The setAttribute method lets the developer control the reverse operation, whereby a string can be inserted into the HTML stream, even if the property value is a number. For example, setAttribute("size","small") puts the string value small into the SIZE attribute. The size property on the element still returns 20.

The removeAttribute method is used to remove an attribute from the object.

The three attribute methods expose an options parameter that controls how the lookup is performed. Currently, the parameter controls only case sensitivity. With the default options value of false, the lookup is case insensitive. With an options value of true, the lookup is case sensitive, using the internal capitalization of the attribute for known attributes and the capitalization defined in the source code for unrecognized attributes.

In general, case-sensitive lookups are not necessary and the attribute methods can be invoked without the optional flag. For multiple properties that are capitalized differently, the property that is returned is the first match found in the properties list. The main purpose of the options parameter is to locate a property when the same property name exists multiple times with different capitalizations.


NOTE: While the designers of the object model were careful to avoid collisions between common reserved words, there may be cases in which an existing attribute collides with a reserved word in the programming language. If this occurs, the three attribute methods can be used to access any property value on the element instead of accessing the attribute directly using the exposed property.

Enumerated Data Types

Many other object models expose value lists as enumerated data types. Usually, the enumerated data type is an integer or other number and a variety of constants are defined to represent its allowed values. To ensure language neutrality, integer-based enumeration is not used in the Dynamic HTML object model. Instead, all value lists are exposed as string values. For example, the ALIGN attribute stores a string that is supposed to be one of the three string values: left, right, and center.

An attribute can be assigned a string capitalized in any manner, and it will be properly evaluated. For example, the ALIGN attribute in HTML or the corresponding align property can be assigned the value left or LeFT, or any other combination of uppercase and lowercase. However, when you retrieve the value, it is always returned all lowercase.

Enumerated string values are converted to lowercase at parse time or assignment time; the original case of these values is not accessible. The getAttribute, setAttribute, and removeAttribute methods will not respect the original capitalization of the enumerated strings and will return them lowercased.

Unrecognized Attributes

Chapter 7, "Document Element Collections," demonstrated how unrecognized elements are handled in the object model. Dynamic HTML also accurately represents unrecognized attributes on any element. The attribute methods provide access to attributes specified in the document that are not recognized by Microsoft Internet Explorer 4.0. Using these methods, unrecognized attributes can be added and removed from any element. With JavaScript, this access is taken one step further—all unrecognized attributes are also exposed as properties of the element, as shown here:

<H1 ID=myH1 badAttribute=Test>

JavaScript can access a property named badAttribute on this H1 object. This property is accessed in the same manner as any other property on the element:

alert(document.all.myH1.badAttribute)                 // Test
alert(document.all.myH1.getAttribute("badAttribute")) // Test

Unrecognized attributes are exposed as properties with the same capitalization they have in the original document. For recognized attributes, the capitalization of the attribute in the document has no relation to its capitalization in the object model. To perform case-insensitive lookups, the attribute methods should be used. In general, these methods should be used instead of accessing unrecognized attributes directly. This technique also eliminates the potential for problems caused by typographical errors in the capitalization of attribute names. In the section "Customizing Existing Elements" later in this chapter, techniques are demonstrated for intelligently using unrecognized attributes.

[Содержание]