Table of contents
  1. 3 Semantics, structure, and APIs of HTML documents
    1. 3.1 Documents
      1. 3.1.1 Documents in the DOM
      2. 3.1.2 Security
      3. 3.1.3 Resource metadata management
      4. 3.1.4 DOM tree accessors
      5. 3.1.5 Creating documents
      6. 3.1.6 Loading XML documents

3 Semantics, structure, and APIs of HTML documents

3.1 Documents

Every XML and HTML document in an HTML UA is represented by a Document object. [DOMCORE]

The document's address is an absolute URL that is set when the Document is created. The document's current address is an absolute URL that can change during the lifetime of the Document, for example when the user navigates to a fragment identifier on the page or when the pushState() method is called with a new URL. The document's current address must be set to the document's address when the Document is created.

Interactive user agents typically expose the document's current address in their user interface.

When a Document is created by a script using the createDocument() or createHTMLDocument() APIs, the document's address is the same as the document's address of the script's document.

Document objects are assumed to be XML documents unless they are flagged as being HTML documents when they are created. Whether a document is an HTML document or an XML document affects the behavior of certain APIs and the case-sensitivity of some selectors.

Each Document object has a reload override flag that is originally unset. The flag is set by the document.open() and document.write() methods in certain situations. When the flag is set, the Document also has a reload override buffer which is a Unicode string that is used as the source of the document when it is reloaded.

When the user agent is to perform an overridden reload, it must act as follows:

  1. Let source be the value of the browsing context's active document's reload override buffer.

  2. Navigate the browsing context to a resource whose source is source, with replacement enabled. When the navigate algorithm creates a Document object for this purpose, set that Document's reload override flag and set its reload override buffer to source.

3.1.1 Documents in the DOM

All Document objects (in user agents implementing this specification) must also implement the HTMLDocument interface, available using binding-specific methods. (This is the case whether or not the document in question is an HTML document or indeed whether it contains any HTML elements at all.) Document objects must also implement the document-level interface of any other namespaces that the UA supports.

For example, if an HTML implementation also supports SVG, then the Document object implements both HTMLDocument and SVGDocument.

Because the HTMLDocument interface is now obtained using binding-specific casting methods instead of simply being the primary interface of the document object, it is no longer defined as inheriting from Document.

[OverrideBuiltins]
interface HTMLDocument {
  // resource metadata management
  [PutForwards=href] readonly attribute Location location;
  readonly attribute DOMString URL;
           attribute DOMString domain;
  readonly attribute DOMString referrer;
           attribute DOMString cookie;
  readonly attribute DOMString lastModified;
  readonly attribute DOMString compatMode;
           attribute DOMString charset;
  readonly attribute DOMString characterSet;
  readonly attribute DOMString defaultCharset;
  readonly attribute DOMString readyState;

  // DOM tree accessors
  getter any (in DOMString name);
           attribute DOMString title;
           attribute DOMString dir;
           attribute HTMLElement body;
  readonly attribute HTMLHeadElement head;
  readonly attribute HTMLCollection images;
  readonly attribute HTMLCollection embeds;
  readonly attribute HTMLCollection plugins;
  readonly attribute HTMLCollection links;
  readonly attribute HTMLCollection forms;
  readonly attribute HTMLCollection scripts;
  NodeList getElementsByName(in DOMString elementName);
  NodeList getElementsByClassName(in DOMString classNames);

  // dynamic markup insertion
           attribute DOMString innerHTML;
  HTMLDocument open(in optional DOMString type, in optional DOMString replace);
  WindowProxy open(in DOMString url, in DOMString name, in DOMString features, in optional boolean replace);
  void close();
  void write(in DOMString... text);
  void writeln(in DOMString... text);

  // user interaction
  readonly attribute WindowProxy defaultView;
  readonly attribute Element activeElement;
  boolean hasFocus();
           attribute DOMString designMode;
  boolean execCommand(in DOMString commandId);
  boolean execCommand(in DOMString commandId, in boolean showUI);
  boolean execCommand(in DOMString commandId, in boolean showUI, in DOMString value);
  boolean queryCommandEnabled(in DOMString commandId);
  boolean queryCommandIndeterm(in DOMString commandId);
  boolean queryCommandState(in DOMString commandId);
  boolean queryCommandSupported(in DOMString commandId);
  DOMString queryCommandValue(in DOMString commandId);
  readonly attribute HTMLCollection commands;

  // event handler IDL attributes
           attribute Function onabort;
           attribute Function onblur;
           attribute Function oncanplay;
           attribute Function oncanplaythrough;
           attribute Function onchange;
           attribute Function onclick;
           attribute Function oncontextmenu;
           attribute Function oncuechange;
           attribute Function ondblclick;
           attribute Function ondrag;
           attribute Function ondragend;
           attribute Function ondragenter;
           attribute Function ondragleave;
           attribute Function ondragover;
           attribute Function ondragstart;
           attribute Function ondrop;
           attribute Function ondurationchange;
           attribute Function onemptied;
           attribute Function onended;
           attribute Function onerror;
           attribute Function onfocus;
           attribute Function oninput;
           attribute Function oninvalid;
           attribute Function onkeydown;
           attribute Function onkeypress;
           attribute Function onkeyup;
           attribute Function onload;
           attribute Function onloadeddata;
           attribute Function onloadedmetadata;
           attribute Function onloadstart;
           attribute Function onmousedown;
           attribute Function onmousemove;
           attribute Function onmouseout;
           attribute Function onmouseover;
           attribute Function onmouseup;
           attribute Function onmousewheel;
           attribute Function onpause;
           attribute Function onplay;
           attribute Function onplaying;
           attribute Function onprogress;
           attribute Function onratechange;
           attribute Function onreadystatechange;
           attribute Function onreset;
           attribute Function onscroll;
           attribute Function onseeked;
           attribute Function onseeking;
           attribute Function onselect;
           attribute Function onshow;
           attribute Function onstalled;
           attribute Function onsubmit;
           attribute Function onsuspend;
           attribute Function ontimeupdate;
           attribute Function onvolumechange;
           attribute Function onwaiting;
};
Document implements HTMLDocument;

Since the HTMLDocument interface holds methods and attributes related to a number of disparate features, the members of this interface are described in various different sections.

3.1.2 Security

User agents must raise a SECURITY_ERR exception whenever any of the members of an HTMLDocument object are accessed by scripts whose effective script origin is not the same as the Document's effective script origin.

3.1.3 Resource metadata management

document . URL

Returns the document's address.

document . referrer

Returns the address of the Document from which the user navigated to this one, unless it was blocked or there was no such document, in which case it returns the empty string.

The noreferrer link type can be used to block the referrer.

The URL attribute must return the document's address.

The referrer attribute must return either the current address of the active document of the source browsing context at the time the navigation was started (that is, the page which navigated the browsing context to the current document), with any <fragment> component removed; or the empty string if there is no such originating page, or if the UA has been configured not to report referrers in this case, or if the navigation was initiated for a hyperlink with a noreferrer keyword.

In the case of HTTP, the referrer IDL attribute will match the Referer (sic) header that was sent when fetching the current page.

Typically user agents are configured to not report referrers in the case where the referrer uses an encrypted protocol and the current page does not (e.g. when navigating from an https: page to an http: page).


document . cookie [ = value ]

Returns the HTTP cookies that apply to the Document. If there are no cookies or cookies can't be applied to this resource, the empty string will be returned.

Can be set, to add a new cookie to the element's set of HTTP cookies.

If the contents are sandboxed into a unique origin (in an iframe with the sandbox attribute) or the resource was labeled as text/html-sandboxed, a SECURITY_ERR exception will be thrown on getting and setting.

The cookie attribute represents the cookies of the resource from which the Document was created.

A Document object that falls into one of the following conditions is a cookie-free Document object:

On getting, if the document is a cookie-free Document object, then the user agent must return the empty string. Otherwise, if the Document's origin is not a scheme/host/port tuple, the user agent must raise a SECURITY_ERR exception. Otherwise, the user agent must first obtain the storage mutex and then return the cookie-string for the document's address for a "non-HTTP" API, decoded as UTF-8, with error handling. [COOKIES]

On setting, if the document is a cookie-free Document object, then the user agent must do nothing. Otherwise, if the Document's origin is not a scheme/host/port tuple, the user agent must raise a SECURITY_ERR exception. Otherwise, the user agent must obtain the storage mutex and then act as it would when receiving a set-cookie-string for the document's address via a "non-HTTP" API, consisting of the new value encoded as UTF-8. [COOKIES] [RFC3629]

Since the cookie attribute is accessible across frames, the path restrictions on cookies are only a tool to help manage which cookies are sent to which parts of the site, and are not in any way a security feature.


document . lastModified

Returns the date of the last modification to the document, as reported by the server, in the form "MM/DD/YYYY hh:mm:ss", in the user's local time zone.

If the last modification date is not known, the current time is returned instead.

The lastModified attribute, on getting, must return the date and time of the Document's source file's last modification, in the user's local time zone, in the following format:

  1. The month component of the date.
  2. A U+002F SOLIDUS character (/).
  3. The day component of the date.
  4. A U+002F SOLIDUS character (/).
  5. The year component of the date.
  6. A U+0020 SPACE character.
  7. The hours component of the time.
  8. A U+003A COLON character (:).
  9. The minutes component of the time.
  10. A U+003A COLON character (:).
  11. The seconds component of the time.

All the numeric components above, other than the year, must be given as two digits in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9) representing the number in base ten, zero-padded if necessary. The year must be given as the shortest possible string of four or more digits in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9) representing the number in base ten, zero-padded if necessary.

The Document's source file's last modification date and time must be derived from relevant features of the networking protocols used, e.g. from the value of the HTTP Last-Modified header of the document, or from metadata in the file system for local files. If the last modification date and time are not known, the attribute must return the current date and time in the above format.


document . compatMode

In a conforming document, returns the string "CSS1Compat". (In quirks mode documents, returns the string "BackCompat", but a conforming document can never trigger quirks mode.)

A Document is always set to one of three modes: no-quirks mode, the default; quirks mode, used typically for legacy documents; and limited-quirks mode, also known as "almost standards" mode. The mode is only ever changed from the default by the HTML parser, based on the presence, absence, or value of the DOCTYPE string.

The compatMode IDL attribute must return the literal string "CSS1Compat" unless the document has been set to quirks mode by the HTML parser, in which case it must instead return the literal string "BackCompat".


document . charset [ = value ]

Returns the document's character encoding.

Can be set, to dynamically change the document's character encoding.

New values that are not IANA-registered aliases supported by the user agent are ignored.

document . characterSet

Returns the document's character encoding.

document . defaultCharset

Returns what might be the user agent's default character encoding. (The user agent might return another character encoding altogether, e.g. to protect the user's privacy, or if the user agent doesn't use a single default encoding.)

Documents have an associated character encoding. When a Document object is created, the document's character encoding must be initialized to UTF-16. Various algorithms during page loading affect this value, as does the charset setter. [IANACHARSET]

The charset IDL attribute must, on getting, return the preferred MIME name of the document's character encoding. On setting, if the new value is an IANA-registered alias for a character encoding supported by the user agent, the document's character encoding must be set to that character encoding. (Otherwise, nothing happens.)

The characterSet IDL attribute must, on getting, return the preferred MIME name of the document's character encoding.

The defaultCharset IDL attribute must, on getting, return the preferred MIME name of a character encoding, possibly the user's default encoding, or an encoding associated with the user's current geographical location, or any arbitrary encoding name.


document . readyState

Returns "loading" while the Document is loading, "interactive" once it is finished parsing but still loading sub-resources, and "complete" once it has loaded.

The readystatechange event fires on the Document object when this value changes.

Each document has a current document readiness. When a Document object is created, it must have its current document readiness set to the string "loading" if the document is associated with an HTML parser or an XML parser, or to the string "complete" otherwise. Various algorithms during page loading affect this value. When the value is set, the user agent must fire a simple event named readystatechange at the Document object.

A Document is said to have an active parser if it is associated with an HTML parser or an XML parser that has not yet been stopped or aborted.

The readyState IDL attribute must, on getting, return the current document readiness.

3.1.4 DOM tree accessors

The html element of a document is the document's root element, if there is one and it's an html element, or null otherwise.


document . head

Returns the head element.

The head element of a document is the first head element that is a child of the html element, if there is one, or null otherwise.

The head attribute, on getting, must return the head element of the document (a head element or null).


document . title [ = value ]

Returns the document's title, as given by the title element.

Can be set, to update the document's title. If there is no head element, the new value is ignored.

In SVG documents, the SVGDocument interface's title attribute takes precedence.

The title element of a document is the first title element in the document (in tree order), if there is one, or null otherwise.

The title attribute must, on getting, run the following algorithm:

  1. If the root element is an svg element in the "http://www.w3.org/2000/svg" namespace, and the user agent supports SVG, then return the value that would have been returned by the IDL attribute of the same name on the SVGDocument interface. [SVG]

  2. Otherwise, let value be a concatenation of the data of all the child text nodes of the title element, in tree order, or the empty string if the title element is null.

  3. Replace any sequence of one or more consecutive space characters in value with a single U+0020 SPACE character.

  4. Remove any leading or trailing space characters in value.

  5. Return value.

On setting, the following algorithm must be run. Mutation events must be fired as appropriate.

  1. If the root element is an svg element in the "http://www.w3.org/2000/svg" namespace, and the user agent supports SVG, then the setter must defer to the setter for the IDL attribute of the same name on the SVGDocument interface (if it is readonly, then this will raise an exception). Stop the algorithm here. [SVG]

  2. If the title element is null and the head element is null, then the attribute must do nothing. Stop the algorithm here.
  3. If the title element is null, then a new title element must be created and appended to the head element. Let element be that element. Otherwise, let element be the title element.
  4. The children of element (if any) must all be removed.
  5. A single Text node whose data is the new value being assigned must be appended to element.

The title attribute on the HTMLDocument interface should shadow the attribute of the same name on the SVGDocument interface when the user agent supports both HTML and SVG. [SVG]


document . body [ = value ]

Returns the body element.

Can be set, to replace the body element.

If the new value is not a body or frameset element, this will throw a HIERARCHY_REQUEST_ERR exception.

The body element of a document is the first child of the html element that is either a body element or a frameset element. If there is no such element, it is null. If the body element is null, then when the specification requires that events be fired at "the body element", they must instead be fired at the Document object.

The body attribute, on getting, must return the body element of the document (either a body element, a frameset element, or null). On setting, the following algorithm must be run:

  1. If the new value is not a body or frameset element, then raise a HIERARCHY_REQUEST_ERR exception and abort these steps.
  2. Otherwise, if the new value is the same as the body element, do nothing. Abort these steps.
  3. Otherwise, if the body element is not null, then replace that element with the new value in the DOM, as if the root element's replaceChild() method had been called with the new value and the incumbent body element as its two arguments respectively, then abort these steps.
  4. Otherwise, the body element is null. Append the new value to the root element.

document . images

Returns an HTMLCollection of the img elements in the Document.

document . embeds
document . plugins

Return an HTMLCollection of the embed elements in the Document.

document . links

Returns an HTMLCollection of the a and area elements in the Document that have href attributes.

document . forms

Return an HTMLCollection of the form elements in the Document.

document . scripts

Return an HTMLCollection of the script elements in the Document.

The images attribute must return an HTMLCollection rooted at the Document node, whose filter matches only img elements.

The embeds attribute must return an HTMLCollection rooted at the Document node, whose filter matches only embed elements.

The plugins attribute must return the same object as that returned by the embeds attribute.

The links attribute must return an HTMLCollection rooted at the Document node, whose filter matches only a elements with href attributes and area elements with href attributes.

The forms attribute must return an HTMLCollection rooted at the Document node, whose filter matches only form elements.

The scripts attribute must return an HTMLCollection rooted at the Document node, whose filter matches only script elements.


collection = document . getElementsByName(name)

Returns a NodeList of elements in the Document that have a name attribute with the value name.

collection = document . getElementsByClassName(classes)
collection = element . getElementsByClassName(classes)

Returns a NodeList of the elements in the object on which the method was invoked (a Document or an Element) that have all the classes given by classes.

The classes argument is interpreted as a space-separated list of classes.

The getElementsByName(name) method takes a string name, and must return a live NodeList containing all the HTML elements in that document that have a name attribute whose value is equal to the name argument (in a case-sensitive manner), in tree order. When the method is invoked on a Document object again with the same argument, the user agent may return the same as the object returned by the earlier call. In other cases, a new NodeList object must be returned.

The getElementsByClassName(classNames) method takes a string that contains a set of space-separated tokens representing classes. When called, the method must return a live NodeList object containing all the elements in the document, in tree order, that have all the classes specified in that argument, having obtained the classes by splitting a string on spaces. (Duplicates are ignored.) If there are no tokens specified in the argument, then the method must return an empty NodeList. If the document is in quirks mode, then the comparisons for the classes must be done in an ASCII case-insensitive manner, otherwise, the comparisons must be done in a case-sensitive manner. When the method is invoked on a Document object again with the same argument, the user agent may return the same object as the object returned by the earlier call. In other cases, a new NodeList object must be returned.

The getElementsByClassName(classNames) method on the HTMLElement interface must return a live NodeList with the nodes that the HTMLDocument getElementsByClassName() method would return when passed the same argument(s), excluding any elements that are not descendants of the HTMLElement object on which the method was invoked. When the method is invoked on an HTMLElement object again with the same argument, the user agent may return the same object as the object returned by the earlier call. In other cases, a new NodeList object must be returned.

HTML, SVG, and MathML elements define which classes they are in by having an attribute with no namespace with the name class containing a space-separated list of classes to which the element belongs. Other specifications may also allow elements in their namespaces to be labeled as being in specific classes.

Given the following XHTML fragment:

<div id="example">
 <p id="p1" class="aaa bbb"/>
 <p id="p2" class="aaa ccc"/>
 <p id="p3" class="bbb ccc"/>
</div>

A call to document.getElementById('example').getElementsByClassName('aaa') would return a NodeList with the two paragraphs p1 and p2 in it.

A call to getElementsByClassName('ccc bbb') would only return one node, however, namely p3. A call to document.getElementById('example').getElementsByClassName('bbb  ccc ') would return the same thing.

A call to getElementsByClassName('aaa,bbb') would return no nodes; none of the elements above are in the "aaa,bbb" class.


The HTMLDocument interface supports named properties. The supported property names at any moment consist of the values of the name content attributes of all the applet, exposed embed, form, iframe, img, and exposed object elements in the Document that have name content attributes, and the values of the id content attributes of all the applet and exposed object elements in the Document that have id content attributes, and the values of the id content attributes of all the img elements in the Document that have both name content attributes and id content attributes.

When the HTMLDocument object is indexed for property retrieval using a name name, then the user agent must return the value obtained using the following steps:

  1. Let elements be the list of named elements with the name name in the Document.

    There will be at least one such element, by definition.

  2. If elements has only one element, and that element is an iframe element, then return the WindowProxy object of the nested browsing context represented by that iframe element, and abort these steps.

  3. Otherwise, if elements has only one element, return that element and abort these steps.

  4. Otherwise return an HTMLCollection rooted at the Document node, whose filter matches only named elements with the name name.

Named elements with the name name, for the purposes of the above algorithm, are those that are either:

An embed or object element is said to be exposed if it has no exposed object ancestor, and, for object elements, is additionally either not showing its fallback content or has no object or embed descendants.


The dir attribute on the HTMLDocument interface is defined along with the dir content attribute.

3.1.5 Creating documents

XML documents can be created from script using the createDocument() method on the DOMImplementation interface.

HTML documents can be created using the createHTMLDocument() method:

[Supplemental, NoInterfaceObject]
interface DOMHTMLImplementation {
  Document createHTMLDocument(in DOMString title);
};
DOMImplementation implements DOMHTMLImplementation;
document = document . implementation . createHTMLDocument( title )

Returns a new Document, with a basic DOM already constructed with an appropriate title element.

The createHTMLDocument(title) method, when invoked, must run the following steps:

  1. Let doc be a newly created Document object.

  2. Mark doc as being an HTML document.

  3. Create a DocumentType node with the name attribute set to the string "html", and the other attributes specific to DocumentType objects set to the empty string, null, and empty lists, as appropriate. Append the newly created node to doc.

  4. Create an html element, and append it to doc.

  5. Create a head element, and append it to the html element created in the previous step.

  6. Create a title element, and append it to the head element created in the previous step.

  7. Create a Text node, and set its data attribute to the string given by the method's argument (which could be the empty string). Append it to the title element created in the previous step.

  8. Create a body element, and append it to the html element created in the earlier step.

  9. Return doc.

3.1.6 Loading XML documents

A Document object that is an XML document that was created by the DOMImplementation.createDocument() factory method must also implement the XMLDocumentLoader interface:

[Supplemental, NoInterfaceObject]
interface XMLDocumentLoader {
  boolean load(in DOMString url);
};

The load(url) method must run the following steps:

  1. Let document be the Document object on which the method was invoked.

  2. Resolve the method's first argument, relative to the entry script's base URL. If this is not successful, throw a SYNTAX_ERR exception and abort these steps. Otherwise, let url be the resulting absolute URL.

  3. If the origin of url is not the same as the origin of document, throw a SECURITY_ERR exception and abort these steps.

  4. Remove all child nodes of document, without firing any mutation events.

  5. Set the current document readiness of document to "loading".

  6. Run the remainder of these steps asynchronously, and return true from the method.

  7. Let result be an Document object.

  8. Let success be false.

  9. Fetch url from the origin of document, with the synchronous flag set and the force same-origin flag set.

  10. If the fetch attempt was successful, and the resource's Content-Type metadata is an XML MIME type, then run these substeps:

    1. Create a new XML parser associated with the result document.

    2. Pass this parser the fetched document.

    3. If there is an XML well-formedness or XML namespace well-formedness error, then remove all child nodes from result. Otherwise let success be true.

  11. Queue a task to run the following steps.

    1. Set the current document readiness of document to "complete".

    2. Replace all the children of document by the children of result (even if it has no children), firing mutation events as if a DocumentFragment containing the new children had been inserted.

    3. Fire a simple event named load at document.