15.4.1 HTML Attributes As Element Properties
The HTMLElement objects that represent the elements of an HTML document define read/write properties that mirror the HTML attributes of the elements. HTMLElement defines properties for the universal HTTP attributes such as id, title lang, and dir, and event handler properties like onclick. Element-specific subtypes define attributes specific to those elements. To query the URL of an image, for example, you can use the src property of the HTMLElement that represents the element:
var image = document.getElementById("myimage"); var imgurl = image.src; // The src attribute is the URL of the image image.id === "myimage" // Since we looked up the image by id
Similarly, you might set the form-submission attributes of aelement with code like this:
var f = document.forms; // Firstin the document f.action = "http://www.example.com/submit.php"; // Set URL to submit it to. f.method = "POST"; // HTTP request type
15.4 Attributes | 375
The properties that represent HTML attributes usually have string value. When the attribute is a boolean or numeric value (the defaultChecked and maxLength attributes of anelement, for example), the properties values are booleans or numbers instead of strings. Event handler attributes always have Function objects (or null) as their values. The HTML5 specification defines a few attributes (such as the form attribute ofand related elements) that convert element IDs to actual Element objects. Finally, the value of the style property of any HTML element is a CSSStyleDeclaration object rather than a string. We’ll see much more about this important property in Chapter 16 .
Note that this property-based API for getting and setting attribute values does not define any way to remove an attribute from an element. In particular, the delete operator cannot be used for this purpose. The section that follows describes a method that you can use to accomplish this.欢迎转载,转载请注明来自一手册:http://yishouce.com/book/1/27922.html