Anda di halaman 1dari 1039

HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

TABLE OF CONTENTS
1
Introduction

2
Common infrastructure 2.4 2.5 2.6 2.7
Common microsyntaxes
URLs
Common DOM interfaces
Namespaces

3
Semantics, structure, and APIs of HTML documents 3.2
Elements

4
The elements of HTML 4.3 4.4 4.5 4.7
Sections
Grouping content
Text-level semantics
Embedded content

4.6
Edits 4.8
Links 4.9
Tabular data 4.10
Forms 4.11
Interactive elements 4.12
Scripting 4.13
Common idioms without dedicated elements 4.14
Disabled elements 5
Microdata

6
Loading Web pages 6.3 6.5
Origin
Session history and navigation 6.4
Sandboxing

http://developers.whatwg.org/[4/16/2014 9:27:07 PM]

HTML: The Living Standard - Edition for Web Developers

6.6
Browsing the Web 6.7 7
Offline Web applications

Web application APIs 7.4 7.5 7.6 7.7


Timers
User prompts
System state and capabilities
Images

8
User interaction 8.7
Drag and drop

9
Communication 10
Conformance requirements 11
Terminology 12
Conformance requirements 13
Terminology 14
Web workers 15
Conformance requirements 16
Terminology 17
The HTML syntax 17.2
Named character references 18
The XHTML syntax 19
Obsolete features 20
IANA considerations Index References Acknowledgments

About this specification


This specification is like no other It has been processed with you, the humble web developer, in mind.

http://developers.whatwg.org/[4/16/2014 9:27:07 PM]

HTML: The Living Standard - Edition for Web Developers

The focus of this specification is readability and ease of access. Unlike the full HTML specification, this "web developer edition" removes information that only browser vendors need know. To read about its conception, construction and future, read the press release. Ben Schwarz

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/[4/16/2014 9:27:07 PM]

1 Introduction HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
Introduction
Is this HTML5?
Background
Audience
Scope
History
Design notes
Serializability of script execution
Compliance with other specifications
Extensibility
HTML vs XHTML
Structure of this specification
How to read this specification
Typographic conventions
Privacy concerns
A quick introduction to HTML
Writing secure applications with HTML
Common pitfalls to avoid when using the scripting APIs
Conformance requirements for authors
Presentational markup
Syntax errors
Restrictions on content models and on attribute values
Suggested reading

INTRODUCTION

http://developers.whatwg.org/introduction.html[4/16/2014 9:27:13 PM]

1 Introduction HTML: The Living Standard - Edition for Web Developers

Is this HTML5?
In short: Yes. In more length: The term "HTML5" is widely used as a buzzword to
refer to modern Web technologies, many of which (though by no means
all) are developed at the WHATWG, in some cases in conjunction with
the W3C and IETF. The WHATWG work is all published in one specification
parts of which are republished in an edition optimized for Web developers
(which you are reading right now). The W3C also publishes parts of this specification as separate
documents. One of these parts is called "HTML5"; it is a forked subset of
the HTML Living Standard.
There are numerous differences between the HTML Living Standard
and the W3C version, some minor, some major. Unfortunately these are not currently accurately
documented anywhere, so there is no way to know which are intentional and which are not.

Background
The World Wide Web's markup language has always been HTML. HTML was primarily designed as a
language for semantically describing scientific documents, although its general design and
adaptations over the years have enabled it to be used to describe a number of other types of
documents. The main area that has not been adequately addressed by HTML is a vague subject referred to as
Web Applications. This specification attempts to rectify this, while at the same time updating the
HTML specifications to address issues raised in the past few years.

Audience
This specification is intended for authors of documents and scripts that use the features
defined in this specification. This document is probably not suited to readers who do not already have at least a passing
familiarity with Web technologies, as in places it sacrifices

http://developers.whatwg.org/introduction.html[4/16/2014 9:27:13 PM]

1 Introduction HTML: The Living Standard - Edition for Web Developers

clarity for precision, and brevity


for completeness. More approachable tutorials and authoring guides can provide a gentler
introduction to the topic. In particular, familiarity with the basics of DOM is necessary for a complete understanding of
some of the more technical parts of this specification. An understanding of Web IDL, HTTP, XML,
Unicode, character encodings, JavaScript, and CSS will also be helpful in places but is not
essential.

Scope
This specification is limited to providing a semantic-level markup language and associated
semantic-level scripting APIs for authoring accessible pages on the Web ranging from static
documents to dynamic applications. The scope of this specification does not include providing mechanisms for media-specific
customization of presentation (although default rendering rules for Web browsers are included at
the end of this specification, and several mechanisms for hooking into CSS are provided as part of
the language). The scope of this specification is not to describe an entire operating system. In particular,
hardware configuration software, image manipulation tools, and applications that users would be
expected to use with high-end workstations on a daily basis are out of scope. In terms of
applications, this specification is targeted specifically at applications that would be expected
to be used by users on an occasional basis, or regularly but from disparate locations, with low
CPU requirements. Examples of such applications include online purchasing systems, searching
systems, games (especially multiplayer online games), public telephone books or address books,
communications software (e-mail clients, instant messaging clients, discussion software), document editing software, etc.

History
For its first five years (1990-1995), HTML went through a number of revisions and experienced a
number of extensions, primarily hosted first at CERN, and then at the IETF. With the creation of the W3C, HTML's development changed venue again. A

http://developers.whatwg.org/introduction.html[4/16/2014 9:27:13 PM]

1 Introduction HTML: The Living Standard - Edition for Web Developers

first abortive attempt


at extending HTML in 1995 known as HTML 3.0 then made way to a more pragmatic approach known as
HTML 3.2, which was completed in 1997. HTML4 quickly followed later that same year. The following year, the W3C membership decided to stop evolving HTML and instead begin work on
an XML-based equivalent, called XHTML. This
effort started with a reformulation of HTML4 in XML, known as XHTML 1.0, which added no new
features except the new serialization, and which was completed in 2000. After XHTML 1.0, the W3C's
focus turned to making it easier for other working groups to extend XHTML, under the banner of
XHTML Modularization. In parallel with this, the W3C also worked on a new language that was not
compatible with the earlier HTML and XHTML languages, calling it XHTML2. Around the time that HTML's evolution was stopped in 1998, parts of the API for HTML developed
by browser vendors were specified and published under the name DOM Level 1 (in 1998) and DOM Level
2 Core and DOM Level 2 HTML (starting in 2000 and culminating in 2003). These efforts then petered
out, with some DOM Level 3 specifications published in 2004 but the working group being closed
before all the Level 3 drafts were completed. In 2003, the publication of XForms, a technology which was positioned as the next generation of
Web forms, sparked a renewed interest in evolving HTML itself, rather than finding replacements
for it. This interest was borne from the realization that XML's deployment as a Web technology was
limited to entirely new technologies (like RSS and later Atom), rather than as a replacement for
existing deployed technologies (like HTML). A proof of concept to show that it was possible to extend HTML4's forms to provide many of the
features that XForms 1.0 introduced, without requiring browsers to implement rendering engines
that were incompatible with existing HTML Web pages, was the first result of this renewed
interest. At this early stage, while the draft was already publicly available, and input was already being solicited from all sources, the specification was only under Opera Software's
copyright. The idea that HTML's evolution should be reopened was tested at a W3C workshop in 2004, where
some of the principles that underlie the HTML5 work (described below), as well as the
aforementioned early draft proposal covering just forms-related features, were presented to the
W3C jointly by Mozilla and Opera. The proposal was rejected on the grounds that the proposal
conflicted with the previously chosen direction for the Web's

http://developers.whatwg.org/introduction.html[4/16/2014 9:27:13 PM]

1 Introduction HTML: The Living Standard - Edition for Web Developers

evolution; the W3C staff and


membership voted to continue developing XMLbased replacements instead. Shortly thereafter, Apple, Mozilla, and Opera jointly announced their intent to continue
working on the effort under the umbrella of a new venue called the WHATWG. A public mailing list
was created, and the draft was moved to the WHATWG site. The copyright was subsequently amended to
be jointly owned by all three vendors, and to allow reuse of the specification. The WHATWG was based on several core principles, in particular that technologies need to be
backwards compatible, that specifications and implementations need to match even if this means
changing the specification rather than the implementations, and that specifications need to be
detailed enough that implementations can achieve complete interoperability without reverse-engineering each other. The latter requirement in particular required that the scope of the HTML5 specification include
what had previously been specified in three separate documents: HTML4, XHTML1, and DOM2 HTML. It
also meant including significantly more detail than had previously been considered the norm. In 2006, the W3C indicated an interest to participate in the development of HTML5 after all,
and in 2007 formed a working group chartered to work with the WHATWG on the development of the
HTML5 specification. Apple, Mozilla, and Opera allowed the W3C to publish the specification under
the W3C copyright, while keeping a version with the less restrictive license on the WHATWG
site. For a number of years, both groups then worked together. In 2011, however, the groups came to
the conclusion that they had different goals: the W3C wanted to publish a "finished" version of
"HTML5", while the WHATWG wanted to continue working on a Living Standard for HTML, continuously maintaining the specification rather than freezing it in a state with known problems, and adding
new features as needed to evolve the platform. Since then, the WHATWG has been working on this specification (amongst others), and the W3C has
been copying fixes made by the WHATWG into their fork of the document, as well as making other
changes, some intentional and some not, with no documentation listing or explaining the
differences.

Design notes
http://developers.whatwg.org/introduction.html[4/16/2014 9:27:13 PM]

1 Introduction HTML: The Living Standard - Edition for Web Developers

It must be admitted that many aspects of HTML appear at first glance to be nonsensical and
inconsistent. HTML, its supporting DOM APIs, as well as many of its supporting technologies, have been
developed over a period of several decades by a wide array of people with different priorities
who, in many cases, did not know of each other's existence. Features have thus arisen from many sources, and have not always been designed in especially
consistent ways. Furthermore, because of the unique characteristics of the Web, implementation
bugs have often become de-facto, and now de-jure, standards, as content is often unintentionally
written in ways that rely on them before they can be fixed. Despite all this, efforts have been made to adhere to certain design goals. These are described
in the next few subsections.

Serializability of script execution


To avoid exposing Web authors to the complexities of multithreading, the HTML and DOM APIs are
designed such that no script can ever detect the simultaneous execution of other scripts. Even
with workers, the intent is that the behavior of implementations can
be thought of as completely serializing the execution of all scripts in all browsing contexts. The navigator.yieldForStorageUpdates() method, in
this model, is equivalent to allowing other scripts to run while the calling script is
blocked.

Compliance with other specifications


This specification interacts with and relies on a wide variety of other specifications. In
certain circumstances, unfortunately, conflicting needs have led to this specification violating
the requirements of these other specifications. Whenever this has occurred, the transgressions
have each been noted as a "willful violation", and the reason for the violation has
been noted.

Extensibility

http://developers.whatwg.org/introduction.html[4/16/2014 9:27:13 PM]

1 Introduction HTML: The Living Standard - Edition for Web Developers

HTML has a wide number of extensibility mechanisms that can be used for adding semantics in a
safe manner:

Authors can use the class attribute to extend elements,


effectively creating
their own elements, while using the most applicable existing "real" HTML element, so that browsers and other tools that don't know of the extension can still support it
somewhat well. This is the tack used by microformats, for example.

Authors can include data for inline client-side scripts or server-side site-wide
scripts to
process using the data-*="" attributes. These are guaranteed to never be touched by browsers, and allow scripts to include data on HTML elements that scripts can
then look for and process.

Authors can use the <meta


metadata names.

name="" content=""> mechanism to


include

page-wide metadata by registering extensions to the


predefined set of

Authors can use the rel="" mechanism to annotate


links with specific
meanings by registering extensions to
the predefined set of link types. This is also used by microformats.

Authors can embed raw data using the <script


how Flash works.

type="">
mechanism with a

custom type, for further handling by inline or server-side scripts.

Authors can create plugins and invoke them using the


embed element. This is Authors can extend APIs using the JavaScript prototyping mechanism. This is
widely used by
script libraries, for instance.

Authors can use the microdata feature (the itemscope=""


and itemprop=""
attributes) to embed nested name-value pairs
of data to be shared with other applications and sites.

HTML vs XHTML
This specification defines an abstract language for describing documents and applications, and
some APIs for interacting with in-memory representations of resources that use this language. The in-memory representation is known as "DOM HTML", or "the DOM" for short. There are various concrete syntaxes that can be used to transmit resources that use this
abstract language, two of which are defined in this specification.

http://developers.whatwg.org/introduction.html[4/16/2014 9:27:13 PM]

1 Introduction HTML: The Living Standard - Edition for Web Developers

The first such concrete syntax is the HTML syntax. This is the format suggested for most
authors. It is compatible with most legacy Web browsers. If a document is transmitted with the
text/html MIME type, then it will be processed as an HTML document by
Web browsers. This specification defines the latest HTML syntax, known simply as "HTML". The second concrete syntax is the XHTML syntax, which is an application of XML. When a document
is transmitted with an XML MIME type, such as application/xhtml+xml ,
then it is treated as an XML document by Web browsers, to be parsed by an XML processor. Authors
are reminded that the processing for XML and HTML differs; in particular, even minor syntax errors
will prevent a document labeled as XML from being rendered fully, whereas they would be ignored in
the HTML syntax. This specification defines the latest XHTML syntax, known simply as "XHTML". The DOM, the HTML syntax, and the XHTML syntax cannot all represent the same content. For
example, namespaces cannot be represented using the HTML syntax, but they are supported in the DOM
and in the XHTML syntax. Similarly, documents that use the noscript feature can be
represented using the HTML syntax, but cannot be represented with the DOM or in the XHTML syntax.
Comments that contain the string "-->" can only be represented in the
DOM, not in the HTML and XHTML syntaxes.

Structure of this specification


This specification is divided into the following major sections: Introduction Non-normative materials providing a context for the HTML standard. Common infrastructure The conformance classes, algorithms, definitions, and the common underpinnings of the rest of
the specification. Semantics, structure, and APIs of HTML documents Documents are built from elements. These elements form a tree using the DOM. This section
defines the features of this DOM, as well as introducing the features common to all elements, and
the concepts used in defining elements. The elements of HTML

http://developers.whatwg.org/introduction.html[4/16/2014 9:27:13 PM]

1 Introduction HTML: The Living Standard - Edition for Web Developers

Each element has a predefined meaning, which is explained in this section. Rules for authors
on how to use the element are also given. This includes large signature features of HTML such
as video playback and subtitles, form controls and form submission, and a 2D graphics API known
as the HTML canvas. Microdata This specification introduces a mechanism for adding machine-readable annotations to
documents, so that tools can extract trees of name-value pairs from the document. This section
describes this mechanism. This section also defines some sample Microdata vocabularies
for contact information, calendar events, and licensing works. Loading Web pages HTML documents do not exist in a vacuum this section defines many of the features
that affect environments that deal with multiple pages, such as Web browsers and offline
caching of Web applications. Web application APIs This section introduces basic features for scripting of applications in HTML. User interaction HTML documents can provide a number of mechanisms for users to interact with and modify
content, which are described in this section, such as how focus works, and drag-and-drop. Web workers This section defines an API for background threads in JavaScript. The communication APIs This section describes some mechanisms that applications written in HTML can use to
communicate with other applications from different domains running on the same client. It also
introduces a server-push event stream mechanism known as Server Sent Events or
EventSource, and a two-way full-duplex socket protocol for scripts known as Web
Sockets. Web storage This section defines a client-side storage mechanism based on name-value pairs. The HTML syntax The XHTML syntax All of these features would be for naught if they couldn't be represented in a serialized
form and sent to other people, and so these sections define the syntaxes of HTML and XHTML. Rendering
http://developers.whatwg.org/introduction.html[4/16/2014 9:27:13 PM]

1 Introduction HTML: The Living Standard - Edition for Web Developers

This section defines the default rendering rules for Web browsers. There are also some appendices, listing obsolete features and IANA considerations, and several indices.

How to read this specification


This specification should be read like all other specifications. First, it should be read
cover-to-cover, multiple times. Then, it should be read backwards at least once. Then it should be
read by picking random sections from the contents list and following all the cross-references. As described in the conformance requirements section below, this specification describes
conformance criteria for a variety of conformance classes. In particular, there are conformance
requirements that apply to producers, for example authors and the documents they create,
and there are conformance requirements that apply to consumers, for example Web browsers.
They can be distinguished by what they are requiring: a requirement on a producer states what is
allowed, while a requirement on a consumer states how software is to act. For example, "the foo attribute's value must be a valid
integer" is a requirement on producers, as it lays out the allowed values; in contrast,
the requirement "the foo attribute's value must be parsed using the
rules for parsing integers" is a requirement on consumers, as it describes how to process the content. Requirements on producers have no bearing whatsoever on consumers. Continuing the above example, a requirement stating that a particular attribute's value is
constrained to being a valid integer emphatically does not imply anything
about the requirements on consumers. It might be that the consumers are in fact required to treat
the attribute as an opaque string, completely unaffected by whether the value conforms to the
requirements or not. It might be (as in the previous example) that the consumers are required to
parse the value using specific rules that define how invalid (non-numeric in this case) values
are to be processed.

http://developers.whatwg.org/introduction.html[4/16/2014 9:27:13 PM]

1 Introduction HTML: The Living Standard - Edition for Web Developers

Typographic conventions
This is a definition, requirement, or explanation. This is a note. This is an example. This is an open issue. This is a warning.

variable = object . method ( [ optionalArgument ] ) This is a note to authors describing the usage of an interface. CSS: /* this is a CSS fragment */ The defining instance of a term is marked up like this. Uses of that
term are marked up like this or like this. The defining instance of an element, attribute, or API is marked up like this. References to that element, attribute, or API are marked
up like this. Other code fragments are marked up like this . Variables are marked up like this. In an algorithm, steps in synchronous sections are
marked with .

In some cases, requirements are given in the form of lists with conditions and corresponding
requirements. In such cases, the requirements that apply to a condition are always the first set
of requirements that follow the condition, even in the case of there being multiple sets of
conditions for those requirements. Such cases are presented as follows: This is a condition This is another condition This is the requirement that applies to the conditions above. This is a third condition This is the requirement that applies to the third condition.

http://developers.whatwg.org/introduction.html[4/16/2014 9:27:13 PM]

1 Introduction HTML: The Living Standard - Edition for Web Developers

Privacy concerns
Some features of HTML trade user convenience for a measure of user privacy. In general, due to the Internet's architecture, a user can be distinguished from another by the
user's IP address. IP addresses do not perfectly match to a user; as a user moves from device to
device, or from network to network, their IP address will change; similarly, NAT routing, proxy
servers, and shared computers enable packets that appear to all come from a single IP address to actually map to multiple users. Technologies such as onion routing can be used to further
anonymize requests so that requests from a single user at one node on the Internet appear to come
from many disparate parts of the network. However, the IP address used for a user's requests is not the only mechanism by which a user's
requests could be related to each other. Cookies, for example, are designed specifically to enable
this, and are the basis of most of the Web's session features that enable you to log into a site
with which you have an account. There are other mechanisms that are more subtle. Certain characteristics of a user's system can
be used to distinguish groups of users from each other; by collecting enough such information, an
individual user's browser's "digital fingerprint" can be computed, which can be as good, if not
better, as an IP address in ascertaining which requests are from the same user. Grouping requests in this manner, especially across multiple sites, can be used for both benign
(and even arguably positive) purposes, as well as for malevolent purposes. An example of a
reasonably benign purpose would be determining whether a particular person seems to prefer sites
with dog illustrations as opposed to sites with cat illustrations (based on how often they visit
the sites in question) and then automatically using the preferred illustrations on subsequent
visits to participating sites. Malevolent purposes, however, could include governments combining
information such as the person's home address (determined from the addresses they use when getting
driving directions on one site) with their apparent political affiliations (determined by
examining the forum sites that they participate in) to determine whether the person should be
prevented from voting in an election. Since the malevolent purposes can be remarkably evil, user agent

http://developers.whatwg.org/introduction.html[4/16/2014 9:27:13 PM]

1 Introduction HTML: The Living Standard - Edition for Web Developers

implementors are encouraged to


consider how to provide their users with tools to minimize leaking information that could be used
to fingerprint a user. Unfortunately, as the first paragraph in this section implies, sometimes there is great benefit
to be derived from exposing the very information that can also be used for fingerprinting
purposes, so it's not as easy as simply blocking all possible leaks. For instance, the ability to
log into a site to post under a specific identity requires that the user's requests be
identifiable as all being from the same user, more or less by definition. More subtly, though, information such as how wide text is, which is necessary for many effects that involve drawing
text onto a canvas (e.g. any effect that involves drawing a border around the text) also leaks
information that can be used to group a user's requests. (In this case, by potentially exposing,
via a brute force search, which fonts a user has installed, information which can vary
considerably from user to user.) Features in this specification which can be used to
fingerprint the user are

marked as this paragraph is.


Other features in the platform can be used for the same purpose, though, including, though not
limited to:

The exact list of which features a user agents supports. The maximum allowed stack depth for recursion in script. Features that describe the user's environment, like Media Queries and the
Screen
object.

The user's time zone.

A quick introduction to HTML


A basic HTML document looks like this: <!DOCTYPE html> <html> <head> <title>Sample page</title> </head> <body> <h1>Sample page</h1>
http://developers.whatwg.org/introduction.html[4/16/2014 9:27:13 PM]

1 Introduction HTML: The Living Standard - Edition for Web Developers

<p>This is a <a href="demo.html">simple</a> sample.</p> <!-- this is a comment --> </body> </html> HTML documents consist of a tree of elements and text. Each element is denoted in the source by
a start tag, such as "<body>", and
an end tag, such as "</body>".
(Certain start tags and end tags can in certain cases be omitted and are implied by other tags.) Tags have to be nested such that elements are all completely within each other, without
overlapping: <p>This is <em>very <strong>wrong</em>!</strong></p> <p>This <em>is <strong>correct</strong>.</em></p> This specification defines a set of elements that can be used in HTML, along with rules about
the ways in which the elements can be nested. Elements can have attributes, which control how the elements work. In the example below, there
is a hyperlink, formed using the a element and its href attribute: <a href="demo.html">simple</a> Attributes are placed inside the start tag, and consist
of a name and a value, separated by an "= " character.
The attribute value can remain unquoted if it doesn't contain space characters or any of " ' ` = < or
>. Otherwise, it has to be quoted using either single or double quotes.
The value, along with the " =" character, can be omitted altogether if the
value is the empty string. <!-- empty attributes --> <input name=address disabled> <input name=address disabled=""> <!-- attributes with a value --> <input name=address maxlength=200> <input name=address maxlength='200'> <input name=address maxlength="200"> HTML user agents (e.g. Web browsers) then parse this markup, turning it into

http://developers.whatwg.org/introduction.html[4/16/2014 9:27:13 PM]

1 Introduction HTML: The Living Standard - Edition for Web Developers

a DOM
(Document Object Model) tree. A DOM tree is an in-memory representation of a document. DOM trees contain several kinds of nodes, in particular a DocumentType node,
Element nodes, Text nodes, Comment nodes, and in some cases ProcessingInstruction nodes. The markup snippet at the top of this section would be
turned into the following DOM tree: DOCTYPE: html html head #text : title #text : Sample page #text : #text : body #text : h1 #text : Sample page #text : p #text : This is a a href="demo.html " #text : simple #text : sample. #text : #text : &blank;&blank; &blank; #comment: this is a comment &blank;&blank; &blank;&blank; &blank; &blank; &blank;&blank;

The root element of this tree is the html element, which is the
element always found at the root of HTML documents. It contains two elements, head
and body, as well as a Text node between them. There are many more Text nodes in the DOM tree than one would initially expect,
because the source contains a number of spaces (represented here by "&blank;") and line breaks
(" ") that all end up as Text nodes in the DOM. However, for historical
reasons not all of the spaces and line breaks in the original markup appear in the DOM. In
particular, all the whitespace before

http://developers.whatwg.org/introduction.html[4/16/2014 9:27:13 PM]

1 Introduction HTML: The Living Standard - Edition for Web Developers

head start tag ends up being dropped silently,


and all the whitespace after the body end tag ends up placed at the end of the
body. The head element contains a title element, which itself contains a
Text node with the text "Sample page". Similarly, the body element
contains an h1 element, a p element, and a comment. This DOM tree can be manipulated from scripts in the page. Scripts (typically in JavaScript)
are small programs that can be embedded using the script element or using event
handler content attributes. For example, here is a form with a script that sets the value
of the form's output element to say "Hello World": <form name="main"> Result: <output name="result"></output> <script> document.forms.main.elements.result.value = 'Hello World'; </script> </form> Each element in the DOM tree is represented by an object, and these objects have APIs so that
they can be manipulated. For instance, a link (e.g. the a element in the tree above)
can have its "href" attribute changed in several ways: var a = document.links[0]; // obtain the first link in the document a.href = 'sample.html'; // change the destination URL of the link a.protocol = 'https'; // change just the scheme part of the URL a.setAttribute('href', 'http://example.com/'); // change the content attribute directly Since DOM trees are used as the way to represent HTML documents when they are processed and
presented by implementations (especially interactive implementations like Web browsers), this
specification is mostly phrased in terms of DOM trees, instead of the markup described above. HTML documents represent a media-independent description of interactive content. HTML documents
might be rendered to a screen, or through a speech synthesizer, or on a braille display. To
influence exactly how such

http://developers.whatwg.org/introduction.html[4/16/2014 9:27:13 PM]

1 Introduction HTML: The Living Standard - Edition for Web Developers

rendering takes place, authors can use a styling language such as


CSS. In the following example, the page has been made yellow-on-blue using CSS. <!DOCTYPE html> <html> <head> <title>Sample styled page</title> <style> body { background: navy; color: yellow; } </style> </head> <body> <h1>Sample styled page</h1> <p>This page is just a demo.</p> </body> </html> For more details on how to use HTML, authors are encouraged to consult tutorials and guides.
Some of the examples included in this specification might also be of use, but the novice author is
cautioned that this specification, by necessity, defines the language with a level of detail that
might be difficult to understand at first.

Writing secure applications with HTML


When HTML is used to create interactive sites, care needs to be taken to avoid introducing
vulnerabilities through which attackers can compromise the integrity of the site itself or of the
site's users. A comprehensive study of this matter is beyond the scope of this document, and authors are
strongly encouraged to study the matter in more detail. However, this section attempts to provide
a quick introduction to some common pitfalls in HTML application development. The security model of the Web is based on the concept of "origins", and correspondingly many of
the potential attacks on the Web involve crossorigin actions. Not validating user input Cross-site scripting (XSS)
http://developers.whatwg.org/introduction.html[4/16/2014 9:27:13 PM]

1 Introduction HTML: The Living Standard - Edition for Web Developers

SQL injection When accepting untrusted input, e.g. user-generated content such as text comments, values in
URL parameters, messages from third-party sites, etc, it is imperative that the data be
validated before use, and properly escaped when displayed. Failing to do this can allow a
hostile user to perform a variety of attacks, ranging from the potentially benign, such as
providing bogus user information like a negative age, to the serious, such as running scripts
every time a user looks at a page that includes the information, potentially propagating the
attack in the process, to the catastrophic, such as deleting all data in the server. When writing filters to validate user input, it is imperative that filters always be
whitelist-based, allowing known-safe constructs and disallowing all other input. Blacklist-based
filters that disallow known-bad inputs and allow everything else are not secure, as not
everything that is bad is yet known (for example, because it might be invented in the
future). For example, suppose a page looked at its URL's query string to determine what to display,
and the site then redirected the user to that page to display a message, as in: <ul> <li><a href="message.cgi?say=Hello">Say Hello</a> <li><a href="message.cgi?say=Welcome">Say Welcome</a> <li><a href="message.cgi?say=Kittens">Say Kittens</a> </ul> If the message was just displayed to the user without escaping, a hostile attacker could
then craft a URL that contained a script element: http://example.com/message.cgi? say=%3Cscript%3Ealert%28%27Oh%20no%21%27%29%3C/script%3E If the attacker then convinced a victim user to visit this page, a script of the attacker's
choosing would run on the page. Such a script could do any number of hostile actions, limited
only by what the site offers: if the site is an e-commerce shop, for instance, such a script
could cause the user to unknowingly make arbitrarily many unwanted purchases. This is called a cross-site scripting attack. There are many constructs that can be used to try to trick a site into executing

http://developers.whatwg.org/introduction.html[4/16/2014 9:27:13 PM]

1 Introduction HTML: The Living Standard - Edition for Web Developers

code. Here
are some that authors are encouraged to consider when writing whitelist filters:

When allowing harmless-seeming elements like img, it is important to


whitelist
any provided attributes as well. If one allowed all attributes then an attacker could, for
instance, use the onload attribute to run arbitrary
script.

When allowing URLs to be provided (e.g. for links), the scheme of each URL
also needs to be
explicitly whitelisted, as there are many schemes that can be abused. The most prominent
example is "javascript:", but user agents can implement (and indeed, have historically implemented) others.

Allowing a base element to be inserted means any script elements


in the
page with relative links can be hijacked, and similarly that any form submissions can
get redirected to a hostile site. Cross-site request forgery (CSRF) If a site allows a user to make form submissions with user-specific side-effects, for example
posting messages on a forum under the user's name, making purchases, or applying for a passport,
it is important to verify that the request was made by the user intentionally, rather than by
another site tricking the user into making the request unknowingly. This problem exists because HTML forms can be submitted to other origins. Sites can prevent such attacks by populating forms with user-specific hidden tokens, or by
checking Origin headers on all requests. Clickjacking A page that provides users with an interface to perform actions that the user might not wish
to perform needs to be designed so as to avoid the possibility that users can be tricked into
activating the interface. One way that a user could be so tricked is if a hostile site places the victim site in a
small iframe and then convinces the user to click, for instance by having the user
play a reaction game. Once the user is playing the game, the hostile site can quickly position
the iframe under the mouse cursor just as the user is about to click, thus tricking the user
into clicking the victim site's interface. To avoid this, sites that do not expect to be used in frames are encouraged to only enable
their interface if they detect that they are not in a frame (e.g. by comparing the window object to the value of the top
attribute).

http://developers.whatwg.org/introduction.html[4/16/2014 9:27:13 PM]

1 Introduction HTML: The Living Standard - Edition for Web Developers

Common pitfalls to avoid when using the scripting APIs


Scripts in HTML have "run-to-completion" semantics, meaning that the browser will generally run
the script uninterrupted before doing anything else, such as firing further events or continuing
to parse the document. On the other hand, parsing of HTML files happens asynchronously and incrementally, meaning that
the parser can pause at any point to let scripts run. This is generally a good thing, but it does
mean that authors need to be careful to avoid hooking event handlers after the events could have
possibly fired. There are two techniques for doing this reliably: use event handler content attributes, or create the element and add the event handlers in the same script. The latter
is safe because, as mentioned earlier, scripts are run to completion before further events can
fire. One way this could manifest itself is with img elements and the load event. The event could fire as soon as the element has been
parsed, especially if the image has already been cached (which is common). Here, the author uses the onload handler on an
img element to catch the load event: <img src="games.png" alt="Games" onload="gamesLogoHasLoaded(event)"> If the element is being added by script, then so long as the event handlers are added in the
same script, the event will still not be missed: <script> var img = new Image(); img.src = 'games.png'; img.alt = 'Games'; img.onload = gamesLogoHasLoaded; // img.addEventListener('load', gamesLogoHasLoaded, false); // would work also </script> However, if the author first created the img element and then in a separate script added the event listeners, there's a chance that the load
event would be fired in between, leading it to be missed:

http://developers.whatwg.org/introduction.html[4/16/2014 9:27:13 PM]

1 Introduction HTML: The Living Standard - Edition for Web Developers

<!-- Do not use this style, it has a race condition! --> <img id="games" src="games.png" alt="Games"> <!-- the 'load' event might fire here while the parser is taking a break, in which case you will not see it! --> <script> var img = document.getElementById('games'); img.onload = gamesLogoHasLoaded; // might never fire! </script>

Conformance requirements for authors


Unlike previous versions of the HTML specification, this specification defines in some detail
the required processing for invalid documents as well as valid documents. However, even though the processing of invalid content is in most cases welldefined,
conformance requirements for documents are still important: in practice, interoperability (the
situation in which all implementations process particular content in a reliable and identical or
equivalent way) is not the only goal of document conformance requirements. This section details
some of the more common reasons for still distinguishing between a conforming document and one
with errors.

Presentational markup
The majority of presentational features from previous versions of HTML are no longer allowed.
Presentational markup in general has been found to have a number of problems: The use of presentational elements leads to poorer accessibility While it is possible to use presentational markup in a way that provides users of assistive
technologies (ATs) with an acceptable experience (e.g. using ARIA), doing so is significantly
more difficult than doing so when using semantically-appropriate markup. Furthermore, even using
such techniques doesn't help make pages accessible for non-AT non-graphical users, such as users
of text-mode browsers.

http://developers.whatwg.org/introduction.html[4/16/2014 9:27:13 PM]

1 Introduction HTML: The Living Standard - Edition for Web Developers

Using media-independent markup, on the other hand, provides an easy way for documents to be
authored in such a way that they work for more users (e.g. text browsers). Higher cost of maintenance It is significantly easier to maintain a site written in such a way that the markup is
style-independent. For example, changing the color of a site that uses
<fontcolor=""> throughout requires changes across the entire site, whereas
a similar change to a site based on CSS can be done by changing a single file. Larger document sizes Presentational markup tends to be much more redundant, and thus results in larger document
sizes. For those reasons, presentational markup has been removed from HTML in this version. This
change should not come as a surprise; HTML4 deprecated presentational markup many years ago and
provided a mode (HTML4 Transitional) to help authors move away from presentational markup; later, XHTML 1.1 went further and obsoleted those features altogether. The only remaining presentational markup features in HTML are the style attribute and the style element. Use of the style attribute is somewhat discouraged in production environments, but
it can be useful for rapid prototyping (where its rules can be directly moved into a separate
style sheet later) and for providing specific styles in unusual cases where a separate style sheet
would be inconvenient. Similarly, the style element can be useful in syndication or
for page-specific styles, but in general an external style sheet is likely to be more convenient
when the styles apply to multiple pages. It is also worth noting that some elements that were previously presentational have been
redefined in this specification to be media-independent: b , i,
hr , s , small, and u .

Syntax errors
The syntax of HTML is constrained to avoid a wide variety of problems. Unintuitive error-handling behavior Certain invalid syntax constructs, when parsed, result in DOM trees that are

http://developers.whatwg.org/introduction.html[4/16/2014 9:27:13 PM]

1 Introduction HTML: The Living Standard - Edition for Web Developers

highly
unintuitive. For example, the following markup fragment results in a DOM with an hr element
that is an earlier sibling of the corresponding table element: <table><hr>... Errors with optional error recovery To allow user agents to be used in controlled environments without having to implement the
more bizarre and convoluted error handling rules, user agents are permitted to fail whenever
encountering a parse error. Errors where the error-handling behavior is not compatible with streaming user agents Some error-handling behavior, such as the behavior for the <table><hr>... example mentioned above, are incompatible with streaming
user agents (user agents that process HTML files in one pass, without storing state). To avoid interoperability problems with such user agents, any syntax resulting in such behavior is
considered invalid. Errors that can result in infoset coercion When a user agent based on XML is connected to an HTML parser, it is possible that certain
invariants that XML enforces, such as comments never containing two consecutive hyphens, will be
violated by an HTML file. Handling this can require that the parser coerce the HTML DOM into an XML-compatible infoset. Most syntax constructs that require such handling are considered
invalid. Errors that result in disproportionally poor performance Certain syntax constructs can result in disproportionally poor performance. To discourage the
use of such constructs, they are typically made nonconforming. For example, the following markup results in poor performance, since all the unclosed
i elements have to be reconstructed in each paragraph, resulting in progressively
more elements in each paragraph: <p><i>He dreamt. <p><i>He dreamt that he ate breakfast. <p><i>Then lunch. <p><i>And finally dinner. The resulting DOM for this fragment would be:

http://developers.whatwg.org/introduction.html[4/16/2014 9:27:13 PM]

1 Introduction HTML: The Living Standard - Edition for Web Developers

p i #text : He dreamt. p i i #text : He dreamt that he ate breakfast. p i i i #text : Then lunch. p i i i i #text : And finally dinner. Errors involving fragile syntax constructs There are syntax constructs that, for historical reasons, are relatively fragile. To help
reduce the number of users who accidentally run into such problems, they are made
non-conforming. For example, the parsing of certain named character references in attributes happens even
with the closing semicolon being omitted. It is safe to include an ampersand followed by
letters that do not form a named character reference, but if the letters are changed to a
string that does form a named character reference, they will be interpreted as that
character instead. In this fragment, the attribute's value is "?bill&ted ": <a href="?bill&ted">Bill and Ted</a> In the following fragment, however, the attribute's value is actually "?art ", not the intended "?art&copy ",
because even without the final semicolon, " &copy " is handled the same
as "&copy;" and thus gets interpreted as " ": <a href="?art&copy">Art and Copy</a> To avoid this problem, all named character references are required to end

http://developers.whatwg.org/introduction.html[4/16/2014 9:27:13 PM]

1 Introduction HTML: The Living Standard - Edition for Web Developers

with a semicolon,
and uses of named character references without a semicolon are flagged as errors. Thus, the correct way to express the above cases is as
follows: <a href="?bill&ted">Bill and Ted</a> <!-- &ted is ok, since it's not a named character reference --> <a href="?art&amp;copy">Art and Copy</a> <!-- the & has to be escaped, since &copy is a named character reference --> Errors involving known interoperability problems in legacy user agents Certain syntax constructs are known to cause especially subtle or serious problems in legacy
user agents, and are therefore marked as non-conforming to help authors avoid them. For example, this is why the U+0060 GRAVE ACCENT character (`) is not allowed in unquoted
attributes. In certain legacy user agents, it is sometimes treated as a
quote character. Another example of this is the DOCTYPE, which is required to trigger noquirks
mode, because the behavior of legacy user agents in quirks mode is often
largely undocumented. Errors that risk exposing authors to security attacks Certain restrictions exist purely to avoid known security problems. For example, the restriction on using UTF-7 exists purely to avoid authors falling prey to a
known cross-site-scripting attack using UTF-7. Cases where the author's intent is unclear Markup where the author's intent is very unclear is often made nonconforming. Correcting
these errors early makes later maintenance easier. For example, it is unclear whether the author intended the following to be an h1 heading or an h2 heading: <h1>Contact details</h2> Cases that are likely to be typos When a user makes a simple typo, it is helpful if the error can be caught early, as this can
save the author a lot of debugging time. This specification therefore usually considers it an
error to use element names, attribute names,

http://developers.whatwg.org/introduction.html[4/16/2014 9:27:13 PM]

1 Introduction HTML: The Living Standard - Edition for Web Developers

and so forth, that do not match the names defined


in this specification. For example, if the author typed <capton> instead of
<caption> , this would be flagged as an error and the author could correct the
typo immediately. Errors that could interfere with new syntax in the future In order to allow the language syntax to be extended in the future, certain otherwise
harmless features are disallowed. For example, "attributes" in end tags are ignored currently, but they are invalid, in case a
future change to the language makes use of that syntax feature without conflicting with
already-deployed (and valid!) content. Some authors find it helpful to be in the practice of always quoting all attributes and always
including all optional tags, preferring the consistency derived from such custom over the minor
benefits of terseness afforded by making use of the flexibility of the HTML syntax. To aid such
authors, conformance checkers can provide modes of operation wherein such conventions are
enforced.

Restrictions on content models and on attribute values


Beyond the syntax of the language, this specification also places restrictions on how elements
and attributes can be specified. These restrictions are present for similar reasons: Errors involving content with dubious semantics To avoid misuse of elements with defined meanings, content models are defined that restrict
how elements can be nested when such nestings would be of dubious value. For example, this specification disallows nesting a section
element inside a kbd element, since it is highly unlikely for an author to indicate
that an entire section should be keyed in. Errors that involve a conflict in expressed semantics Similarly, to draw the author's attention to mistakes in the use of elements, clear
contradictions in the semantics expressed are also considered conformance errors. In the fragments below, for example, the semantics are nonsensical: a

http://developers.whatwg.org/introduction.html[4/16/2014 9:27:13 PM]

1 Introduction HTML: The Living Standard - Edition for Web Developers

separator cannot
simultaneously be a cell, nor can a radio button be a progress bar. <hr role="cell"> <input type=radio role=progressbar> Another example is the restrictions on the content models of the
ul element, which only allows li element children. Lists by definition
consist just of zero or more list items, so if a ul element contains something
other than an li element, it's not clear what was meant. Cases where the default styles are likely to lead to confusion Certain elements have default styles or behaviors that make certain combinations likely to
lead to confusion. Where these have equivalent alternatives without this problem, the confusing
combinations are disallowed. For example, div elements are rendered as block boxes, and
span elements as inline boxes. Putting a block box in an inline box is
unnecessarily confusing; since either nesting just div elements, or nesting just
span elements, or nesting span elements inside div
elements all serve the same purpose as nesting a div element in a span
element, but only the latter involves a block box in an inline box, the latter combination is
disallowed. Another example would be the way interactive content cannot be
nested. For example, a button element cannot contain a textarea
element. This is because the default behavior of such nesting interactive elements would be highly confusing to users. Instead of nesting these elements, they can be placed side by
side. Errors that indicate a likely misunderstanding of the specification Sometimes, something is disallowed because allowing it would likely cause author
confusion. For example, setting the disabled
attribute to the value "false " is disallowed, because despite the
appearance of meaning that the element is enabled, it in fact means that the element is
disabled (what matters for implementations is the presence of the attribute, not its
value). Errors involving limits that have been imposed merely to simplify the language Some conformance errors simplify the language that authors need to learn.

http://developers.whatwg.org/introduction.html[4/16/2014 9:27:13 PM]

1 Introduction HTML: The Living Standard - Edition for Web Developers

For example, the area element's shape attribute, despite accepting both circ and circle values in practice as synonyms, disallows
the use of the circ value, so as to simplify
tutorials and other learning aids. There would be no benefit to allowing both, but it would
cause extra confusion when teaching the language. Errors that involve peculiarities of the parser Certain elements are parsed in somewhat eccentric ways (typically for historical reasons),
and their content model restrictions are intended to avoid exposing the author to these
issues. For example, a form element isn't allowed inside phrasing content,
because when parsed as HTML, a form element's start tag will imply a
p element's end tag. Thus, the following markup results in two paragraphs, not one: <p>Welcome. <form><label>Name:</label> <input></form> It is parsed exactly like the following: <p>Welcome. </p><form><label>Name:</label> <input></form> Errors that would likely result in scripts failing in hard-to-debug ways Some errors are intended to help prevent script problems that would be hard to debug. This is why, for instance, it is non-conforming to have two id attributes with the same value. Duplicate IDs lead to the wrong
element being selected, with sometimes disastrous effects whose cause is hard to determine. Errors that waste authoring time Some constructs are disallowed because historically they have been the cause of a lot of
wasted authoring time, and by encouraging authors to avoid making them, authors can save time in
future efforts. For example, a script element's src attribute causes the element's contents to be ignored.
However, this isn't obvious, especially if the element's contents appear to be executable script
which can lead to authors spending a lot of time trying to debug the inline script
without realizing that it is not executing. To reduce this problem, this specification makes it
nonconforming to have executable script in a script element when the src attribute is present. This means that authors who are
validating their documents are less likely to waste time with this kind of mistake.

http://developers.whatwg.org/introduction.html[4/16/2014 9:27:13 PM]

1 Introduction HTML: The Living Standard - Edition for Web Developers

Errors that involve areas that affect authors migrating to and from XHTML Some authors like to write files that can be interpreted as both XML and HTML with similar
results. Though this practice is discouraged in general due to the myriad of subtle
complications involved (especially when involving scripting, styling, or any kind of automated
serialization), this specification has a few restrictions intended to at least somewhat mitigate
the difficulties. This makes it easier for authors to use this as a transitionary step when migrating between HTML and XHTML. For example, there are somewhat complicated rules surrounding the lang and xml:lang attributes
intended to keep the two synchronized. Another example would be the restrictions on the values of xmlns attributes in the HTML serialization, which are intended to ensure that
elements in conforming documents end up in the same namespaces whether processed as HTML or
XML. Errors that involve areas reserved for future expansion As with the restrictions on the syntax intended to allow for new syntax in future revisions
of the language, some restrictions on the content models of elements and values of attributes
are intended to allow for future expansion of the HTML vocabulary. For example, limiting the values of the target attribute that start with an U+005F LOW LINE
character (_) to only specific predefined values allows new predefined values to be introduced
at a future time without conflicting with author-defined values. Errors that indicate a mis-use of other specifications Certain restrictions are intended to support the restrictions made by other specifications. For example, requiring that attributes that take media queries use only
valid media queries reinforces the importance of following the conformance rules of
that specification.

Suggested reading
The following documents might be of interest to readers of this specification.

http://developers.whatwg.org/introduction.html[4/16/2014 9:27:13 PM]

1 Introduction HTML: The Living Standard - Edition for Web Developers

Character Model for the World Wide Web 1.0: Fundamentals This Architectural Specification provides authors of specifications, software developers, and content developers with a common reference for interoperable text manipulation on
the World Wide Web, building on the Universal Character Set, defined jointly by the Unicode
Standard and ISO/IEC 10646. Topics addressed include use of the terms 'character', 'encoding' and
'string', a reference processing model, choice and identification of character encodings,
character escaping, and string indexing. Unicode Security Considerations Because Unicode contains such a large number of characters and incorporates the varied writing systems of the world, incorrect usage can expose programs or systems to
possible security attacks. This is especially important as more and more products are
internationalized. This document describes some of the security considerations that programmers,
system analysts, standards developers, and users should take into account, and provides specific recommendations to reduce the risk of problems. Web Content Accessibility Guidelines (WCAG) 2.0 Web Content Accessibility Guidelines (WCAG) 2.0 covers a wide range of recommendations for making Web content more accessible. Following these guidelines will make
content accessible to a wider range of people with disabilities, including blindness and low
vision, deafness and hearing loss, learning disabilities, cognitive limitations, limited
movement, speech disabilities, photosensitivity and combinations of these. Following these guidelines will also often make your Web content more usable to users in general.

Up next

2 Common infrastructure

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/introduction.html[4/16/2014 9:27:13 PM]

2 Common infrastructure HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
Common infrastructure
Terminology
Resources
XML
DOM trees
Scripting
Plugins
Character encodings
Extensibility
Case-sensitivity and string comparison

COMMON INFRASTRUCTURE

Terminology
This specification refers to both HTML and XML attributes and IDL attributes, often in the same
context. When it is not clear which is being referred to, they are referred to as content attributes for HTML and XML attributes, and IDL
attributes for those defined on IDL interfaces. Similarly, the term "properties" is used for
both JavaScript object properties and CSS properties. When these are ambiguous they are qualified
as object properties and CSS properties respectively. Generally, when the specification states that a feature applies to the HTML syntax
or the XHTML syntax, it also includes the other. When a feature specifically only
applies to one of the two languages, it is called out by explicitly stating that it does not apply
to the other format, as in "for HTML, ... (this does not apply to XHTML)".

http://developers.whatwg.org/infrastructure.html[4/16/2014 9:27:22 PM]

2 Common infrastructure HTML: The Living Standard - Edition for Web Developers

This specification uses the term document to refer to any use of HTML, ranging from short static documents to long essays or reports with rich multimedia, as well as to
fully-fledged interactive applications. The term is used to refer both to Document
objects and their descendant DOM trees, and to serialized byte streams using the HTML syntax or XHTML syntax, depending
on context. In the context of the DOM structures, the terms HTML
document and XML document are used as defined in the DOM
specification, and refer specifically to two different modes that Document objects
can find themselves in. (Such uses are always hyperlinked to their
definition.) In the context of byte streams, the term HTML document refers to resources labeled as
text/html, and the term XML document refers to resources labeled with an XML
MIME type. The term XHTML document is used to refer to both Documents in the XML document mode that contains element nodes in the HTML
namespace, and byte streams labeled with an XML MIME type that contain
elements from the HTML namespace, depending on context. For simplicity, terms such as shown, displayed, and
visible might sometimes be used when referring to the way a document is
rendered to the user. These terms are not meant to imply a visual medium; they must be considered
to apply to other media in equivalent ways. The term "transparent black" refers to the color with red, green, blue, and alpha channels all
set to zero.

Resources
The specification uses the term supported when referring to whether a user agent has an implementation capable of decoding the semantics of an external resource. A format or
type is said to be supported if the implementation can process an external resource of that
format or type without critical aspects of the resource being ignored. Whether a specific resource
is supported can depend on what features of the resource's format are in use. For example, a PNG image would be considered to be in a supported format if its
pixel data could be decoded and rendered, even if, unbeknownst to the implementation, the image
also contained animation data.

http://developers.whatwg.org/infrastructure.html[4/16/2014 9:27:22 PM]

2 Common infrastructure HTML: The Living Standard - Edition for Web Developers

An MPEG-4 video file would not be considered to be in a supported format if the


compression format used was not supported, even if the implementation could determine the
dimensions of the movie from the file's metadata. What some specifications, in particular the HTTP specification, refer to as a representation is referred to in this specification as a resource. The term MIME type is used to refer to what is sometimes called an Internet media
type in protocol literature. The term media type in this specification is used to refer
to the type of media intended for presentation, as used by the CSS specifications. A string is a valid MIME type if it matches the media-type
rule defined in section 3.7 "Media Types" of RFC 2616. In particular, a valid MIME
type may include MIME type parameters. [HTTP] A string is a valid MIME type with no parameters if it matches the media-type rule defined in section 3.7 "Media Types" of RFC 2616, but does not
contain any U+003B SEMICOLON characters (;). In other words, if it consists only of a type and
subtype, with no MIME Type parameters. [HTTP] The term HTML MIME type is used to refer to the MIME type
text/html . A resource's critical subresources are those that the resource needs to have available to be correctly processed. Which resources are considered critical or not is defined by
the specification that defines the resource's format. The term data: URL refers to URLs that use the data: scheme.

XML
To ease migration from HTML to XHTML, UAs conforming to this specification
will place elements in HTML in the http://www.w3.org/1999/xhtml namespace, at least
for the purposes of the DOM and CSS. The term "HTML elements", when used in this
specification, refers to any element in that namespace, and thus refers to both HTML and XHTML
elements. Except where otherwise stated, all elements defined or mentioned in this specification are in
the HTML namespace (" http://www.w3.org/1999/xhtml"), and all attributes
defined or mentioned in this specification have no namespace.

http://developers.whatwg.org/infrastructure.html[4/16/2014 9:27:22 PM]

2 Common infrastructure HTML: The Living Standard - Edition for Web Developers

The term element type is used to refer to the set of elements that have a given local name and namespace. For example, button elements are elements with the element
type button , meaning they have the local name "button " and (implicitly as defined above) the HTML namespace. Attribute names are said to be XML-compatible if they match the Name production defined in
XML, they contain no U+003A COLON characters (:), and their first three characters are not an
ASCII case-insensitive match for the string "xml". The term XML MIME type is used to refer to the MIME
types text/xml, application/xml, and any
MIME type whose subtype ends with the four characters "+xml".

DOM trees
The root element of a Document object is that Document's
first element child, if any. If it does not have one then the Document has no root
element. The term root element, when not referring to a Document object's root element, means the furthest ancestor element node of whatever node is being discussed, or the node
itself if it has no ancestors. When the node is a part of the document, then the node's root
element is indeed the document's root element; however, if the node is not currently part
of the document tree, the root element will be an orphaned node. When an element's root element is the root element of a
Document object, it is said to be in a Document. An
element is said to have been inserted into a document when its root element changes and is now the document's root element. Analogously, an element is said to have been removed from a document when its root element changes from being the
document's root element to being another element. A node's home subtree is the subtree rooted at that node's root
element. When a node is in a Document, its home
subtree is that Document's tree. The Document of a Node (such as an element) is the
Document that the Node's ownerDocument IDL attribute returns. When a
Node is in a Document then that Document is
always the Node's Document, and the Node's ownerDocument IDL attribute thus always returns that
Document.

http://developers.whatwg.org/infrastructure.html[4/16/2014 9:27:22 PM]

2 Common infrastructure HTML: The Living Standard - Edition for Web Developers

The Document of a content attribute is the Document of the


attribute's element. The term tree order means a pre-order, depth-first traversal of DOM nodes involved
(through the parentNode/childNodes relationship). When it is stated that some element or attribute is ignored, or
treated as some other value, or handled as if it was something else, this refers only to the processing of the node after it is in the DOM. A content attribute is said to change value only if its new value is
different than its previous value; setting an attribute to a value it already has does not change
it. The term empty, when used of an attribute value, Text node, or
string, means that the length of the text is zero (i.e. not even containing spaces or control characters).

Scripting
The construction "a Foo object", where Foo is actually an interface,
is sometimes used instead of the more accurate "an object implementing the interface
Foo". An IDL attribute is said to be getting when its value is being retrieved
(e.g. by author script), and is said to be setting when a new value is
assigned to it. If a DOM object is said to be live, then the attributes and methods on that object
operate on the actual underlying data, not a snapshot of the
data. In the contexts of events, the terms fire and dispatch are used as defined in the
DOM specification: firing an event means to create and dispatch it, and dispatching an event means to follow the steps that propagate
the event through the tree. The term trusted event is
used to refer to events whose isTrusted attribute is
initialized to true. [DOM]

Plugins
The term plugin refers to a user-agent defined set of content handlers used by the
user agent that can take part in the user agent's rendering of a Document object, but
that neither act as child browsing contexts of the
Document nor
http://developers.whatwg.org/infrastructure.html[4/16/2014 9:27:22 PM]

2 Common infrastructure HTML: The Living Standard - Edition for Web Developers

introduce any Node objects to the Document's


DOM. Typically such content handlers are provided by third parties, though a user agent can also
designate built-in content handlers as plugins. One example of a plugin would be a PDF viewer that is instantiated in a browsing context when the user navigates to a PDF file. This would count as a plugin
regardless of whether the party that implemented the PDF viewer component was the same as that
which implemented the user agent itself. However, a PDF viewer application that launches separate
from the user agent (as opposed to using the same interface) is not a plugin by this definition. This specification does not define a mechanism for interacting with plugins, as it
is expected to be user-agent- and platform-specific. Some UAs might opt to support a plugin
mechanism such as the Netscape Plugin API; others might use remote content converters or have
built-in support for certain types. Indeed, this specification doesn't require user agents to
support plugins at all. A plugin can be secured if it honors the semantics of
the sandbox attribute. For example, a secured plugin would prevent its contents from creating popup
windows when the plugin is instantiated inside a sandboxed iframe.

Character encodings
A character encoding, or just encoding where that is not
ambiguous, is a defined way to convert between byte streams and Unicode strings, as defined in the
WHATWG Encoding standard. An encoding has an encoding name and one or more
encoding labels, referred to as the encoding's name and
labels in the Encoding specification. An ASCII-compatible character encoding is a single-byte or variable-length encoding in which the bytes 0x09, 0x0A, 0x0C, 0x0D, 0x20 - 0x22, 0x26, 0x27, 0x2C -
0x3F, 0x41 - 0x5A, and 0x61 - 0x7A, ignoring bytes that are the second and later bytes of multibyte
sequences, all correspond to single-byte sequences that map to the same Unicode characters as
those bytes in Windows-1252. [ENCODING] This includes such encodings as Shift_JIS, HZ-GB-2312, and variants of ISO-

http://developers.whatwg.org/infrastructure.html[4/16/2014 9:27:22 PM]

2 Common infrastructure HTML: The Living Standard - Edition for Web Developers

2022,
even though it is possible in these encodings for bytes like 0x70 to be part of longer sequences
that are unrelated to their interpretation as ASCII. It excludes UTF-16 variants, as well as
obsolete legacy encodings such as UTF-7, GSM03.38, and EBCDIC variants. The term a UTF-16 encoding refers to any variant of UTF-16: UTF-16LE or UTF-16BE,
regardless of the presence or absence of a BOM. [ENCODING] The term code unit is used as defined in the Web IDL specification: a 16 bit unsigned integer, the smallest atomic component of a DOMString. (This is a narrower
definition than the one used in Unicode, and is not the same as a code point.) The term Unicode code point means a Unicode scalar value where
possible, and an isolated surrogate code point when not. When a conformance requirement is defined
in terms of characters or Unicode code points, a pair of code units
consisting of a high surrogate followed by a low surrogate must be treated as the single code
point represented by the surrogate pair, but isolated surrogates must each be treated as the
single code point with the value of the surrogate. In this specification, the term character, when not qualified as Unicode character, is synonymous with the term Unicode code point. The term Unicode character is used to mean a Unicode scalar value
(i.e. any Unicode code point that is not a surrogate code point). [UNICODE] The code-unit length of a string is the number of code
units in that string. This complexity results from the historical decision to define the DOM API in terms of 16 bit (UTF-16) code units, rather than in terms of Unicode characters.

Extensibility
Vendor-specific proprietary user agent extensions to this specification are strongly
discouraged. Documents must not use such extensions, as doing so reduces interoperability and
fragments the user base, allowing only users of specific user agents to access the content in
question. When vendor-neutral extensions to this specification are needed, either this

http://developers.whatwg.org/infrastructure.html[4/16/2014 9:27:22 PM]

2 Common infrastructure HTML: The Living Standard - Edition for Web Developers

specification can
be updated accordingly, or an extension specification can be written that overrides the
requirements in this specification. When someone applying this specification to their activities
decides that they will recognize the requirements of such an extension specification, it becomes
an applicable specification for the purposes of
conformance requirements in this specification. Someone could write a specification that defines any arbitrary byte stream as conforming, and then claim that their random junk is conforming. However, that does not mean that
their random junk actually is conforming for everyone's purposes: if someone else decides that
that specification does not apply to their work, then they can quite legitimately say that the aforementioned random junk is just that, junk, and not conforming at all. As far as conformance
goes, what matters in a particular community is what that community agrees is
applicable.

Case-sensitivity and string comparison


Comparing two strings in a case-sensitive manner means comparing them exactly, code
point for code point. Comparing two strings in an ASCII case-insensitive manner means comparing them
exactly, code point for code point, except that the characters in the range U+0041 to U+005A (i.e.
LATIN CAPITAL LETTER A to LATIN CAPITAL LETTER Z) and the corresponding characters in the range
U+0061 to U+007A (i.e. LATIN SMALL LETTER A to LATIN SMALL LETTER Z) are considered to also
match. Comparing two strings in a compatibility caseless manner means using the Unicode
compatibility caseless match operation to compare the two strings, with no language-specific tailoirings. [UNICODE] Except where otherwise stated, string comparisons must be performed in a case-sensitive manner. A string pattern is a prefix match for a string s when pattern is not longer than s and
truncating s to pattern's length leaves the two strings as
matches of each other.

http://developers.whatwg.org/infrastructure.html[4/16/2014 9:27:22 PM]

2 Common infrastructure HTML: The Living Standard - Edition for Web Developers
Up next

2.4 Common microsyntaxes

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/infrastructure.html[4/16/2014 9:27:22 PM]

2.4 Common microsyntaxes HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
Common microsyntaxes
Boolean attributes
Keywords and enumerated attributes
Numbers
Signed integers
Non-negative integers
Floating-point numbers
Lists of integers
Dates and times
Months
Dates
Yearless dates
Times
Local dates and times
Time zones
Global dates and times
Weeks
Durations
Vaguer moments in time
Colors
Space-separated tokens
Comma-separated tokens
References
Media queries

Common microsyntaxes
There are various places in HTML that accept particular data types, such as

http://developers.whatwg.org/common-microsyntaxes.html[4/16/2014 9:27:27 PM]

2.4 Common microsyntaxes HTML: The Living Standard - Edition for Web Developers

dates or numbers.
This section describes what the conformance criteria for content in those formats is, and how to
parse them. The space characters, for the purposes of this
specification, are U+0020 SPACE, U+0009 CHARACTER TABULATION (tab), U+000A LINE FEED (LF), U+000C
FORM FEED (FF), and U+000D CARRIAGE RETURN (CR). The White_Space characters are those that have the Unicode
property "White_Space" in the Unicode PropList.txt data file. This should not be confused with the "White_Space" value (abbreviated "WS") of the
"Bidi_Class" property in the Unicode.txt data file. The control characters are those whose Unicode "General_Category" property has the
value "Cc" in the Unicode UnicodeData.txt data file. [UNICODE] The uppercase ASCII letters are the characters in the range U+0041 LATIN CAPITAL
LETTER A to U+005A LATIN CAPITAL LETTER Z. The lowercase ASCII letters are the characters in the range U+0061 LATIN SMALL
LETTER A to U+007A LATIN SMALL LETTER Z. The ASCII digits are the characters in the range U+0030 DIGIT ZERO (0) to U+0039
DIGIT NINE (9). The alphanumeric ASCII characters are those that are either uppercase ASCII
letters, lowercase ASCII letters, or ASCII digits. The ASCII hex digits are the characters in the ranges U+0030 DIGIT ZERO (0) to
U+0039 DIGIT NINE (9), U+0041 LATIN CAPITAL LETTER A to U+0046 LATIN CAPITAL LETTER F, and U+0061
LATIN SMALL LETTER A to U+0066 LATIN SMALL LETTER F. The uppercase ASCII hex digits are the characters in the ranges U+0030 DIGIT ZERO (0) to
U+0039 DIGIT NINE (9) and U+0041 LATIN CAPITAL LETTER A to U+0046 LATIN CAPITAL LETTER F only. The lowercase ASCII hex digits are the characters in the ranges U+0030 DIGIT ZERO
(0) to U+0039 DIGIT NINE (9) and U+0061 LATIN SMALL LETTER A to U+0066 LATIN SMALL LETTER F
only.

Boolean attributes

http://developers.whatwg.org/common-microsyntaxes.html[4/16/2014 9:27:27 PM]

2.4 Common microsyntaxes HTML: The Living Standard - Edition for Web Developers

A number of attributes are boolean attributes. The


presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value. If the attribute is present, its value must either be the empty string or a value that is an
ASCII case-insensitive match for the attribute's canonical name, with no leading or
trailing whitespace. The values "true" and "false" are not allowed on boolean attributes. To represent
a false value, the attribute has to be omitted altogether. Here is an example of a checkbox that is checked and disabled. The checked and disabled
attributes are the boolean attributes. <label><input type=checkbox checked name=cheese disabled> Cheese</label> This could be equivalently written as this: <label><input type=checkbox checked=checked name=cheese disabled=disabled> Cheese</label> You can also mix styles; the following is still equivalent: <label><input type='checkbox' checked name=cheese disabled=""> Cheese</label>

Keywords and enumerated attributes


Some attributes are defined as taking one of a finite set of keywords. Such attributes are
called enumerated attributes. The keywords are each
defined to map to a particular state (several keywords might map to the same state, in which case some of the keywords are synonyms of each other; additionally, some of the keywords can
be said to be non-conforming, and are only in the specification for historical reasons). In
addition, two default states can be given. The first is the invalid value default, the
second is the missing value default. If an enumerated attribute is specified, the attribute's value must be an ASCII case-insensitive match for one of the given keywords that are not said to be non-conforming, with no leading or trailing whitespace.

http://developers.whatwg.org/common-microsyntaxes.html[4/16/2014 9:27:27 PM]

2.4 Common microsyntaxes HTML: The Living Standard - Edition for Web Developers

When the attribute is specified, if its value is an ASCII case-insensitive match for one of the given keywords then that keyword's state is the state that the attribute
represents. If the attribute value matches none of the given keywords, but the attribute has an
invalid value default, then the attribute represents that state. Otherwise, if the
attribute value matches none of the keywords but there is a missing value default state
defined, then that is the state represented by the attribute. Otherwise, there is no
default, and invalid values mean that there is no state represented. When the attribute is not specified, if there is a missing value default state defined, then that is the state represented by the (missing) attribute. Otherwise, the absence of
the attribute means that there is no state represented. The empty string can be a valid keyword.

Numbers

Signed integers
A string is a valid integer if it consists of one or more ASCII digits,
optionally prefixed with a U+002D HYPHEN-MINUS character (-). A valid integer without a U+002D HYPHEN-MINUS (-) prefix represents the number
that is represented in base ten by that string of digits. A valid integer with a U+002D HYPHEN-MINUS (-) prefix represents the number represented in base ten by
the string of digits that follows the U+002D HYPHEN-MINUS, subtracted from zero.

Non-negative integers
A string is a valid non-negative integer if it consists of one or more ASCII digits. A valid non-negative integer represents the number that is represented in base ten
by that string of digits.

http://developers.whatwg.org/common-microsyntaxes.html[4/16/2014 9:27:27 PM]

2.4 Common microsyntaxes HTML: The Living Standard - Edition for Web Developers

Floating-point numbers
A string is a valid floating-point number if it consists of: 1. Optionally, a U+002D HYPHEN-MINUS character (-). 2. One or both of the following, in the given order: 1. A series of one or more ASCII digits. 2. 1. A single U+002E FULL STOP character (.). 2. A series of one or more ASCII digits. 3. Optionally: 1. Either a U+0065 LATIN SMALL LETTER E character (e) or a U+0045 LATIN CAPITAL LETTER E
character (E). 2. Optionally, a U+002D HYPHEN-MINUS character (-) or U+002B PLUS SIGN character (+). 3. A series of one or more ASCII digits. A valid floating-point number represents the number obtained by multiplying the
significand by ten raised to the power of the exponent, where the significand is the first number,
interpreted as base ten (including the decimal point and the number after the decimal point, if
any, and interpreting the significand as a negative number if the whole string starts with a
U+002D HYPHEN-MINUS character (-) and the number is not zero), and where the exponent is the
number after the E, if any (interpreted as a negative number if there is a U+002D HYPHEN-MINUS
character (-) between the E and the number and the number is not zero, or else ignoring a U+002B
PLUS SIGN character (+) between the E and the number if there is one). If there is no E, then the
exponent is treated as zero. The Infinity and Not-a-Number (NaN) values are not valid floating-point numbers.

Lists of integers
A valid list of integers is a number of valid
integers separated by U+002C COMMA characters, with no other characters (e.g. no space characters). In addition, there might be restrictions on the
number of integers that can be given, or on the range of values allowed.

http://developers.whatwg.org/common-microsyntaxes.html[4/16/2014 9:27:27 PM]

2.4 Common microsyntaxes HTML: The Living Standard - Edition for Web Developers

Dates and times


In the algorithms below, the number of days in month month of year
year is: 31 if month is 1, 3, 5, 7, 8,
10, or 12; 30 if month is 4, 6, 9, or 11; 29 if month is 2 and year is a number divisible by 400, or if year is a number divisible by 4 but not by 100; and 28 otherwise. This
takes into account leap years in the Gregorian calendar. When ASCII digits are used in the date and time syntaxes defined in this section,
they express numbers in base ten. Where this specification refers to the proleptic Gregorian calendar, it means the
modern Gregorian calendar, extrapolated backwards to year 1. A date in the proleptic
Gregorian calendar, sometimes explicitly referred to as a proleptic-Gregorian
date, is one that is described using that calendar even if that calendar was not in use at
the time (or place) in question. [GREGORIAN] The use of the Gregorian calendar as the wire format in this specification is an
arbitrary choice resulting from the cultural biases of those involved in the decision. See also
the section discussing date, time, and number formats in forms
and the time element.

Months
A month consists of a specific proleptic-Gregorian
date with no time-zone information and no date information beyond a year and a month. [GREGORIAN] A string is a valid month string representing a year year and
month month if it consists of the following components in the given order: 1. Four or more ASCII digits, representing year, where year>0 2. A U+002D HYPHEN-MINUS character (-) 3. Two ASCII digits, representing the month month, in the range
1month12

Dates
A date consists of a specific proleptic-Gregorian
date with no time-zone information, consisting of a year, a month, and a day. [GREGORIAN]

http://developers.whatwg.org/common-microsyntaxes.html[4/16/2014 9:27:27 PM]

2.4 Common microsyntaxes HTML: The Living Standard - Edition for Web Developers

A string is a valid date string representing a year year, month


month, and day day if it consists of the following
components in the given order: 1. A valid month string, representing year and month 2. A U+002D HYPHEN-MINUS character (-) 3. Two ASCII digits, representing day, in the range
1daymaxday where maxday is the number of
days in the month month and year year

Yearless dates
A yearless date consists of a Gregorian month and a
day within that month, but with no associated year. [GREGORIAN] A string is a valid yearless date string representing a month month and a day day if it consists of the following components
in the given order: 1. Optionally, two U+002D HYPHEN-MINUS characters (-) 2. Two ASCII digits, representing the month month, in the range
1month12 3. A U+002D HYPHEN-MINUS character (-) 4. Two ASCII digits, representing day, in the range
1daymaxday where maxday is the number of
days in the month month and any arbitrary leap year (e.g. 4 or
2000) In other words, if the month is "02 ",
meaning February, then the day can be 29, as if the year was a leap year.

Times
A time consists of a specific time with no time-zone
information, consisting of an hour, a minute, a second, and a fraction of a second. A string is a valid time string representing an hour hour, a
minute minute, and a second second if it consists of the
following components in the given order: 1. Two ASCII digits, representing hour, in the range
0hour23 2. A U+003A COLON character (:) 3. Two ASCII digits, representing minute, in the range
0minute59 4. Optionally (required if second is
non-zero): 1. A U+003A COLON character (:)

http://developers.whatwg.org/common-microsyntaxes.html[4/16/2014 9:27:27 PM]

2.4 Common microsyntaxes HTML: The Living Standard - Edition for Web Developers

2. Two ASCII digits, representing the integer part of second,


in the range 0s59 3. Optionally (required if second is not an
integer): 1. A 002E FULL STOP character (.) 2. One, two, or three ASCII digits, representing the fractional part of second The second component cannot be 60 or 61; leap seconds cannot
be represented.

Local dates and times


A local date and time consists of a specific
proleptic-Gregorian date, consisting of a year, a month, and a day, and a time,
consisting of an hour, a minute, a second, and a fraction of a second, but expressed without a
time zone. [GREGORIAN] A string is a valid local date and time string representing a date and time if it consists of the following components in the given order: 1. A valid date string representing the date 2. A U+0054 LATIN CAPITAL LETTER T character (T) or a U+0020 SPACE character 3. A valid time string representing the time A string is a valid normalized local date and time string representing a date and
time if it consists of the following components in the given order: 1. A valid date string representing the date 2. A U+0054 LATIN CAPITAL LETTER T character (T) 3. A valid time string representing the time, expressed as the shortest possible string for the given time (e.g. omitting the seconds component entirely if the given time is zero
seconds past the minute)

Time zones
A time-zone offset consists of a signed number of hours and
minutes. A string is a valid time-zone offset string representing a time-zone offset if it consists of either:

http://developers.whatwg.org/common-microsyntaxes.html[4/16/2014 9:27:27 PM]

2.4 Common microsyntaxes HTML: The Living Standard - Edition for Web Developers

A U+005A LATIN CAPITAL LETTER Z character (Z), allowed only if the time
zone is
UTC

Or, the following components, in the given order: Either a U+002B PLUS SIGN character (+) or, if the time-zone offset is not
zero, a U+002D
HYPHEN-MINUS character (-), representing the sign of the time-zone offset

Two ASCII digits, representing the hours component hour of


the time-zone
offset, in the range 0hour23

Optionally, a U+003A COLON character (:) Two ASCII digits, representing the minutes component minute of the timezone offset, in the range 0minute59 This format allows for time-zone offsets from -23:59 to +23:59. Right now, in practice, the range of offsets of actual time zones is -12:00 to +14:00, and the minutes component
of offsets of actual time zones is always either 00, 30, or 45. There is no guarantee that this
will remain so forever, however, since time zones are used as political footballs and are thus
subject to very whimsical policy decisions. See also the usage notes and examples in the global
date and time section below for details on using time-zone offsets with historical times
that predate the formation of formal time zones.

Global dates and times


A global date and time consists of a specific
proleptic-Gregorian date, consisting of a year, a month, and a day, and a time,
consisting of an hour, a minute, a second, and a fraction of a second, expressed with a time-zone offset, consisting of a signed number of hours and minutes. [GREGORIAN] A string is a valid global date and time string representing a date, time, and a time-zone offset if it consists of the following components in the given order: 1. A valid date string representing the date 2. A U+0054 LATIN CAPITAL LETTER T character (T) or a U+0020 SPACE character 3. A valid time string representing the time 4. A valid time-zone offset string representing the time-zone offset

http://developers.whatwg.org/common-microsyntaxes.html[4/16/2014 9:27:27 PM]

2.4 Common microsyntaxes HTML: The Living Standard - Edition for Web Developers

Times in dates before the formation of UTC in the mid twentieth century must be expressed and
interpreted in terms of UT1 (contemporary Earth solar time at the 0 longitude), not UTC (the
approximation of UT1 that ticks in SI seconds). Time before the formation of time zones must be
expressed and interpeted as UT1 times with explicit time zones that approximate the contemporary
difference between the appropriate local time and the time observed at the location of Greenwich,
London. The following are some examples of dates written as valid global date and time strings. "0037-12-13 00:00Z" Midnight in areas using London time on the birthday of Nero (the Roman Emperor). See below
for further discussion on which date this actually corresponds to. "1979-10-14T12:00:00.001-04:00" One millisecond after noon on October 14th 1979, in the time zone in use on the east coast
of the USA during daylight saving time. "8592-01-01T02:09+02:09" Midnight UTC on the 1st of January, 8592. The time zone associated with that time is two
hours and nine minutes ahead of UTC, which is not currently a real time zone, but is nonetheless
allowed. Several things are notable about these dates:

Years with fewer than four digits have to be zero-padded. The date "37-1213" would not be a
valid date.

If the "T" is replaced by a space, it must be a single space


character. The
string "2001-12-2112:00Z" (with two spaces
between the components) would not be parsed successfully.

To unambiguously identify a moment in time prior to the introduction of the


Gregorian
calendar (insofar as moments in time before the formation of UTC can be unambiguously
identified), the date has to be first converted to the Gregorian calendar from the calendar in
use at the time (e.g. from the Julian calendar). The date of Nero's birth is the 15th of
December 37, in the Julian Calendar, which is the 13th of December 37 in the proleptic
Gregorian calendar.

The time and time-zone offset components are not optional. Dates before the year one can't be represented as a datetime in this version of
HTML.

Times of specific events in ancient times are, at best, approximations, since


http://developers.whatwg.org/common-microsyntaxes.html[4/16/2014 9:27:27 PM]

2.4 Common microsyntaxes HTML: The Living Standard - Edition for Web Developers

time was not


well coordinated or measured until relatively recent decades.

Time-zone offsets differ based on daylight savings time.


A string is a valid normalized forced-UTC global date and time string representing a
date, time, and a time-zone offset if it consists of the following components in the given
order: 1. A valid date string representing the date converted to the UTC time zone 2. A U+0054 LATIN CAPITAL LETTER T character (T) 3. A valid time string representing the time converted to the UTC time zone and expressed as the shortest possible string for the given time (e.g. omitting the seconds component
entirely if the given time is zero seconds past the minute) 4. A U+005A LATIN CAPITAL LETTER Z character (Z)

Weeks
A week consists of a week-year number and a week number
representing a seven-day period starting on a Monday. Each week-year in this calendaring system
has either 52 or 53 such seven-day periods, as defined below. The seven-day period starting on the
Gregorian date Monday December 29th 1969 (1969-12-29) is defined as week number 1 in week-year
1970. Consecutive weeks are numbered sequentially. The week before the number 1 week in a week-year is the last week in the previous week-year, and vice versa. [GREGORIAN] A week-year with a number year has 53 weeks if it corresponds to either a
year year in the proleptic Gregorian calendar that has a Thursday
as its first day (January 1st), or a year year in the proleptic
Gregorian calendar that has a Wednesday as its first day (January 1st) and where year is a number divisible by 400, or a number divisible by 4 but not by 100. All
other week-years have 52 weeks. The week number of the last day of a week-year with 53 weeks is 53; the week number
of the last day of a week-year with 52 weeks is 52. The week-year number of a particular day can be different than the number of the
year that contains that day in the proleptic Gregorian calendar. The first week in a
week-year y is the week that contains the first Thursday of the Gregorian year
y. For modern purposes, a week as defined here is
equivalent to ISO weeks as

http://developers.whatwg.org/common-microsyntaxes.html[4/16/2014 9:27:27 PM]

2.4 Common microsyntaxes HTML: The Living Standard - Edition for Web Developers

defined in ISO 8601. A string is a valid week string representing a week-year year
and week week if it consists of the following components in the given
order: 1. Four or more ASCII digits, representing year, where year>0 2. A U+002D HYPHEN-MINUS character (-) 3. A U+0057 LATIN CAPITAL LETTER W character (W) 4. Two ASCII digits, representing the week week, in the range 1weekmaxweek, where maxweek is the week number of the last day of week-year year

Durations
A duration consists of a number of seconds. Since months and seconds are not comparable (a month is not a precise number of
seconds, but is instead a period whose exact length depends on the precise day from which it is
measured) a duration as defined in this specification cannot
include months (or years, which are equivalent to
twelve months). Only durations that describe a specific number of seconds can be described. A string is a valid duration string representing a duration t if it consists of either of the
following:

A literal U+0050 LATIN CAPITAL LETTER P character followed by one or


more of the following
subcomponents, in the order given, where the number of days, hours, minutes, and
seconds corresponds to the same number of seconds as in t:

One or more ASCII digits followed by a U+0044 LATIN CAPITAL LETTER


D
character, representing a number of days.

A U+0054 LATIN CAPITAL LETTER T character followed by one or more


of the following
subcomponents, in the order given:

One or more ASCII digits followed by a U+0048 LATIN CAPITAL


LETTER H
character, representing a number of hours.

One or more ASCII digits followed by a U+004D LATIN CAPITAL


LETTER M
character, representing a number of minutes.

http://developers.whatwg.org/common-microsyntaxes.html[4/16/2014 9:27:27 PM]

2.4 Common microsyntaxes HTML: The Living Standard - Edition for Web Developers

The following components: One or more ASCII digits, representing a number of seconds. Optionally, a U+002E FULL STOP character (.) followed by one, two,
or three
ASCII digits, representing a fraction of a second.

A U+0053 LATIN CAPITAL LETTER S character.


This, as with a number of other date- and time-related microsyntaxes defined in
this specification, is based on one of the formats defined in ISO 8601. [ISO8601]

One or more duration time components, each with


a different duration time
component scale, in any order; the sum of the represented
seconds being equal to the number of seconds in t. A duration time component is a string consisting of the following components:

Zero or more space characters. One or more ASCII digits, representing a number of time units, scaled by
the duration time component scale specified (see below) to represent a number of
seconds.

If the duration time component scale specified is 1 (i.e. the units are
seconds), then, optionally, a U+002E FULL STOP character (.) followed by one, two, or three
ASCII digits, representing a fraction of a second.

Zero or more space characters. One of the following characters, representing the duration time component
scale
of the time unit used in the numeric part of the duration time component: U+0057 LATIN CAPITAL LETTER W character U+0077 LATIN SMALL LETTER W character Weeks. The scale is 604800. U+0044 LATIN CAPITAL LETTER D character U+0064 LATIN SMALL LETTER D character Days. The scale is 86400. U+0048 LATIN CAPITAL LETTER H character U+0068 LATIN SMALL LETTER H character

http://developers.whatwg.org/common-microsyntaxes.html[4/16/2014 9:27:27 PM]

2.4 Common microsyntaxes HTML: The Living Standard - Edition for Web Developers

Hours. The scale is 3600. U+004D LATIN CAPITAL LETTER M character U+006D LATIN SMALL LETTER M character Minutes. The scale is 60. U+0053 LATIN CAPITAL LETTER S character U+0073 LATIN SMALL LETTER S character Seconds. The scale is 1.

Zero or more space


characters.
This is not based on any of the formats in ISO 8601. It is intended to be a more
human-readable alternative to the ISO 8601 duration format.

Vaguer moments in time


A string is a valid date string with optional time if
it is also one of the following:

A valid date string A valid global date and time string

Colors
A simple color consists of three 8-bit numbers in the range 0..255, representing the
red, green, and blue components of the color respectively, in the sRGB color space. A string is a valid simple color if it is exactly seven characters long, and the first character is a U+0023 NUMBER SIGN character (#), and the remaining six characters are all
ASCII hex digits, with the first two digits representing the red component, the
middle two digits representing the green component, and the last two digits representing the blue
component, in hexadecimal. A string is a valid lowercase simple color if it is a valid simple
color and doesn't use any characters in the range U+0041 LATIN CAPITAL LETTER A to U+0046
LATIN CAPITAL LETTER F. The 2D graphics context has a separate
color syntax that also handles opacity.

http://developers.whatwg.org/common-microsyntaxes.html[4/16/2014 9:27:27 PM]

2.4 Common microsyntaxes HTML: The Living Standard - Edition for Web Developers

Space-separated tokens
A set of space-separated tokens is a string containing zero or more words (known as
tokens) separated by one or more space characters, where
words consist of any string of one or more characters, none of which are space characters. A string containing a set of space-separated tokens may have leading or trailing
space characters. An unordered set of unique space-separated tokens is a set of space-separated
tokens where none of the tokens are duplicated. An ordered set of unique space-separated tokens is a set of space-separated tokens where none of the tokens are duplicated but where the order of the tokens is
meaningful. Sets of space-separated tokens sometimes
have a defined set of allowed values. When a set of allowed values is defined, the tokens must all
be from that list of allowed values; other values are non-conforming. If no such set of allowed values is provided, then all values are conforming. How tokens in a set of space-separated tokens are to be compared
(e.g. casesensitively or not) is defined on a per-set basis.

Comma-separated tokens
A set of comma-separated tokens is a string containing zero or more tokens each
separated from the next by a single U+002C COMMA character (,), where tokens consist of any string
of zero or more characters, neither beginning nor ending with space
characters, nor containing any U+002C COMMA characters (,), and optionally surrounded by
space characters. For instance, the string "a,b,,dd" consists of four tokens: "a", "b", the empty
string, and "dd". Leading and trailing whitespace around each token doesn't count as part of
the token, and the empty string can be a token. Sets of comma-separated tokens sometimes
have further restrictions on what consists a valid token. When such restrictions are defined, the
tokens must all fit within those restrictions; other values are non-conforming. If no such restrictions are specified, then all values are conforming.

http://developers.whatwg.org/common-microsyntaxes.html[4/16/2014 9:27:27 PM]

2.4 Common microsyntaxes HTML: The Living Standard - Edition for Web Developers

References
A valid hash-name reference to an element of type type is a
string consisting of a U+0023 NUMBER SIGN character (#) followed by a string which exactly matches
the value of the name attribute of an element with type type in the document.

Media queries
A string is a valid media query if it matches the media_query_list production of the Media Queries specification. A string matches the environment of the user if it is the empty string, a string consisting of only space characters, or is a media query
that matches the user's environment according to the definitions given in the Media Queries specification. [MQ]

Up next

2.5 URLs

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/common-microsyntaxes.html[4/16/2014 9:27:27 PM]

2.5 URLs HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
URLs
Terminology
CORS settings attributes
Common DOM interfaces
Reflecting content attributes in IDL attributes
Collections
HTMLAllCollection
HTMLFormControlsCollection
HTMLOptionsCollection
HTMLPropertiesCollection
DOMStringMap
DOMElementMap
Transferable objects
Callbacks
Namespaces

URLs

Terminology
A URL is a valid URL if it conforms to the authoring conformance requirements in the URL standard. A string is a valid non-empty URL if it is a valid URL but it is not
the empty string. A string is a valid URL potentially surrounded by spaces if, after stripping

http://developers.whatwg.org/urls.html[4/16/2014 9:27:32 PM]

2.5 URLs HTML: The Living Standard - Edition for Web Developers

leading and trailing whitespace


from it, it is a valid URL. A string is a valid non-empty URL potentially surrounded by spaces if, after stripping leading and trailing whitespace
from it, it is a valid non-empty URL. This specification defines the URL about:legacy-compat as a reserved, though unresolvable, about: URL, for use in DOCTYPEs in HTML documents when needed for
compatibility with XML tools. This specification defines the URL about:srcdoc as a reserved, though unresolvable, about: URL, that is used as the document's
address of iframe srcdoc documents. [ABOUT] The fallback base URL of a Document object is the absolute
URL obtained by running these substeps: 1. If the Document is an iframe srcdoc document, then return the document base
URL of the Document's browsing context's browsing context
container's Document and abort these steps. 2. If the document's address is about:blank , and the
Document's browsing context has a creator browsing
context, then return the document base URL of the creator
Document, and abort these steps. 3. Return the document's address. The document base URL of a Document object is the absolute
URL obtained by running these substeps: 1. If there is no base element that has an href attribute in the Document, then the
document base URL is the Document's fallback base URL;
abort these steps. 2. Otherwise, the document base URL is the frozen base URL of the
first base element in the Document that has an href attribute, in tree order.

CORS settings attributes


A CORS settings attribute is an enumerated attribute. The following
table lists the keywords and states for the attribute the keywords in the left column map
to the states in the cell in the second column on the same row as the keyword.

http://developers.whatwg.org/urls.html[4/16/2014 9:27:32 PM]

2.5 URLs HTML: The Living Standard - Edition for Web Developers

Keyword anonymous

State Anonymous

Brief description Cross-origin CORS requests for the element will have the omit credentials flag set.

usecredentials

Use Credentials

Cross-origin CORS requests for the element will not have the omit credentials flag set.

The empty string is also a valid keyword, and maps to the Anonymous state. The attribute's invalid value
default is the Anonymous state. For the
purposes of reflection, the canonical case for the Anonymous state is the anonymous keyword. The missing value
default, used when the attribute is omitted, is the No
CORS state.

Common DOM interfaces

Reflecting content attributes in IDL attributes


Some IDL attributes are defined to reflect a particular content attribute. This means that on getting, the IDL attribute returns the current value of the content attribute, and
on setting, the IDL attribute changes the value of the content attribute to the given value.

Collections
The HTMLAllCollection , HTMLFormControlsCollection, HTMLOptionsCollection , and HTMLPropertiesCollection interfaces are collections derived from the HTMLCollection interface.

HTMLAllCollection
The HTMLAllCollection interface is used for generic collections of
elements just like HTMLCollection , with the exception that its namedItem() method returns an
HTMLCollection object when there are multiple matching elements, and that its item() method can be used as a synonym for its

http://developers.whatwg.org/urls.html[4/16/2014 9:27:32 PM]

2.5 URLs HTML: The Living Standard - Edition for Web Developers

namedItem() method. It is intended only for the


legacy document.all attribute. collection . length Returns the number of elements in the collection. element = collection . item(index) collection[index] Returns the item with index index from the collection. The items are sorted in tree order. element = collection . item(name) collection = collection . item(name) element = collection . namedItem (name) collection = collection . namedItem (name) collection[name] collection(name) Returns the item with ID or name name from the collection. If there are multiple matching items, then an HTMLCollection object containing all those elements is returned. Only a , applet , area, embed ,
form, frame, frameset, iframe,
img, and object elements can have a name for the purpose of this
method; their name is given by the value of their name attribute. collection = collection . tags(tagName) Returns a collection that is a filtered view of the current collection, containing only elements with the given tag name.

HTMLFormControlsCollection
The HTMLFormControlsCollection interface is used for collections of
listed elements in form and
fieldset elements. collection . length Returns the number of elements in the collection. element = collection . item(index) collection[index]

http://developers.whatwg.org/urls.html[4/16/2014 9:27:32 PM]

2.5 URLs HTML: The Living Standard - Edition for Web Developers

Returns the item with index index from the collection. The items are sorted in tree order. element = collection . namedItem (name) radioNodeList = collection . namedItem (name) collection[name] collection(name) Returns the item with ID or name name from the collection. If there are multiple matching items, then a RadioNodeList object containing all those elements is returned. radioNodeList . value [ = value ] Returns the value of the first checked radio button represented by the object. Can be set, to check the first radio button with the given value represented by the object.

HTMLOptionsCollection
The HTMLOptionsCollection interface is used for collections of
option elements. It is always rooted on a select element and has
attributes and methods that manipulate that element's descendants. collection . length [ = value ] Returns the number of elements in the collection. When set to a smaller number, truncates the number of option elements in the corresponding container. When set to a greater number, adds new blank option elements to that container. element = collection . item(index) collection[index] Returns the item with index index from the collection. The items are sorted in tree order. element = collection . namedItem (name) nodeList = collection . namedItem (name) collection[name] collection(name)
http://developers.whatwg.org/urls.html[4/16/2014 9:27:32 PM]

2.5 URLs HTML: The Living Standard - Edition for Web Developers

Returns the item with ID or name name from the collection. If there are multiple matching items, then the first is returned. collection . add(element [, before ] ) Inserts element before the node given by before. The before argument can be a number, in which case element is inserted before the item with that number, or an element from the
collection, in which case element is inserted before that element. If before is omitted, null, or a number out of range, then element will be added at the end of the list. This method will throw a HierarchyRequestError exception if element is an ancestor of the element into which it is to be inserted. collection . selectedIndex [ = value ] Returns the index of the first selected item, if any, or 1 if there is no selected item. Can be set, to change the selection.

HTMLPropertiesCollection
The HTMLPropertiesCollection interface is used for collections of
elements that add name-value pairs to a particular
item in the microdata model. collection . length Returns the number of elements in the collection. element = collection . item(index) collection[index] Returns the element with index index from the collection. The items are sorted in tree order. propertyNodeList = collection . namedItem (name) Returns a PropertyNodeList object containing any elements that add a property named name. collection[name] Returns a PropertyNodeList object containing any elements that add a

http://developers.whatwg.org/urls.html[4/16/2014 9:27:32 PM]

2.5 URLs HTML: The Living Standard - Edition for Web Developers

property named name. The name index has to be one of the values listed in the names list. collection . names Returns an array with the property names of the elements in the collection. propertyNodeList . getValues() Returns an array of the various values that the relevant elements have.

DOMStringMap
The DOMStringMap interface represents a set of name-value pairs. It exposes these
using the scripting language's native mechanisms for property access. The dataset attribute on elements exposes the data-* attributes on the element. Given the following fragment and elements with similar constructions: <img class="tower" id="tower5" data-x="12" data-y="5" data-ai="robotarget" data-hp="46" data-ability="flames" src="towers/rocket.png alt="Rocket Tower"> ...one could imagine a function splashDamage() that takes some arguments, the first
of which is the element to process: function splashDamage(node, x, y, damage) { if (node.classList.contains('tower') && // checking the 'class' attribute node.dataset.x == x && // reading the 'data-x' attribute node.dataset.y == y) { // reading the 'data-y' attribute var hp = parseInt(node.dataset.hp); // reading the 'datahp' attribute hp = hp - damage; if (hp < 0) { hp = 0; node.dataset.ai = 'dead'; // setting the 'data-ai' attribute delete node.dataset.ability; // removing the 'data-

http://developers.whatwg.org/urls.html[4/16/2014 9:27:32 PM]

2.5 URLs HTML: The Living Standard - Edition for Web Developers

ability' attribute } node.dataset.hp = hp; // setting the 'data-hp' attribute } }

DOMElementMap
The DOMElementMap interface represents a set of name-element mappings. It exposes
these using the scripting language's native mechanisms for property access.

Transferable objects
Some objects support being copied and closed in one operation.
This is called transferring the object, and is used in
particular to transfer ownership of unsharable or expensive
resources across worker boundaries. The following Transferable types exist:

ArrayBuffer CanvasProxy (defined in this specification) MessagePort (defined in this specification)

Callbacks
The following callback function type is used in various APIs that interact with File objects:

Namespaces
The HTML namespace is: http://www.w3.org/1999/xhtml The MathML namespace is: http://www.w3.org/1998/Math/MathML The SVG namespace is: http://www.w3.org/2000/svg

http://developers.whatwg.org/urls.html[4/16/2014 9:27:32 PM]

2.5 URLs HTML: The Living Standard - Edition for Web Developers

The XLink namespace is: http://www.w3.org/1999/xlink The XML namespace is: http://www.w3.org/XML/1998/namespace The XMLNS namespace is: http://www.w3.org/2000/xmlns/ Data mining tools and other user agents that perform operations
on content without running scripts, evaluating CSS or XPath
expressions, or otherwise exposing the resulting DOM to arbitrary
content, may "support namespaces" by just asserting that their DOM
node analogues are in certain namespaces, without actually exposing
the above strings. In the HTML syntax, namespace prefixes
and namespace declarations do not have the same effect as in XML.
For instance, the colon has no special meaning in HTML element
names.

Up next

3 Semantics, structure, and APIs of HTML documents

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/urls.html[4/16/2014 9:27:32 PM]

3 Semantics, structure, and APIs of HTML documents HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
Semantics, structure, and APIs of HTML documents
Documents
The Document object
Security
Resource metadata management
DOM tree accessors

SEMANTICS, STRUCTURE, AND APIS OF HTML DOCUMENTS

Documents
Every XML and HTML document in an HTML UA is represented by a Document object. The document's address is an absolute URL that is initially set when
the Document is created but 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. Interactive user agents typically expose the document's address in
their user interface. This is the primary mechanism by which a user can tell if a site is attempting to impersonate another. 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 responsible
document specified by the script's settings
object, and the Document is both ready for post-load tasks and completely loaded immediately.

http://developers.whatwg.org/dom.html[4/16/2014 9:27:38 PM]

3 Semantics, structure, and APIs of HTML documents HTML: The Living Standard - Edition for Web Developers

The document's referrer is an absolute URL that can be set when the Document is created. If it is not explicitly set, then its value is the empty
string. 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. Let address be the browsing context's active
document's address. 3. 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. When it comes time to set the document's address in the navigation algorithm, use address as the
override URL.

The Document object


The DOM specification defines a Document interface, which
this specification extends significantly:

Security
User agents must throw a SecurityError exception whenever any
properties of a Document object are accessed when the incumbent script
has an effective script origin that is not the same
as the Document's effective script origin. When the incumbent script's effective script origin is different than
a Document object's effective script origin, the user agent must act as
if all the properties of
that Document object had their [[Enumerable]] attribute set to false.

http://developers.whatwg.org/dom.html[4/16/2014 9:27:38 PM]

3 Semantics, structure, and APIs of HTML documents HTML: The Living Standard - Edition for Web Developers

Resource metadata management


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.

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 (e.g. in an iframe with the sandbox attribute), a SecurityError exception
will be thrown on getting and setting. document . lastModified Returns the date of the last modification to the document, as reported by the server, in the
form "MM/DD/YYYYhh:mm:ss", in the user's local time zone. If the last modification date is not known, the current time is returned instead. 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

http://developers.whatwg.org/dom.html[4/16/2014 9:27:38 PM]

3 Semantics, structure, and APIs of HTML documents HTML: The Living Standard - Edition for Web Developers

changes.

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. 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. 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 HierarchyRequestError 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. document . images

http://developers.whatwg.org/dom.html[4/16/2014 9:27:38 PM]

3 Semantics, structure, and APIs of HTML documents HTML: The Living Standard - Edition for Web Developers

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. collection = document . getElementsByName(name) Returns a NodeList of elements in the
Document that have a name
attribute with the value name. element . cssElementMap Returns a DOMElementMap object for the
Document representing the current CSS element reference
identifiers. document . currentScript Returns the script element that is currently executing. In the case of reentrant
script execution, returns the one that most recently started executing amongst
those that have not yet finished executing. Returns null if the Document is not currently executing a script
element (e.g. because the running script is an event handler, or a timeout). The dir attribute on the
Document interface is defined along with the dir content attribute.

Up next

3.2 Elements

http://developers.whatwg.org/dom.html[4/16/2014 9:27:38 PM]

3 Semantics, structure, and APIs of HTML documents HTML: The Living Standard - Edition for Web Developers

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/dom.html[4/16/2014 9:27:38 PM]

3.2 Elements HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
Elements
Semantics
Elements in the DOM
Element definitions
Attributes

Elements

Semantics
Elements, attributes, and attribute values in HTML are defined (by this specification) to have
certain meanings (semantics). For example, the ol element represents an ordered list,
and the lang attribute represents the language of the content. These definitions allow HTML processors, such as Web browsers or search engines, to present and
use documents and applications in a wide variety of contexts that the author might not have
considered. As a simple example, consider a Web page written by an author who only considered desktop
computer Web browsers: <!DOCTYPE HTML> <html> <head> <title>My Page</title> </head> <body> <h1>Welcome to my page</h1>

http://developers.whatwg.org/elements.html[4/16/2014 9:27:43 PM]

3.2 Elements HTML: The Living Standard - Edition for Web Developers

<p>I like cars and lorries and have a big Jeep!</p> <h2>Where I live</h2> <p>I live in a small hut on a mountain!</p> </body> </html> Because HTML conveys meaning, rather than presentation, the same
page can also be used by a small browser on a mobile phone, without any change to the page.
Instead of headings being in large letters as on the desktop, for example, the browser on the
mobile phone might use the same size text for the whole the page, but with the headings in
bold. But it goes further than just differences in screen size: the same page could equally be used
by a blind user using a browser based around speech synthesis, which instead of displaying the
page on a screen, reads the page to the user, e.g. using headphones. Instead of large text for
the headings, the speech browser might use a different volume or a slower voice. That's not all, either. Since the browsers know which parts of the page are the headings, they
can create a document outline that the user can use to quickly navigate around the document,
using keys for "jump to next heading" or "jump to previous heading". Such features are especially common with speech browsers, where users would otherwise find quickly navigating a page quite
difficult. Even beyond browsers, software can make use of this information. Search engines can use the
headings to more effectively index a page, or to provide quick links to subsections of the page
from their results. Tools can use the headings to create a table of contents (that is in fact how
this very specification's table of contents is generated). This example has focused on headings, but the same principle applies to all of the semantics
in HTML. Authors must not use elements, attributes, or attribute values for purposes other than their
appropriate intended semantic purpose, as doing so prevents software from correctly processing the
page. For example, the following document is non-conforming, despite being syntactically
correct: <!DOCTYPE HTML> <html lang="en-GB">

http://developers.whatwg.org/elements.html[4/16/2014 9:27:43 PM]

3.2 Elements HTML: The Living Standard - Edition for Web Developers

<head> <title> Demonstration </title> </head> <body> <table> <tr> <td> My favourite animal is the cat. </td> </tr> <tr> <td> <a href="http://example.org/~ernest/"> <cite>Ernest</cite></a>, in an essay from 1992 </td> </tr> </table> </body> </html> ...because the data placed in the cells is clearly not tabular data (and the cite
element mis-used). This would make software that relies on these semantics fail: for example, a
speech browser that allowed a blind user to navigate tables in the document would report the
quote above as a table, confusing the user; similarly, a tool that extracted titles of works from
pages would extract "Ernest" as the title of a work, even though it's actually a person's name,
not a title. A corrected version of this document might be: <!DOCTYPE HTML> <html lang="en-GB"> <head> <title> Demonstration </title> </head> <body> <blockquote> <p> My favourite animal is the cat. </p> </blockquote> <p> <a href="http://example.org/~ernest/">Ernest</a>, in an essay from 1992 </p> </body> </html> This next document fragment, intended to represent the heading of a corporate site, is
similarly non-conforming because the second line is not

http://developers.whatwg.org/elements.html[4/16/2014 9:27:43 PM]

3.2 Elements HTML: The Living Standard - Edition for Web Developers

intended to be a heading of a subsection,


but merely a subheading or subtitle (a subordinate heading for the same section). <body> <h1>ABC Company</h1> <h2>Leading the way in widget design since 1432</h2> ... The hgroup element is intended for these kinds of situations: <body> <hgroup> <h1>ABC Company</h1> <h2>Leading the way in widget design since 1432</h2> </hgroup> ... Authors must not use elements, attributes, or attribute values that are not permitted by this
specification or other applicable specifications, as doing so makes it significantly
harder for the language to be extended in the future. In the next example, there is a non-conforming attribute value ("carpet") and a non-conforming
attribute ("texture"), which is not permitted by this specification: <label>Carpet: <input type="carpet" name="c" texture="deep pile"></label> Here would be an alternative and correct way to mark this up: <label>Carpet: <input type="text" class="carpet" name="c" data-texture="deep pile"></label> Through scripting and using other mechanisms, the values of attributes, text, and indeed the
entire structure of the document may change dynamically while a user agent is processing it. The
semantics of a document at an instant in time are those represented by the state of the document
at that instant in time, and the semantics of a document can therefore change over time. User agents update their presentation of the document as this
occurs. HTML has a progress element that describes a progress bar. If its
"value" attribute is dynamically updated by a script, the UA would update the rendering to show
the progress changing.
http://developers.whatwg.org/elements.html[4/16/2014 9:27:43 PM]

3.2 Elements HTML: The Living Standard - Edition for Web Developers

Elements in the DOM


The nodes representing HTML elements in the DOM implement, and expose to scripts, the interfaces listed for them in the relevant sections of this specification. This includes HTML elements in XML documents, even when those documents are in another context (e.g. inside an XSLT transform). Elements in the DOM represent things; that is, they have
intrinsic meaning, also known as semantics. For example, an ol element represents an ordered list. The basic interface, from which all the HTML elements' interfaces inherit, is the HTMLElement interface. The HTMLElement interface holds methods and attributes related to a number of
disparate features, and the members of this interface are therefore described in various different
sections of this specification.

Element definitions
Each element in this specification has a definition that includes the following information: Categories A list of categories to which the element belongs.
These are used when defining the content models for each element. Contexts in which this element can be used A non-normative description of where the element can be used. This information is
redundant with the content models of elements that allow this one as a child, and is provided
only as a convenience. For simplicity, only the most specific expectations are listed. For example, an element that is both flow content and phrasing content can be used anywhere that either flow content or phrasing content is expected, but
since anywhere that flow content is expected, phrasing content is also
expected (since all phrasing content is flow content), only "where
phrasing content is expected" will be listed.

http://developers.whatwg.org/elements.html[4/16/2014 9:27:43 PM]

3.2 Elements HTML: The Living Standard - Edition for Web Developers

Content model A normative description of what content must be included as children and descendants of
the element. Tag omission in text/html A non-normative description of whether, in the text/html syntax, the
start and end tags can
be omitted. This information is redundant with the normative requirements given in the optional tags section, and is provided in the element
definitions only as a convenience. Content attributes A normative list of attributes that may be specified on the element (except where
otherwise disallowed), along with non-normative descriptions of those attributes. (The content to
the left of the dash is normative, the content to the right of the dash is not.) DOM interface A normative definition of a DOM interface that such elements must implement. This is then followed by a description of what the element represents, along with
any additional normative conformance criteria that may apply to authors. Examples are sometimes also included.

Attributes
Except where otherwise specified, attributes on HTML elements
may have any string value, including the empty string. Except where explicitly stated, there is no
restriction on what text can be specified in such attributes.

Up next

3.2.4 Content models

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/elements.html[4/16/2014 9:27:43 PM]

4 The elements of HTML HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
The elements of HTML
The root element
The html element
Document metadata
The head element
The title element
The base element
The link element
The meta element
Standard metadata names
Other metadata names
Pragma directives
Other pragma directives
Specifying the document's character encoding
The style element
Styling

THE ELEMENTS OF HTML

The root element

The html element


Categories: None. Contexts in which this element can be used:
http://developers.whatwg.org/semantics.html[4/16/2014 9:27:48 PM]

4 The elements of HTML HTML: The Living Standard - Edition for Web Developers

As the root element of a document. Wherever a subdocument fragment is allowed in a compound document. Content model: A head element followed by a body element. Tag omission in text/html: An html element's start tag can be omitted
if the first thing inside the html element is not a comment. An html element's end tag can be omitted if
the html element is not immediately followed by a comment. Content attributes: Global attributes manifest Application cache manifest DOM interface: The html element represents the root of an HTML document. Authors are encouraged to specify a lang attribute on the root
html element, giving the document's language. This aids speech synthesis tools to
determine what pronunciations to use, translation tools to determine what rules to use, and so
forth. The manifest attribute gives the address of
the document's application cache manifest, if there is one. If the attribute is present,
the attribute's value must be a valid non-empty URL potentially surrounded by
spaces. The manifest attribute only has an effect during the early stages of document load.
Changing the attribute dynamically thus has no effect (and thus, no DOM API is provided for this
attribute). For the purposes of application cache
selection, later base elements cannot affect the resolving of relative URLs in manifest
attributes, as the attributes are processed before those elements are seen. The window.applicationCache IDL
attribute provides scripted access to the offline application cache mechanism. The html element in the following example declares that the document's language
is English.

http://developers.whatwg.org/semantics.html[4/16/2014 9:27:48 PM]

4 The elements of HTML HTML: The Living Standard - Edition for Web Developers

<!DOCTYPE html> <html lang="en"> <head> <title>Swapping Songs</title> </head> <body> <h1>Swapping Songs</h1> <p>Tonight I swapped some of the songs I wrote with some friends, who gave me some of the songs they wrote. I love sharing my music.</p> </body> </html>

Document metadata

The head element


Categories: None. Contexts in which this element can be used: As the first element in an html element. Content model: If the document is an iframe srcdoc document or if title information is available from a higher-level protocol: Zero or more elements of metadata content, of which no more than one is a title element and no more than one is a base element. Otherwise: One or more elements of metadata content, of which exactly one is a title element and no more than one is a base element. Tag omission in text/html: A head element's start tag can be omitted if
the element is empty, or if the first thing inside the head element is an
element. A head element's end tag can be omitted if the
head element is not immediately followed by a space character or a comment. Content attributes:

http://developers.whatwg.org/semantics.html[4/16/2014 9:27:48 PM]

4 The elements of HTML HTML: The Living Standard - Edition for Web Developers

Global attributes DOM interface: The head element represents a collection of metadata for the
Document. The collection of metadata in a head element can be large or small. Here is an
example of a very short one: <!doctype html> <html> <head> <title>A document with a short head</title> </head> <body> ... Here is an example of a longer one: <!DOCTYPE HTML> <HTML> <HEAD> <META CHARSET="UTF-8"> <BASE HREF="http://www.example.com/"> <TITLE>An application with a long head</TITLE> <LINK REL="STYLESHEET" HREF="default.css"> <LINK REL="STYLESHEET ALTERNATE" HREF="big.css" TITLE="Big Text"> <SCRIPT SRC="support.js"></SCRIPT> <META NAME="APPLICATION-NAME" CONTENT="Long headed application"> </HEAD> <BODY> ... The title element is a required child in most situations, but when a
higherlevel protocol provides title information, e.g. in the Subject line of an e-mail when HTML
is used as an e-mail authoring format, the title element can be omitted.

http://developers.whatwg.org/semantics.html[4/16/2014 9:27:48 PM]

4 The elements of HTML HTML: The Living Standard - Edition for Web Developers

The title element


Categories: Metadata content. Contexts in which this element can be used: In a head element containing no other title elements. Content model: Text that is not inter-element whitespace. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes DOM interface: The title element represents the document's title or name. Authors
should use titles that identify their documents even when they are used out of context, for
example in a user's history or bookmarks, or in search results. The document's title is often
different from its first heading, since the first heading does not have to stand alone when taken
out of context. There must be no more than one title element per document. If it's reasonable for the Document to have no title, then the
title element is probably not required. See the head element's content
model for a description of when the element is required. title . text [ = value ] Returns the contents of the element, ignoring child nodes that aren't Text nodes. Can be set, to replace the element's children with the given value. Here are some examples of appropriate titles, contrasted with the top-level headings that
might be used on those same pages. <title>Introduction to The Mating Rituals of Bees</title> ... <h1>Introduction</h1> <p>This companion guide to the highly successful
http://developers.whatwg.org/semantics.html[4/16/2014 9:27:48 PM]

4 The elements of HTML HTML: The Living Standard - Edition for Web Developers

<cite>Introduction to Medieval Bee-Keeping</cite> book is... The next page might be a part of the same site. Note how the title describes the subject
matter unambiguously, while the first heading assumes the reader knows what the context is and
therefore won't wonder if the dances are Salsa or Waltz: <title>Dances used during bee mating rituals</title> ... <h1>The Dances</h1> The string to use as the document's title is given by the document.title IDL attribute.

The base element


Categories: Metadata content. Contexts in which this element can be used: In a head element containing no other base elements. Content model: Empty. Tag omission in text/html: No end tag. Content attributes: Global attributes href Document base URL target Default browsing context for hyperlink navigation and form submission DOM interface: The base element allows authors to specify the document base URL for
the purposes of resolving relative URLs, and the name of the
default browsing context for the purposes of following hyperlinks. The
element does not represent any content beyond this
information.

http://developers.whatwg.org/semantics.html[4/16/2014 9:27:48 PM]

4 The elements of HTML HTML: The Living Standard - Edition for Web Developers

There must be no more than one base element per document. A base element must have either an href
attribute, a target attribute, or both. The href content attribute, if specified, must
contain a valid URL potentially surrounded by spaces. A base element, if it has an href attribute,
must come before any other elements in the tree that have attributes defined as taking URLs, except the html element (its manifest attribute isn't affected by base
elements). The target attribute, if specified, must
contain a valid browsing context name or keyword, which specifies which
browsing context is to be used as the default when hyperlinks and forms in the
Document cause navigation. A base element, if it has a target
attribute, must come before any elements in the tree that represent hyperlinks. In this example, a base element is used to set the document base
URL: <!DOCTYPE html> <html> <head> <title>This is an example for the &lt;base&gt; element</title> <base href="http://www.example.com/news/index.html"> </head> <body> <p>Visit the <a href="archives.html">archives</a>. </p> </body> </html> The link in the above example would be a link to " http://www.example.com/news/archives.html ".

The link element


Categories: Metadata content.

http://developers.whatwg.org/semantics.html[4/16/2014 9:27:48 PM]

4 The elements of HTML HTML: The Living Standard - Edition for Web Developers

If the itemprop attribute is present: flow content. If the itemprop attribute is present: phrasing content. Contexts in which this element can be used: Where metadata content is expected. In a noscript element that is a child of a head element. If the itemprop attribute is present: where phrasing content is expected. Content model: Empty. Tag omission in text/html: No end tag. Content attributes: Global attributes href Address of the hyperlink crossorigin How the element handles crossorigin requests rel Relationship between the document containing the hyperlink and the destination resource media Applicable media hreflang Language of the linked resource type Hint for the type of the referenced resource sizes Sizes of the icons (for rel="icon") Also, the title attribute has special semantics on this element. Title of the link Alternative style sheet set name DOM interface: The link element allows authors to link their document to other resources. The destination of the link(s) is given by the href attribute, which must be present and must contain a
valid non-empty URL potentially surrounded by spaces. A link element must have either a rel attribute
or an itemprop attribute, but not both. If the rel attribute is used, the element is
restricted to the head element. When used with the itemprop attribute, the element can be used both in the head element and in the body of the page, subject to the constraints of
the
http://developers.whatwg.org/semantics.html[4/16/2014 9:27:48 PM]

4 The elements of HTML HTML: The Living Standard - Edition for Web Developers

microdata model. The types of link indicated (the relationships) are given by the value of the rel attribute, which, if present, must have a value that
is a set of space-separated tokens. The allowed keywords and
their meanings are defined in a later section. Two categories of links can be created using the link element: Links to external resources and hyperlinks. The link types section defines
whether a particular link type is an external resource or a hyperlink. One link
element can create multiple links (of which some might be external resource links and some might
be hyperlinks); exactly which and how many links are created depends on the keywords given in the
rel attribute. User agents must process the links on a per-link
basis, not a per-element basis. Each link created for a link element is handled separately. For
instance, if there are two link elements with rel="stylesheet",
they each count as a separate external resource, and each is affected by its own attributes independently. Similarly, if a single link element has a rel attribute with the value next stylesheet,
it creates both a hyperlink (for the next keyword) and
an external resource link (for the stylesheet
keyword), and they are affected by other attributes (such as media or title )
differently. For example, the following link element creates two hyperlinks (to the same page): <link rel="author license" href="/about"> The two links created by this element are one whose semantic is that the target page has
information about the current page's author, and one whose semantic is that the target page has
information regarding the license under which the current page is provided. The crossorigin attribute is a CORS
settings attribute. It is intended for use with external resource links. The exact behavior for links to external resources depends on the exact relationship, as
defined for the relevant link type. Some of the attributes control whether or not the external
resource is to be applied (as defined below). Hyperlinks created with the link element and its rel attribute apply to the

http://developers.whatwg.org/semantics.html[4/16/2014 9:27:48 PM]

4 The elements of HTML HTML: The Living Standard - Edition for Web Developers

whole page. This contrasts with the rel attribute of a and area elements, which indicates the type of a link whose context is given by the link's location within the
document. The media attribute says which media the
resource applies to. The value must be a valid media query. The default, if the media attribute is
omitted, is "all ", meaning that by default links apply to all media. The hreflang attribute on the
link element has the same semantics as the hreflang attribute on a and
area elements. The type attribute gives the MIME
type of the linked resource. It is purely advisory. The value must be a valid MIME
type. For external resource links, the type attribute is used as a hint to user agents so that they can
avoid fetching resources they do not support. The title attribute gives the title of the
link. With one exception, it is purely advisory. The value is text. The exception is for style
sheet links, where the title attribute defines
alternative style sheet sets. The title attribute on link
elements differs from the global title attribute of most other
elements in that a link without a title does not inherit the title of the parent element: it
merely has no title. The sizes attribute is used with the icon link type. The attribute must not be specified on link
elements that do not have a rel attribute that specifies the icon keyword. The IDL attribute disabled only applies to
style sheet links. When the link element defines a style sheet link, then the disabled attribute behaves as defined for the alternative style sheets DOM. For all other
link elements it always return false and does nothing on setting. The LinkStyle interface is also implemented by this element; the styling processing model defines how. Here, a set of link elements provide some style sheets: <!-- a persistent style sheet --> <link rel="stylesheet" href="default.css">

http://developers.whatwg.org/semantics.html[4/16/2014 9:27:48 PM]

4 The elements of HTML HTML: The Living Standard - Edition for Web Developers

<!-- the preferred alternate style sheet --> <link rel="stylesheet" href="green.css" title="Green styles"> <!-- some alternate style sheets --> <link rel="alternate stylesheet" href="contrast.css" title="High contrast"> <link rel="alternate stylesheet" href="big.css" title="Big fonts"> <link rel="alternate stylesheet" href="wide.css" title="Wide screen"> The following example shows how you can specify versions of the page that use alternative
formats, are aimed at other languages, and that are intended for other media: <link rel=alternate href="/en/html" hreflang=en type=text/html title="English HTML"> <link rel=alternate href="/fr/html" hreflang=fr type=text/html title="French HTML"> <link rel=alternate href="/en/html/print" hreflang=en type=text/html media=print title="English HTML (for printing)"> <link rel=alternate href="/fr/html/print" hreflang=fr type=text/html media=print title="French HTML (for printing)"> <link rel=alternate href="/en/pdf" hreflang=en type=application/pdf title="English PDF"> <link rel=alternate href="/fr/pdf" hreflang=fr type=application/pdf title="French PDF">

The meta element


Categories: Metadata content. If the itemprop attribute is present: flow content. If the itemprop attribute is present: phrasing content. Contexts in which this element can be used: If the charset attribute is present, or if the element's http-equiv attribute is

http://developers.whatwg.org/semantics.html[4/16/2014 9:27:48 PM]

4 The elements of HTML HTML: The Living Standard - Edition for Web Developers

in the Encoding declaration state: in a head element. If the http-equiv attribute is present but not in the Encoding declaration state: in a head element. If the http-equiv attribute is present but not in the Encoding declaration state: in a noscript element that is a child of a head element. If the name attribute is present: where metadata content is expected. If the itemprop attribute is present: where metadata content is expected. If the itemprop attribute is present: where phrasing content is expected. Content model: Empty. Tag omission in text/html: No end tag. Content attributes: Global attributes name Metadata name http-equiv Pragma directive content Value of the element charset Character encoding declaration DOM interface: The meta element represents various kinds of metadata that cannot be expressed using the title , base, link, style ,
and script elements. The meta element can represent document-level metadata with the name attribute, pragma directives with the http-equiv attribute, and the file's character encoding
declaration when an HTML document is serialized to string form (e.g. for transmission over
the network or for disk storage) with the charset
attribute. Exactly one of the name, http-equiv , charset,
and itemprop attributes must be specified. If either name, http-equiv, or itemprop is
specified, then the content attribute must also be
specified. Otherwise, it must be omitted. The charset attribute specifies the character
encoding used by the document. This is a character encoding declaration. If the
attribute is present in an XML

http://developers.whatwg.org/semantics.html[4/16/2014 9:27:48 PM]

4 The elements of HTML HTML: The Living Standard - Edition for Web Developers

document, its value must be an


ASCII case-insensitive match for the string " UTF-8 " (and the
document is therefore forced to use UTF-8 as its encoding). The charset attribute on the
meta element has no effect in XML documents, and is only allowed in order to
facilitate migration to and from XHTML. There must not be more than one meta element with a charset attribute per document. The content attribute gives the value of the
document metadata or pragma directive when the element is used for those purposes. The allowed
values depend on the exact context, as described in subsequent sections of this specification. If a meta element has a name
attribute, it sets document metadata. Document metadata is expressed in terms of name-value pairs,
the name attribute on the meta element giving the
name, and the content attribute on the same element giving
the value. The name specifies what aspect of metadata is being set; valid names and the meaning of
their values are described in the following sections. If a meta element has no content attribute, then the value part of the metadata name-value
pair is the empty string.

Standard metadata names


This specification defines a few names for the name
attribute of the meta element. Names are case-insensitive. application-name The value must be a short free-form string giving the name of the Web application that the
page represents. If the page is not a Web application, the application-name metadata name must not be used. There must
not be more than one meta element with its name
attribute set to the value application-name per
document. author The value must be a free-form string giving the name of one of the page's authors. description

http://developers.whatwg.org/semantics.html[4/16/2014 9:27:48 PM]

4 The elements of HTML HTML: The Living Standard - Edition for Web Developers

The value must be a free-form string that describes the page. The value must be
appropriate for use in a directory of pages, e.g. in a search engine. There must not be more than
one meta element with its name attribute set to
the value description per document. generator The value must be a free-form string that identifies one of the software packages used to
generate the document. This value must not be used on pages whose markup is not generated by
software, e.g. pages whose markup was written by a user in a text editor. Here is what a tool called "Frontweaver" could include in its output, in the page's
head element, to identify itself as the tool used to generate the page: <meta name=generator content="Frontweaver 8.2"> keywords The value must be a set of comma-separated tokens, each of which is a keyword
relevant to the page. This page about typefaces on British motorways uses a meta element to specify
some keywords that users might use to look for the page: <!DOCTYPE HTML> <html> <head> <title>Typefaces on UK motorways</title> <meta name="keywords" content="british,type face,font,fonts,highway,highways"> </head> <body> ... Many search engines do not consider such keywords, because this feature has
historically been used unreliably and even misleadingly as a way to spam search engine results
in a way that is not helpful for users.

Other metadata names


Extensions to the predefined set of metadata names
may be registered in the WHATWG Wiki
MetaExtensions page.

http://developers.whatwg.org/semantics.html[4/16/2014 9:27:48 PM]

4 The elements of HTML HTML: The Living Standard - Edition for Web Developers

Anyone is free to edit the WHATWG Wiki MetaExtensions page at any time to add a type. These new
names must be specified with the following information: Keyword The actual name being defined. The name should not be confusingly similar to any other
defined name (e.g. differing only in case). Brief description A short non-normative description of what the metadata name's meaning is, including the
format the value is required to be in. Specification A link to a more detailed description of the metadata name's semantics and requirements. It
could be another page on the Wiki, or a link to an external page. Synonyms A list of other names that have exactly the same processing requirements. Authors should
not use the names defined to be synonyms, they are only intended to allow user agents to support
legacy content. Anyone may remove synonyms that are not used in practice; only names that need to
be processed as synonyms for compatibility with legacy content are to be registered in this way. Status One of the following: Proposed The name has not received wide peer review and approval. Someone has proposed it and is, or
soon will be, using it. Ratified The name has received wide peer review and approval. It has a specification that
unambiguously defines how to handle pages that use the name, including when they use it in
incorrect ways. Discontinued The metadata name has received wide peer review and it has been found wanting. Existing
pages are using this metadata name, but new pages should avoid it. The "brief description" and
"specification" entries will give details of what authors should use instead, if anything.

http://developers.whatwg.org/semantics.html[4/16/2014 9:27:48 PM]

4 The elements of HTML HTML: The Living Standard - Edition for Web Developers

If a metadata name is found to be redundant with existing values, it should be removed and
listed as a synonym for the existing value. If a metadata name is registered in the "proposed" state for a period of a month or more
without being used or specified, then it may be removed from the registry. If a metadata name is added with the "proposed" status and found to be redundant with
existing values, it should be removed and listed as a synonym for the existing value. If a
metadata name is added with the "proposed" status and found to be harmful, then it should be
changed to "discontinued" status. Anyone can change the status at any time, but should only do so in accordance with the
definitions above. Metadata names whose values are to be URLs must not be proposed or accepted. Links must be represented using the link element, not the meta element.

Pragma directives
When the http-equiv attribute is specified
on a meta element, the element is a pragma directive. The http-equiv attribute is an enumerated
attribute. The following table lists the keywords defined for this attribute. The states
given in the first cell of the rows with keywords give the states to which those keywords map. State Encoding declaration Default style Refresh Keyword content-type default-style refresh Notes

Encoding declaration state (http-equiv="content-type" ) The Encoding declaration state is just


an alternative form of setting the charset attribute: it is a
character encoding declaration. For meta elements with an http-equiv
attribute in the Encoding declaration state, the content attribute must have a value
that is an ASCII case-

http://developers.whatwg.org/semantics.html[4/16/2014 9:27:48 PM]

4 The elements of HTML HTML: The Living Standard - Edition for Web Developers

insensitive match for a string that consists of: the literal


string "text/html;", optionally followed by any number of space characters, followed by the literal string "charset=", followed by one of the labels of
the character encoding of the character encoding
declaration. A document must not contain both a meta element with an http-equiv attribute in the Encoding declaration state and a
meta element with the charset attribute
present. The Encoding declaration state may be
used in HTML documents, but elements with an http-equiv attribute in that state must not be used in
XML documents. Default style state (http-equiv="default-style") This pragma sets the name of the default alternative style sheet set. Refresh state (http-equiv="refresh") This pragma acts as timed redirect. For meta elements with an http-equiv
attribute in the Refresh state, the content attribute must have a value consisting either of:

just a valid non-negative integer, or a valid non-negative integer, followed by a U+003B SEMICOLON character
(;), followed by one or more space characters, followed
by a substring that is an ASCII case-insensitive match for the string " URL", followed by a U+003D EQUALS SIGN character (=), followed by a valid
URL that does not start with a literal U+0027 APOSTROPHE (') or U+0022 QUOTATION MARK
(") character. In the former case, the integer represents a number of seconds before the page is to be
reloaded; in the latter case the integer represents a number of seconds before the page is to be
replaced by the page at the given URL. A news organization's front page could include the following markup in the page's
head element, to ensure that the page automatically reloads from the server every
five minutes: <meta http-equiv="Refresh" content="300"> A sequence of pages could be used as an automated slide show by making each page refresh to
the next page in the sequence, using markup such as the following:

http://developers.whatwg.org/semantics.html[4/16/2014 9:27:48 PM]

4 The elements of HTML HTML: The Living Standard - Edition for Web Developers

<meta http-equiv="Refresh" content="20; URL=page4.html">

There must not be more than one meta element with any particular state in the
document at a time.

Other pragma directives


Extensions to the predefined set of pragma
directives may, under certain conditions, be registered in the WHATWG Wiki PragmaExtensions page. [WHATWGWIKI] Such extensions must use a name that is identical to an HTTP header registered in the Permanent
Message Header Field Registry, and must have behavior identical to that described for the HTTP
header. Pragma directives corresponding to headers describing metadata, or not requiring specific user
agent processing, must not be registered; instead, use metadata names. Pragma directives corresponding to headers
that affect the HTTP processing model (e.g. caching) must not be registered, as they would result
in HTTP-level behavior being different for user agents that implement HTML than for user agents
that do not. Anyone is free to edit the WHATWG Wiki PragmaExtensions page at any time to add a pragma
directive satisfying these conditions. Such registrations must specify the following
information: Keyword The actual name being defined. The name must match a previously-registered HTTP name with
the same requirements. Brief description A short non-normative description of the purpose of the pragma directive. Specification A link to the specification defining the corresponding HTTP header.

Specifying the document's character encoding


A character encoding declaration is a mechanism by which the character

http://developers.whatwg.org/semantics.html[4/16/2014 9:27:48 PM]

4 The elements of HTML HTML: The Living Standard - Edition for Web Developers

encoding used to store or transmit a document is specified. The following restrictions apply to character
encoding declarations:

The character encoding name given must be an ASCII case-insensitive match


for
one of the labels of the character
encoding used to serialize the file.

The character encoding declaration must be serialized without the use of


character references or character escapes of any kind.

The element containing the character encoding


declaration must be serialized
completely within the first 1024 bytes of the
document. In addition, due to a number of restrictions on meta elements, there can only be
one meta-based character encoding declaration per document. If an HTML document does not start with a BOM, and its
encoding is not explicitly given by Content-Type
metadata, and the document is not an iframe srcdoc document, then the character encoding used must be
an ASCII-compatible character encoding, and the encoding must be specified using a
meta element with a charset attribute or a
meta element with an http-equiv attribute
in the Encoding declaration state. A character encoding declaration is required (either in the Content-Type metadata or explicitly in the file) even if the encoding
is US-ASCII, because a character encoding is needed to process non-ASCII characters entered by the
user in forms, in URLs generated by scripts, and so forth. If the document is an iframe srcdoc
document, the document must not have a character encoding declaration. (In
this case, the source is already decoded, since it is part of the document that contained the
iframe.) If an HTML document contains a meta element
with a charset attribute or a meta element
with an http-equiv attribute in the Encoding declaration state, then the character
encoding used must be an ASCII-compatible character encoding. Authors should use UTF-8. Conformance checkers may advise authors against using legacy
encodings. Encodings in which a series of bytes in the range 0x20 to 0x7E can encode characters other than
the corresponding characters in the range U+0020 to U+007E represent a potential security
vulnerability: a user agent that does not support the encoding (or does not support the label used
to declare the encoding, or does not use the same mechanism to detect the encoding of

http://developers.whatwg.org/semantics.html[4/16/2014 9:27:48 PM]

4 The elements of HTML HTML: The Living Standard - Edition for Web Developers

unlabeled
content as another user agent) might end up interpreting technically benign plain text content as
HTML tags and JavaScript. Authors should therefore not use these encodings. For example, this
applies to encodings in which the bytes corresponding to "<script>" in
ASCII can encode a different string. Authors should not use such encodings, which are known to
include JIS_C6226-1983, JIS_X0212-1990,
HZ-GB-2312, JOHAB (Windows code page 1361), encodings based on
ISO-2022, and encodings based on EBCDIC. Furthermore, authors must not use the CESU-8, UTF-7, BOCU-1 and SCSU encodings,
which also fall into this category; these encodings were never intended for use for Web content. Authors should not use UTF-32, as the encoding detection algorithms described in this
specification intentionally do not distinguish it from UTF-16. Using non-UTF-8 encodings can have unexpected results on form submission and URL
encodings, which use the document's character encoding by default. In XHTML, the XML declaration should be used for inline character encoding information, if
necessary. In HTML, to declare that the character encoding is UTF-8, the author could include the
following markup near the top of the document (in the head element): <meta charset="utf-8"> In XML, the XML declaration would be used instead, at the very top of the markup: <?xml version="1.0" encoding="utf-8"?>

The style element


Categories: Metadata content. If the scoped attribute is present: flow content. Contexts in which this element can be used: If the scoped attribute is absent: where metadata content is expected.

http://developers.whatwg.org/semantics.html[4/16/2014 9:27:48 PM]

4 The elements of HTML HTML: The Living Standard - Edition for Web Developers

If the scoped attribute is absent: in a noscript element that is a child of a head element. If the scoped attribute is present: where flow content is expected, but before any other flow content other than inter-element whitespace and style elements, and not as the child of an element whose content model is transparent. Content model: Depends on the value of the type attribute, but must match requirements described in prose below. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes media Applicable media type Type of embedded resource scoped Whether the styles apply to the entire document or just the parent subtree Also, the title attribute has special semantics on this element. Alternative style sheet set name DOM interface: The style element allows authors to embed style information in their documents.
The style element is one of several inputs to the styling processing
model. The element does not represent content for the
user. The type attribute gives the styling language.
If the attribute is present, its value must be a valid MIME type that designates a
styling language. The charset parameter must not be specified. The default
value for the type attribute, which is used if the attribute
is absent, is "text/css". The media attribute says which media the
styles apply to. The value must be a valid media query. The default, if the media
attribute is omitted, is "all ", meaning that by default styles apply to all
media. The scoped attribute is a boolean
attribute. If present, it indicates that the styles are intended just for the subtree
rooted at the style element's parent

http://developers.whatwg.org/semantics.html[4/16/2014 9:27:48 PM]

4 The elements of HTML HTML: The Living Standard - Edition for Web Developers

element, as opposed to the whole


Document. If the scoped attribute is present and the element has a
parent element, then the style element must precede any flow content in
its parent element other than inter-element whitespace and other style
elements, and the parent element's content model must not have a transparent
component. This implies that scoped style elements cannot be children of, e.g.,
a or ins elements, even when those are used as flow content
containers. A style element without a scoped attribute is restricted to appearing in the head of the document. The title attribute on
style elements defines alternative style sheet sets. If the
style element has no title attribute, then it
has no title; the title attribute of ancestors does not apply to
the style element. [CSSOM] The title attribute on style
elements, like the title attribute on link elements, differs from the global title attribute in that a
style block without a title does not inherit the title of the parent element: it
merely has no title. The textContent of a style element must match the style production in the following ABNF, the character set for which is Unicode. style start ) no-c-start c-start no-c-end c-end = < any string that doesn't contain a substring = "<!--" = < any string that doesn't contain a substring = "-->" that matches c-start > = no-c-start *( c-start no-c-end c-end no-c-

that matches c-end >

This specification does not specify a style system, but CSS is expected to be supported by most Web browsers. The disabled IDL attribute behaves as
defined for the alternative style sheets DOM. The LinkStyle interface is also implemented by this element; the styling processing model defines how. [CSSOM]

http://developers.whatwg.org/semantics.html[4/16/2014 9:27:48 PM]

4 The elements of HTML HTML: The Living Standard - Edition for Web Developers

The following document has its stress emphasis styled as bright red text rather than italics
text, while leaving titles of works and Latin words in their default italics. It shows how using
appropriate elements enables easier restyling of documents. <!DOCTYPE html> <html lang="en-US"> <head> <title>My favorite book</title> <style> body { color: black; background: white; } em { font-style: normal; color: red; } </style> </head> <body> <p>My <em>favorite</em> book of all time has <em>got</em> to be <cite>A Cat's Life</cite>. It is a book by P. Rahmel that talks about the <i lang="la">Felis Catus</i> in modern human society.</p> </body> </html>

Styling
The link and style elements can provide styling information for the
user agent to use when rendering the document. The CSS and CSSOM specifications specify what
styling information is to be used by the user agent and how it is to be used. [CSS] [CSSOM] The style and link elements implement the LinkStyle
interface. [CSSOM]

Up next

4.3 Sections

This document is a work in progress, if you spot something that you feel isn't quite right,

http://developers.whatwg.org/semantics.html[4/16/2014 9:27:48 PM]

4 The elements of HTML HTML: The Living Standard - Edition for Web Developers

please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/semantics.html[4/16/2014 9:27:48 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
Sections
The body element
The article element
The section element
The nav element
The aside element
The h1 , h2 , h3, h4, h5, and
h6 elements
The hgroup element
The header element
The footer element
The address element
Headings and sections
Creating an outline
Sample outlines
Usage summary
Article or section?

Sections

The body element


Categories: Sectioning root. Contexts in which this element can be used: As the second element in an html element. Content model: Flow content.
http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

Tag omission in text/html: A body element's start tag can be omitted if


the element is empty, or if the first thing inside the body element is not a
space character or a comment, except if the
first thing inside the body element is a meta, link, script , style , or template
element. A body element's end tag can be omitted if the
body element is not immediately followed by a comment. Content attributes: Global attributes onafterprint onbeforeprint onbeforeunload onhashchange onmessage onoffline ononline onpagehide onpageshow onpopstate onresize onstorage onunload DOM interface: The body element represents the main content of the document. In conforming documents, there is only one body element. The document.body IDL attribute provides scripts with easy access to
a document's body element. The body element exposes as event handler content attributes a number
of the event handlers of the Window object. It also mirrors their
event handler IDL attributes. The onblur, onerror,
onfocus, onload, and
onscroll event handlers of the

http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

Window object, exposed on the body element, replace the generic


event handlers with the same names normally supported by HTML
elements. Thus, for example, a bubbling error event
dispatched on a child of the body element of a Document would first
trigger the onerror event handler content
attributes of that element, then that of the root html element, and only
then would it trigger the onerror event handler content attribute on the body element. This is because the event would bubble from the target, to the body, to the
html, to the Document, to the Window, and the event handler on the body is watching the
Window not the body. A regular event listener attached to the
body using addEventListener() , however, would be run when the event bubbled through the body and not when it reaches the Window
object. This page updates an indicator to show whether or not the user is online: <!DOCTYPE HTML> <html> <head> <title>Online or offline?</title> <script> function update(online) { document.getElementById('status').textContent = online ? 'Online' : 'Offline'; } </script> </head> <body ononline="update(true)" onoffline="update(false)" onload="update(navigator.onLine)"> <p>You are: <span id="status">(Unknown)</span></p> </body> </html>

The article element


Categories: Flow content. Sectioning content. Palpable content.
http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

Contexts in which this element can be used: Where flow content is expected. Content model: Flow content. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes DOM interface: Uses HTMLElement. The article element represents a complete, or self-contained,
composition in a document, page, application, or site and that is, in principle, independently distributable or reusable, e.g. in syndication. This could be a forum post, a magazine or
newspaper article, a blog entry, a user-submitted comment, an interactive widget or gadget, or any
other independent item of content. When article elements are nested, the inner article elements
represent articles that are in principle related to the contents of the outer article. For instance, a blog entry on a site that accepts user-submitted comments could represent the comments
as article elements nested within the article element for the blog
entry. Author information associated with an article element (q.v. the
address element) does not apply to nested article elements. When used specifically with content to be redistributed in syndication, the article element is similar in purpose to the entry element in
Atom. The schema.org microdata vocabulary can be used to provide the publication date
for an article element, using one of the CreativeWork subtypes. When the main content of the page (i.e. excluding footers, headers, navigation blocks, and
sidebars) is all one single self-contained composition, that content may be marked with an
article, but it is technically redundant in that case (since it's self-evident that
the page is a single composition, as it is a single document). This example shows a blog post using the article element, with some schema.org
annotations:
http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

<article itemscope itemtype="http://schema.org/BlogPosting"> <header> <h1 itemprop="headline">The Very First Rule of Life</h1> <p><time itemprop="datePublished" datetime="2009-10-09">3 days ago</time></p> <link itemprop="url" href="?comments=0"> </header> <p>If there's a microphone anywhere near you, assume it's hot and sending whatever you're saying to the world. Seriously.</p> <p>...</p> <footer> <a itemprop="discussionUrl" href="?comments=1">Show comments...</a> </footer> </article> Here is that same blog post, but showing some of the comments: <article itemscope itemtype="http://schema.org/BlogPosting"> <header> <h1 itemprop="headline">The Very First Rule of Life</h1> <p><time itemprop="datePublished" datetime="2009-10-09">3 days ago</time></p> <link itemprop="url" href="?comments=0"> </header> <p>If there's a microphone anywhere near you, assume it's hot and sending whatever you're saying to the world. Seriously.</p> <p>...</p> <section> <h1>Comments</h1> <article itemprop="comment" itemscope itemtype="http://schema.org/UserComments" id="c1"> <link itemprop="url" href="#c1"> <footer> <p>Posted by: <span itemprop="creator" itemscope itemtype="http://schema.org/Person"> <span itemprop="name">George Washington</span> </span></p>

http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

<p><time itemprop="commentTime" datetime="2009-10-10">15 minutes ago</time></p> </footer> <p>Yeah! Especially when talking about your lobbyist friends!</p> </article> <article itemprop="comment" itemscope itemtype="http://schema.org/UserComments" id="c2"> <link itemprop="url" href="#c2"> <footer> <p>Posted by: <span itemprop="creator" itemscope itemtype="http://schema.org/Person"> <span itemprop="name">George Hammond</span> </span></p> <p><time itemprop="commentTime" datetime="2009-10-10">5 minutes ago</time></p> </footer> <p>Hey, you have the same first name as me.</p> </article> </section> </article> Notice the use of footer to give the information for each comment (such as who
wrote it and when): the footer element can appear at the start of its section when appropriate, such as in this case. (Using header in this case wouldn't
be wrong either; it's mostly a matter of authoring preference.)

The section element


Categories: Flow content. Sectioning content. Palpable content. Contexts in which this element can be used: Where flow content is expected. Content model: Flow content.

http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes DOM interface: Uses HTMLElement. The section element represents a generic section of a document or application. A section, in this context, is a thematic grouping of content, typically with a
heading. Examples of sections would be chapters, the various tabbed pages in a tabbed
dialog box, or the numbered sections of a thesis. A Web site's home page could be split into
sections for an introduction, news items, and contact information. Authors are encouraged to use the article element instead of the
section element when it would make sense to syndicate the contents of the
element. The section element is not a generic
container element. When an element is needed only for styling purposes or as a convenience for
scripting, authors are encouraged to use the div element instead. A general rule is
that the section element is appropriate only if the element's contents would be
listed explicitly in the document's outline. In the following example, we see an article (part of a larger Web page) about apples,
containing two short sections. <article> <hgroup> <h1>Apples</h1> <h2>Tasty, delicious fruit!</h2> </hgroup> <p>The apple is the pomaceous fruit of the apple tree.</p> <section> <h1>Red Delicious</h1> <p>These bright red apples are the most common found in many supermarkets.</p> </section>

http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

<section> <h1>Granny Smith</h1> <p>These juicy, green apples make a great filling for apple pies.</p> </section> </article> Notice how the use of section means that the author can use h1
elements throughout, without having to worry about whether a particular section is at the top
level, the second level, the third level, and so on. Here is a graduation programme with two sections, one for the list of people graduating, and
one for the description of the ceremony. (The markup in this example features an uncommon style
sometimes used to minimize the amount of inter-element whitespace.) <!DOCTYPE Html> <Html ><Head ><Title >Graduation Ceremony Summer 2022</Title ></Head ><Body ><H1 >Graduation</H1 ><Section ><H1 >Ceremony</H1 ><P >Opening Procession</P ><P >Speech by Validactorian</P ><P >Speech by Class President</P ><P >Presentation of Diplomas</P ><P >Closing Speech by Headmaster</P ></Section ><Section ><H1

http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

>Graduates</H1 ><Ul ><Li >Molly Carpenter</Li ><Li >Anastasia Luccio</Li ><Li >Ebenezar McCoy</Li ><Li >Karrin Murphy</Li ><Li >Thomas Raith</Li ><Li >Susan Rodriguez</Li ></Ul ></Section ></Body ></Html> In this example, a book author has marked up some sections as chapters and some as appendices,
and uses CSS to style the headers in these two classes of section differently. The whole book is
wrapped in an article element as part of an even larger document containing other
books. <article class="book"> <style> section { border: double medium; margin: 2em; } section.chapter h1 { font: 2em Roboto, Helvetica Neue, sans-serif; } section.appendix h1 { font: small-caps 2em Roboto, Helvetica Neue, sans-serif; } </style> <header> <hgroup> <h1>My Book</h1> <h2>A sample with not much content</h2> </hgroup> <p><small>Published by Dummy Publicorp Ltd.</small></p> </header> <section class="chapter"> <h1>My First Chapter</h1>
http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

<p>This is the first of my chapters. It doesn't say much. </p> <p>But it has two paragraphs!</p> </section> <section class="chapter"> <h1>It Continutes: The Second Chapter</h1> <p>Bla dee bla, dee bla dee bla. Boom.</p> </section> <section class="chapter"> <h1>Chapter Three: A Further Example</h1> <p>It's not like a battle between brightness and earthtones would go unnoticed.</p> <p>But it might ruin my story.</p> </section> <section class="appendix"> <h1>Appendix A: Overview of Examples</h1> <p>These are demonstrations.</p> </section> <section class="appendix"> <h1>Appendix B: Some Closing Remarks</h1> <p>Hopefully this long example shows that you <em>can</em> style sections, so long as they are used to indicate actual sections.</p> </section> </article>

The nav element


Categories: Flow content. Sectioning content. Palpable content. Contexts in which this element can be used: Where flow content is expected. Content model:

http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

Flow content, but with no main element descendants. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes DOM interface: Uses HTMLElement. The nav element represents a section of a page that links to other
pages or to parts within the page: a section with navigation links. Not all groups of links on a page need to be in a nav element
the element is primarily intended for sections that consist of major navigation blocks. In particular, it is common for footers to have a short list of links to various pages of a site,
such as the terms of service, the home page, and a copyright page. The footer element
alone is sufficient for such cases; while a nav element can be used in such cases, it
is usually unnecessary. User agents (such as screen readers) that are targeted at users who can benefit
from navigation information being omitted in the initial rendering, or who can benefit from
navigation information being immediately available, can use this element as a way to determine
what content on the page to initially skip or provide on request (or both). In the following example, the page has several places where links are present, but only one of
those places is considered a navigation section. <body itemscope itemtype="http://schema.org/Blog"> <header> <h1>Wake up sheeple!</h1> <p><a href="news.html">News</a> <a href="blog.html">Blog</a> <a href="forums.html">Forums</a></p> <p>Last Modified: <span itemprop="dateModified">2009-0401</span></p> <nav> <h1>Navigation</h1> <ul> <li><a href="articles.html">Index of all articles</a> </li>

http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

<li><a href="today.html">Things sheeple need to wake up for today</a></li> <li><a href="successes.html">Sheeple we have managed to wake</a></li> </ul> </nav> </header> <main> <article itemprop="blogPosts" itemscope itemtype="http://schema.org/BlogPosting"> <header> <h1 itemprop="headline">My Day at the Beach</h1> </header> <main itemprop="articleBody"> <p>Today I went to the beach and had a lot of fun.</p> ...more content... </main> <footer> <p>Posted <time itemprop="datePublished" datetime="200910-10">Thursday</time>.</p> </footer> </article> ...more blog posts... </main> <footer> <p>Copyright <span itemprop="copyrightYear">2010</span> <span itemprop="copyrightHolder">The Example Company</span> </p> <p><a href="about.html">About</a> <a href="policy.html">Privacy Policy</a> <a href="contact.html">Contact Us</a></p> </footer> </body> Notice the main elements being used to wrap all the contents of the page other
than the header and footer, and all the contents of the blog entry other than its header and
footer. You can also see microdata annotations in the above example that use the

http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

schema.org vocabulary
to provide the publication date and other metadata about the blog post. In the following example, there are two nav elements, one for primary navigation
around the site, and one for secondary navigation around the page itself. <body> <h1>The Wiki Center Of Exampland</h1> <nav> <ul> <li><a href="/">Home</a></li> <li><a href="/events">Current Events</a></li> ...more... </ul> </nav> <article> <header> <h1>Demos in Exampland</h1> <p>Written by A. N. Other.</p> </header> <nav> <ul> <li><a href="#public">Public demonstrations</a></li> <li><a href="#destroy">Demolitions</a></li> ...more... </ul> </nav> <div> <section id="public"> <h1>Public demonstrations</h1> <p>...more...</p> </section> <section id="destroy"> <h1>Demolitions</h1> <p>...more...</p> </section> ...more... </div> <footer> <p><a href="?edit">Edit</a> | <a href="?delete">Delete</a>

http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

| <a href="?Rename">Rename</a></p> </footer> </article> <footer> <p><small> copyright 1998 Exampland Emperor</small></p> </footer> </body> A nav element doesn't have to contain a list, it can contain other kinds of content as well. In this navigation block, links are provided in prose: <nav> <h1>Navigation</h1> <p>You are on my home page. To the north lies <a href="/blog">my blog</a>, from whence the sounds of battle can be heard. To the east you can see a large mountain, upon which many <a href="/school">school papers</a> are littered. Far up thus mountain you can spy a little figure who appears to be me, desperately scribbling a <a href="/school/thesis">thesis</a>.</p> <p>To the west are several exits. One fun-looking exit is labeled <a href="http://games.example.com/">"games"</a>. Another more boring-looking exit is labeled <a href="http://isp.example.net/">ISP</a>.</p> <p>To the south lies a dark and dank <a href="/about">contacts page</a>. Cobwebs cover its disused entrance, and at one point you see a rat run quickly out of the page.</p> </nav>

The aside element


Categories: Flow content.

http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

Sectioning content. Palpable content. Contexts in which this element can be used: Where flow content is expected. Content model: Flow content, but with no main element descendants. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes DOM interface: Uses HTMLElement. The aside element represents a section of a page that consists of
content that is tangentially related to the content around the aside element, and
which could be considered separate from that content. Such sections are often represented as
sidebars in printed typography. The element can be used for typographical effects like pull quotes or sidebars, for
advertising, for groups of nav elements, and for other content that is considered
separate from the main content of the page. It's not appropriate to use the aside element just for
parentheticals, since those are part of the main flow of the document. The following example shows how an aside is used to mark up background material on Switzerland
in a much longer news story on Europe. <aside> <h1>Switzerland</h1> <p>Switzerland, a land-locked country in the middle of geographic Europe, has not joined the geopolitical European Union, though it is a signatory to a number of European treaties.</p> </aside> The following example shows how an aside is used to mark up a pull quote in a longer
article.

http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

... <p>He later joined a large company, continuing on the same work. <q>I love my job. People ask me what I do for fun when I'm not at work. But I'm paid to do my hobby, so I never know what to answer. Some people wonder what they would do if they didn't have to work... but I know what I would do, because I was unemployed for a year, and I filled that time doing exactly what I do now.</q> </p> <aside> <q> People ask me what I do for fun when I'm not at work. But I'm paid to do my hobby, so I never know what to answer. </q> </aside> <p>Of course his work or should that be hobby? isn't his only passion. He also enjoys other pleasures.</p> ... The following extract shows how aside can be used for blogrolls and other side
content on a blog: <body> <header> <h1>My wonderful blog</h1> <p>My tagline</p> </header> <aside> <!-- this aside contains two sections that are tangentially related to the page, namely, links to other blogs, and links to blog posts from this blog --> <nav>

http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

<h1>My blogroll</h1> <ul> <li><a href="http://blog.example.com/">Example Blog</a> </ul> </nav> <nav> <h1>Archives</h1> <ol reversed> <li><a href="/last-post">My last post</a> <li><a href="/first-post">My first post</a> </ol> </nav> </aside> <aside> <!-- this aside is tangentially related to the page also, it contains twitter messages from the blog author --> <h1>Twitter Feed</h1> <blockquote cite="http://twitter.example.net/t31351234"> I'm on vacation, writing my blog. </blockquote> <blockquote cite="http://twitter.example.net/t31219752"> I'm going to go on vacation soon. </blockquote> </aside> <article> <!-- this is a blog post --> <h1>My last post</h1> <p>This is my last post.</p> <footer> <p><a href="/last-post" rel=bookmark>Permalink</a> </footer> </article> <article> <!-- this is also a blog post --> <h1>My first post</h1> <p>This is my first post.</p> <aside> <!-- this aside is about the blog post, since it's inside the

http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

<article> element; it would be wrong, for instance, to put the blogroll here, since the blogroll isn't really related to this post specifically, only to the page as a whole --> <h1>Posting</h1> <p>While I'm thinking about it, I wanted to say something about posting. Posting is fun!</p> </aside> <footer> <p><a href="/first-post" rel=bookmark>Permalink</a> </footer> </article> <footer> <nav> <a href="/archives">Archives</a> <a href="/about">About me</a> <a href="/copyright">Copyright</a> </nav> </footer> </body>

The h1, h2 , h3, h4 , h5, and


h6 elements
Categories: Flow content. Heading content. Palpable content. Contexts in which this element can be used: As a child of an hgroup element. Where flow content is expected. Content model: Phrasing content. Tag omission in text/html: Neither tag is omissible.

http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

Content attributes: Global attributes DOM interface: These elements represent headings for their sections. The semantics and meaning of these elements are defined in the section on headings and
sections. These elements have a rank given by the number in their name. The h1 element is said to have the highest rank, the h6 element has the lowest rank, and two
elements with the same name have equal rank. As far as their respective document outlines (their heading and section structures) are
concerned, these two snippets are semantically equivalent: <body> <h1>Let's call it a draw(ing surface)</h1> <h2>Diving in</h2> <h2>Simple shapes</h2> <h2>Canvas coordinates</h2> <h3>Canvas coordinates diagram</h3> <h2>Paths</h2> </body> <body> <h1>Let's call it a draw(ing surface)</h1> <section> <h1>Diving in</h1> </section> <section> <h1>Simple shapes</h1> </section> <section> <h1>Canvas coordinates</h1> <section> <h1>Canvas coordinates diagram</h1> </section> </section> <section> <h1>Paths</h1>

http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

</section> </body> Authors might prefer the former style for its terseness, or the latter style for its
convenience in the face of heavy editing; which is best is purely an issue of preferred authoring
style.

The hgroup element


Categories: Flow content. Heading content. Palpable content. Contexts in which this element can be used: Where flow content is expected. Content model: One or more h1 , h2, h3 , h4 , h5, h6 , and script-supporting elements. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes DOM interface: Uses HTMLElement. The hgroup element represents the heading of a section, which
consists of all the h1 h6 element children of the
hgroup element. The element is used to group a set of
h1h6 elements when the heading has multiple levels, such as subheadings, alternative titles, or taglines. The rank of an hgroup element is the rank of the highest-ranked
h1 h6 element descendant of the hgroup element, if
there are any such elements, or otherwise the same as for an h1 element (the highest
rank). Other elements of heading content in the hgroup element indicate
subheadings or subtitles. The section on headings and sections defines how hgroup elements are assigned to individual sections.

http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

Here are some examples of valid headings. <hgroup> <h1>The reality dysfunction</h1> <h2>Space is not the only void</h2> </hgroup> <hgroup> <h1>Dr. Strangelove</h1> <h2>Or: How I Learned to Stop Worrying and Love the Bomb</h2> </hgroup> The point of using hgroup in these examples is to mask the h2
element (which acts as a secondary title) from the outline algorithm. How a user agent exposes such multi-level headings in user interfaces (e.g. in tables of
contents or search results) is left open to implementors, as it is a user interface issue. The
first example above could be rendered as: The reality dysfunction: Space is not the only void Alternatively, it could look like this: The reality dysfunction (Space is not the only void) In interfaces where a title can be rendered on multiple lines, it could be rendered as
follows, maybe with the first line in a bigger font size: The reality dysfunction Space is not the only void

The header element


Categories: Flow content. Palpable content. Contexts in which this element can be used: Where flow content is expected. Content model:
http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

Flow content, but with no header , footer , or main element descendants. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes DOM interface: Uses HTMLElement. The header element represents a group of introductory or navigational
aids. A header element is intended to usually contain the section's heading
(an h1 h6 element or an hgroup element), but this is
not required. The header element can also be used to wrap a section's table of
contents, a search form, or any relevant logos. Here are some sample headers. This first one is for a game: <header> <p>Welcome to...</p> <h1>Voidwars!</h1> </header> The following snippet shows how the element can be used to mark
up a specification's header: <header> <hgroup> <h1>Scalable Vector Graphics (SVG) 1.2</h1> <h2>W3C Working Draft 27 October 2004</h2> </hgroup> <dl> <dt>This version:</dt> <dd><a href="http://www.w3.org/TR/2004/WD-SVG1220041027/">http://www.w3.org/TR/2004/WD-SVG12-20041027/</a> </dd> <dt>Previous version:</dt> <dd><a href="http://www.w3.org/TR/2004/WD-SVG1220040510/">http://www.w3.org/TR/2004/WD-SVG12-20040510/</a> </dd> <dt>Latest version of SVG 1.2:</dt>

http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

<dd><a href="http://www.w3.org/TR/SVG12/">http://www.w3.org/TR/SVG12 /</a></dd> <dt>Latest SVG Recommendation:</dt> <dd><a href="http://www.w3.org/TR/SVG/">http://www.w3.org/TR/SVG/</a ></dd> <dt>Editor:</dt> <dd>Dean Jackson, W3C, <a href="mailto:dean@w3.org">dean@w3.org</a></dd> <dt>Authors:</dt> <dd>See <a href="#authors">Author List</a></dd> </dl> <p class="copyright"><a href="http://www.w3.org/Consortium/Legal/ipr-notic ... </header> The header element is not sectioning content; it doesn't
introduce a new section. In this example, the page has a page heading given by the h1 element, and two
subsections whose headings are given by h2 elements. The content after the
header element is still part of the last subsection started in the
header element, because the header element doesn't take part in the
outline algorithm. <body> <header> <h1>Little Green Guys With Guns</h1> <nav> <ul> <li><a href="/games">Games</a> <li><a href="/forum">Forum</a> <li><a href="/download">Download</a> </ul> </nav> <h2>Important News</h2> <!-- this starts a second subsection --> <!-- this is part of the subsection entitled "Important News" --> <p>To play today's games you will need to update your
http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

client.</p> <h2>Games</h2> <!-- this starts a third subsection --> </header> <p>You have three active games:</p> <!-- this is still part of the subsection entitled "Games" -> ...

The footer element


Categories: Flow content. Palpable content. Contexts in which this element can be used: Where flow content is expected. Content model: Flow content, but with no header , footer , or main element descendants. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes DOM interface: Uses HTMLElement. The footer element represents a footer for its nearest ancestor
sectioning content or sectioning root element. A footer typically
contains information about its section such as who wrote it, links to related documents, copyright data, and the like. When the footer element contains entire sections, they represent appendices, indexes, long colophons, verbose license
agreements, and other such content. Contact information for the author or editor of a section belongs in an address element, possibly itself inside a footer . Bylines and other information that could be suitable for both a header or a footer can be placed in either (or neither). The primary purpose of these elements is merely to help the author
write self-explanatory markup that is easy to

http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

maintain and style; they are not intended to impose


specific structures on authors. Footers don't necessarily have to appear at the end of a section, though they usually
do. When the nearest ancestor sectioning content or sectioning root
element is the body element, then it applies to the whole page. The footer element is not sectioning content; it doesn't
introduce a new section. Here is a page with two footers, one at the top and one at the bottom, with the same
content: <body> <footer><a href="../">Back to index...</a></footer> <hgroup> <h1>Lorem ipsum</h1> <h2>The ipsum of all lorems</h2> </hgroup> <p>A dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <footer><a href="../">Back to index...</a></footer> </body> Here is an example which shows the footer element being used both for a site-wide
footer and for a section footer. <!DOCTYPE HTML> <HTML><HEAD> <TITLE>The Ramblings of a Scientist</TITLE>

http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

<BODY> <H1>The Ramblings of a Scientist</H1> <ARTICLE> <H1>Episode 15</H1> <VIDEO SRC="/fm/015.ogv" CONTROLS PRELOAD> <P><A HREF="/fm/015.ogv">Download video</A>.</P> </VIDEO> <FOOTER> <!-- footer for article --> <P>Published <TIME DATETIME="2009-10-21T18:26-07:00">on 2009/10/21 at 6:26pm</TIME></P> </FOOTER> </ARTICLE> <ARTICLE> <H1>My Favorite Trains</H1> <P>I love my trains. My favorite train of all time is a Kf. </P> <P>It is fun to see them pull some coal cars because they look so dwarfed in comparison.</P> <FOOTER> <!-- footer for article --> <P>Published <TIME DATETIME="2009-09-15T14:54-07:00">on 2009/09/15 at 2:54pm</TIME></P> </FOOTER> </ARTICLE> <FOOTER> <!-- site wide footer --> <NAV> <P><A HREF="/credits.html">Credits</A> <A HREF="/tos.html">Terms of Service</A> <A HREF="/index.html">Blog Index</A></P> </NAV> <P>Copyright 2009 Gordon Freeman</P> </FOOTER> </BODY> </HTML> Some site designs have what is sometimes referred to as "fat footers" footers that
contain a lot of material, including images, links to other articles, links to pages for sending
feedback, special offers... in some ways, a whole "front page" in the footer. This fragment shows the bottom of a page on a site with a "fat footer":

http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

... <footer> <nav> <section> <h1>Articles</h1> <p><img src="images/somersaults.jpeg" alt=""> Go to the gym with our somersaults class! Our teacher Jim takes you through the paces in this two-part article. <a href="articles/somersaults/1">Part 1</a> <a href="articles/somersaults/2">Part 2</a></p> <p><img src="images/kindplus.jpeg"> Tired of walking on the edge of a clif<!-- sic -->? Our guest writer Lara shows you how to bumble your way through the bars. <a href="articles/kindplus/1">Read more...</a></p> <p><img src="images/crisps.jpeg"> The chips are down, now all that's left is a potato. What can you do with it? <a href="articles/crisps/1">Read more...</a></p> </section> <ul> <li> <a href="/about">About us...</a> <li> <a href="/feedback">Send feedback!</a> <li> <a href="/sitemap">Sitemap</a> </ul> </nav> <p><small>Copyright 2015 The Snacker <a href="/tos">Terms of Service</a></small></p> </footer> </body>

The address element


Categories:

http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

Flow content. Palpable content. Contexts in which this element can be used: Where flow content is expected. Content model: Flow content, but with no heading
content descendants, no sectioning content descendants, and no header , footer , or
address element descendants. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes DOM interface: Uses HTMLElement. The address element represents the contact information for its
nearest article or body element ancestor. If that is the body
element, then the contact information applies to the document as a whole. For example, a page at the W3C Web site related to HTML might
include the following contact information: <ADDRESS> <A href="../People/Raggett/">Dave Raggett</A>, <A href="../People/Arnaud/">Arnaud Le Hors</A>, contact persons for the <A href="Activity">W3C HTML Activity</A> </ADDRESS> The address element must not be used to represent arbitrary addresses (e.g. postal
addresses), unless those addresses are in fact the relevant contact information. (The
p element is the appropriate element for marking up postal addresses in general.) The address element must not contain information other than contact information. For example, the following is non-conforming use of the
address element: <ADDRESS>Last Modified: 1999/12/24 23:37:50</ADDRESS>

http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

Typically, the address element would be included along with other information in a
footer element. In this example the footer contains contact information and a copyright notice. <footer> <address> For more details, contact <a href="mailto:js@example.com">John Smith</a>. </address> <p><small> copyright 2038 Example Corp.</small></p> </footer>

Headings and sections


The h1 h6 elements and the hgroup element are
headings. The first element of heading content in an element of sectioning
content represents the heading for that section. Subsequent headings of equal
or higher rank start new (implied) sections, headings of lower rank
start implied subsections that are part of the previous one. In both cases, the element represents the heading of the implied section. Certain elements are said to be sectioning roots, including
blockquote and td elements. These elements can have their own outlines,
but the sections and headings inside these elements do not contribute to the outlines of their ancestors.

blockquote body details dialog fieldset figure td


Sectioning content elements are always considered subsections of their nearest
ancestor sectioning root or their nearest ancestor element of sectioning
content, whichever is nearest, regardless of what implied sections other headings may have
created.
http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

For the following fragment: <body> <h1>Foo</h1> <h2>Bar</h2> <blockquote> <h3>Bla</h3> </blockquote> <p>Baz</p> <h2>Quux</h2> <section> <h3>Thud</h3> </section> <p>Grunt</p> </body> ...the structure would be: 1. Foo (heading of explicit body section, containing the "Grunt" paragraph) 1. Bar (heading starting implied section, containing a block quote and the "Baz" paragraph) 2. Quux (heading starting implied section with no content other than the heading itself) 3. Thud (heading of explicit section section) Notice how the section ends the earlier implicit section so that a later paragraph ("Grunt") is back at the top level. Sections may contain headings of any rank, but authors are strongly encouraged to
either use only h1 elements, or to use elements of the appropriate rank
for the section's nesting level. Authors are also encouraged to explicitly wrap sections in elements of sectioning
content, instead of relying on the implicit sections generated by having multiple headings
in one element of sectioning content. For example, the following is correct: <body> <h4>Apples</h4> <p>Apples are fruit.</p> <section>

http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

<h2>Taste</h2> <p>They taste lovely.</p> <h6>Sweet</h6> <p>Red apples are sweeter than green ones.</p> <h1>Color</h1> <p>Apples come in various colors.</p> </section> </body> However, the same document would be more clearly expressed as: <body> <h1>Apples</h1> <p>Apples are fruit.</p> <section> <h2>Taste</h2> <p>They taste lovely.</p> <section> <h3>Sweet</h3> <p>Red apples are sweeter than green ones.</p> </section> </section> <section> <h2>Color</h2> <p>Apples come in various colors.</p> </section> </body> Both of the documents above are semantically identical and would produce the same outline in
compliant user agents. This third example is also semantically identical, and might be easier to maintain (e.g. if
sections are often moved around in editing): <body> <h1>Apples</h1> <p>Apples are fruit.</p> <section> <h1>Taste</h1> <p>They taste lovely.</p> <section> <h1>Sweet</h1>
http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

<p>Red apples are sweeter than green ones.</p> </section> </section> <section> <h1>Color</h1> <p>Apples come in various colors.</p> </section> </body> This final example would need explicit style rules to be rendered well in legacy browsers.
Legacy browsers without CSS support would render all the headings as top-level headings.

Creating an outline
The outline for a sectioning content element or a sectioning
root element consists of a list of one or more potentially nested sections. A section is a container that corresponds to some nodes in the original DOM tree. Each section can have one
heading associated with it, and can contain any number of further nested sections. (The sections in the outline aren't
section elements, though some may correspond to such elements they are merely conceptual sections.) The following markup fragment: <body> <h1>A</h1> <p>B</p> <h2>C</h2> <p>D</p> <h2>E</h2> <p>F</p> </body> ...results in the following outline being created for the body node (and thus the
entire document): 1. Section created for body node. Associated with heading "A".

http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

Also associated with paragraph "B". Nested sections: 1. Section implied for first h2 element. Associated with heading "C". Also associated with paragraph "D". No nested sections. 2. Section implied for second h2 element. Associated with heading "E". Also associated with paragraph "F". No nested sections.

Sample outlines
The following document shows a straight-forward application of the outline algorithm. First, here is the document, which is a book with very short chapters and
subsections: <!DOCTYPE HTML> <title>The Tax Book (all in one page)</title> <h1>The Tax Book</h1> <h2>Earning money</h2> <p>Earning money is good.</p> <h3>Getting a job</h3> <p>To earn money you typically need a job.</p> <h2>Spending money</h2> <p>Spending is what money is mainly used for.</p> <h3>Cheap things</h3> <p>Buying cheap things often not cost-effective.</p> <h3>Expensive things</h3> <p>The most expensive thing is often not the most costeffective either.</p> <h2>Investing money</h2> <p>You can lend your money to other people.</p> <h2>Losing money</h2>

http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

<p>If you spend money or invest money, sooner or later you will lose money. <h3>Poor judgement</h3> <p>Usually if you lose money it's because you made a mistake. </p> This book would form the following outline: 1. The Tax Book 1. Earning money 1. Getting a job 2. Spending money 1. Cheap things 2. Expensive things 3. Investing money 4. Losing money 1. Poor judgement Notice that the title element does not participate in the outline. Here is a similar document, but this time using section elements to get the same
effect: <!DOCTYPE HTML> <title>The Tax Book (all in one page)</title> <h1>The Tax Book</h1> <section> <h1>Earning money</h1> <p>Earning money is good.</p> <section> <h1>Getting a job</h1> <p>To earn money you typically need a job.</p> </section> </section> <section> <h1>Spending money</h1> <p>Spending is what money is mainly used for.</p> <section> <h1>Cheap things</h1> <p>Buying cheap things often not cost-effective.</p> </section>
http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

<section> <h1>Expensive things</h1> <p>The most expensive thing is often not the most costeffective either.</p> </section> </section> <section> <h1>Investing money</h1> <p>You can lend your money to other people.</p> </section> <section> <h1>Losing money</h1> <p>If you spend money or invest money, sooner or later you will lose money. <section> <h1>Poor judgement</h1> <p>Usually if you lose money it's because you made a mistake.</p> </section> </section> This book would form the same outline: 1. The Tax Book 1. Earning money 1. Getting a job 2. Spending money 1. Cheap things 2. Expensive things 3. Investing money 4. Losing money 1. Poor judgement A document can contain multiple top-level headings: <!DOCTYPE HTML> <title>Alphabetic Fruit</title> <h1>Apples</h1> <p>Pomaceous.</p> <h1>Bananas</h1>

http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

<p>Edible.</p> <h1>Carambola</h1> <p>Star.</p> This would form the following simple outline consisting of three top-level sections: 1. Apples 2. Bananas 3. Carambola Effectively, the body element is split into three. Mixing both the h1 h6 model and the
section / h1 model can lead to some unintuitive results. Consider for example the following, which is just the previous example but with the contents
of the (implied) body wrapped in a section: <!DOCTYPE HTML> <title>Alphabetic Fruit</title> <section> <h1>Apples</h1> <p>Pomaceous.</p> <h1>Bananas</h1> <p>Edible.</p> <h1>Carambola</h1> <p>Star.</p> </section> The resulting outline would be: 1. (untitled page) 1. Apples 2. Bananas 3. Carambola This result is described as unintuitive because it results in three subsections even
though there's only one section element. Effectively, the section is split into three, just like the implied body element in the previous example. (In this example, "(untitled page)" is the implied heading for the body element, since it has no explicit heading.)

http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

Headings never rise above other sections. Thus, in the following example, the first
h1 does not actually describe the page header; it describes the header for the
second half of the page: <!DOCTYPE HTML> <title>Feathers on The Site of Encyclopedic Knowledge</title> <section> <h1>A plea from our caretakers</h1> <p>Please, we beg of you, send help! We're stuck in the server room!</p> </section> <h1>Feathers</h1> <p>Epidermal growths.</p> The resulting outline would be: 1. (untitled page) 1. A plea from our caretakers 2. Feathers Thus, when an article element starts with a nav block and only later
has its heading, the result is that the nav block is not part of the same section as
the rest of the article in the outline. For instance, take this document: <!DOCTYPE HTML> <title>We're adopting a child! Ray's blog</title> <h1>Ray's blog</h1> <article> <header> <nav> <a href="?t=-1d">Yesterday</a>; <a href="?t=-7d">Last week</a>; <a href="?t=-1m">Last month</a> </nav> <h1>We're adopting a child!</h1> </header> <main> <p>As of today, Janine and I have signed the papers to become the proud parents of baby Diane! We've been looking forward to

http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

this day for weeks.</p> </main> </article> The resulting outline would be: 1. Ray's blog 1. Untitled article 1. Untitled navigation section 2. We're adopting a child! Also worthy of note in this example is that the header and main
elements have no effect whatsoever on the document outline. The hgroup element can be used for subheadings. For example: <!DOCTYPE HTML> <title>Chronotype: CS Student</title> <hgroup> <h1> The morning </h1> <h2> 06:00 to 12:00 </h2> </hgroup> <p>We sleep.</p> <hgroup> <h1> The afternoon </h1> <h2> 12:00 to 18:00 </h2> </hgroup> <p>We study.</p> <hgroup> <h2>Additional Commentary</h2> <h3>Because not all this is necessarily true</h3> <h6>Ok it's almost certainly not true</h6> </hgroup> <p>Yeah we probably play, rather than study.</p> <hgroup> <h1> The evening </h1> <h2> 18:00 to 00:00 </h2> </hgroup> <p>We play.</p> <hgroup> <h1> The night </h1>

http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

<h2> 00:00 to 06:00 </h2> </hgroup> <p>We play some more.</p> The resulting outline would be: 1. The morning 06:00 to 12:00 2. The afternoon 12:00 to 18:00 1. Additional Commentary Because not all this is necessarily true Ok it's almost
certainly not true

3. The evening 18:00 to 00:00 4. The night 00:00 to 06:00 Exactly how this is represented by user agents, as most interface issues, is left as a matter
of implementation preference, but the key part is that the hgroup 's descendant
h1 h6 elements are what form the element's heading. Thus, the
following would be equally valid: 1. The morning 06:00 to 12:00 2. The afternoon 12:00 to 18:00 1. Additional Commentary Because not all this is necessarily true Ok it's almost certainly not true 3. The evening 18:00 to 00:00 4. The night 00:00 to 06:00 But so would the following: 1. The morning 2. The afternoon 1. Additional Commentary 3. The evening 4. The night The following would also be valid, though maybe less practical in most contexts: 1. The morning 06:00 to 12:00 2. The afternoon

http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

12:00 to 18:00 1. Additional Commentary Because not all this is necessarily true Ok it's almost certainly not true 3. The evening 18:00 to 00:00 4. The night 00:00 to 06:00

Usage summary
Element Purpose Example body The main content of the document. <!DOCTYPE HTML> <html> <head> <title>Steve Hill's Home Page</title> </head> <body> <p>Hard Trance is My Life.</p> </body> </html> article A complete, or self-contained, composition in a document, page, application, or site and that is, in principle, independently distributable or reusable, e.g. in syndication. This could be a forum post, a magazine or newspaper article, a blog entry, a user-submitted comment, an interactive widget or gadget, or any other independent item of content. <article> <img src="/tumblr_masqy2s5yn1rzfqbpo1_500.jpg" alt="Yellow smiley face with the caption 'masif'">

http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

<p>My fave Masif tee so far!</p> <footer>Posted 2 days ago</footer> </article> <article> <img src="/tumblr_m9tf6wSr6W1rzfqbpo1_500.jpg" alt=""> <p>Happy 2nd birthday Masif Saturdays!!!</p> <footer>Posted 3 weeks ago</footer> </article> section A generic section of a document or application. A section, in this context, is a thematic grouping of content, typically with a heading. <h1>Biography</h1> <section> <h1>The facts</h1> <p>1500+ shows, 14+ countries</p> </section> <section> <h1>2010/2011 figures per year</h1> <p>100+ shows, 8+ countries</p> </section> nav A section of a page that links to other pages or to parts within the page: a section with navigation links. <nav> <p><a href="/">Home</a> <p><a href="/biog.html">Bio</a> <p><a href="/discog.html">Discog</a> </nav> aside A section of a page that consists of content that is tangentially related to the content around the aside element, and which could be considered separate from that content. Such sections are often represented as sidebars in printed typography. <h1>Music</h1>

http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

<p>As any burner can tell you, the event has a lot of trance.</p> <aside>You can buy the music we played at our <a href="buy.html">playlist page</a>.</aside> <p>This year we played a kind of trance that originated in Belgium, Germany, and the Netherlands in the mid 90s.</p> h1 h6 A section heading <h1>The Guide To Music On The Playa</h1> <h2>The Main Stage</h2> <p>If you want to play on a stage, you should bring one.</p> <h2>Amplified Music</h2> <p>Amplifiers up to 300W or 90dB are welcome.</p> hgroup The heading of a section, which consists of all the h1 h6 element children of the hgroup element. The element is used to group a set of h1 h6 elements when the heading has multiple levels, such as subheadings, alternative titles, or taglines. <hgroup> <h1>Burning Music</h1> <h2>The Guide To Music On The Playa</h2> </hgroup> <section> <hgroup> <h1>Main Stage</h1> <h2>The Fiction Of A Music Festival</h2> </hgroup> <p>If you want to play on a stage, you should bring one.</p> </section> <section> <hgroup> <h1>Loudness!</h1> <h2>Questions About Amplified Music</h2> </hgroup>
http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

<p>Amplifiers up to 300W or 90dB are welcome. </p> </section> header A group of introductory or navigational aids. <article> <header> <h1>Hard Trance is My Life</h1> <p>By DJ Steve Hill and Technikal</p> </header> <p>The album with the amusing punctuation has red artwork.</p> </article> footer A footer for its nearest ancestor sectioning content or sectioning root element. A footer typically contains information about its section such as who wrote it, links to related documents, copyright data, and the like. <article> <h1>Hard Trance is My Life</h1> <p>The album with the amusing punctuation has red artwork.</p> <footer> <p>Artists: DJ Steve Hill and Technikal</p> </footer> </article>

Article or section?
A section forms part of something else. An article is its own thing.
But how does one know which is which? Mostly the real answer is "it depends on author intent". For example, one could imagine a book with a "Granny Smith" chapter that just said "These
juicy, green apples make a great filling for apple pies."; that would be a section
because there'd be lots of other chapters on (maybe)
http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.3 Sections HTML: The Living Standard - Edition for Web Developers

other kinds of apples. On the other hand, one could imagine a tweet or reddit comment or tumblr post or newspaper
classified ad that just said "Granny Smith. These juicy, green apples make a great filling for
apple pies."; it would then be articles because that was the whole thing. A comment on an article is not part of the article on which it is commenting,
therefore it is its own article.

Up next

4.4 Grouping content

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/sections.html[4/16/2014 9:28:00 PM]

4.4 Grouping content HTML: The Living Standard - Edition for Web Developers

WH A T WG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
Grouping content
The p element
The hr element
The pre element
The blockquote element
The ol element
The ul element
The li element
The dl element
The dt element
The dd element
The figure element
The figcaption element
The main element
The div element

Grouping content

The p element
Categories: Flow content. Palpable content. Contexts in which this element can be used: Where flow content is expected. Content model: Phrasing content. Tag omission in text/html: A p element's end tag can be omitted if the
p element is immediately followed by an address, article,
aside , blockquote , div, dl ,
fieldset, footer, form, h1, h2 ,
h3 , h4, h5 , h6 , header,
hgroup , hr, main, menu, nav,
ol, p , pre, section, table, or
ul , element, or if there is no more content in the parent

http://developers.whatwg.org/grouping-content.html[4/16/2014 9:28:22 PM]

4.4 Grouping content HTML: The Living Standard - Edition for Web Developers

element and the parent


element is not an a element. Content attributes: Global attributes DOM interface: The p element represents a paragraph. While paragraphs are usually represented in visual media by blocks of text that
are physically separated from adjacent blocks through blank lines, a style sheet or user agent
would be equally justified in presenting paragraph breaks in a different manner, for instance
using inline pilcrows (). The following examples are conforming HTML fragments: <p>The little kitten gently seated himself on a piece of carpet. Later in his life, this would be referred to as the time the cat sat on the mat.</p> <fieldset> <legend>Personal information</legend> <p> <label>Name: <input name="n"></label> <label><input name="anon" type="checkbox"> Hide from other users</label> </p> <p><label>Address: <textarea name="a"></textarea></label> </p> </fieldset> <p>There was once an example from Femley,<br> Whose markup was of dubious quality.<br> The validator complained,<br> So the author was pained,<br> To move the error from the markup to the rhyming.</p> The p element should not be used when a more specific element is more appropriate. The following example is technically correct: <section> <!-- ... --> <p>Last modified: 2001-04-23</p> <p>Author: fred@example.com</p> </section>

http://developers.whatwg.org/grouping-content.html[4/16/2014 9:28:22 PM]

4.4 Grouping content HTML: The Living Standard - Edition for Web Developers

However, it would be better marked-up as: <section> <!-- ... --> <footer>Last modified: 2001-04-23</footer> <address>Author: fred@example.com</address> </section> Or: <section> <!-- ... --> <footer> <p>Last modified: 2001-04-23</p> <address>Author: fred@example.com</address> </footer> </section> List elements (in particular, ol and ul elements) cannot be children
of p elements. When a sentence contains a bulleted list, therefore, one might wonder
how it should be marked up. For instance, this fantastic sentence has bullets relating to

wizards, faster-than-light travel, and telepathy,


and is further discussed below. The solution is to realise that a paragraph, in HTML terms, is not a logical concept,
but a structural one. In the fantastic example above, there are actually five paragraphs as defined by this specification: one before the list, one
for each bullet, and one after the list. The markup for the above example could therefore be: <p>For instance, this fantastic sentence has bullets relating to</p> <ul> <li>wizards, <li>faster-than-light travel, and <li>telepathy, </ul> <p>and is further discussed below.</p> Authors wishing to conveniently style such "logical" paragraphs consisting of multiple
"structural" paragraphs can use the div element instead of the p element.

http://developers.whatwg.org/grouping-content.html[4/16/2014 9:28:22 PM]

4.4 Grouping content HTML: The Living Standard - Edition for Web Developers

Thus for instance the above example could become the following: <div>For instance, this fantastic sentence has bullets relating to <ul> <li>wizards, <li>faster-than-light travel, and <li>telepathy, </ul> and is further discussed below.</div> This example still has five structural paragraphs, but now the author can style just the
div instead of having to consider each part of the example separately.

The hr element
Categories: Flow content. Contexts in which this element can be used: Where flow content is expected. Content model: Empty. Tag omission in text/html: No end tag. Content attributes: Global attributes DOM interface: The hr element represents a paragraph-level thematic
break, e.g. a scene change in a story, or a transition to another topic within a section of a reference book. The following fictional extract from a project manual shows two sections that use the
hr element to separate topics within the section. <section> <h1>Communication</h1> <p>There are various methods of communication. This section covers a few of the important ones used by the project.</p> <hr> <p>Communication stones seem to come in pairs and have

http://developers.whatwg.org/grouping-content.html[4/16/2014 9:28:22 PM]

4.4 Grouping content HTML: The Living Standard - Edition for Web Developers

mysterious properties:</p> <ul> <li>They can transfer thoughts in two directions once activated if used alone.</li> <li>If used with another device, they can transfer one's consciousness to another body.</li> <li>If both stones are used with another device, the consciousnesses switch bodies.</li> </ul> <hr> <p>Radios use the electromagnetic spectrum in the meter range and longer.</p> <hr> <p>Signal flares use the electromagnetic spectrum in the nanometer range.</p> </section> <section> <h1>Food</h1> <p>All food at the project is rationed:</p> <dl> <dt>Potatoes</dt> <dd>Two per day</dd> <dt>Soup</dt> <dd>One bowl per day</dd> </dl> <hr> <p>Cooking is done by the chefs on a set rotation.</p> </section> There is no need for an hr element between the
sections themselves, since the section elements and
the h1 elements imply thematic changes themselves. The following extract from Pandora's Star by Peter
F. Hamilton shows two paragraphs that precede a scene change and
the paragraph that follows it. The scene change, represented in the
printed book by a gap containing a solitary centered star between
the second and third paragraphs, is here represented using the
hr element. <p>Dudley was ninety-two, in his second life, and fast approaching time for another rejuvenation. Despite his body having the physical age of a standard fifty-year-old, the prospect of a long degrading

http://developers.whatwg.org/grouping-content.html[4/16/2014 9:28:22 PM]

4.4 Grouping content HTML: The Living Standard - Edition for Web Developers

campaign within academia was one he regarded with dread. For a supposedly advanced civilization, the Intersolar Commonwealth could be appallingly backward at times, not to mention cruel.</p> <p><i>Maybe it won't be that bad</i>, he told himself. The lie was comforting enough to get him through the rest of the night's shift.</p> <hr> <p>The Carlton AllLander drove Dudley home just after dawn. Like the astronomer, the vehicle was old and worn, but perfectly capable of doing its job. It had a cheap diesel engine, common enough on a semi-frontier world like Gralmond, although its drive array was a thoroughly modern photoneural processor. With its high suspension and deep-tread tyres it could plough along the dirt track to the observatory in all weather and seasons, including the metredeep snow of Gralmond's winters.</p> The hr element does not affect the
document's outline.

The pre element


Categories: Flow content. Palpable content. Contexts in which this element can be used: Where flow content is expected. Content model: Phrasing content. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes DOM interface:

http://developers.whatwg.org/grouping-content.html[4/16/2014 9:28:22 PM]

4.4 Grouping content HTML: The Living Standard - Edition for Web Developers

The pre element represents a block of


preformatted text, in which structure is represented by typographic
conventions rather than by elements. In the HTML syntax, a leading
newline character immediately following the pre element
start tag is stripped. Some examples of cases where the pre element could
be used:

Including an e-mail, with paragraphs indicated by blank lines,


lists indicated
by lines prefixed with a bullet, and so on.

Including fragments of computer code, with structure indicated


according to
the conventions of that language.

Displaying ASCII art.


Authors are encouraged to consider how preformatted
text will be experienced when the formatting is lost, as will be the
case for users of speech synthesizers, braille displays, and the
like. For cases like ASCII art, it is likely that an alternative
presentation, such as a textual description, would be more
universally accessible to the readers of the document. To represent a block of computer code, the pre
element can be used with a code element; to represent a
block of computer output the pre element can be used
with a samp element. Similarly, the kbd
element can be used within a pre element to indicate
text that the user is to enter. In the following snippet, a sample of computer code is
presented. <p>This is the <code>Panel</code> constructor:</p> <pre><code>function Panel(element, canClose, closeHandler) { this.element = element; this.canClose = canClose; this.closeHandler = function () { if (closeHandler) closeHandler() }; }</code></pre> In the following snippet, samp and kbd
elements are mixed in the contents of a pre element to
show a session of Zork I. <pre><samp>You are in an open field west of a big white house with a boarded front door. There is a small mailbox here. ></samp> <kbd>open mailbox</kbd> <samp>Opening the mailbox reveals: A leaflet.

http://developers.whatwg.org/grouping-content.html[4/16/2014 9:28:22 PM]

4.4 Grouping content HTML: The Living Standard - Edition for Web Developers

></samp></pre> The following shows a contemporary poem that uses the


pre element to preserve its unusual formatting, which
forms an intrinsic part of the poem itself. <pre> it is with a heavy that i admit loss of a feline so a friend lost to the unknown (night) ~cdr 11dec07</pre> loved maxling heart

The blockquote element


Categories: Flow content. Sectioning root. Palpable content. Contexts in which this element can be used: Where flow content is expected. Content model: Flow content. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes cite Link to the source of the quotation or more information about the edit DOM interface: The HTMLQuoteElement interface is
also used by the q element.

The blockquote element represents a section that is quoted from


another source. Content inside a blockquote must be quoted from another source, whose

http://developers.whatwg.org/grouping-content.html[4/16/2014 9:28:22 PM]

4.4 Grouping content HTML: The Living Standard - Edition for Web Developers

address, if
it has one, may be cited in the cite
attribute. If the cite attribute is present, it must be a
valid URL potentially surrounded by spaces. User agents may allow users to follow such
citation links, but they are primarily intended for private use (e.g. by server-side scripts
collecting statistics about a site's use of quotations), not for readers. The content of a blockquote may be abbreviated or may have context added in the
conventional manner for the text's language. For example, in English this is traditionally done using square brackets. Consider a page with
the sentence "Fred ate the cracker. He then said he liked apples and fish."; it could be quoted
as follows: <blockquote> <p>[Fred] then said he liked [...] fish.</p> </blockquote> Attribution for the quotation, if any, must be placed outside the blockquote element. For example, here the attribution is given in a paragraph after the quote: <blockquote> <p>I contend that we are both atheists. I just believe in one fewer god than you do. When you understand why you dismiss all the other possible gods, you will understand why I dismiss yours.</p> </blockquote> <p> Stephen Roberts</p> The other examples below show other ways of showing attribution. Here a blockquote element is used in conjunction with a figure
element and its figcaption to clearly relate a quote to its attribution (which is
not part of the quote and therefore doesn't belong inside the blockquote
itself): <figure> <blockquote> <p>The truth may be puzzling. It may take some work to grapple with. It may be counterintuitive. It may contradict deeply held prejudices. It may not be consonant with what we desperately want to be true. But our preferences do not determine what's true. We have a method, and that method helps us to reach not absolute truth, only

http://developers.whatwg.org/grouping-content.html[4/16/2014 9:28:22 PM]

4.4 Grouping content HTML: The Living Standard - Edition for Web Developers

asymptotic approaches to the truth never there, just closer and closer, always finding vast new oceans of undiscovered possibilities. Cleverly designed experiments are the key. </p> </blockquote> <figcaption>Carl Sagan, in "<cite>Wonder and Skepticism</cite>", from the <cite>Skeptical Enquirer</cite> Volume 19, Issue 1 (January-February 1995)</figcaption> </figure> This next example shows the use of cite alongside blockquote: <p>His next piece was the aptly named <cite>Sonnet 130</cite>:</p> <blockquote cite="http://quotes.example.org/s/sonnet130.html"> <p>My mistress' eyes are nothing like the sun,<br> Coral is far more red, than her lips red,<br> ... This example shows how a forum post could use blockquote to show what post a user
is replying to. The article element is used for each post, to mark up the
threading. <article> <h1><a href="http://bacon.example.com/?blog=109431">Bacon on a crowbar</a></h1> <article> <header><strong>t3yw</strong> 12 points 1 hour ago</header> <p>I bet a narwhal would love that.</p> <footer><a href="?pid=29578">permalink</a></footer> <article> <header><strong>greg</strong> 8 points 1 hour ago</header> <blockquote><p>I bet a narwhal would love that.</p> </blockquote> <p>Dude narwhals don't eat bacon.</p> <footer><a href="?pid=29579">permalink</a></footer> <article> <header><strong>t3yw</strong> 15 points 1 hour ago</header> <blockquote> <blockquote><p>I bet a narwhal would love that.</p> </blockquote> <p>Dude narwhals don't eat bacon.</p>

http://developers.whatwg.org/grouping-content.html[4/16/2014 9:28:22 PM]

4.4 Grouping content HTML: The Living Standard - Edition for Web Developers

</blockquote> <p>Next thing you'll be saying they don't get capes and wizard hats either!</p> <footer><a href="?pid=29580">permalink</a></footer> <article> <article> <header><strong>boing</strong> -5 points 1 hour ago</header> <p>narwhals are worse than ceiling cat</p> <footer><a href="?pid=29581">permalink</a></footer> </article> </article> </article> </article> <article> <header><strong>fred</strong> 1 points 23 minutes ago</header> <blockquote><p>I bet a narwhal would love that.</p> </blockquote> <p>I bet they'd love to peel a banana too.</p> <footer><a href="?pid=29582">permalink</a></footer> </article> </article> </article> This example shows the use of a blockquote for short snippets, demonstrating that
one does not have to use p elements inside blockquote elements: <p>He began his list of "lessons" with the following:</p> <blockquote>One should never assume that his side of the issue will be recognized, let alone that it will be conceded to have merits.</blockquote> <p>He continued with a number of similar points, ending with: </p> <blockquote>Finally, one should be prepared for the threat of breakdown in negotiations at any given moment and not be cowed by the possibility.</blockquote> <p>We shall now discuss these points... Examples of how to represent a conversation are shown
in a later section; it is not appropriate to use the cite and blockquote
elements for this purpose.

The ol element
http://developers.whatwg.org/grouping-content.html[4/16/2014 9:28:22 PM]

4.4 Grouping content HTML: The Living Standard - Edition for Web Developers

Categories: Flow content. If the element's children include at least one li element: Palpable content. Contexts in which this element can be used: Where flow content is expected. Content model: Zero or more li and script-supporting elements. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes reversed Number the list backwards start Ordinal value of the first item type Kind of list marker DOM interface: The ol element represents a list of items, where the items have been intentionally ordered, such that changing the order would change the meaning of the document. The items of the list are the li element child nodes of the ol
element, in tree order. The reversed attribute is a boolean
attribute. If present, it indicates that the list is a descending list (..., 3, 2, 1). If
the attribute is omitted, the list is an ascending list (1, 2, 3, ...). The start attribute, if present, must be a
valid integer giving the ordinal value of the first list item. The type attribute can be used to specify the kind
of marker to use in the list, in the cases where that matters (e.g. because items are to be
referenced by their number/letter). The attribute, if specified, must have a value that is a case-sensitive match for one of the characters given in the first cell of one of the
rows of the following table. Keyword 1 (U+0031) a (U+0061) loweralpha State decimal Description Examples for values 1-3 and 3999-4001 Decimal numbers Lowercase latin alphabet a. b. c. ... ewu. ewv. eww. ... 1. 2. 3. ... 3999. 4000. 4001. ...

http://developers.whatwg.org/grouping-content.html[4/16/2014 9:28:22 PM]

4.4 Grouping content HTML: The Living Standard - Edition for Web Developers

A (U+0041) i (U+0069) I (U+0049)

upperalpha

Uppercase latin alphabet

A.

B.

C.

...

EWU.

EWV.

EWW.

...

lowerroman

Lowercase roman numerals

i.

ii.

iii.

...

mmmcmxcix.

. iv

ivi.

...

upperroman

Uppercase roman numerals

I.

II.

III.

...

MMMCMXCIX. IV.

IVI.

...

The following markup shows a list where the order matters, and where the ol
element is therefore appropriate. Compare this list to the equivalent list in the ul
section to see an example of the same items using the ul element. <p>I have lived in the following countries (given in the order of when I first lived there):</p> <ol> <li>Switzerland <li>United Kingdom <li>United States <li>Norway </ol> Note how changing the order of the list changes the meaning of the document. In the following
example, changing the relative order of the first two items has changed the birthplace of the
author: <p>I have lived in the following countries (given in the order of when I first lived there):</p> <ol> <li>United Kingdom <li>Switzerland <li>United States <li>Norway </ol>

The ul element
Categories: Flow content. If the element's children include at least one li element: Palpable content. Contexts in which this element can be used:

http://developers.whatwg.org/grouping-content.html[4/16/2014 9:28:22 PM]

4.4 Grouping content HTML: The Living Standard - Edition for Web Developers

Where flow content is expected. Content model: Zero or more li and script-supporting elements. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes DOM interface: The ul element represents a list of items, where the order of the
items is not important that is, where changing the order would not materially change the
meaning of the document. The items of the list are the li element child nodes of the ul
element. The following markup shows a list where the order does not matter, and where the
ul element is therefore appropriate. Compare this list to the equivalent list in the
ol section to see an example of the same items using the ol
element. <p>I have lived in the following countries:</p> <ul> <li>Norway <li>Switzerland <li>United Kingdom <li>United States </ul> Note that changing the order of the list does not change the meaning of the document. The
items in the snippet above are given in alphabetical order, but in the snippet below they are
given in order of the size of their current account balance in 2007, without changing the meaning
of the document whatsoever: <p>I have lived in the following countries:</p> <ul> <li>Switzerland <li>Norway <li>United Kingdom <li>United States </ul>

The li element

http://developers.whatwg.org/grouping-content.html[4/16/2014 9:28:22 PM]

4.4 Grouping content HTML: The Living Standard - Edition for Web Developers

Categories: None. Contexts in which this element can be used: Inside ol elements. Inside ul elements. Inside menu elements whose type attribute is in the toolbar state. Content model: Flow content. Tag omission in text/html: An li element's end tag can be omitted if the
li element is immediately followed by another li element or if there is
no more content in the parent element. Content attributes: Global attributes If the element is a child of an ol element: value Ordinal value of the list item DOM interface: The li element represents a list item. If its parent element is an
ol , ul, or menu element, then the element is an item of the
parent element's list, as defined for those elements. Otherwise, the list item has no defined
list-related relationship to any other li element. If the parent element is an ol element, then the li element has an
ordinal value. The value attribute, if present, must be a
valid integer giving the ordinal value of the list item. The following example, the top ten movies are listed (in reverse order). Note the way the list
is given a title by using a figure element and its figcaption
element. <figure> <figcaption>The top 10 movies of all time</figcaption> <ol> <li value="10"><cite>Josie and the Pussycats</cite>, 2001</li> <li value="9"><cite lang="sh">&TScy;&rcy;&ncy;&acy; &mcy;&acy;&chcy;&kcy;&acy;, &bcy;&iecy;&lcy;&icy; &mcy;&acy;&chcy;&ocy;&rcy;</cite>, 1998</li> <li value="8"><cite>A Bug's Life</cite>, 1998</li> <li value="7"><cite>Toy Story</cite>, 1995</li> <li value="6"><cite>Monsters, Inc</cite>, 2001</li>

http://developers.whatwg.org/grouping-content.html[4/16/2014 9:28:22 PM]

4.4 Grouping content HTML: The Living Standard - Edition for Web Developers

<li value="5"><cite>Cars</cite>, 2006</li> <li value="4"><cite>Toy Story 2</cite>, 1999</li> <li value="3"><cite>Finding Nemo</cite>, 2003</li> <li value="2"><cite>The Incredibles</cite>, 2004</li> <li value="1"><cite>Ratatouille</cite>, 2007</li> </ol> </figure> The markup could also be written as follows, using the reversed attribute on the ol element: <figure> <figcaption>The top 10 movies of all time</figcaption> <ol reversed> <li><cite>Josie and the Pussycats</cite>, 2001</li> <li><cite lang="sh">&TScy;&rcy;&ncy;&acy; &mcy;&acy;&chcy;&kcy;&acy;, &bcy;&iecy;&lcy;&icy; &mcy;&acy;&chcy;&ocy;&rcy;</cite>, 1998</li> <li><cite>A Bug's Life</cite>, 1998</li> <li><cite>Toy Story</cite>, 1995</li> <li><cite>Monsters, Inc</cite>, 2001</li> <li><cite>Cars</cite>, 2006</li> <li><cite>Toy Story 2</cite>, 1999</li> <li><cite>Finding Nemo</cite>, 2003</li> <li><cite>The Incredibles</cite>, 2004</li> <li><cite>Ratatouille</cite>, 2007</li> </ol> </figure> While it is conforming to include heading elements (e.g. h1) inside
li elements, it likely does not convey the semantics that the author intended. A heading starts a new section, so a heading in a list implicitly splits the list into spanning
multiple sections.

The dl element
Categories: Flow content. If the element's children include at least one name-value group: Palpable content. Contexts in which this element can be used: Where flow content is expected. Content model: Zero or more groups each consisting of one or more dt elements followed by

http://developers.whatwg.org/grouping-content.html[4/16/2014 9:28:22 PM]

4.4 Grouping content HTML: The Living Standard - Edition for Web Developers

one or more dd elements, optionally intermixed with script-supporting elements. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes DOM interface: The dl element represents an association list consisting of zero or
more namevalue groups (a description list). A name-value group consists of one or more names
(dt elements) followed by one or more values (dd elements), ignoring any
nodes other than dt and dd elements. Within a single dl
element, there should not be more than one dt element for each name. Name-value groups may be terms and definitions, metadata topics and values, questions and
answers, or any other groups of name-value data. The values within a group are alternatives; multiple paragraphs forming part of the same value
must all be given within the same dd element. The order of the list of groups, and of the names and values within each group, may be
significant. In the following example, one entry ("Authors") is linked to two values ("John" and
"Luke"). <dl> <dt> Authors <dd> John <dd> Luke <dt> Editor <dd> Frank </dl> In the following example, one definition is linked to two terms. <dl> <dt lang="en-US"> <dfn>color</dfn> </dt> <dt lang="en-GB"> <dfn>colour</dfn> </dt> <dd> A sensation which (in humans) derives from the ability of the fine structure of the eye to distinguish three differently filtered analyses of a view. </dd> </dl> The following example illustrates the use of the dl element to mark up

http://developers.whatwg.org/grouping-content.html[4/16/2014 9:28:22 PM]

4.4 Grouping content HTML: The Living Standard - Edition for Web Developers

metadata
of sorts. At the end of the example, one group has two metadata labels ("Authors" and "Editors")
and two values ("Robert Rothman" and "Daniel Jackson"). <dl> <dt> Last modified time </dt> <dd> 2004-12-23T23:33Z </dd> <dt> Recommended update interval </dt> <dd> 60s </dd> <dt> Authors </dt> <dt> Editors </dt> <dd> Robert Rothman </dd> <dd> Daniel Jackson </dd> </dl> The following example shows the dl element used to give a set of instructions.
The order of the instructions here is important (in the other examples, the order of the blocks
was not important). <p>Determine the victory points as follows (use the first matching case):</p> <dl> <dt> If you have exactly five gold coins </dt> <dd> You get five victory points </dd> <dt> If you have one or more gold coins, and you have one or more silver coins </dt> <dd> You get two victory points </dd> <dt> If you have one or more silver coins </dt> <dd> You get one victory point </dd> <dt> Otherwise </dt> <dd> You get no victory points </dd> </dl> The following snippet shows a dl element being used as a glossary. Note the use
of dfn to indicate the word being defined. <dl> <dt><dfn>Apartment</dfn>, n.</dt> <dd>An execution context grouping one or more threads with one or more COM objects.</dd> <dt><dfn>Flat</dfn>, n.</dt> <dd>A deflated tire.</dd> <dt><dfn>Home</dfn>, n.</dt> <dd>The user's login directory.</dd> </dl>

http://developers.whatwg.org/grouping-content.html[4/16/2014 9:28:22 PM]

4.4 Grouping content HTML: The Living Standard - Edition for Web Developers

The dl element is inappropriate for marking up dialogue. Examples of how to mark up dialogue are shown below.

The dt element
Categories: None. Contexts in which this element can be used: Before dd or dt elements inside dl elements. Content model: Flow content, but with no header , footer , sectioning content, or heading content descendants. Tag omission in text/html: A dt element's end tag can be omitted if the
dt element is immediately followed by another dt element or a
dd element. Content attributes: Global attributes DOM interface: Uses HTMLElement. The dt element represents the term, or name, part of a
term-description group in a description list (dl element). The dt element itself, when used in a dl element, does
not indicate that its contents are a term being defined, but this can be indicated using the
dfn element. This example shows a list of frequently asked questions (a FAQ) marked up using the
dt element for questions and the dd element for answers. <article> <h1>FAQ</h1> <dl> <dt>What do we want?</dt> <dd>Our data.</dd> <dt>When do we want it?</dt> <dd>Now.</dd> <dt>Where is it?</dt> <dd>We are not sure.</dd> </dl> </article>

http://developers.whatwg.org/grouping-content.html[4/16/2014 9:28:22 PM]

4.4 Grouping content HTML: The Living Standard - Edition for Web Developers

The dd element
Categories: None. Contexts in which this element can be used: After dt or dd elements inside dl elements. Content model: Flow content. Tag omission in text/html: A dd element's end tag can be omitted if the
dd element is immediately followed by another dd element or a
dt element, or if there is no more content in the parent element. Content attributes: Global attributes DOM interface: Uses HTMLElement. The dd element represents the description, definition, or value, part
of a termdescription group in a description list (dl element). A dl can be used to define a vocabulary list, like in a dictionary. In the following example, each entry, given by a dt with a dfn, has several
dds, showing the various parts of the definition. <dl> <dt><dfn>happiness</dfn></dt> <dd class="pronunciation">/'h p. nes/</dd> <dd class="part-of-speech"><i><abbr>n.</abbr></i></dd> <dd>The state of being happy.</dd> <dd>Good fortune; success. <q>Oh <b>happiness</b>! It worked!</q></dd> <dt><dfn>rejoice</dfn></dt> <dd class="pronunciation">/ri jois'/</dd> <dd><i class="part-of-speech"><abbr>v.intr.</abbr></i> To be delighted oneself.</dd> <dd><i class="part-of-speech"><abbr>v.tr.</abbr></i> To cause one to be delighted.</dd> </dl>

The figure element


Categories:

http://developers.whatwg.org/grouping-content.html[4/16/2014 9:28:22 PM]

4.4 Grouping content HTML: The Living Standard - Edition for Web Developers

Flow content. Sectioning root. Palpable content. Contexts in which this element can be used: Where flow content is expected. Content model: Either: One figcaption element followed by flow content. Or: Flow content followed by one figcaption element. Or: Flow content. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes DOM interface: Uses HTMLElement. The figure element represents some flow content,
optionally with a caption, that is self-contained (like a complete sentence) and is typically
referenced as a single unit from the main flow of the document. Self-contained in this context does not necessarily mean independent. For example,
each sentence in a paragraph is self-contained; an image that is part of a sentence would be
inappropriate for figure , but an entire sentence made of images would be fitting. The element can thus be used to annotate illustrations, diagrams, photos, code listings, etc. When a figure is referred to from the main content of the document by identifying
it by its caption (e.g. by figure number), it enables such content to be easily moved away from
that primary content, e.g. to the side of the page, to dedicated pages, or to an appendix, without
affecting the flow of the document. If a figure element is referenced by its relative position, e.g. "in the photograph above" or "as the next figure shows", then moving the figure would disrupt the page's
meaning. Authors are encouraged to consider using labels to refer to figures, rather than using
such relative references, so that the page can easily be restyled without affecting the page's
meaning. The figcaption element child of the element, if
any, represents the caption of the figure element's contents. If there is no child
figcaption element, then there is no caption. A element's contents are part of the surrounding flow. If the purpose

http://developers.whatwg.org/grouping-content.html[4/16/2014 9:28:22 PM]

4.4 Grouping content HTML: The Living Standard - Edition for Web Developers

figure of
the page is to display the figure, for example a photograph on an image sharing site, the
figure and figcaption elements can be used to explicitly provide a
caption for that figure. For content that is only tangentially related, or that serves a separate
purpose than the surrounding flow, the aside element should be used (and can itself
wrap a figure ). For example, a pull quote that repeats content from an
article would be more appropriate in an aside than in a
figure, because it isn't part of the content, it's a repetition of the content for
the purposes of enticing readers or highlighting key topics. This example shows the figure element to mark up a code listing. <p>In <a href="#l4">listing 4</a> we see the primary core interface API declaration.</p> <figure id="l4"> <figcaption>Listing 4. The primary core interface API declaration.</figcaption> <pre><code>interface PrimaryCore { boolean verifyDataLine(); void sendData(in sequence&lt;byte> data); void initSelfDestruct(); }</code></pre> </figure> <p>The API is designed to use UTF-8.</p> Here we see a figure element to mark up a photo that is the main content of the
page (as in a gallery). <!DOCTYPE HTML> <title>Bubbles at work My Gallery</title> <figure> <img src="bubbles-work.jpeg" alt="Bubbles, sitting in his office chair, works on his latest project intently."> <figcaption>Bubbles at work</figcaption> </figure> <nav><a href="19414.html">Prev</a> <a href="19416.html">Next</a></nav> In this example, we see an image that is not a figure, as well as an image and a
video that are. The first image is literally part of the example's second sentence, so it's not a
self-contained unit, and thus figure would be inappropriate. <h2>Malinko's comics</h2>

http://developers.whatwg.org/grouping-content.html[4/16/2014 9:28:22 PM]

4.4 Grouping content HTML: The Living Standard - Edition for Web Developers

<p>This case centered on some sort of "intellectual property" infringement related to a comic (see Exhibit A). The suit started after a trailer ending with these words: <blockquote> <img src="promblem-packed-action.png" alt="ROUGH COPY! Promblem-Packed Action!"> </blockquote> <p>...was aired. A lawyer, armed with a Bigger Notebook, launched a preemptive strike using snowballs. A complete copy of the trailer is included with Exhibit B. <figure> <img src="ex-a.png" alt="Two squiggles on a dirty piece of paper."> <figcaption>Exhibit A. The alleged <cite>rough copy</cite> comic.</figcaption> </figure> <figure> <video src="ex-b.mov"></video> <figcaption>Exhibit B. The <cite>Rough Copy</cite> trailer. </figcaption> </figure> <p>The case was resolved out of court. Here, a part of a poem is marked up using figure. <figure> <p>'Twas brillig, and the slithy toves<br> Did gyre and gimble in the wabe;<br> All mimsy were the borogoves,<br> And the mome raths outgrabe.</p> <figcaption><cite>Jabberwocky</cite> (first verse). Lewis Carroll, 1832-98</figcaption> </figure> In this example, which could be part of a much larger work discussing a castle, nested
figure elements are used to provide both a group caption and individual captions for
each figure in the group: <figure>

http://developers.whatwg.org/grouping-content.html[4/16/2014 9:28:22 PM]

4.4 Grouping content HTML: The Living Standard - Edition for Web Developers

<figcaption>The castle through the ages: 1423, 1858, and 1999 respectively.</figcaption> <figure> <figcaption>Etching. Anonymous, ca. 1423.</figcaption> <img src="castle1423.jpeg" alt="The castle has one tower, and a tall wall around it."> </figure> <figure> <figcaption>Oil-based paint on canvas. Maria Towle, 1858. </figcaption> <img src="castle1858.jpeg" alt="The castle now has two towers and two walls."> </figure> <figure> <figcaption>Film photograph. Peter Jankle, 1999. </figcaption> <img src="castle1999.jpeg" alt="The castle lies in ruins, the original tower all that remains in one piece."> </figure> </figure> The previous example could also be more succintly written as follows (using title attributes in place of the nested
figure /figcaption pairs): <figure> <img src="castle1423.jpeg" title="Etching. Anonymous, ca. 1423." alt="The castle has one tower, and a tall wall around it."> <img src="castle1858.jpeg" title="Oil-based paint on canvas. Maria Towle, 1858." alt="The castle now has two towers and two walls."> <img src="castle1999.jpeg" title="Film photograph. Peter Jankle, 1999." alt="The castle lies in ruins, the original tower all that remains in one piece."> <figcaption>The castle through the ages: 1423, 1858, and 1999 respectively.</figcaption> </figure> The figure is sometimes referenced only implicitly from the content: <article> <h1>Fiscal negotiations stumble in Congress as deadline nears</h1> <figure> <img src="obama-reid.jpeg" alt="Obama and Reid sit together

http://developers.whatwg.org/grouping-content.html[4/16/2014 9:28:22 PM]

4.4 Grouping content HTML: The Living Standard - Edition for Web Developers

smiling in the Oval Office."> <figcaption>Barrak Obama and Harry Reid. White House press photograph.</figcaption> </figure> <p>Negotiations in Congress to end the fiscal impasse sputtered on Tuesday, leaving both chambers grasping for a way to reopen the government and raise the country's borrowing authority with a Thursday deadline drawing near.</p> ... </article>

The figcaption element


Categories: None. Contexts in which this element can be used: As the first or last child of a figure element. Content model: Flow content. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes DOM interface: Uses HTMLElement. The figcaption element represents a caption or legend for the rest of
the contents of the figcaption element's parent figure element.

The main element


Categories: Flow content. Palpable content. Contexts in which this element can be used: Where flow content is expected. Content model: Flow content. Tag omission in text/html:

http://developers.whatwg.org/grouping-content.html[4/16/2014 9:28:22 PM]

4.4 Grouping content HTML: The Living Standard - Edition for Web Developers

Neither tag is omissible. Content attributes: Global attributes DOM interface: Uses HTMLElement. The main element can be used as a container for the dominant contents of another
element. It represents its children. The main element is distinct from the section and
article elements in that the main element does not contribute to the
document outline. In this example, the author has used a presentation where each component of the page is
rendered in a box. To wrap the main content of the page (as opposed to the header, the footer,
the navigation bar, and a sidebar), the main element is used. <!DOCTYPE html> <title>RPG System 17</title> <style> header, nav, aside, main, footer { margin: 0.5em; border: thin solid; padding: 0.5em; background: #EFF; color: black; box-shadow: 0 0 0.25em #033; } h1, h2, p { margin: 0; } nav, main { float: left; } aside { float: right; } footer { clear: both; } </style> <header> <h1>System Eighteen</h1> </header> <nav> <a href="../16/">&slarr; System 17</a> <a href="../18/">RPXIX &srarr;</a> </nav> <aside> <p>This system has no HP mechanic, so there's no healing. </aside> <main> <h2>Character creation</h2> <p>Attributes (magic, strength, agility) are purchased at the cost of one point per level.</p> <h2>Rolls</h2>

http://developers.whatwg.org/grouping-content.html[4/16/2014 9:28:22 PM]

4.4 Grouping content HTML: The Living Standard - Edition for Web Developers

<p>Each encounter, roll the dice for all your skills. If you roll more than the opponent, you win.</p> </main> <footer> <p>Copyright 2013 </footer>

The div element


Categories: Flow content. Palpable content. Contexts in which this element can be used: Where flow content is expected. Content model: Flow content. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes DOM interface: The div element has no special meaning at all. It represents its
children. It can be used with the class , lang, and title attributes to mark up
semantics common to a group of consecutive elements. Authors are strongly encouraged to view the div element as an element
of last resort, for when no other element is suitable. Use of more appropriate elements instead of
the div element leads to better accessibility for readers and easier maintainability
for authors. For example, a blog post would be marked up using article, a chapter using
section , a page's navigation aids using nav, and a group of form controls using fieldset . On the other hand, div elements can be useful for stylistic purposes or to wrap
multiple paragraphs within a section that are all to be annotated in a similar way. In the
following example, we see div elements used as a way to set the language of two
paragraphs at once, instead of setting the language on the two paragraph elements separately: <article lang="en-US"> <h1>My use of language and my cats</h1>

http://developers.whatwg.org/grouping-content.html[4/16/2014 9:28:22 PM]

4.4 Grouping content HTML: The Living Standard - Edition for Web Developers

<p>My cat's behavior hasn't changed much since her absence, except that she plays her new physique to the neighbors regularly, in an attempt to get pets.</p> <div lang="en-GB"> <p>My other cat, coloured black and white, is a sweetie. He followed us to the pool today, walking down the pavement with us. Yesterday he apparently visited our neighbours. I wonder if he recognises that their flat is a mirror image of ours.</p> <p>Hm, I just noticed that in the last paragraph I used British English. But I'm supposed to write in American English. So I shouldn't say "pavement" or "flat" or "colour"...</p> </div> <p>I should say "sidewalk" and "apartment" and "color"!</p> </article>

Up next

4.5 Text-level semantics

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/grouping-content.html[4/16/2014 9:28:22 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
Text-level semantics
The a element
The em element
The strong element
The small element
The s element
The cite element
The q element
The dfn element
The abbr element
The data element
The time element
The code element
The var element
The samp element
The kbd element
The sub and sup elements
The i element
The b element
The u element
The mark element
The ruby element
The rt element
The rp element
The bdi element
The bdo element
The span element
The br element
The wbr element
Usage summary

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

Text-level semantics

The a element
Categories: Flow content. Phrasing content. Interactive content. Palpable content. Contexts in which this element can be used: Where phrasing content is expected. Content model: Transparent, but there must be no interactive content descendant. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes href Address of the hyperlink target Browsing context for hyperlink navigation download Whether to download the resource instead of navigating to it, and its file name if so ping URLs to ping rel Relationship between the document containing the hyperlink and the destination resource hreflang Language of the linked resource type Hint for the type of the referenced resource DOM interface: If the a element has an href attribute,
then it represents a hyperlink (a hypertext anchor) labeled by its
contents. If the a element has no href attribute,
then the element represents a placeholder for where a link might otherwise have been
placed, if it had been

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

relevant, consisting of just the element's contents. The target, download, ping,
rel, hreflang, and type
attributes must be omitted if the href attribute is not
present. If the itemprop attribute is specified on an a element,
then the href attribute must also be specified. If a site uses a consistent navigation toolbar on every page, then the link that would
normally link to the page itself could be marked up using an a element: <nav> <ul> <li> <a href="/">Home</a> </li> <li> <a href="/news">News</a> </li> <li> <a>Examples</a> </li> <li> <a href="/legal">Legal</a> </li> </ul> </nav>

a . text Same as textContent. The a element may be wrapped around entire paragraphs, lists, tables, and so
forth, even entire sections, so long as there is no interactive content within (e.g. buttons or
other links). This example shows how this can be used to make an entire advertising block into a
link: <aside class="advertising"> <h1>Advertising</h1> <a href="http://ad.example.com/?adid=1929&amp;pubid=1422"> <section> <h1>Mellblomatic 9000!</h1> <p>Turn all your widgets into mellbloms!</p> <p>Only $9.99 plus shipping and handling.</p> </section> </a> <a href="http://ad.example.com/?adid=375&amp;pubid=1422"> <section> <h1>The Mellblom Browser</h1>

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

<p>Web browsing at the speed of light.</p> <p>No other browser goes faster!</p> </section> </a> </aside>

The em element
Categories: Flow content. Phrasing content. Palpable content. Contexts in which this element can be used: Where phrasing content is expected. Content model: Phrasing content. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes DOM interface: Uses HTMLElement. The em element represents stress emphasis of its contents. The level of stress that a particular piece of content has is given by its number of ancestor
em elements. The placement of stress emphasis changes the meaning of the sentence. The element thus forms an
integral part of the content. The precise way in which stress is used in this way depends on the
language. These examples show how changing the stress emphasis changes the meaning. First, a general
statement of fact, with no stress: <p>Cats are cute animals.</p> By emphasizing the first word, the statement implies that the kind of animal
http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

under discussion
is in question (maybe someone is asserting that dogs are cute): <p><em>Cats</em> are cute animals.</p> Moving the stress to the verb, one highlights that the truth of the entire sentence is in
question (maybe someone is saying cats are not cute): <p>Cats <em>are</em> cute animals.</p> By moving it to the adjective, the exact nature of the cats is reasserted (maybe someone
suggested cats were mean animals): <p>Cats are <em>cute</em> animals.</p> Similarly, if someone asserted that cats were vegetables, someone correcting this might
emphasize the last word: <p>Cats are cute <em>animals</em>.</p> By emphasizing the entire sentence, it becomes clear that the speaker is fighting hard to get
the point across. This kind of stress emphasis also typically affects the punctuation, hence the
exclamation mark here. <p><em>Cats are cute animals!</em></p> Anger mixed with emphasizing the cuteness could lead to markup such as: <p><em>Cats are <em>cute</em> animals!</em></p> The em element isn't a generic "italics" element. Sometimes, text is intended to
stand out from the rest of the paragraph, as if it was in a different mood or voice. For this,
the i element is more appropriate. The em element also isn't intended to convey importance; for that purpose, the
strong element is more appropriate.

The strong element


Categories:

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

Flow content. Phrasing content. Palpable content. Contexts in which this element can be used: Where phrasing content is expected. Content model: Phrasing content. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes DOM interface: Uses HTMLElement. The strong element represents strong importance for its contents. The relative level of importance of a piece of content is given by its number of ancestor
strong elements; each strong element increases the importance of its
contents. Changing the importance of a piece of text with the strong element does not change
the meaning of the sentence. Here is an example of a warning notice in a game, with the
various parts marked up according to how important they are: <p><strong>Warning.</strong> This dungeon is dangerous. <strong>Avoid the ducks.</strong> Take any gold you find. <strong><strong>Do not take any of the diamonds</strong>, they are explosive and <strong>will destroy anything within ten meters.</strong></strong> You have been warned.</p>

The small element


Categories: Flow content. Phrasing content.

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

Palpable content. Contexts in which this element can be used: Where phrasing content is expected. Content model: Phrasing content. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes DOM interface: Uses HTMLElement. The small element represents side comments such as small print. Small print typically features disclaimers, caveats, legal restrictions, or copyrights. Small print is also sometimes used for attribution, or for satisfying licensing
requirements. The small element does not "de-emphasize" or lower the importance of
text emphasized by the em element or marked as important with the strong element. To mark text as not emphasized or important, simply do not mark it up with the
em or strong elements respectively. The small element should not be used for extended spans of text, such as multiple
paragraphs, lists, or sections of text. It is only intended for short runs of text. The text of a
page listing terms of use, for instance, would not be a suitable candidate for the
small element: in such a case, the text is not a side comment, it is the main content
of the page. The small element must not be used for subheadings; for that purpose, use the
hgroup element. In this example, the small element is used to indicate that value-added tax is not included in a price of a hotel room: <dl> <dt>Single room <dd>199 <small>breakfast included, VAT not included</small> <dt>Double room

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

<dd>239 <small>breakfast included, VAT not included</small> </dl> In this second example, the small element is used for a side comment in an article. <p>Example Corp today announced record profits for the second quarter <small>(Full Disclosure: Foo News is a subsidiary of Example Corp)</small>, leading to speculation about a third quarter merger with Demo Group.</p> This is distinct from a sidebar, which might be multiple paragraphs long and is removed from
the main flow of text. In the following example, we see a sidebar from the same article. This
sidebar also has small print, indicating the source of the information in the sidebar. <aside> <h1>Example Corp</h1> <p>This company mostly creates small software and Web sites.</p> <p>The Example Corp company mission is "To provide entertainment and news on a sample basis".</p> <p><small>Information obtained from <a href="http://example.com/about.html">example.com</a> home page.</small></p> </aside> In this last example, the small element is marked as being important
small print. <p><strong><small>Continued use of this service will result in a kiss.</small></strong></p>

The s element
Categories:

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

Flow content. Phrasing content. Palpable content. Contexts in which this element can be used: Where phrasing content is expected. Content model: Phrasing content. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes DOM interface: Uses HTMLElement. The s element represents contents that are no longer accurate or no
longer relevant. The s element is not appropriate when indicating document edits; to
mark a span of text as having been removed from a document, use the del element. In this example a recommended retail price has been marked as no longer relevant as the
product in question has a new sale price. <p>Buy our Iced Tea and Lemonade!</p> <p><s>Recommended retail price: $3.99 per bottle</s></p> <p><strong>Now selling for just $2.99 a bottle!</strong></p>

The cite element


Categories: Flow content. Phrasing content. Palpable content. Contexts in which this element can be used: Where phrasing content is expected. Content model:
http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

Phrasing content. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes DOM interface: Uses HTMLElement. The cite element represents the title
of a work (e.g.
a book,
a paper,
an essay, a poem,
a score,
a song,
a script,
a film,
a TV show,
a game,
a sculpture,
a painting,
a theatre production,
a play,
an opera,
a musical,
an exhibition,
a legal case report,
etc). This can be a work that is being quoted or
referenced in detail (i.e. a citation), or it can just be a work
that is mentioned in passing. A person's name is not the title of a work even if people call that person a piece of
work and the element must therefore not be used to mark up people's names. (In some cases,
the b element might be appropriate for names; e.g. in a gossip article where the
names of famous people are keywords rendered with a different style to draw attention to them. In
other cases, if an element is really needed, the span element can be
used.) This next example shows a typical use of the cite element: <p>My favorite book is <cite>The Reality Dysfunction</cite> by Peter F. Hamilton. My favorite comic is <cite>Pearls Before Swine</cite> by Stephan Pastis. My favorite track is <cite>Jive Samba</cite> by the Cannonball Adderley Sextet.</p> This is correct usage: <p>According to the Wikipedia article <cite>HTML</cite>, as it stood in mid-February 2008, leaving attribute values unquoted is unsafe. This is obviously an over-simplification.</p> The following, however, is incorrect usage, as the cite element here is containing far more than the title of the work:

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

<!-- do not copy this example, it is an example of bad usage! --> <p>According to <cite>the Wikipedia article on HTML</cite>, as it stood in mid-February 2008, leaving attribute values unquoted is unsafe. This is obviously an over-simplification.</p> The cite element is obviously a key part of any citation in a bibliography, but
it is only used to mark the title: <p><cite>Universal Declaration of Human Rights</cite>, United Nations, December 1948. Adopted by General Assembly resolution 217 A (III).</p> A citation is not a quote (for which the q element
is appropriate). This is incorrect usage, because cite is not for quotes: <p><cite>This is wrong!</cite>, said Ian.</p> This is also incorrect usage, because a person is not a work: <p><q>This is still wrong!</q>, said <cite>Ian</cite>.</p> The correct usage does not use a cite element: <p><q>This is correct</q>, said Ian.</p> As mentioned above, the b element might be relevant for marking names as being
keywords in certain kinds of documents: <p>And then <b>Ian</b> said <q>this might be right, in a gossip column, maybe!</q>.</p>

The q element
Categories: Flow content.

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

Phrasing content. Palpable content. Contexts in which this element can be used: Where phrasing content is expected. Content model: Phrasing content. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes cite Link to the source of the quotation or more information about the edit DOM interface: Uses HTMLQuoteElement. The q element represents some phrasing
content quoted from another source. Quotation punctuation (such as quotation marks) that is quoting the contents of the element
must not appear immediately before, after, or inside q elements; they will be
inserted into the rendering by the user agent. Content inside a q element must be quoted from another source, whose address, if
it has one, may be cited in the cite attribute. The
source may be fictional, as when quoting characters in a novel or screenplay. If the cite attribute is present, it must be a valid URL
potentially surrounded by spaces. User agents may allow users to follow such citation links, but they are
primarily intended for private use (e.g. by server-side scripts collecting statistics about a
site's use of quotations), not for readers. The q element must not be used in place of quotation marks that do not represent
quotes; for example, it is inappropriate to use the q element for marking up
sarcastic statements. The use of q elements to mark up quotations is entirely optional; using explicit
quotation punctuation without q elements is just as correct. Here is a simple example of the use of the q element: <p>The man said <q>Things that are impossible just take longer</q>. I disagreed with him.</p>

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

Here is an example with both an explicit citation link in the q element, and an
explicit citation outside: <p>The W3C page <cite>About W3C</cite> says the W3C's mission is <q cite="http://www.w3.org/Consortium/">To lead the World Wide Web to its full potential by developing protocols and guidelines that ensure long-term growth for the Web</q>. I disagree with this mission.</p> In the following example, the quotation itself contains a quotation: <p>In <cite>Example One</cite>, he writes <q>The man said <q>Things that are impossible just take longer</q>. I disagreed with him</q>. Well, I disagree even more!</p> In the following example, quotation marks are used instead of the q element: <p>His best argument was I disagree , which

I thought was laughable.</p> In the following example, there is no quote the quotation marks are used to name a
word. Use of the q element in this case would be inappropriate. <p>The word "ineffable" could have been used to describe the disaster resulting from the campaign's mismanagement.</p>

The dfn element


Categories: Flow content. Phrasing content. Palpable content. Contexts in which this element can be used: Where phrasing content is expected. Content model:

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

Phrasing content, but there must be no dfn element descendants. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes Also, the title attribute has special semantics on this element. Full term or expansion of abbreviation DOM interface: Uses HTMLElement. The dfn element represents the defining instance of a term. The paragraph, description list group, or section that is the nearest ancestor of the dfn element must also contain the definition(s) for the term given
by the dfn element. Defining term: If the dfn element has a title attribute, then the exact value of that attribute
is the term being defined. Otherwise, if it contains exactly one element child node and no child
Text nodes, and that child element is an abbr element with a title attribute, then the exact value of that attribute is the term being defined. Otherwise, it is the exact textContent of the
dfn element that gives the term being defined. If the title attribute of the dfn element is
present, then it must contain only the term being defined. The title attribute of ancestor elements does not
affect dfn elements. An a element that links to a dfn element represents an instance of
the term defined by the dfn element. In the following fragment, the term "Garage Door Opener" is first defined in the first
paragraph, then used in the second. In both cases, its abbreviation is what is actually
displayed. <p>The <dfn><abbr title="Garage Door Opener">GDO</abbr></dfn> is a device that allows off-world teams to open the iris.</p> <!-- ... later in the document: --> <p>Teal'c activated his <abbr title="Garage Door Opener">GDO</abbr> and so Hammond ordered the iris to be opened.</p>

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

With the addition of an a element, the reference can be made explicit: <p>The <dfn id=gdo><abbr title="Garage Door Opener">GDO</abbr></dfn> is a device that allows off-world teams to open the iris.</p> <!-- ... later in the document: --> <p>Teal'c activated his <a href=#gdo><abbr title="Garage Door Opener">GDO</abbr></a> and so Hammond ordered the iris to be opened.</p>

The abbr element


Categories: Flow content. Phrasing content. Palpable content. Contexts in which this element can be used: Where phrasing content is expected. Content model: Phrasing content. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes Also, the title attribute has special semantics on this element. Full term or expansion of abbreviation DOM interface: Uses HTMLElement. The abbr element represents an abbreviation or acronym, optionally
with its expansion. The title attribute may be
used to provide an expansion of the abbreviation. The attribute, if specified, must contain an
expansion of the abbreviation, and nothing else. The paragraph below contains an abbreviation marked up with the abbr element.
This paragraph defines the term "Web Hypertext Application

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

Technology Working Group". <p>The <dfn id=whatwg><abbr title="Web Hypertext Application Technology Working Group">WHATWG</abbr></dfn> is a loose unofficial collaboration of Web browser manufacturers and interested parties who wish to develop new technologies designed to allow authors to write and deploy Applications over the World Wide Web.</p> An alternative way to write this would be: <p>The <dfn id=whatwg>Web Hypertext Application Technology Working Group</dfn> (<abbr title="Web Hypertext Application Technology Working Group">WHATWG</abbr>) is a loose unofficial collaboration of Web browser manufacturers and interested parties who wish to develop new technologies designed to allow authors to write and deploy Applications over the World Wide Web.</p> This paragraph has two abbreviations. Notice how only one is defined; the other, with no
expansion associated with it, does not use the abbr element. <p>The <abbr title="Web Hypertext Application Technology Working Group">WHATWG</abbr> started working on HTML5 in 2004.</p> This paragraph links an abbreviation to its definition. <p>The <a href="#whatwg"><abbr title="Web Hypertext Application Technology Working Group">WHATWG</abbr></a> community does not have much representation from Asia.</p>

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

This paragraph marks up an abbreviation without giving an expansion, possibly as a hook to


apply styles for abbreviations (e.g. smallcaps). <p>Philip` and Dashiva both denied that they were going to get the issue counts from past revisions of the specification to backfill the <abbr>WHATWG</abbr> issue graph.</p> If an abbreviation is pluralized, the expansion's grammatical number (plural vs singular) must
match the grammatical number of the contents of the element. Here the plural is outside the element, so the expansion is in the singular: <p>Two <abbr title="Working Group">WG</abbr>s worked on this specification: the <abbr>WHATWG</abbr> and the <abbr>HTMLWG</abbr>.</p> Here the plural is inside the element, so the expansion is in the plural: <p>Two <abbr title="Working Groups">WGs</abbr> worked on this specification: the <abbr>WHATWG</abbr> and the <abbr>HTMLWG</abbr>.</p> Abbreviations do not have to be marked up using this element. It is expected to be useful in
the following cases:

Abbreviations for which the author wants to give expansions, where using the
abbr element with a title attribute is an
alternative to including the expansion inline (e.g. in parentheses).

Abbreviations that are likely to be unfamiliar to the document's readers, for


which authors
are encouraged to either mark up the abbreviation using an abbr element with a title attribute or include the expansion inline in the text the first
time the abbreviation is used.

Abbreviations whose presence needs to be semantically annotated, e.g. so that


they can be
identified from a style sheet and given specific styles, for which the abbr element
can be used without a title attribute. Providing an expansion in a title attribute once
will not necessarily cause other abbr elements in the same document with the same
contents but without a title attribute to behave as if they had
the same expansion. Every abbr element is independent.

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

The data element


Categories: Flow content. Phrasing content. Palpable content. Contexts in which this element can be used: Where phrasing content is expected. Content model: Phrasing content. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes value Machine-readable value DOM interface: The data element represents its contents, along with a
machine-readable form of those contents in the value
attribute. The value attribute must be present. Its value
must be a representation of the element's contents in a machine-readable format. When the value is date- or time-related, the more specific time
element can be used instead. The element can be used for several purposes. When combined with microformats or the microdata attributes defined in
this specification, the element serves to provide both a machine-readable value for the purposes
of data processors, and a human-readable value for the purposes of rendering in a Web browser. In
this case, the format to be used in the value attribute is
determined by the microformats or microdata vocabulary in use. The element can also, however, be used in conjunction with scripts in the page, for when a
script has a literal value to store alongside a human-readable

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

value. In such cases, the format to


be used depends only on the needs of the script. (The data-*
attributes can also be useful in such situations.) Here, a short table has its numeric values encoded using data so that the table sorting model can provide a sorting mechanism on each column, despite the
numbers being presented in textual form in one column and in a decomposed form in another. <table sortable> <thead> <tr> <th> Game <th> Corporations <th> Map Size <tbody> <tr> <td> 1830 <td> <data value="8">Eight</data> <td> <data value="93">19+74 hexes (93 total)</data> <tr> <td> 1856 <td> <data value="11">Eleven</data> <td> <data value="99">12+87 hexes (99 total)</data> <tr> <td> 1870 <td> <data value="10">Ten</data> <td> <data value="149">4+145 hexes (149 total)</data> </table>

The time element


Categories: Flow content. Phrasing content. Palpable content. Contexts in which this element can be used: Where phrasing content is expected. Content model: Phrasing content. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes datetime Machine-readable value DOM interface:

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

The time element represents its contents, along with a


machine-readable form of those contents in the datetime
attribute. The kind of content is limited to various kinds of dates, times, time-zone offsets, and
durations, as described below. The datetime attribute may be present. If
present, its value must be a representation of the element's contents in a machine-readable
format. A time element that does not have a datetime content attribute must not have any element
descendants. The datetime value of a time element is the value of the element's
datetime content attribute, if it has one, or the
element's textContent, if it does not. The datetime value of a time element must match one of the following syntaxes. A valid month string <time>2011-11</time> A valid date string <time>2011-11-12</time> A valid yearless date string <time>11-12</time> A valid time string <time>14:54</time> <time>14:54:39</time> <time>14:54:39.929</time> A valid local date and time string <time>2011-11-12T14:54</time> <time>2011-11-12T14:54:39</time>

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

<time>2011-11-12T14:54:39.929</time> <time>2011-11-12 14:54</time> <time>2011-11-12 14:54:39</time> <time>2011-11-12 14:54:39.929</time> Times with dates but without a time zone offset are useful for specifying events
that are observed at the same specific time in each time zone, throughout a day. For example,
the 2020 new year is celebrated at 2020-0101 00:00 in each time zone, not at the same precise
moment across all time zones. For events that occur at the same time across all time zones, for example a videoconference meeting, a valid global date and time string is likely
more useful. A valid time-zone offset string <time>Z</time> <time>+0000</time> <time>+00:00</time> <time>-0800</time> <time>-08:00</time> For times without dates (or times referring to events that recur on multiple dates), specifying the geographic location that controls the time is usually more useful than
specifying a time zone offset, because geographic locations change time zone offsets with
daylight savings time. In some cases, geographic locations even change time zone, e.g. when the
boundaries of those time zones are redrawn, as happened with Samoa at the end of 2011. There
exists a time zone database that describes the boundaries of time zones and what rules apply
within each such zone, known as the time zone database. A valid global date and time string <time>2011-11-12T14:54Z</time>

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

<time>2011-11-12T14:54:39Z</time> <time>2011-11-12T14:54:39.929Z</time> <time>2011-11-12T14:54+0000</time> <time>2011-11-12T14:54:39+0000</time> <time>2011-11-12T14:54:39.929+0000</time> <time>2011-11-12T14:54+00:00</time> <time>2011-11-12T14:54:39+00:00</time> <time>2011-11-12T14:54:39.929+00:00</time> <time>2011-11-12T06:54-0800</time> <time>2011-11-12T06:54:39-0800</time> <time>2011-11-12T06:54:39.929-0800</time> <time>2011-11-12T06:54-08:00</time> <time>2011-11-12T06:54:39-08:00</time> <time>2011-11-12T06:54:39.929-08:00</time> <time>2011-11-12 14:54Z</time> <time>2011-11-12 14:54:39Z</time> <time>2011-11-12 14:54:39.929Z</time> <time>2011-11-12 14:54+0000</time> <time>2011-11-12 14:54:39+0000</time> <time>2011-11-12 14:54:39.929+0000</time> <time>2011-11-12 14:54+00:00</time>

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

<time>2011-11-12 14:54:39+00:00</time> <time>2011-11-12 14:54:39.929+00:00</time> <time>2011-11-12 06:54-0800</time> <time>2011-11-12 06:54:39-0800</time> <time>2011-11-12 06:54:39.929-0800</time> <time>2011-11-12 06:54-08:00</time> <time>2011-11-12 06:54:39-08:00</time> <time>2011-11-12 06:54:39.929-08:00</time> Times with dates and a time zone offset are useful for specifying specific events, or recurring virtual events where the time is not anchored to a specific geographic
location. For example, the precise time of an asteroid impact, or a particular meeting in a
series of meetings held at 1400 UTC every day, regardless of whether any particular part of the
world is observing daylight savings time or not. For events where the precise time varies by the local time zone offset of a specific geographic location, a valid local date and time
string combined with that geographic location is likely more useful. A valid week string <time>2011-W46</time> Four or more ASCII digits, at least one of which is not U+0030 DIGIT ZERO (0) <time>2011</time> <time>0001</time> A valid duration string <time>PT4H18M3S</time> <time>4h 18m 3s</time>

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

The time element can be used to encode dates, for example in microformats. The
following shows a hypothetical way of encoding an event using a variant on hCalendar that uses
the time element: <div class="vevent"> <a class="url" href="http://www.web2con.com/">http://www.web2con.com/</a> <span class="summary">Web 2.0 Conference</span>: <time class="dtstart" datetime="2005-10-05">October 5</time> <time class="dtend" datetime="2005-10-07">7</time>, at the <span class="location">Argent Hotel, San Francisco, CA</span> </div> Here, a fictional microdata vocabulary based on the Atom vocabulary is used with the
time element to mark up a blog post's publication date. <article itemscope itemtype="http://n.example.org/rfc4287"> <h1 itemprop="title">Big tasks</h1> <footer>Published <time itemprop="published" datetime="200908-29">two days ago</time>.</footer> <p itemprop="content">Today, I went out and bought a bike for my kid.</p> </article> In this example, another article's publication date is marked up using time, this
time using the schema.org microdata vocabulary: <article itemscope itemtype="http://schema.org/BlogPosting"> <h1 itemprop="headline">Small tasks</h1> <footer>Published <time itemprop="datePublished" datetime="2009-08-30">yesterday</time>.</footer> <p itemprop="articleBody">I put a bike bell on his bike.</p> </article> In the following snippet, the time element is used to encode a date in the ISO8601 format, for later processing by a script: <p>Our first date was <time datetime="2006-09-23">a Saturday</time>.</p>

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

In this second snippet, the value includes a time: <p>We stopped talking at <time datetime="2006-09-24T05:0007:00">5am the next morning</time>.</p> A script loaded by the page (and thus privy to the page's internal convention of marking up
dates and times using the time element) could scan through the page and look at all
the time elements therein to create an index of dates and times. For example, this element conveys the string "Tuesday" with the additional semantic that the
12th of November 2011 is the meaning that corresponds to "Tuesday": Today is <time datetime="2011-11-12">Tuesday</time>. In this example, a specific time in the Pacific Standard Time timezone is specified: Your next meeting is at <time datetime="2011-11-12T15:0008:00">3pm</time>.

The code element


Categories: Flow content. Phrasing content. Palpable content. Contexts in which this element can be used: Where phrasing content is expected. Content model: Phrasing content. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes DOM interface:

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

Uses HTMLElement. The code element represents a fragment of computer code. This could
be an XML element name, a file name, a computer program, or any other string that a computer would
recognize. There is no formal way to indicate the language of computer code being marked up. Authors who
wish to mark code elements with the language used, e.g. so that syntax highlighting
scripts can use the right rules, can use the class attribute, e.g.
by adding a class prefixed with "language- " to the element. The following example shows how the element can be used in a paragraph to mark up element
names and computer code, including punctuation. <p>The <code>code</code> element represents a fragment of computer code.</p> <p>When you call the <code>activate()</code> method on the <code>robotSnowman</code> object, the eyes glow.</p> <p>The example below uses the <code>begin</code> keyword to indicate the start of a statement block. It is paired with an <code>end</code> keyword, which is followed by the <code>.</code> punctuation character (full stop) to indicate the end of the program.</p> The following example shows how a block of code could be marked up using the pre
and code elements. <pre><code class="language-pascal">var i: Integer; begin i := 1; end.</code></pre> A class is used in that example to indicate the language used. See the pre element for more details.

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

The var element


Categories: Flow content. Phrasing content. Palpable content. Contexts in which this element can be used: Where phrasing content is expected. Content model: Phrasing content. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes DOM interface: Uses HTMLElement. The var element represents a variable. This could be an actual
variable in a mathematical expression or programming context, an identifier representing a
constant, a symbol identifying a physical quantity, a function parameter, or just be a term used
as a placeholder in prose. In the paragraph below, the letter "n" is being used as a
variable in prose: <p>If there are <var>n</var> pipes leading to the ice cream factory then I expect at <em>least</em> <var>n</var> flavors of ice cream to be available for purchase!</p> For mathematics, in particular for anything beyond the simplest of expressions, MathML is more
appropriate. However, the var element can still be used to refer to specific
variables that are then mentioned in MathML expressions. In this example, an equation is shown, with a legend that references the variables in the
equation. The expression itself is marked up with MathML, but the variables are mentioned in the
figure's legend using var .

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

<figure> <math> <mi>a</mi> <mo>=</mo> <msqrt> <msup><mi>b</mi><mn>2</mn></msup> <mi>+</mi> <msup><mi>c</mi><mn>2</mn></msup> </msqrt> </math> <figcaption> Using Pythagoras' theorem to solve for the hypotenuse <var>a</var> of a triangle with sides <var>b</var> and <var>c</var> </figcaption> </figure> Here, the equation describing mass-energy equivalence is used in a sentence, and the
var element is used to mark the variables and constants in that equation: <p>Then he turned to the blackboard and picked up the chalk. After a few moment's thought, he wrote <var>E</var> = <var>m</var> <var>c</var> <sup>2</sup>. The teacher looked pleased.</p>

The samp element


Categories: Flow content. Phrasing content. Palpable content. Contexts in which this element can be used: Where phrasing content is expected. Content model: Phrasing content.

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes DOM interface: Uses HTMLElement. The samp element represents (sample) output from a program or
computing system. See the pre and kbd elements for more details. This example shows the samp element being used
inline: <p>The computer said <samp>Too much cheese in tray two</samp> but I didn't know what that meant.</p> This second example shows a block of sample output. Nested samp and
kbd elements allow for the styling of specific elements of the sample output using a
style sheet. There's also a few parts of the samp that are annotated with even more
detailed markup, to enable very precise styling. To achieve this, span elements are
used. <pre><samp><span class="prompt">jdoe@mowmow:~$</span> <kbd>ssh demo.example.com</kbd> Last login: Tue Apr 12 09:10:17 2005 from mowmow.example.com on pts/1 Linux demo 2.6.10-grsec+gg3+e+fhs6b+nfs+gr0501+++p3+c4a+gr2breslog-v6.189 #1 SMP Tue Feb 1 11:22:36 PST 2005 i686 unknown <span class="prompt">jdoe@demo:~$</span> <span class="cursor">_</span></samp></pre>

The kbd element


Categories: Flow content. Phrasing content.

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

Palpable content. Contexts in which this element can be used: Where phrasing content is expected. Content model: Phrasing content. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes DOM interface: Uses HTMLElement. The kbd element represents user input (typically keyboard input,
although it may also be used to represent other input, such as voice commands). When the kbd element is nested inside a samp element, it represents
the input as it was echoed by the system. When the kbd element contains a samp element, it represents
input based on system output, for example invoking a menu item. When the kbd element is nested inside another kbd element, it
represents an actual key or other single unit of input as appropriate for the input mechanism. Here the kbd element is used to indicate keys to press: <p>To make George eat an apple, press <kbd><kbd>Shift</kbd>+ <kbd>F3</kbd></kbd></p> In this second example, the user is told to pick a particular menu item. The outer
kbd element marks up a block of input, with the inner kbd elements representing each individual step of the input, and the samp elements inside them
indicating that the steps are input based on something being displayed by the system, in this
case menu labels: <p>To make George eat an apple, select <kbd><kbd><samp>File</samp></kbd>|<kbd><samp>Eat Apple... </samp></kbd></kbd> </p>

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

Such precision isn't necessary; the following is equally fine: <p>To make George eat an apple, select <kbd>File | Eat Apple...</kbd></p>

The sub and sup elements


Categories: Flow content. Phrasing content. Palpable content. Contexts in which this element can be used: Where phrasing content is expected. Content model: Phrasing content. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes DOM interface: Use HTMLElement. The sup element represents a superscript and the sub
element represents a subscript. These elements must be used only to mark up typographical conventions with specific meanings,
not for typographical presentation for presentation's sake. For example, it would be inappropriate
for the sub and sup elements to be used in the name of the LaTeX
document preparation system. In general, authors should use these elements only if the
absence of those elements would change the meaning of the content. In certain languages, superscripts are part of the typographical conventions for some
abbreviations. <p>The most beautiful women are <span lang="fr"><abbr>M<sup>lle</sup></abbr>

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

Gwendoline</span> and <span lang="fr"><abbr>M<sup>me</sup></abbr> Denise</span>. </p> The sub element can be used inside a var element, for variables that
have subscripts. Here, the sub element is used to represent the subscript that identifies the variable in a family of variables: <p>The coordinate of the <var>i</var>th point is (<var>x<sub><var>i</var></sub></var>, <var>y<sub><var>i</var> </sub></var>). For example, the 10th point has coordinate (<var>x<sub>10</sub></var>, <var>y<sub>10</sub></var>).</p> Mathematical expressions often use subscripts and superscripts. Authors are encouraged to use
MathML for marking up mathematics, but authors may opt to use sub and
sup if detailed mathematical markup is not desired. <var>E</var>=<var>m</var><var>c</var><sup>2</sup> f(<var>x</var>, <var>n</var>) = log<sub>4</sub><var>x</var> <sup><var>n</var></sup>

The i element
Categories: Flow content. Phrasing content. Palpable content. Contexts in which this element can be used: Where phrasing content is expected. Content model: Phrasing content. Tag omission in text/html: Neither tag is omissible. Content attributes:

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

Global attributes DOM interface: Uses HTMLElement. The i element represents a span of text in an alternate voice or
mood, or otherwise offset from the normal prose in a manner indicating a different quality of
text, such as a taxonomic designation, a technical term, an idiomatic phrase from another
language, transliteration, a thought, or a ship name in Western texts. Terms in languages different from the main text should be annotated with lang attributes (or, in XML, lang attributes in the XML namespace). The examples below show uses of the i element: <p>The <i class="taxonomy">Felis silvestris catus</i> is cute.</p> <p>The term <i>prose content</i> is defined above.</p> <p>There is a certain <i lang="fr">je ne sais quoi</i> in the air.</p> In the following example, a dream sequence is marked up using
i elements. <p>Raymond tried to sleep.</p> <p><i>The ship sailed away on Thursday</i>, he dreamt. <i>The ship had many people aboard, including a beautiful princess called Carey. He watched her, day-in, day-out, hoping she would notice him, but she never did.</i></p> <p><i>Finally one night he picked up the courage to speak with her</i></p> <p>Raymond woke with a start as the fire alarm rang out.</p> Authors can use the class attribute on the i
element to identify why the element is being used, so that if the style of a particular use (e.g.
dream sequences as opposed to taxonomic terms) is to be changed at a later date, the author
doesn't have to go through the entire document (or series of related documents) annotating each
use. Authors are encouraged to consider whether other elements might be more
http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

applicable than the


i element, for instance the em element for marking up stress emphasis,
or the dfn element to mark up the defining instance of a term. Style sheets can be used to format i elements, just like any other
element can be restyled. Thus, it is not the case that content in i elements will
necessarily be italicized.

The b element
Categories: Flow content. Phrasing content. Palpable content. Contexts in which this element can be used: Where phrasing content is expected. Content model: Phrasing content. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes DOM interface: Uses HTMLElement. The b element represents a span of text to which attention is being
drawn for utilitarian purposes without conveying any extra importance and with no implication of
an alternate voice or mood, such as key words in a document abstract, product names in a review,
actionable words in interactive textdriven software, or an article lede. The following example shows a use of the b element to highlight key words without
marking them up as important: <p>The <b>frobonitor</b> and <b>barbinator</b> components are fried.</p>

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

In the following example, objects in a text adventure are highlighted as being special by use
of the b element. <p>You enter a small room. Your <b>sword</b> glows brighter. A <b>rat</b> scurries past the corner wall.</p> Another case where the b element is appropriate is in marking up the lede (or
lead) sentence or paragraph. The following example shows how a BBC article about
kittens adopting a rabbit as their own could be marked up: <article> <h2>Kittens 'adopted' by pet rabbit</h2> <p><b class="lede">Six abandoned kittens have found an unexpected new mother figure a pet rabbit.</b></p> <p>Veterinary nurse Melanie Humble took the three-week-old kittens to her Aberdeen home.</p> [...] As with the i element, authors can use the class
attribute on the b element to identify why the element is being used, so that if the
style of a particular use is to be changed at a later date, the author doesn't have to go through annotating each use. The b element should be used as a last resort when no other element is more appropriate. In particular, headings should use the h1 to h6 elements,
stress emphasis should use the em element, importance should be denoted with the strong element, and text marked or highlighted should use the mark
element. The following would be incorrect usage: <p><b>WARNING!</b> Do not frob the barbinator!</p> In the previous example, the correct element to use would have been strong, not
b . Style sheets can be used to format b elements, just like any other
element can be restyled. Thus, it is not the case that content in b elements will
necessarily be boldened.

The u element

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

Categories: Flow content. Phrasing content. Palpable content. Contexts in which this element can be used: Where phrasing content is expected. Content model: Phrasing content. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes DOM interface: Uses HTMLElement. The u element represents a span of text with an unarticulated, though explicitly rendered, non-textual annotation, such as labeling the text as being a proper name in
Chinese text (a Chinese proper name mark), or labeling the text as being misspelt. In most cases, another element is likely to be more appropriate: for marking stress emphasis,
the em element should be used; for marking key words or phrases either the
b element or the mark element should be used, depending on the context;
for marking book titles, the cite element should be used; for labeling text with explicit textual annotations, the
ruby element should be used; for labeling ship names in Western texts, the
i element should be used. The default rendering of the u element in visual presentations
clashes with the conventional rendering of hyperlinks (underlining). Authors are encouraged to
avoid using the u element where it could be confused for a hyperlink.

The mark element


Categories: Flow content.

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

Phrasing content. Palpable content. Contexts in which this element can be used: Where phrasing content is expected. Content model: Phrasing content. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes DOM interface: Uses HTMLElement. The mark element represents a run of text in one document marked or highlighted for reference purposes, due to its relevance in another context. When used in a
quotation or other block of text referred to from the prose, it indicates a highlight that was not
originally present but which has been added to bring the reader's attention to a part of the text
that might not have been considered important by the original author when the block was originally written, but which is now under previously unexpected scrutiny. When used in the main prose of a
document, it indicates a part of the document that has been highlighted due to its likely
relevance to the user's current activity. This example shows how the mark element can be used to bring attention to a
particular part of a quotation: <p lang="en-US">Consider the following quote:</p> <blockquote lang="en-GB"> <p>Look around and you will find, no-one's really <mark>colour</mark> blind.</p> </blockquote> <p lang="en-US">As we can tell from the <em>spelling</em> of the word, the person writing this quote is clearly not American.</p> (If the goal was to mark the element as misspelt, however, the u element, possibly with a class, would be more appropriate.) Another example of the mark element is highlighting parts of a document that

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

are
matching some search string. If someone looked at a document, and the server knew that the user
was searching for the word "kitten", then the server might return the document with one paragraph
modified as follows: <p>I also have some <mark>kitten</mark>s who are visiting me these days. They're really cute. I think they like my garden! Maybe I should adopt a <mark>kitten</mark>.</p> In the following snippet, a paragraph of text refers to a specific part of a code
fragment. <p>The highlighted part below is where the error lies:</p> <pre><code>var i: Integer; begin i := <mark>1.1</mark>; end.</code></pre> This is separate from syntax highlighting, for which span is more appropriate. Combining both, one would get: <p>The highlighted part below is where the error lies:</p> <pre><code><span class=keyword>var</span> <span class=ident>i</span>: <span class=type>Integer</span>; <span class=keyword>begin</span> <span class=ident>i</span> := <span class=literal> <mark>1.1</mark></span>; <span class=keyword>end</span>.</code></pre> This is another example showing the use of mark to highlight a part of quoted
text that was originally not emphasized. In this example, common typographic conventions have led
the author to explicitly style mark elements in quotes to render in italics. <article> <style scoped> blockquote mark, q mark { font: inherit; font-style: italic; text-decoration: none; background: transparent; color: inherit; } .bubble em {
http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

font: inherit; font-size: larger; text-decoration: underline; } </style> <h1>She knew</h1> <p>Did you notice the subtle joke in the joke on panel 4? </p> <blockquote> <p class="bubble">I didn't <em>want</em> to believe. <mark>Of course on some level I realized it was a known-plaintext attack. </mark> But I couldn't admit it until I saw for myself.</p> </blockquote> <p>(Emphasis mine.) I thought that was great. It's so pedantic, yet it explains everything neatly.</p> </article> Note, incidentally, the distinction between the em element in this example, which
is part of the original text being quoted, and the mark element, which is
highlighting a part for comment. The following example shows the difference between denoting the importance of a span
of text (strong) as opposed to denoting the relevance of a span of text
(mark ). It is an extract from a textbook, where the extract has had the parts
relevant to the exam highlighted. The safety warnings, important though they may be, are
apparently not relevant to the exam. <h3>Wormhole Physics Introduction</h3> <p><mark>A wormhole in normal conditions can be held open for a maximum of just under 39 minutes.</mark> Conditions that can increase the time include a powerful energy source coupled to one or both of the gates connecting the wormhole, and a large gravity well (such as a black hole).</p>

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

<p><mark>Momentum is preserved across the wormhole. Electromagnetic radiation can travel in both directions through a wormhole, but matter cannot.</mark></p> <p>When a wormhole is created, a vortex normally forms. <strong>Warning: The vortex caused by the wormhole opening will annihilate anything in its path.</strong> Vortexes can be avoided when using sufficiently advanced dialing technology.</p> <p><mark>An obstruction in a gate will prevent it from accepting a wormhole connection.</mark></p>

The ruby element


Categories: Flow content. Phrasing content. Palpable content. Contexts in which this element can be used: Where phrasing content is expected. Content model: See prose. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes DOM interface: Uses HTMLElement. The ruby element allows one or more spans of phrasing content to be marked with
ruby annotations. Ruby annotations are short runs of text presented alongside base text, primarily
used in East Asian typography as a guide for

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

pronunciation or to include other annotations. In


Japanese, this form of typography is also known as furigana. The content model of ruby elements consists of one or more of the following sequences: 1. One or the other of the following:

Phrasing content, but with no ruby elements and with no ruby element
descendants

A single ruby element that itself has no ruby element descendants


2. One or the other of the following:

One or more rt elements An rp element followed by one or more rt elements, each of which is itself
followed by an rp element The ruby and rt elements can be used for a variety of kinds of
annotations, including in particular (though by no means limited to) those described below. For
more details on Japanese Ruby in particular, and how to render Ruby for Japanese, see
Requirements for Japanese Text Layout. At the time of writing, CSS does not yet provide a way to fully control the rendering of the HTML ruby element. It is hoped that CSS will be extended to support
the styles described below in due course.

Mono-ruby for individual base characters in Japanese One or more hiragana or katakana characters (the ruby annotation) are placed with each
ideographic character (the base text). This is used to provide readings of kanji characters. <ruby>B<rt>annotation</ruby> In this example, notice how each annotation corresponds to a single base character. <ruby><rt></ruby> </ruby>

<ruby><rt></ruby><ruby><rt></ruby><ruby><rt>

This example can also be written as follows, using one ruby element with two

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

segments of base text and two annotations (one for each) rather than two back-to-back
ruby elements each with one base text segment and annotation (as in the markup
above): <ruby><rt></rt><rt></ruby><ruby><rt></ruby> <ruby><rt></ruby>

Mono-ruby for compound words (jukugo) This is similar to the previous case: each ideographic character in the compound word (the
base text) has its reading given in hiragana or katakana characters (the ruby annotation). The
difference is that the base text segments form a compound word rather than being separate from
each other. <ruby>B<rt>annotation</rt>B<rt>annotation</ruby> In this example, notice again how each annotation corresponds to a single base character. In this example, each compound word (jukugo) corresponds to a single ruby element. The rendering here is expected to be that each annotation be placed over (or next to, in vertical text) the corresponding base character, with the annotations not overhanging any of the adjacent characters. <ruby><rt></rt><rt></rt></ruby><ruby><rt> </rt><rt></rt></ruby><ruby><rt> </rt><rt></rt></ruby> Jukugo-ruby This is semantically identical to the previous case (each individual ideographic character in
the base compound word has its reading given in an annotation in hiragana or katakana
characters), but the rendering is the more complicated Jukugo Ruby rendering. This is the same example as above for mono-ruby for compound words. The different rendering is expected to be achieved using different styling (e.g. in CSS), and is not shown here. <ruby><rt></rt><rt></rt></ruby><ruby><rt> </rt><rt></rt></ruby> </rt><rt></rt></ruby><ruby><rt>

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

For more details on Jukugo Ruby rendering, see


Appendix F in the Requirements for Japanese Text Layout. [JLREQ] Group ruby for describing meanings The annotation describes the meaning of the base text, rather than (or in addition to) the
pronunciation. As such, both the base text and the annotation can be multiple characters long. <ruby>BASE<rt>annotation</ruby> Here a compound ideographic word has its corresponding katakana given as an annotation. <ruby><rt></ruby>

Here a compound ideographic word has its translation in English provided as an annotation. <ruby lang="ja"><rt lang="en">editor</ruby> Group ruby for Jukuji readings A phonetic reading that corresponds to multiple base characters, because a one-to-one mapping
would be difficult. (In English, the words "Colonel" and "Lieutenant" are examples of words
where a direct mapping of pronunciation to individual letters is, in some dialects, rather
unclear.) In this example, the name of a species of flowers has a phonetic reading provided using group ruby: <ruby><rt></ruby> Text with both phonetic and semantic annotations (double-sided ruby) Sometimes, ruby styles described above are combined. If this results in two annotations covering the same single base segment, then the
annotations can just be placed back to back.
editor

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

<ruby>BASE<rt>annotation 1<rt>annotation 2</ruby> <ruby>B<rt>a<rt>a</ruby><ruby>A<rt>a<rt>a</ruby> <ruby>S<rt>a<rt>a</ruby><ruby>E<rt>a<rt>a</ruby> In this contrived example, some symbols are given names in English and French. <ruby> <rt> Heart <rt lang=fr> Cur <rt> Shamrock <rt lang=fr> Trfle &sext; <rt> Star <rt lang=fr> toile </ruby> In more complication situations such as following examples, a nested ruby element is used to give the inner annotations, and then that whole ruby is then
given an annotation at the "outer" level. <ruby><ruby>B<rt>a</rt>A<rt>n</rt>S<rt>t</rt>E<rt>n</rt> </ruby><rt>annotation</ruby> Here both a phonetic reading and the meaning are given in ruby annotations. The annotation on the nested ruby element gives a mono-ruby phonetic annotation for each base character, while the annotation in the rt element that is a child of the outer ruby element gives the meaning using hiragana. <ruby><ruby><rt></rt><rt></rt></ruby><rt> </rt></ruby>

This is the same example, but the meaning is given in English instead of Japanese: <ruby><ruby><rt></rt><rt></rt></ruby><rt lang=en>Southeast</rt></ruby>

Southeast

Within a ruby element that does not have a ruby element ancestor,
content is

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

segmented and segments are placed into three categories: base text segments, annotation
segments, and ignored segments. Ignored segments do not form part of the document's semantics
(they consist of some inter-element whitespace and rp elements, the
latter of which are used for legacy user agents that do not support ruby at all). Base text
segments can overlap (with a limit of two segments overlapping any one position in the DOM, and
with any segment having an earlier start point than an overlapping segment also having an equal or
later end point, and any segment have a later end point than an overlapping segment also having an
equal or earlier start point). Annotation segments correspond to rt elements. Each annotation
segment can be associated with a base text segment, and each base text segment can have annotation
segments associated with it. (In a conforming document, each base text segment is associated with
at least one annotation segment, and each annotation segment is associated with one base text
segment.) A ruby element represents the union of the segments of base
text it contains, along with the mapping from those base text segments to annotation segments.
Segments are described in terms of DOM ranges; annotation segment ranges always consist of exactly
one element. At any particular time, the segmentation and categorisation of content of a ruby
element is the result that would be obtained from running the following algorithm: 1. Let base text segments be an empty list of base text segments, each
potentially with a list of base text subsegments. 2. Let annotation segments be an empty list of annotation segments, each potentially being associated with a base text segment or subsegment. 3. Let root be the ruby element for which the algorithm is
being run. 4. If root has a ruby element ancestor, then jump to the
step labeled end. 5. Let current parent be root. 6. Let index be 0. 7. Let start index be null. 8. Let parent start index be null. 9. Let current base text be null. 10. Start mode: If index is equal to or greater than the number of
child nodes in

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

current parent, then jump to the step labeled end


mode. 11. If the indexth node in current parent is an
rt or rp element, jump to the step labeled annotation
mode. 12. Set start index to the value of index. 13. Base mode: If the indexth node in current
parent is a ruby element, and if current parent is the
same element as root, then push a ruby level and then jump to
the step labeled start mode. 14. If the indexth node in current parent is an
rt or rp element, then set the current base text and then
jump to the step labeled annotation mode. 15. Increment index by one. 16. Base mode post-increment: If index is equal to or greater than
the number of child nodes in current parent, then jump to the step labeled
end mode. 17. Jump back to the step labeled base mode. 18. Annotation mode: If the indexth node in current
parent is an rt element, then push a ruby annotation and jump to
the step labeled annotation mode increment. 19. If the indexth node in current parent is an
rp element, jump to the step labeled annotation mode increment. 20. If the indexth node in current parent is not a
Text node, or is a Text node that is not inter-element
whitespace, then jump to the step labeled base mode. 21. Annotation mode increment: Let lookahead index be index plus one. 22. Annotation mode white-space skipper: If lookahead index is
equal to the number of child nodes in current parent then jump to the step
labeled end mode. 23. If the lookahead indexth node in current parent is
an rt element or an rp element, then set index to
lookahead index and jump to the step labeled annotation mode. 24. If the lookahead indexth node in current parent is
not a Text node, or is a Text node that is not inter-element
whitespace, then jump to the step labeled base mode (without further incrementing
index, so the inter-element

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

whitespace seen so far becomes part


of the next base text segment). 25. Increment lookahead index by one. 26. Jump to the step labeled annotation mode white-space skipper. 27. End mode: If current parent is not the same element as root, then pop a ruby level and jump to the step labeled base mode
post-increment. 28. End: Return base text segments and annotation
segments. Any content of the ruby element not described by segments in either
of those lists is implicitly in an ignored segment. When the steps above say to set the current base text, it means to run the following
steps at that point in the algorithm: 1. Let text range be a DOM range whose start is the boundary
point (current parent, start index) and whose
end is the boundary
point (current parent, index). 2. Let new text segment be a base text segment described by the range annotation range. 3. Add new text segment to base text
segments. 4. Let current base text be new text
segment. 5. Let start index be null. When the steps above say to push a ruby level, it means to run the following steps
at that point in the algorithm: 1. Let current parent be the indexth node in current parent. 2. Let index be 0. 3. Set saved start index to the value of start
index. 4. Let start index be null. When the steps above say to pop a ruby level, it means to run the following steps at
that point in the algorithm: 1. Let index be the position of current parent in
root. 2. Let current parent be root.

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

3. Increment index by one. 4. Set start index to the value of saved start
index. 5. Let saved start index be null. When the steps above say to push a ruby annotation, it means to run the following
steps at that point in the algorithm: 1. Let rt be the rt element that is the indexth node of current parent. 2. Let annotation range be a DOM range whose start is the boundary
point (current parent, index) and whose end is the boundary point
(current parent, index plus one) (i.e. that contains only
rt). 3. Let new annotation segment be an annotation segment described by the
range annotation range. 4. If current base text is not null, associate new
annotation segment with current base text. 5. Add new annotation segment to annotation
segments. In this example, each ideograph in the Japanese text is annotated with its reading in hiragana. ... ... This might be rendered as:

<ruby><rt></rt><rt></rt></ruby>

In this example, each ideograph in the traditional Chinese text is annotated with its bopomofo reading. <ruby><rt> </rt><rt> </rt></ruby>

This might be rendered as:

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

In this example, each ideograph in the simplified Chinese text is annotated with its pinyin reading. ...<ruby><rt>hn</rt><rt>z</rt></ruby>... This might be rendered as:

In this more contrived example, the acronym "HTML" has four annotations: one for the whole
acronym, briefly describing what it is, one for the letters "HT" expanding them to "Hypertext",
one for the letter "M" expanding it to "Markup", and one for the letter "L" expanding it to
"Language". <ruby> <ruby>HT<rt>Hypertext</rt>M<rt>Markup</rt>L<rt>Language</rt> </ruby> <rt>An abstract language for describing documents and applications </ruby>

The rt element
Categories: None. Contexts in which this element can be used: As a child of a ruby element. Content model: Phrasing content. Tag omission in text/html: An rt element's end tag can be omitted if the
rt element is immediately

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

followed by an rt or rp element,
or if there is no more content in the parent element. Content attributes: Global attributes DOM interface: Uses HTMLElement. The rt element marks the ruby text component of a ruby annotation. When it is the
child of a ruby element, it doesn't represent
anything itself, but the ruby element uses it as part of determining what it
represents.

The rp element
Categories: None. Contexts in which this element can be used: As a child of a ruby element, either immediately before or immediately after an rt element. Content model: Phrasing content. Tag omission in text/html: An rp element's end tag can be omitted if the
rp element is immediately followed by an rt or rp element,
or if there is no more content in the parent element. Content attributes: Global attributes DOM interface: Uses HTMLElement. The rp element can be used to provide parentheses or other content around a ruby
text component of a ruby annotation, to be shown by user agents that don't support ruby
annotations. An rp element represents nothing. The example above, in which each ideograph in the text is annotated

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

with its phonetic reading, could be expanded to


use rp so that in legacy user agents the readings are in parentheses: ...

<rt></rt><rp>) </rp></ruby> ...

<ruby><rp> (</rp><rt></rt><rp>) </rp><rp> (</rp>

In conforming user agents the rendering would be as above, but in user agents that do not
support ruby, the rendering would be: ... () () ... When there are multiple annotations for a segment, rp elements can also be placed
between the annotations. Here is another copy of an earlier contrived example showing some
symbols with names given in English and French, but this time with rp elements as
well: <ruby> <rp>: </rp><rt>Heart</rt><rp>, </rp><rt lang=fr>Cur</rt> <rp>.</rp> <rp>: </rp><rt>Shamrock</rt><rp>, </rp><rt lang=fr>Trfle</rt><rp>.</rp> &sext;<rp>: </rp><rt>Star</rt><rp>, </rp><rt lang=fr>toile</rt><rp>.</rp> </ruby> This would make the example render as follows in non-ruby-capable user agents: : Heart, Cur. : Shamrock, Trfle. &sext;: Star, toile.

The bdi element


Categories: Flow content. Phrasing content. Palpable content. Contexts in which this element can be used:

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

Where phrasing content is expected. Content model: Phrasing content. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes Also, the dir global attribute has special semantics on this element. DOM interface: Uses HTMLElement. The bdi element represents a span of text that is to be isolated from
its surroundings for the purposes of bidirectional text formatting. The dir global attribute defaults to auto on this element (it never inherits from the parent element like
with other elements). This element is especially useful when embedding user-generated content with an unknown
directionality. In this example, usernames are shown along with the number of posts that the user has
submitted. If the bdi element were not used, the username of the Arabic user would
end up confusing the text (the bidirectional algorithm would put the colon and the number "3"
next to the word "User" rather than next to the word "posts"). <ul> <li>User <bdi>jcranmer</bdi>: 12 posts. <li>User <bdi>hober</bdi>: 5 posts. <li>User <bdi></bdi>: 3 posts. </ul>

The bdo element


Categories: Flow content. Phrasing content.

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

Palpable content. Contexts in which this element can be used: Where phrasing content is expected. Content model: Phrasing content. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes Also, the dir global attribute has special semantics on this element. DOM interface: Uses HTMLElement. The bdo element represents explicit text directionality formatting
control for its children. It allows authors to override the Unicode bidirectional algorithm by
explicitly specifying a direction override. [BIDI] Authors must specify the dir attribute on this element, with the
value ltr to specify a left-to-right override and with the value rtl to
specify a right-to-left override.

The span element


Categories: Flow content. Phrasing content. Palpable content. Contexts in which this element can be used: Where phrasing content is expected. Content model: Phrasing content. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

DOM interface: The span element doesn't mean anything on its own,
but can be useful when used together with the global
attributes, e.g. class, lang, or dir.
It represents its children. In this example, a code fragment is marked up using
span elements and class attributes so that its keywords and
identifiers can be color-coded from CSS: <pre><code class="lang-c"><span class="keyword">for</span> (<span class="ident">j</span> = 0; <span class="ident">j</span> &lt; 256; <span class="ident">j</span>++) { <span class="ident">i_t3</span> = (<span class="ident">i_t3</span> & 0x1ffff) | (<span class="ident">j</span> &lt;&lt; 17); <span class="ident">i_t6</span> = (((((((<span class="ident">i_t3</span> >> 3) ^ <span class="ident">i_t3</span>) >> 1) ^ <span class="ident">i_t3</span>) >> 8) ^ <span class="ident">i_t3</span>) >> 5) & 0xff; <span class="keyword">if</span> (<span class="ident">i_t6</span> == <span class="ident">i_t1</span>) <span class="keyword">break</span>; }</code></pre>

The br element
Categories: Flow content. Phrasing content. Contexts in which this element can be used: Where phrasing content is expected. Content model: Empty. Tag omission in text/html: No end tag.
http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

Content attributes: Global attributes DOM interface: The br element represents a line break. While line breaks are usually represented in visual media by physically moving
subsequent text to a new line, a style sheet or user agent would be equally justified in causing
line breaks to be rendered in a different manner, for instance as green dots, or as extra
spacing. br elements must be used only for line breaks that are actually part of the content, as in poems or addresses. The following example is correct usage of the br element: <p>P. Sherman<br> 42 Wallaby Way<br> Sydney</p> br elements must not be used for separating thematic groups in a paragraph. The following examples are non-conforming, as they abuse the br element: <p><a ...>34 comments.</a><br> <a ...>Add a comment.</a></p> <p><label>Name: <input name="name"></label><br> <label>Address: <input name="address"></label></p> Here are alternatives to the above, which are correct: <p><a ...>34 comments.</a></p> <p><a ...>Add a comment.</a></p> <p><label>Name: <input name="name"></label></p> <p><label>Address: <input name="address"></label></p> If a paragraph consists of nothing but a single br element, it
represents a placeholder blank line (e.g. as in a template). Such blank lines must not be used for
presentation purposes.

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

The wbr element


Categories: Flow content. Phrasing content. Contexts in which this element can be used: Where phrasing content is expected. Content model: Empty. Tag omission in text/html: No end tag. Content attributes: Global attributes DOM interface: Uses HTMLElement. The wbr element represents a line break opportunity. In the following example, someone is quoted as saying something which, for effect, is written
as one long word. However, to ensure that the text can be wrapped in a readable fashion, the
individual words in the quote are separated using a wbr element. <p>So then he pointed at the tiger and screamed "there<wbr>is<wbr>no<wbr>way<wbr>you<wbr>are<wbr>ever<wbr>goi ng<wbr>to<wbr>catch<wbr>me"!</p> Here, especially long lines of code in a program listing have suggested wrapping points given
using wbr elements. <pre>... Heading heading = Helm.HeadingFactory(HeadingCoordinates[1], <wbr>HeadingCoordinates[2], <wbr>HeadingCoordinates[3], <wbr>HeadingCoordinates[4]); Course course = Helm.CourseFactory(Heading, <wbr>Maps.MapFactoryFromHeading(heading), <wbr>Speeds.GetMaximumSpeed().ConvertToWarp());

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

...</pre>

Usage summary
Element Purpose a Hyperlinks Example Visit my <a href="drinks.html">drinks</a> page. em Stress emphasis

I must say I <em>adore</em> lemonade.

strong

Importance

This tea is <strong>very hot</strong>.

small

Side comments

These grapes are made into wine. <small>Alcohol is addictive. </small>

Inaccurate text

Price: <s>4.50</s> 2.00!

cite

Titles of works

The case <cite>Hugo v. Danielle</cite> is relevant here.

Quotations

The judge said <q>You can drink water from the fish tank</q> but advised against it.

dfn

Defining instance

The term <dfn>organic food</dfn> refers to food produced without synthetic chemicals.

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

abbr

Abbreviations

Organic food in Ireland is certified by the <abbr title="Irish Organic Farmers and Growers Association">IOFGA</abbr>.

data

Machinereadable equivalent

Available starting today! <data value="UPC:022014640201">North Coast Organic Apple Cider</data>

time

Machinereadable equivalent of date- or timerelated data

Available starting on <time datetime="2011-11-12">November 12th</time>!

code

Computer code

The <code>fruitdb</code> program can be used for tracking fruit production.

var

Variables

If there are <var>n</var> fruit in the bowl, at least <var>n</var>2 will be ripe.

samp

Computer output

The computer said <samp>Unknown error -3</samp>.

kbd

User input

Hit <kbd>F1</kbd> to continue.

sub

Subscripts

Water is H<sub>2</sub>O.

sup

Superscripts

The Hydrogen in heavy water is usually <sup>2</sup>H.

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

Alternative voice

Lemonade consists primarily of <i>Citrus limon</i>.

Keywords

Take a <b>lemon</b> and squeeze it with a <b>juicer</b>.

Annotations

The mixture of apple juice and <u class="spelling">eldeflower</u> juice is very pleasant.

mark

Highlight

Elderflower cordial, with one <mark>part</mark> cordial to ten <mark>part</mark>s water, stands a<mark>part</mark> from the rest.

ruby, rt , rp

Ruby annotations

<ruby> OJ <rp>(<rt>Orange Juice<rp>)</ruby>

bdi

Text directionality isolation

The recommended restaurant is <bdi lang="">My Juice Caf (At The Beach)</bdi>.

bdo

Text directionality formatting

The proposal is to write English, but in reverse order. "Juice" would become "<bdo dir=rtl>Juice</bdo>"

span

Other

In French we call it <span lang="fr">sirop de sureau</span>.

br

Line break

Simply Orange Juice Company<br>Apopka, FL 32703<br>U.S.A.

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.5 Text-level semantics HTML: The Living Standard - Edition for Web Developers

wbr

Line breaking opportunity

www.simply<wbr>orange<wbr>juice.com

Up next

4.6 Edits

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/text-level-semantics.html[4/16/2014 9:28:29 PM]

4.6 Edits HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
Edits
The ins element
The del element
Attributes common to ins and del elements
Edits and paragraphs
Edits and lists
Edits and tables

Edits
The ins and del elements represent edits to the document.

The ins element


Categories: Flow content. Phrasing content. Palpable content. Contexts in which this element can be used: Where phrasing content is expected. Content model: Transparent. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes

http://developers.whatwg.org/edits.html[4/16/2014 9:28:37 PM]

4.6 Edits HTML: The Living Standard - Edition for Web Developers

cite Link to the source of the quotation or more information about the edit datetime Date and (optionally) time of the change DOM interface: Uses the HTMLModElement interface. The ins element represents an addition to the document. The following represents the addition of a single paragraph: <aside> <ins> <p> I like fruit. </p> </ins> </aside> As does the following, because everything in the aside element here counts as
phrasing content and therefore there is just one paragraph: <aside> <ins> Apples are <em>tasty</em>. </ins> <ins> So are pears. </ins> </aside> ins elements should not cross implied paragraph
boundaries. The following example represents the addition of two paragraphs, the second of which was
inserted in two parts. The first ins element in this example thus crosses a
paragraph boundary, which is considered poor form. <aside> <!-- don't do this --> <ins datetime="2005-03-16 00:00Z"> <p> I like fruit. </p> Apples are <em>tasty</em>. </ins> <ins datetime="2007-12-19 00:00Z"> So are pears.

http://developers.whatwg.org/edits.html[4/16/2014 9:28:37 PM]

4.6 Edits HTML: The Living Standard - Edition for Web Developers

</ins> </aside> Here is a better way of marking this up. It uses more elements, but none of the elements cross
implied paragraph boundaries. <aside> <ins datetime="2005-03-16 00:00Z"> <p> I like fruit. </p> </ins> <ins datetime="2005-03-16 00:00Z"> Apples are <em>tasty</em>. </ins> <ins datetime="2007-12-19 00:00Z"> So are pears. </ins> </aside>

The del element


Categories: Flow content. Phrasing content. Contexts in which this element can be used: Where phrasing content is expected. Content model: Transparent. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes cite Link to the source of the quotation or more information about the edit datetime Date and (optionally) time of the change DOM interface: Uses the HTMLModElement interface.

http://developers.whatwg.org/edits.html[4/16/2014 9:28:37 PM]

4.6 Edits HTML: The Living Standard - Edition for Web Developers

The del element represents a removal from the document. del elements should not cross implied paragraph
boundaries. The following shows a "to do" list where items that have been done are crossed-off with the
date and time of their completion. <h1>To Do</h1> <ul> <li>Empty the dishwasher</li> <li><del datetime="2009-10-11T01:25-07:00">Watch Walter Lewin's lectures</del></li> <li><del datetime="2009-10-10T23:38-07:00">Download more tracks</del></li> <li>Buy a printer</li> </ul>

Attributes common to ins and del elements


The cite attribute may be used to specify the
address of a document that explains the change. When that document is long, for instance the
minutes of a meeting, authors are encouraged to include a fragment identifier pointing to the
specific part of that document that discusses the change. If the cite attribute is present, it must be a valid
URL potentially surrounded by spaces that explains the change. User agents may allow users to follow such
citation links, but they are primarily intended for private use (e.g. by server-side scripts
collecting statistics about a site's edits), not for readers. The datetime attribute may be used to specify
the time and date of the change. If present, the datetime attribute's value must be a
valid date string with optional time. This value is primarily intended for
private use. The ins and del elements implement the
HTMLModElement interface:

Edits and paragraphs

http://developers.whatwg.org/edits.html[4/16/2014 9:28:37 PM]

4.6 Edits HTML: The Living Standard - Edition for Web Developers

Since the ins and del elements do not affect paragraphing, it is possible, in some cases where paragraphs are implied (without explicit p elements), for an
ins or del element to span both an entire paragraph or other
non-phrasing content elements and part of another paragraph. For example: <section> <ins> <p> This is a paragraph that was inserted. </p> This is another paragraph whose first sentence was inserted at the same time as the paragraph above. </ins> This is a second sentence, which was there all along. </section> By only wrapping some paragraphs in p elements, one can even get the end of one
paragraph, a whole second paragraph, and the start of a third paragraph to be covered by the same
ins or del element (though this is very confusing, and not considered
good practice): <section> This is the first paragraph. <ins>This sentence was inserted. <p>This second paragraph was inserted.</p> This sentence was inserted too.</ins> This is the third paragraph in this example. <!-- (don't do this) --> </section> However, due to the way implied paragraphs are defined, it is
not possible to mark up the end of one paragraph and the start of the very next one using the same
ins or del element. You instead have to use one (or two) p
element(s) and two ins or del elements, as for example: <section> <p>This is the first paragraph. <del>This sentence was deleted.</del></p> <p><del>This sentence was deleted too.</del> That sentence needed a separate &lt;del&gt; element.</p> </section>

http://developers.whatwg.org/edits.html[4/16/2014 9:28:37 PM]

4.6 Edits HTML: The Living Standard - Edition for Web Developers

Partly because of the confusion described above, authors are strongly encouraged to always mark
up all paragraphs with the p element, instead of having ins or
del elements that cross implied paragraphs
boundaries.

Edits and lists


The content models of the ol and ul elements do not allow
ins and del elements as children. Lists always represent all their
items, including items that would otherwise have been marked as deleted. To indicate that an item is inserted or deleted, an ins or del
element can be wrapped around the contents of the li element. To indicate that an
item has been replaced by another, a single li element can have one or more
del elements followed by one or more ins elements. In the following example, a list that started empty had items added and removed from it over
time. The bits in the example that have been emphasized show the parts that are the "current"
state of the list. The list item numbers don't take into account the edits, though. <h1>Stop-ship bugs</h1> <ol> <li><ins datetime="2008-02-12T15:20Z">Bug 225: Rain detector doesn't work in snow</ins></li> <li><del datetime="2008-03-01T20:22Z"><ins datetime="200802-14T12:02Z">Bug 228: Water buffer overflows in April</ins></del></li> <li><ins datetime="2008-02-16T13:50Z">Bug 230: Water heater doesn't use renewable fuels</ins></li> <li><del datetime="2008-02-20T21:15Z"><ins datetime="200802-16T14:25Z">Bug 232: Carbon dioxide emissions detected after startup</ins></del> </li> </ol> In the following example, a list that started with just fruit was replaced by a list with just
colors. <h1>List of <del>fruits</del><ins>colors</ins></h1> <ul>
http://developers.whatwg.org/edits.html[4/16/2014 9:28:37 PM]

4.6 Edits HTML: The Living Standard - Edition for Web Developers

<li><del>Lime</del><ins>Green</ins></li> <li><del>Apple</del></li> <li>Orange</li> <li><del>Pear</del></li> <li><ins>Teal</ins></li> <li><del>Lemon</del><ins>Yellow</ins></li> <li>Olive</li> <li><ins>Purple</ins></li> </ul>

Edits and tables


The elements that form part of the table model have complicated content model requirements that
do not allow for the ins and del elements, so indicating edits to a
table can be difficult. To indicate that an entire row or an entire column has been added or removed, the entire
contents of each cell in that row or column can be wrapped in ins or del
elements (respectively). Here, a table's row has been added: <table> <thead> <tr> <th> Game name Verdict <tbody> <tr> <td> Diablo 2 8/10 <tr> <td> Portal 10/10 <tr> <td> <ins>Portal 2</ins> <td> <ins>Valve</ins> <td> <ins>10/10</ins> </table> Here, a column has been removed (the time at which it was removed is given also, as is a link
to the page explaining why): <table> <thead> <td> Valve <td> <td> Blizzard <td> <th> Game publisher <th>

http://developers.whatwg.org/edits.html[4/16/2014 9:28:37 PM]

4.6 Edits HTML: The Living Standard - Edition for Web Developers

<tr> <th> Game name 14:23Z">Verdict</del> <tbody> <tr> <td> Diablo 2 14:23Z">8/10</del> <tr> <td> Portal 14:23Z">10/10</del> <tr> <td> Portal 2 14:23Z">10/10</del> </table>

<th> Game publisher

<th>

<del cite="/edits/r192" datetime="2011-05-02

<td> Blizzard

<td>

<del cite="/edits/r192" datetime="2011-05-02 <td> Valve <td>

<del cite="/edits/r192" datetime="2011-05-02 <td> Valve <td>

<del cite="/edits/r192" datetime="2011-05-02

Generally speaking, there is no good way to indicate more complicated edits (e.g. that a cell
was removed, moving all subsequent cells up or to the left).

Up next

4.7 Embedded content

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/edits.html[4/16/2014 9:28:37 PM]

4.7 Embedded content HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
Embedded content
The img element
Requirements for providing text to act as an alternative for images
General guidelines
A link or button containing nothing but the image
A phrase or paragraph with an alternative graphical representation: charts, diagrams, graphs, maps, illustrations
A short phrase or label with an alternative graphical representation: icons, logos
Text that has been rendered to a graphic for typographical effect
A graphical representation of some of the surrounding text
A purely decorative image that doesn't add any information
A group of images that form a single larger picture with no links
A group of images that form a single larger picture with links
A key part of the content
An image not intended for the user
An image in an e-mail or private document intended for a specific person who is known to be able to view images
Adaptive images

Embedded content

The img element


Categories: Flow content. Phrasing content. Embedded content.
http://developers.whatwg.org/embedded-content-1.html[4/16/2014 9:28:42 PM]

4.7 Embedded content HTML: The Living Standard - Edition for Web Developers

Form-associated element. If the element has a usemap attribute: Interactive content. Palpable content. Contexts in which this element can be used: Where embedded content is expected. Content model: Empty. Tag omission in text/html: No end tag. Content attributes: Global attributes alt Replacement text for use when images are not available src Address of the resource srcset Images to use in different situations (e.g. high-resolution displays, small monitors, etc) crossorigin How the element handles crossorigin requests usemap Name of image map to use ismap Whether the image is a server-side image map width Horizontal dimension height Vertical dimension DOM interface: An img element represents an image. The image given by the src and srcset attributes is the embedded content; the value of
the alt attribute provides equivalent content for
those who cannot process images or who have image loading disabled (i.e. it is the
img element's fallback content). The requirements on the alt attribute's value are described
in the next section. The src attribute must be present, and must contain a
valid non-empty URL potentially surrounded by spaces referencing a non-interactive,
optionally animated, image resource that is neither paged nor scripted.

http://developers.whatwg.org/embedded-content-1.html[4/16/2014 9:28:42 PM]

4.7 Embedded content HTML: The Living Standard - Edition for Web Developers

The srcset attribute may also be present. If present, its


value must consist of one or more image candidate
strings, each separated from the next by a U+002C COMMA character (,). This attribute
allows authors to provide alternative images for environments with smaller screens or screens with higher pixel densities. The srcset attribute allows authors to provide a set of
images to handle graphical displays of varying dimensions and pixel densities. The attribute essentially takes a comma-separated list of URLs each with one or more
descriptors giving the maximum viewport dimensions and pixel density allowed to use the image.
From the available options, the user agent then picks the most appropriate image. If the viewport
dimensions or pixel density changes, the user agent can replace the image data with a new image on the fly. To specify an image, give first a URL, then one or more descriptors of the form 100w, 100h, or
2x, where "100w" means "maximum viewport width of 100 CSS pixels", "100h" is the same but for
height, and "2x" means "maximum pixel density of 2 device pixels per CSS pixel". An image candidate string consists of the following components, in order, with the
further restrictions described below this list: 1. Zero or more space characters. 2. A valid non-empty URL referencing a non-interactive, optionally animated, image
resource that is neither paged nor scripted. 3. Zero or more space characters. 4. Optionally a width descriptor, consisting of: a space character, a
valid nonnegative integer representing the width descriptor value, and a
U+0077 LATIN SMALL LETTER W character. 5. Zero or more space characters. 6. Optionally a height descriptor, consisting of: a space character, a
valid nonnegative integer representing the height descriptor value, and a
U+0068 LATIN SMALL LETTER H character. 7. Zero or more space characters. 8. Optionally a pixel density descriptor, consisting of: a space character,
a valid floating-point number giving a number greater than zero representing the pixel density descriptor value, and a U+0078 LATIN SMALL LETTER X character. 9. Zero or more space characters.

http://developers.whatwg.org/embedded-content-1.html[4/16/2014 9:28:42 PM]

4.7 Embedded content HTML: The Living Standard - Edition for Web Developers

Each image candidate string must have at least one of the three optional descriptors. There must not be two image candidate
strings in a srcset attribute whose width
descriptor value, height descriptor value, and pixel density descriptor value
are each identical to their counterpart in the other image candidate string; for the
purposes of this requirement, omitted width descriptors and height descriptors are
considered to have the value "Infinity", and omitted pixel density descriptors are
considered to have the value 1. In this example, a banner that takes half the viewport is provided in two versions, one for
wide screen and one for narrow screens. <h1><img alt="The Breakfast Combo" src="banner.jpeg" srcset="banner-HD.jpeg 2x, banner-phone.jpeg 100w, banner-phone-HD.jpeg 100w 2x"></h1> The requirements above imply that images can be static bitmaps (e.g. PNGs, GIFs,
JPEGs), single-page vector documents (single-page PDFs, XML files with an SVG root element),
animated bitmaps (APNGs, animated GIFs), animated vector graphics (XML files with an SVG root
element that use declarative SMIL animation), and so forth. However, these definitions preclude
SVG files with script, multipage PDF files, interactive MNG files, HTML documents, plain text
documents, and so forth. The img element must not be used as a layout tool. In particular, img
elements should not be used to display transparent images, as such images rarely convey meaning and
rarely add anything useful to the document. The crossorigin attribute is a CORS
settings attribute. Its purpose is to allow images from third-party sites that allow
cross-origin access to be used with canvas . The usemap attribute,
if present, can indicate that the image has an associated image map. The ismap
attribute, when used on an element that is a descendant of an
a element with an href attribute, indicates by its
presence that the element provides access to a server-side image
map. This affects how events are handled on the corresponding
a element. The ismap attribute is a
boolean attribute. The attribute must not be specified on an element that does not have an ancestor a element
with an href

http://developers.whatwg.org/embedded-content-1.html[4/16/2014 9:28:42 PM]

4.7 Embedded content HTML: The Living Standard - Edition for Web Developers

attribute. The img element supports dimension


attributes. image . width [ = value ] image . height [ = value ] These attributes return the actual rendered dimensions of the
image, or zero if the dimensions are not known. They can be set, to change the corresponding content
attributes. image . naturalWidth image . naturalHeight These attributes return the intrinsic dimensions of the image,
or zero if the dimensions are not known. image . complete Returns true if the image has been completely downloaded or if
no image is specified; otherwise, returns false. image = new Image ( [ width [, height ] ] ) Returns a new img element, with the width and height attributes set to the values
passed in the relevant arguments, if applicable. A single image can have different appropriate alternative text depending on the context. In each of the following cases, the same image is used, yet the alt text is different each time. The image is the coat of arms of the
Carouge municipality in the canton Geneva in Switzerland. Here it is used as a supplementary icon: <p>I lived in <img src="carouge.svg" alt=""> Carouge.</p> Here it is used as an icon representing the town: <p>Home town: <img src="carouge.svg" alt="Carouge"></p> Here it is used as part of a text on the town: <p>Carouge has a coat of arms.</p> <p><img src="carouge.svg" alt="The coat of arms depicts a

http://developers.whatwg.org/embedded-content-1.html[4/16/2014 9:28:42 PM]

4.7 Embedded content HTML: The Living Standard - Edition for Web Developers

lion, sitting in front of a tree."></p> <p>It is used as decoration all over the town.</p> Here it is used as a way to support a similar text where the description is given as well as,
instead of as an alternative to, the image: <p>Carouge has a coat of arms.</p> <p><img src="carouge.svg" alt=""></p> <p>The coat of arms depicts a lion, sitting in front of a tree. It is used as decoration all over the town.</p> Here it is used as part of a story: <p>He picked up the folder and a piece of paper fell out.</p> <p><img src="carouge.svg" alt="Shaped like a shield, the paper had a red background, a green tree, and a yellow lion with its tongue hanging out and whose tail was shaped like an S."></p> <p>He stared at the folder. S! The answer he had been looking for all this time was simply the letter S! How had he not seen that before? It all came together now. The phone call where Hector had referred to a lion's tail, the time Marco had stuck his tongue out...</p> Here it is not known at the time of publication what the image will be, only that it will be a
coat of arms of some kind, and thus no replacement text can be provided, and instead only a brief
caption for the image is provided, in the title attribute: <p>The last user to have uploaded a coat of arms uploaded this one:</p> <p><img src="last-uploaded-coat-of-arms.cgi" title="Useruploaded coat of arms."></p> Ideally, the author would find a way to provide real replacement text even in this case, e.g.
by asking the previous user. Not providing replacement text makes the document more difficult to
use for people who are unable to view images, e.g. blind users, or users or very low-bandwidth
connections or who
http://developers.whatwg.org/embedded-content-1.html[4/16/2014 9:28:42 PM]

4.7 Embedded content HTML: The Living Standard - Edition for Web Developers

pay by the byte, or users who are forced to use a text-only Web browser. Here are some more examples showing the same picture used in different contexts, with
different appropriate alternate texts each time. <article> <h1>My cats</h1> <h2>Fluffy</h2> <p>Fluffy is my favorite.</p> <img src="fluffy.jpg" alt="She likes playing with a ball of yarn."> <p>She's just too cute.</p> <h2>Miles</h2> <p>My other cat, Miles just eats and sleeps.</p> </article> <article> <h1>Photography</h1> <h2>Shooting moving targets indoors</h2> <p>The trick here is to know how to anticipate; to know at what speed and what distance the subject will pass by.</p> <img src="fluffy.jpg" alt="A cat flying by, chasing a ball of yarn, can be photographed quite nicely using this technique."> <h2>Nature by night</h2> <p>To achieve this, you'll need either an extremely sensitive film, or immense flash lights.</p> </article> <article> <h1>About me</h1> <h2>My pets</h2> <p>I've got a cat named Fluffy and a dog named Miles.</p> <img src="fluffy.jpg" alt="Fluffy, my cat, tends to keep itself busy."> <p>My dog Miles and I like go on long walks together.</p> <h2>music</h2> <p>After our walks, having emptied my mind, I like listening to Bach.</p>

http://developers.whatwg.org/embedded-content-1.html[4/16/2014 9:28:42 PM]

4.7 Embedded content HTML: The Living Standard - Edition for Web Developers

</article> <article> <h1>Fluffy and the Yarn</h1> <p>Fluffy was a cat who liked to play with yarn. He also liked to jump.</p> <aside><img src="fluffy.jpg" alt="" title="Fluffy"></aside> <p>He would play in the morning, he would play in the evening.</p> </article>

Requirements for providing text to act as an alternative for images

General guidelines Except where otherwise specified, the alt attribute must be
specified and its value must not be empty; the value must be an appropriate replacement for the
image. The specific requirements for the alt attribute depend on
what the image is intended to represent, as described in the following sections. The most general rule to consider when writing alternative text is the following: the
intent is that replacing every image with the text of its alt
attribute not change the meaning of the page. So, in general, alternative text can be written by considering what one would have written had
one not been able to include the image. A corollary to this is that the alt attribute's value should
never contain text that could be considered the image's caption, title, or
legend. It is supposed to contain replacement text that could be used by users
instead of the image; it is not meant to supplement the image. The title attribute can be used for supplemental information. Another corollary is that the alt attribute's value should
not repeat information that is already provided in the prose next to the image. One way to think of alternative text is to think about how you would read the page
containing the image to someone over the phone, without mentioning that there is an image present.
Whatever you say instead of the image is

http://developers.whatwg.org/embedded-content-1.html[4/16/2014 9:28:42 PM]

4.7 Embedded content HTML: The Living Standard - Edition for Web Developers

typically a good start for writing the alternative


text.

A link or button containing nothing but the image When an a element that creates a hyperlink, or a button
element, has no textual content but contains one or more images, the alt attributes must contain text that together convey the purpose of
the link or button. In this example, a user is asked to pick his preferred color from a list of three. Each color
is given by an image, but for users who have configured their user agent not to display images,
the color names are used instead: <h1>Pick your color</h1> <ul> <li><a href="green.html"><img src="green.jpeg" alt="Green"></a></li> <li><a href="blue.html"><img src="blue.jpeg" alt="Blue"></a> </li> <li><a href="red.html"><img src="red.jpeg" alt="Red"></a> </li> </ul> In this example, each button has a set of images to indicate the kind of color output desired
by the user. The first image is used in each case to give the alternative text. <button name="rgb"><img src="red" alt="RGB"><img src="green" alt=""><img src="blue" alt=""></button> <button name="cmyk"><img src="cyan" alt="CMYK"><img src="magenta" alt=""><img src="yellow" alt=""><img src="black" alt=""></button> Since each image represents one part of the text, it could also be written like this: <button name="rgb"><img src="red" alt="R"><img src="green" alt="G"><img src="blue" alt="B"></button> <button name="cmyk"><img src="cyan" alt="C"><img src="magenta" alt="M"><img src="yellow" alt="Y"><img src="black" alt="K"></button>

http://developers.whatwg.org/embedded-content-1.html[4/16/2014 9:28:42 PM]

4.7 Embedded content HTML: The Living Standard - Edition for Web Developers

However, with other alternative text, this might not work, and putting all the alternative
text into one image in each case might make more sense: <button name="rgb"><img src="red" alt="sRGB profile"><img src="green" alt=""><img src="blue" alt=""></button> <button name="cmyk"><img src="cyan" alt="CMYK profile"><img src="magenta" alt=""><img src="yellow" alt=""><img src="black" alt=""></button>

A phrase or paragraph with an alternative graphical representation: charts, diagrams, graphs, maps, illustrations Sometimes something can be more clearly stated in graphical form, for example as a flowchart, a
diagram, a graph, or a simple map showing directions. In such cases, an image can be given using
the img element, but the lesser textual version must still be given, so that users
who are unable to view the image (e.g. because they have a very slow connection, or because they
are using a text-only browser, or because they are listening to the page being read out by a
hands-free automobile voice Web browser, or simply because they are blind) are still able to
understand the message being conveyed. The text must be given in the alt attribute, and must convey
the same message as the image specified in the src
attribute. It is important to realize that the alternative text is a replacement for the image,
not a description of the image. In the following example we have a flowchart
in image form, with text in the alt attribute rephrasing the
flowchart in prose form: <p>In the common case, the data handled by the tokenization stage comes from the network, but it can also come from script.</p> <p><img src="images/parsing-model-overview.png" alt="The Network passes data to the Input Stream Preprocessor, which passes it to the Tokenizer, which passes it to the Tree Construction stage. From there, data goes to both the DOM and to Script Execution. Script

http://developers.whatwg.org/embedded-content-1.html[4/16/2014 9:28:42 PM]

4.7 Embedded content HTML: The Living Standard - Edition for Web Developers

Execution is linked to the DOM, and, using document.write(), passes data to the Tokenizer."></p> Here's another example, showing a good solution and a bad solution to the problem of including
an image in a description. First, here's the good solution. This sample shows how the alternative text should just be
what you would have put in the prose if the image had never existed. <!-- This is the correct way to do things. --> <p> You are standing in an open field west of a house. <img src="house.jpeg" alt="The house is white, with a boarded front door."> There is a small mailbox here. </p> Second, here's the bad solution. In this incorrect way of doing things, the alternative text
is simply a description of the image, instead of a textual replacement for the image. It's bad
because when the image isn't shown, the text doesn't flow as well as in the first example. <!-- This is the wrong way to do things. --> <p> You are standing in an open field west of a house. <img src="house.jpeg" alt="A white house, with a boarded front door."> There is a small mailbox here. </p> Text such as "Photo of white house with boarded door" would be equally bad alternative text
(though it could be suitable for the title attribute or in the figcaption element of a figure with this image).

A short phrase or label with an alternative graphical representation: icons, logos A document can contain information in iconic form. The icon is intended to

http://developers.whatwg.org/embedded-content-1.html[4/16/2014 9:28:42 PM]

4.7 Embedded content HTML: The Living Standard - Edition for Web Developers

help users of visual


browsers to recognize features at a glance. In some cases, the icon is supplemental to a text label conveying the same meaning. In those
cases, the alt attribute must be present but must be empty. Here the icons are next to text that conveys the same meaning, so they have an empty alt attribute: <nav> <p><a href="/help/"><img src="/icons/help.png" alt=""> Help</a></p> <p><a href="/configure/"><img src="/icons/configuration.png" alt=""> Configuration Tools</a></p> </nav> In other cases, the icon has no text next to it describing what it means; the icon is supposed
to be self-explanatory. In those cases, an equivalent textual label must be given in the alt attribute. Here, posts on a news site are labeled with an icon indicating their topic. <body> <article> <header> <h1>Ratatouille wins <i>Best Movie of the Year</i> award</h1> <p><img src="movies.png" alt="Movies"></p> </header> <p>Pixar has won yet another <i>Best Movie of the Year</i> award, making this its 8th win in the last 12 years.</p> </article> <article> <header> <h1>Latest TWiT episode is online</h1> <p><img src="podcasts.png" alt="Podcasts"></p> </header> <p>The latest TWiT episode has been posted, in which we hear several tech news stories as well as learning much more

http://developers.whatwg.org/embedded-content-1.html[4/16/2014 9:28:42 PM]

4.7 Embedded content HTML: The Living Standard - Edition for Web Developers

about the iPhone. This week, the panelists compare how reflective their iPhones' Apple logos are.</p> </article> </body> Many pages include logos, insignia, flags, or emblems, which stand for a particular entity such
as a company, organization, project, band, software package, country, or some such. If the logo is being used to represent the entity, e.g. as a page heading, the alt attribute must contain the name of the entity being represented by
the logo. The alt attribute must not contain text like
the word "logo", as it is not the fact that it is a logo that is being conveyed, it's the entity
itself. If the logo is being used next to the name of the entity that it represents, then the logo is
supplemental, and its alt attribute must instead be empty. If the logo is merely used as decorative material (as branding, or, for example, as a side
image in an article that mentions the entity to which the logo belongs), then the entry below on
purely decorative images applies. If the logo is actually being discussed, then it is being used
as a phrase or paragraph (the description of the logo) with an alternative graphical
representation (the logo itself), and the first entry above applies. In the following snippets, all four of the above cases are present. First, we see a logo used
to represent a company: <h1><img src="XYZ.gif" alt="The XYZ company"></h1> Next, we see a paragraph which uses a logo right next to the company name, and so doesn't have
any alternative text: <article> <h2>News</h2> <p>We have recently been looking at buying the <img src="alpha.gif" alt=""> company, a small Greek company specializing in our type of product.</p> In this third snippet, we have a logo being used in an aside, as part of the larger article
discussing the acquisition:
http://developers.whatwg.org/embedded-content-1.html[4/16/2014 9:28:42 PM]

4.7 Embedded content HTML: The Living Standard - Edition for Web Developers

<aside><p><img src="alpha-large.gif" alt=""></p></aside> <p>The company has had a good quarter, and our pie chart studies of their accounts suggest a much bigger blue slice than its green and orange slices, which is always a good sign.</p> </article> Finally, we have an opinion piece talking about a logo, and the logo is therefore described in
detail in the alternative text. <p>Consider for a moment their logo:</p> <p><img src="/images/logo" alt="It consists of a green circle with a green question mark centered inside it."></p> <p>How unoriginal can you get? I mean, oooooh, a question mark, how <em>revolutionary</em>, how utterly <em>ground-breaking</em>, I'm sure everyone will rush to adopt those specifications now! They could at least have tried for some sort of, I don't know, sequence of rounded squares with varying shades of green and bold white outlines, at least that would look good on the cover of a blue book. </p> This example shows how the alternative text should be written such that if the image isn't available, and the text is used instead, the text flows seamlessly into
the surrounding text, as if the image had never been there in the first place.

Text that has been rendered to a graphic for typographical effect Sometimes, an image just consists of text, and the purpose of the image is not to highlight the
actual typographic effects used to render the text, but just to convey the text itself.
http://developers.whatwg.org/embedded-content-1.html[4/16/2014 9:28:42 PM]

4.7 Embedded content HTML: The Living Standard - Edition for Web Developers

In such cases, the alt attribute must be present but must


consist of the same text as written in the image itself. Consider a graphic containing the text "Earth Day", but with the letters all decorated with
flowers and plants. If the text is merely being used as a heading, to spice up the page for
graphical users, then the correct alternative text is just the same text "Earth Day", and no
mention need be made of the decorations: <h1><img src="earthdayheading.png" alt="Earth Day"></h1> An illuminated manuscript might use graphics for some of its images. The alternative text in
such a situation is just the character that the image represents. <p><img src="initials/o.svg" alt="O">nce upon a time and a long long time ago, late at night, when it was dark, over the hills, through the woods, across a great ocean, in a land far away, in a small house, on a hill, under a full moon... When an image is used to represent a character that cannot otherwise be represented in Unicode,
for example gaiji, itaiji, or new characters such as novel currency symbols, the alternative text
should be a more conventional way of writing the same thing, e.g. using the phonetic hiragana or
katakana to give the character's pronunciation. In this example from 1997, a new-fangled currency symbol that looks like a curly E with two
bars in the middle instead of one is represented using an image. The alternative text gives the
character's pronunication. <p>Only <img src="euro.png" alt="euro ">5.99! An image should not be used if Unicode characters would serve an identical purpose. Only when
the text cannot be directly represented using Unicode, e.g. because of decorations or because the
character is not in the Unicode character set (as in the case of gaiji), would an image be
appropriate. If an author is tempted to use an image because their default system font does not
support a given character, then Web Fonts are a better solution than images.

http://developers.whatwg.org/embedded-content-1.html[4/16/2014 9:28:42 PM]

4.7 Embedded content HTML: The Living Standard - Edition for Web Developers

A graphical representation of some of the surrounding text In many cases, the image is actually just supplementary, and its presence merely reinforces the
surrounding text. In these cases, the alt attribute must be
present but its value must be the empty string. In general, an image falls into this category if removing the image doesn't make the page any
less useful, but including the image makes it a lot easier for users of visual browsers to
understand the concept. A flowchart that repeats the previous paragraph in graphical form: <p>The Network passes data to the Input Stream Preprocessor, which passes it to the Tokenizer, which passes it to the Tree Construction stage. From there, data goes to both the DOM and to Script Execution. Script Execution is linked to the DOM, and, using document.write(), passes data to the Tokenizer.</p> <p><img src="images/parsing-model-overview.png" alt=""></p> In these cases, it would be wrong to include alternative text that consists of just a caption.
If a caption is to be included, then either the title attribute can be used, or the figure and figcaption elements can be used. In the latter case, the image would in fact be a phrase or paragraph with an alternative graphical
representation, and would thus require alternative text. <!-- Using the title="" attribute --> <p>The Network passes data to the Input Stream Preprocessor, which passes it to the Tokenizer, which passes it to the Tree Construction stage. From there, data goes to both the DOM and to Script Execution. Script Execution is linked to the DOM, and, using document.write(), passes data to the Tokenizer.</p> <p><img src="images/parsing-model-overview.png" alt=""

http://developers.whatwg.org/embedded-content-1.html[4/16/2014 9:28:42 PM]

4.7 Embedded content HTML: The Living Standard - Edition for Web Developers

title="Flowchart representation of the parsing model."></p> <!-- Using <figure> and <figcaption> --> <p>The Network passes data to the Input Stream Preprocessor, which passes it to the Tokenizer, which passes it to the Tree Construction stage. From there, data goes to both the DOM and to Script Execution. Script Execution is linked to the DOM, and, using document.write(), passes data to the Tokenizer.</p> <figure> <img src="images/parsing-model-overview.png" alt="The Network leads to the Input Stream Preprocessor, which leads to the Tokenizer, which leads to the Tree Construction stage. The Tree Construction stage leads to two items. The first is Script Execution, which leads via document.write() back to the Tokenizer. The second item from which Tree Construction leads is the DOM. The DOM is related to the Script Execution."> <figcaption>Flowchart representation of the parsing model. </figcaption> </figure> <!-- This is WRONG. Do not do this. Instead, do what the above examples do. --> <p>The Network passes data to the Input Stream Preprocessor, which passes it to the Tokenizer, which passes it to the Tree Construction stage. From there, data goes to both the DOM and to Script Execution. Script Execution is linked to the DOM, and, using

http://developers.whatwg.org/embedded-content-1.html[4/16/2014 9:28:42 PM]

4.7 Embedded content HTML: The Living Standard - Edition for Web Developers

document.write(), passes data to the Tokenizer.</p> <p><img src="images/parsing-model-overview.png" alt="Flowchart representation of the parsing model."> </p> <!-- Never put the image's caption in the alt="" attribute! -> A graph that repeats the previous paragraph in graphical form: <p>According to a study covering several billion pages, about 62% of documents on the Web in 2007 triggered the Quirks rendering mode of Web browsers, about 30% triggered the Almost Standards mode, and about 9% triggered the Standards mode. </p> <p><img src="rendering-mode-pie-chart.png" alt=""></p>

A purely decorative image that doesn't add any information If an image is decorative but isn't especially page-specific for example an image that
forms part of a site-wide design scheme the image should be specified in the site's CSS,
not in the markup of the document. However, a decorative image that isn't discussed by the surrounding text but still has some
relevance can be included in a page using the img element. Such images are
decorative, but still form part of the content. In these cases, the alt attribute must be present but its value must be the empty
string. Examples where the image is purely decorative despite being relevant would include things like
a photo of the Black Rock City landscape in a blog post about an event at Burning Man, or an
image of a painting inspired by a poem, on a page reciting that poem. The following snippet shows
an example of the latter case (only the first verse is included in this snippet): <h1>The Lady of Shalott</h1> <p><img src="shalott.jpeg" alt=""></p> <p>On either side the river lie<br> Long fields of barley and of rye,<br> That clothe the wold and meet the sky;<br>

http://developers.whatwg.org/embedded-content-1.html[4/16/2014 9:28:42 PM]

4.7 Embedded content HTML: The Living Standard - Edition for Web Developers

And through the field the road run by<br> To many-tower'd Camelot;<br> And up and down the people go,<br> Gazing where the lilies blow<br> Round an island there below,<br> The island of Shalott.</p>

A group of images that form a single larger picture with no links When a picture has been sliced into smaller image files that are then displayed together to
form the complete picture again, one of the images must have its alt attribute set as per the relevant rules that would be appropriate
for the picture as a whole, and then all the remaining images must have their alt attribute set to the empty string. In the following example, a picture representing a company logo for XYZ Corp has been split into two pieces, the first containing the letters "XYZ" and the second
with the word "Corp". The alternative text ("XYZ Corp") is all in the first image. <h1><img src="logo1.png" alt="XYZ Corp"><img src="logo2.png" alt=""></h1> In the following example, a rating is shown as three filled stars and two empty stars. While
the alternative text could have been "&bigstar;&bigstar;&bigstar;&star;&star;", the author has
instead decided to more helpfully give the rating in the form "3 out of 5". That is the alternative text of the first image, and the rest have blank alternative text. <p>Rating: <meter max=5 value=3><img src="1" alt="3 out of 5" ><img src="1" alt=""><img src="1" alt=""><img src="0" alt="" ><img src="0" alt=""></meter></p>

A group of images that form a single larger picture with links Generally, image maps should be used instead of slicing an image
for links. However, if an image is indeed sliced and any of the components of the sliced picture are the
sole contents of links, then one image per link must have

http://developers.whatwg.org/embedded-content-1.html[4/16/2014 9:28:42 PM]

4.7 Embedded content HTML: The Living Standard - Edition for Web Developers

alternative text in its alt attribute representing the purpose of the link. In the following example, a picture representing the flying spaghetti monster emblem, with
each of the left noodly appendages and the right noodly appendages in different images, so that
the user can pick the left side or the right side in an adventure. <h1>The Church</h1> <p>You come across a flying spaghetti monster. Which side of His Noodliness do you wish to reach out for?</p> <p><a href="?go=left" ><img src="fsm-left.png" side. "></a ><img src="fsm-middle.png" alt="" ><a href="?go=right"><img src="fsm-right.png" alt="Right side."></a></p> alt="Left

A key part of the content In some cases, the image is a critical part of the content. This could be the case, for
instance, on a page that is part of a photo gallery. The image is the whole point of the
page containing it. How to provide alternative text for an image that is a key part of the content depends on the
image's provenance. The general case When it is possible for detailed alternative text to be provided, for example if the image is
part of a series of screenshots in a magazine review, or part of a comic strip, or is a
photograph in a blog entry about that photograph, text that can serve as a substitute for the
image must be given as the contents of the alt attribute. A screenshot in a gallery of screenshots for a new OS, with some alternative text: <figure> <img src="KDE%20Light%20desktop.png" alt="The desktop is blue, with icons along the left hand side in two columns, reading System, Home, K-Mail, etc. A

http://developers.whatwg.org/embedded-content-1.html[4/16/2014 9:28:42 PM]

4.7 Embedded content HTML: The Living Standard - Edition for Web Developers

window is open showing that menus wrap to a second line if they cannot fit in the window. The window has a list of icons along the top, with an address bar below it, a list of icons for tabs along the left edge, a status bar on the bottom, and two panes in the middle. The desktop has a bar at the bottom of the screen with a few buttons, a pager, a list of open applications, and a clock."> <figcaption>Screenshot of a KDE desktop.</figcaption> </figure> A graph in a financial report: <img src="sales.gif" title="Sales graph" alt="From 1998 to 2005, sales increased by the following percentages with each year: 624%, 75%, 138%, 40%, 35%, 9%, 21%"> Note that "sales graph" would be inadequate alternative text for a sales graph. Text that
would be a good caption is not generally suitable as replacement text. Images that defy a complete description In certain cases, the nature of the image might be such that providing thorough alternative
text is impractical. For example, the image could be indistinct, or could be a complex fractal,
or could be a detailed topographical map. In these cases, the alt attribute must contain some
suitable alternative text, but it may be somewhat brief. Sometimes there simply is no text that can do justice to an image. For example, there is
little that can be said to usefully describe a Rorschach inkblot test. However, a description,
even if brief, is still better than nothing:

http://developers.whatwg.org/embedded-content-1.html[4/16/2014 9:28:42 PM]

4.7 Embedded content HTML: The Living Standard - Edition for Web Developers

<figure> <img src="/commons/a/a7/Rorschach1.jpg" alt="A shape with left-right symmetry with indistinct edges, with a small gap in the center, two larger gaps offset slightly from the center, with two similar gaps under them. The outline is wider in the top half than the bottom half, with the sides extending upwards higher than the center, and the center extending below the sides."> <figcaption>A black outline of the first of the ten cards in the Rorschach inkblot test.</figcaption> </figure> Note that the following would be a very bad use of alternative text: <!-- This example is wrong. Do not copy it. --> <figure> <img src="/commons/a/a7/Rorschach1.jpg" alt="A black outline of the first of the ten cards in the Rorschach inkblot test."> <figcaption>A black outline of the first of the ten cards in the Rorschach inkblot test.</figcaption> </figure> Including the caption in the alternative text like this isn't useful because it effectively
duplicates the caption for users who don't have images, taunting them twice yet not helping
them any more than if they had only read or heard the caption once. Another example of an image that defies full description is a fractal, which, by definition,
is infinite in detail. The following example shows one possible way of providing alternative text for the full view
of an image of the Mandelbrot set. <img src="ms1.jpeg" alt="The Mandelbrot set appears as a cardioid with its cusp on the real axis in the positive direction, with a smaller

http://developers.whatwg.org/embedded-content-1.html[4/16/2014 9:28:42 PM]

4.7 Embedded content HTML: The Living Standard - Edition for Web Developers

bulb aligned along the same center line, touching it in the negative direction, and with these two shapes being surrounded by smaller bulbs of various sizes."> Similarly, a photograph of a person's face, for example in a biography, can be considered
quite relevant and key to the content, but it can be hard to fully substitute text for <section class="bio"> <h1>A Biography of Isaac Asimov</h1> <p>Born <b>Isaak Yudovich Ozimov</b> in 1920, Isaac was a prolific author.</p> <p><img src="headpics/asimov.jpeg" alt="Isaac Asimov had dark hair, a tall forehead, and wore glasses. Later in life, he wore long white sideburns."> <p>Asimov was born in Russia, and moved to the US when he was three years old.</p> <p>... </section> In such cases it is unnecessary (and indeed discouraged) to include a reference to the
presence of the image itself in the alternative text, since such text would be redundant with
the browser itself reporting the presence of the image. For example, if the alternative text
was "A photo of Isaac Asimov", then a conforming user agent might read that out as "(Image) A
photo of Isaac Asimov" rather than the more useful "(Image) Isaac Asimov had dark hair, a tall
forehead, and wore glasses...". Images whose contents are not known In some unfortunate cases, there might be no alternative text available at all, either
because the image is obtained in some automated fashion without any associated alternative text
(e.g. a Webcam), or because the page is being generated by a script using user-provided images
where the user did not provide suitable or usable alternative text (e.g. photograph sharing
sites), or because the author does not himself know what the images represent (e.g. a blind
photographer sharing an image on his blog). In such cases, the alt attribute may be omitted, but one of
the following conditions must be met as well:

http://developers.whatwg.org/embedded-content-1.html[4/16/2014 9:28:42 PM]

4.7 Embedded content HTML: The Living Standard - Edition for Web Developers

The img element is in a


figure element that contains a figcaption element
that contains
content other than inter-element whitespace, and, ignoring the figcaption element and its descendants, the figure element has no
Text node descendants other than inter-element whitespace, and no
embedded content descendant other than the img element.

The title attribute is present and has a non-empty


value.
Relying on the title attribute is currently
discouraged as many user agents do not expose the attribute in an accessible manner as
required by this specification (e.g. requiring a pointing device such as a mouse to cause a tooltip to appear, which excludes keyboard-only users and touch-only users, such as anyone
with a modern phone or tablet). Such cases are to be kept to an absolute minimum. If there is even the slightest
possibility of the author having the ability to provide real alternative text, then it would not
be acceptable to omit the alt attribute. A photo on a photo-sharing site, if the site received the image with no metadata other than
the caption, could be marked up as follows: <figure> <img src="1100670787_6a7c664aef.jpg"> <figcaption>Bubbles traveled everywhere with us. </figcaption> </figure> It would be better, however, if a detailed description of the important parts of the image
obtained from the user and included on the page. A blind user's blog in which a photo taken by the user is shown. Initially, the user might
not have any idea what the photo he took shows: <article> <h1>I took a photo</h1> <p>I went out today and took a photo!</p> <figure> <img src="photo2.jpeg"> <figcaption>A photograph taken blindly from my front porch. </figcaption> </figure> </article>

http://developers.whatwg.org/embedded-content-1.html[4/16/2014 9:28:42 PM]

4.7 Embedded content HTML: The Living Standard - Edition for Web Developers

Eventually though, the user might obtain a description of the image from his friends and
could then include alternative text: <article> <h1>I took a photo</h1> <p>I went out today and took a photo!</p> <figure> <img src="photo2.jpeg" alt="The photograph shows my squirrel feeder hanging from the edge of my roof. It is half full, but there are no squirrels around. In the background, out-of-focus trees fill the shot. The feeder is made of wood with a metal grate, and it contains peanuts. The edge of the roof is wooden too, and is painted white with light blue streaks."> <figcaption>A photograph taken blindly from my front porch. </figcaption> </figure> </article> Sometimes the entire point of the image is that a textual description is not available, and
the user is to provide the description. For instance, the point of a CAPTCHA image is to see if
the user can literally read the graphic. Here is one way to mark up a CAPTCHA (note the title attribute): <p><label>What does this image say? <img src="captcha.cgi?id=8934" title="CAPTCHA"> <input type=text name=captcha></label> (If you cannot see the image, you can use an <a href="?audio">audio</a> test instead.)</p> Another example would be software that displays images and asks for alternative text
precisely for the purpose of then writing a page with correct alternative text. Such a page
could have a table of images, like this: <table> <thead> <tr> <th> Image <th> Description
http://developers.whatwg.org/embedded-content-1.html[4/16/2014 9:28:42 PM]

4.7 Embedded content HTML: The Living Standard - Edition for Web Developers

<tbody> <tr> <td> <img src="2421.png" title="Image 640 by 100, filename 'banner.gif'"> <td> <input name="alt2421"> <tr> <td> <img src="2422.png" title="Image 200 by 480, filename 'ad3.gif'"> <td> <input name="alt2422"> </table> Notice that even in this example, as much useful information as possible is still included
in the title attribute. Since some users cannot use images at all (e.g. because they have a very slow connection, or because they are using a text-only browser, or because they are listening to the
page being read out by a hands-free automobile voice Web browser, or simply because they are
blind), the alt attribute is only allowed to be omitted rather
than being provided with replacement text when no alternative text is available and none can be
made available, as in the above examples. Lack of effort from the part of the author is not an acceptable reason for omitting the alt attribute.

An image not intended for the user Generally authors should avoid using img elements for purposes other than showing
images. If an img element is being used for purposes other than showing an image, e.g. as
part of a service to count page views, then the alt attribute
must be the empty string. In such cases, the width and height attributes should both be set to zero.

An image in an e-mail or private document intended for a specific person who is known to be able to view images This section does not apply to documents that are publicly accessible, or whose target
audience is not necessarily personally known to the author, such as documents on a Web site,
e-mails sent to public mailing lists, or

http://developers.whatwg.org/embedded-content-1.html[4/16/2014 9:28:42 PM]

4.7 Embedded content HTML: The Living Standard - Edition for Web Developers

software documentation. When an image is included in a private communication (such as an HTML email) aimed at a
specific person who is known to be able to view images, the alt
attribute may be omitted. However, even in such cases authors are strongly urged to include
alternative text (as appropriate according to the kind of image involved, as described in the
above entries), so that the e-mail is still usable should the user use a mail client that does not
support images, or should the document be forwarded on to other users whose abilities might not
include easily seeing images.

Adaptive images
CSS and media queries can be used to construct graphical page layouts that adapt dynamically to
the user's environment, in particular to different viewport dimensions and pixel densities. For
content, however, CSS does not help; instead, we have the img element's srcset attribute. This section walks through a sample case showing
how to use this attribute. Consider a situation where on wide screens (wider than 600 CSS pixels) a 300150 image
named a-rectangle.png is to be used, but on smaller screens (600 CSS pixels
and less), a smaller 100100 image called a-square.png is to be used.
The markup for this would look like this: <figure> <img src="a-rectangle.png" srcset="a-square.png 600w" alt="Barney Frank wears a suit and glasses."> <figcaption>Barney Frank, 2011</figcaption> </figure> For details on what to put in the alt attribute,
see the earlier sections. The problem with this is that the user agent does not necessarily know what dimensions to use
for the image when the image is loading. To avoid the layout having to be reflowed multiple times
as the page is loading, CSS and CSS media queries can be used to provide the dimensions: <figure> <style scoped> #a { width: 300px; height: 150px; } @media all and (max-width: 600px) { #a { width: 100px;
http://developers.whatwg.org/embedded-content-1.html[4/16/2014 9:28:42 PM]

4.7 Embedded content HTML: The Living Standard - Edition for Web Developers

height: 100px; } } </style> <img src="a-rectangle.png" srcset="a-square.png 600w" id="a" alt="Barney Frank wears a suit and glasses."> <figcaption>Barney Frank, 2011</figcaption> </figure> Alternatively, the width and height attributes can be used to provide the width for legacy user
agents, using CSS just for the user agents that support srcset : <figure> <style scoped media="all and (max-width: 600px)"> #a { width: 100px; height: 100px; } </style> <img src="a-rectangle.png" width="300" height="100" srcset="a-square.png 600w" id=a alt="Barney Frank wears a suit and glasses."> <figcaption>Barney Frank, 2011</figcaption> </figure> The srcset attribute is used with the src attribute, which gives the URL of the image to use for legacy user
agents that do not support the srcset attribute. This leads
to a question of which image to provide in the src attribute. The answer that results in the least duplication is to provide the image suitable for an
infinite width and infinite height viewport with a pixel density of 1 CSS pixel per device
pixel: <img src="pear-desktop.jpeg" srcset="pear-mobile.jpeg 720w, pear-tablet.jpeg 1280w" alt="The pear is juicy."> However, if legacy mobile user agents are more important, one can list all three images in the
srcset attribute, overriding the src attribute entirely. To do this, the widest image has to have the
pixel density descriptor instead of the width, since there is no way to specify an infinite width
explicitly: <img src="pear-mobile.jpeg" srcset="pear-mobile.jpeg 720w, pear-tablet.jpeg 1280w, pear-desktop.jpeg 1x"
http://developers.whatwg.org/embedded-content-1.html[4/16/2014 9:28:42 PM]

4.7 Embedded content HTML: The Living Standard - Edition for Web Developers

alt="The pear is juicy."> Since at this point the src attribute is actually being
ignored entirely by srcset -supporting user agents, the src attribute can default to any image, including one that is neither
the smallest nor biggest: <img src="pear-tablet.jpeg" srcset="pear-mobile.jpeg 720w, pear-tablet.jpeg 1280w, pear-desktop.jpeg 1x" alt="The pear is juicy."> The dimensions in the srcset attribute are the maximum
(viewport) dimensions that an image is intended for. It is possible to think of the numbers as
minimums, though... if the images are listed in order, then the minimum for an image is the
dimension given for the previous image. This example attempts to demonstrate this by using the
file names to show the minimum values for each image: <img src="pear-tablet.jpeg" srcset="pear-min0.jpeg 720w, pear-min721.jpeg 1280w, pear-min1281.jpeg 1x" alt="The pear is juicy.">

Up next

4.7.2 The iframe element

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/embedded-content-1.html[4/16/2014 9:28:42 PM]

4.8 Links HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
Links
Introduction
Links created by a and area elements
Downloading resources
Link types
Link type "alternate "
Link type " author"
Link type "bookmark "
Link type "external "
Link type "help"
Link type "icon"
Link type "license "
Link type "nofollow "
Link type "noreferrer"
Link type "pingback "
Link type "prefetch "
Link type " search"
Link type "sidebar "
Link type "stylesheet"
Link type "tag "
Sequential link types
Link type "next"
Link type "prev"
Other link types

Links

http://developers.whatwg.org/links.html[4/16/2014 9:28:48 PM]

4.8 Links HTML: The Living Standard - Edition for Web Developers

Introduction
Links are a conceptual construct, created by a, area, and
link elements, that represent a connection between
two resources, one of which is the current Document. There are two kinds of links in
HTML: Links to external resources These are links to resources that are to be used to augment the current document,
generally automatically processed by the user agent. Hyperlinks These are links to other resources that are generally exposed to the user by the user
agent so that the user can cause the user agent to navigate to those resources, e.g.
to visit them in a browser or download them. For link elements with an href attribute and a
rel attribute, links must be created for the keywords of the
rel attribute, as defined for those keywords in the link types section. Similarly, for a and area elements with an href attribute and a rel attribute, links must be created for the keywords of the
rel attribute as defined for those keywords in the link types section. Unlike link elements, however,
a and area element with an href
attribute that either do not have a rel attribute, or
whose rel attribute has no keywords that are defined as specifying hyperlinks, must also create a hyperlink.
This implied hyperlink has no special meaning (it has no link type)
beyond linking the element's document to the resource given by the element's href attribute. A hyperlink can have one or more hyperlink
annotations that modify the processing semantics of that hyperlink.

Links created by a and area elements


The href attribute on a and
area elements must have a value that is a valid URL potentially surrounded by
spaces. The href attribute on a and
area elements is not required; when those elements do not have href attributes they do not create hyperlinks. The target attribute, if present, must be
a valid browsing context name or

http://developers.whatwg.org/links.html[4/16/2014 9:28:48 PM]

4.8 Links HTML: The Living Standard - Edition for Web Developers

keyword. It gives the name of the browsing


context that will be used. When an a or area element's activation behavior is
invoked, the user agent may allow the user to indicate a preference regarding whether the
hyperlink is to be used for navigation or whether the resource it
specifies is to be downloaded. In the absence of a user preference, the default should be navigation if the element has no
download attribute, and should be to download the
specified resource if it does. Whether determined by the user's preferences or via the presence or absence of the attribute,
if the decision is to use the hyperlink for navigation then the user
agent must follow the hyperlink, and if the decision is
to use the hyperlink to download a resource, the user agent must download the hyperlink. These terms are defined in subsequent sections
below. The download attribute, if present,
indicates that the author intends the hyperlink to be used for downloading a resource. The
attribute may have a value; the value, if any, specifies the default file name that the author recommends for use in labeling the resource in a local file system. There are no restrictions on
allowed values, but authors are cautioned that most file systems have limitations with regard to
what punctuation is supported in file names, and user agents are likely to adjust file names
accordingly. The ping attribute, if present,
gives the URLs of the resources that are interested in being notified if the user follows the
hyperlink. The value must be a set of space-separated tokens, each of which must be a
valid non-empty URL. The rel attribute on a and
area elements controls what kinds of links the elements create. The attribute's value
must be a set of space-separated tokens. The allowed keywords
and their meanings are defined below. The rel attribute has no default value. If the
attribute is omitted or if none of the values in the attribute are recognized by the user agent,
then the document has no particular relationship with the destination resource other than there
being a hyperlink between the two. The hreflang attribute on
a and area elements that create hyperlinks, if present, gives the language of the linked resource. It is
purely advisory. The value must be a valid BCP 47 language tag.

http://developers.whatwg.org/links.html[4/16/2014 9:28:48 PM]

4.8 Links HTML: The Living Standard - Edition for Web Developers

The type attribute, if present, gives the


MIME type of the linked resource. It is purely advisory. The value must be a
valid MIME type.

Downloading resources
In some cases, resources are intended for later use rather than immediate viewing. To indicate
that a resource is intended to be downloaded for use later, rather than immediately used, the
download attribute can be specified on the
a or area element that creates the hyperlink to that
resource. The attribute can furthermore be given a value, to specify the file name that user agents are
to use when storing the resource in a file system. This value can be overridden by the Content-Disposition HTTP header's filename parameters. In cross-origin situations, the download attribute
has to be combined with the Content-Disposition HTTP
header, specifically with the attachment disposition type, to avoid the user
being warned of possibly nefarious activity. (This is to protect users from being made to download
sensitive personal or confidential information without their full understanding.) The ping attribute is redundant with pre-existing
technologies like HTTP redirects and JavaScript in allowing Web pages to track which off-site
links are most popular or allowing advertisers to track click-through rates. However, the ping attribute provides these advantages
to the user over those alternatives:

It allows the user to see the final target URL unobscured. It allows the UA to inform the user about the out-of-band notifications. It allows the user to disable the notifications without losing the underlying
link
functionality.

It allows the UA to optimize the use of available network bandwidth so that


the target page
loads faster. Thus, while it is possible to track users without this feature, authors are encouraged to use
the ping attribute so that the user agent can make the user experience more transparent.

http://developers.whatwg.org/links.html[4/16/2014 9:28:48 PM]

4.8 Links HTML: The Living Standard - Edition for Web Developers

Link types
The following table summarizes the link types that are defined by this specification. This
table is non-normative; the actual definitions for the link types are given in the next few
sections. In this section, the term referenced document refers to the resource identified by the
element representing the link, and the term current document refers to the resource within
which the element representing the link finds itself. Except where otherwise specified, a keyword must not be specified more than once per rel attribute. Link types are always ASCII case-insensitive. Thus, rel="next" is the same as rel="NEXT". Link type Effect on... link alternate author Hyperlink a and area Hyperlink Gives alternate representations of the current document. Hyperlink Hyperlink Gives a link to the author of the current document or article. bookmark external not allowed not allowed Hyperlink Hyperlink Gives the permalink for the nearest ancestor section. Indicates that the referenced document is not part of the same site as the current document. help icon license Hyperlink Hyperlink Provides a link to contextsensitive help. External Resource Hyperlink not allowed Hyperlink Imports an icon to represent the current document. Indicates that the main content of the current document is covered by the copyright license described by the referenced document. Brief description

http://developers.whatwg.org/links.html[4/16/2014 9:28:48 PM]

4.8 Links HTML: The Living Standard - Edition for Web Developers

next

Hyperlink

Hyperlink

Indicates that the current document is a part of a series, and that the next document in the series is the referenced document.

nofollow

not allowed

Annotation

Indicates that the current document's original author or publisher does not endorse the referenced document.

noreferrer

not allowed

Annotation

Requires that the user agent not send an HTTP Referer (sic) header if the user follows the hyperlink.

pingback

External Resource

not allowed

Gives the address of the pingback server that handles pingbacks to the current document.

prefetch

External Resource

External Resource

Specifies that the target resource should be preemptively cached.

prev

Hyperlink

Hyperlink

Indicates that the current document is a part of a series, and that the previous document in the series is the referenced document.

search

Hyperlink

Hyperlink

Gives a link to a resource that can be used to search through the current document and its related pages.

sidebar

Hyperlink

Hyperlink

Specifies that the referenced document, if retrieved, is intended to be shown in the browser's sidebar (if it has one).

stylesheet

External Resource not

not allowed Hyperlink

Imports a stylesheet.

Gives a tag (identified by the

http://developers.whatwg.org/links.html[4/16/2014 9:28:48 PM]

4.8 Links HTML: The Living Standard - Edition for Web Developers

tag allowed given address) that applies to the current document.

Link type "alternate "


The alternate keyword may be used with link,
a , and area elements. The meaning of this keyword depends on the values of the other attributes. If the element is a link element and the rel
attribute also contains the keyword stylesheet The alternate keyword modifies the meaning of the stylesheet keyword in the way described for that keyword. The
alternate keyword does not create a link of its own. If the alternate keyword is used with the type attribute set to the value application/rss+xml or the value application/atom+xml The keyword creates a hyperlink referencing a syndication feed (though not necessarily syndicating exactly the same content as the current page). Otherwise The keyword creates a hyperlink referencing an alternate representation of the
current document. The nature of the referenced document is given by the hreflang, and type attributes. If the alternate keyword is used with the hreflang attribute, and that attribute's value differs
from the root element's language, it indicates that the referenced
document is a translation. If the alternate keyword is used with the type attribute, it indicates that the referenced document is
a reformulation of the current document in the specified format. The hreflang and type attributes can be combined when specified with the alternate keyword. For example, the following link is a French translation that uses the PDF format:

http://developers.whatwg.org/links.html[4/16/2014 9:28:48 PM]

4.8 Links HTML: The Living Standard - Edition for Web Developers

<link rel=alternate type=application/pdf hreflang=fr href=manual-fr> This relationship is transitive that is, if a document links to two other documents
with the link type "alternate ", then, in addition to implying
that those documents are alternative representations of the first document, it is also implying
that those two documents are alternative representations of each other.

Link type "author "


The author keyword may be used with link,
a , and area elements. This keyword creates a hyperlink. For a and area elements, the author
keyword indicates that the referenced document provides further information about the author of
the nearest article element ancestor of the element defining the hyperlink, if there
is one, or of the page as a whole, otherwise. For link elements, the author keyword indicates
that the referenced document provides further information about the author for the page as a whole. The "referenced document" can be, and often is, a mailto:
URL giving the email address of the author.

Link type "bookmark "


The bookmark keyword may be used with a and
area elements. This keyword creates a hyperlink. The bookmark keyword gives a permalink for the nearest
ancestor article element of the linking element in question, or of the section the linking element is most closely associated with, if
there are no ancestor article elements. The following snippet has three permalinks. A user agent could determine which permalink
applies to which part of the spec by looking at where the permalinks are given.

http://developers.whatwg.org/links.html[4/16/2014 9:28:48 PM]

4.8 Links HTML: The Living Standard - Edition for Web Developers

... <body> <h1>Example of permalinks</h1> <div id="a"> <h2>First example</h2> <p><a href="a.html" rel="bookmark">This</a> permalink applies to only the content from the first H2 to the second H2. The DIV isn't exactly that section, but it roughly corresponds to it. </p> </div> <h2>Second example</h2> <article id="b"> <p><a href="b.html" rel="bookmark">This</a> permalink applies to the outer ARTICLE element (which could be, e.g., a blog post).</p> <article id="c"> <p><a href="c.html" rel="bookmark">This</a> permalink applies to the inner ARTICLE element (which could be, e.g., a blog comment).</p> </article> </article> </body> ...

Link type "external "


The external keyword may be used with a and
area elements. This keyword creates a hyperlink. The external keyword indicates that the link is leading to a
document that is not part of the site that the current document forms a part of.

Link type "help "

http://developers.whatwg.org/links.html[4/16/2014 9:28:48 PM]

4.8 Links HTML: The Living Standard - Edition for Web Developers

The help keyword may be used with link,


a , and area elements. This keyword creates a hyperlink. For a and area elements, the help
keyword indicates that the referenced document provides further help information for the parent of
the element defining the hyperlink, and its children. In the following example, the form control has associated context-sensitive help. The user
agent could use this information, for example, displaying the referenced document if the user
presses the "Help" or "F1" key. <p><label> Topic: <input name=topic> <a href="help/topic.html" rel="help">(Help)</a></label></p> For link elements, the help keyword indicates that
the referenced document provides help for the page as a whole. For a and area elements, on some browsers, the help keyword causes the link to use a different cursor.

Link type "icon "


The icon keyword may be used with link elements.
This keyword creates an external resource link. Icons could be auditory icons, visual icons, or other kinds of icons. The sizes attribute gives the sizes of icons
for visual media. Its value, if present, is merely advisory. User agents may use the value to
decide which icon(s) to use if multiple icons are available. If specified, the attribute must have a value that is an unordered set of unique space-separated tokens which are ASCII case-insensitive. Each value must be either an ASCII case-insensitive match for the string "any", or a value that consists of two valid non-negative integers that do not have a leading U+0030 DIGIT
ZERO (0) character and that are separated by a single U+0078 LATIN SMALL LETTER X or U+0058 LATIN
CAPITAL LETTER X character. The keywords represent icon sizes. The any keyword represents that the
resource contains a scalable icon, e.g. as provided by an SVG image.

http://developers.whatwg.org/links.html[4/16/2014 9:28:48 PM]

4.8 Links HTML: The Living Standard - Edition for Web Developers

The keywords specified on the sizes attribute must not


represent icon sizes that are not actually available in the linked resource. The following snippet shows the top part of an application with several icons. <!DOCTYPE HTML> <html> <head> <title>lsForums Inbox</title> <link rel=icon href=favicon.png sizes="16x16" type="image/png"> <link rel=icon href=windows.ico sizes="32x32 48x48" type="image/vnd.microsoft.icon"> <link rel=icon href=mac.icns sizes="128x128 512x512 8192x8192 32768x32768"> <link rel=icon href=iphone.png sizes="57x57" type="image/png"> <link rel=icon href=gnome.svg sizes="any" type="image/svg+xml"> <link rel=stylesheet href=lsforums.css> <script src=lsforums.js></script> <meta name=application-name content="lsForums"> </head> <body> ... For historical reasons, the icon keyword may be preceded by the
keyword " shortcut". If the "shortcut" keyword is
present, it must be come immediately before the icon keyword and the
two keywords must be separated by only a single U+0020 SPACE character.

Link type "license "


The license keyword may be used with link,
a , and area elements. This keyword creates a hyperlink. The license keyword indicates that the referenced document
provides the copyright license terms under which the main content of the current document is
provided.

http://developers.whatwg.org/links.html[4/16/2014 9:28:48 PM]

4.8 Links HTML: The Living Standard - Edition for Web Developers

This specification does not specify how to distinguish between the main content of a document
and content that is not deemed to be part of that main content. The distinction should be made
clear to the user. Consider a photo sharing site. A page on that site might describe and show a photograph, and
the page might be marked up as follows: <!DOCTYPE HTML> <html> <head> <title>Exampl Pictures: Kissat</title> <link rel="stylesheet" href="/style/default"> </head> <body> <h1>Kissat</h1> <nav> <a href="../">Return to photo index</a> </nav> <figure> <img src="/pix/39627052_fd8dcd98b5.jpg"> <figcaption>Kissat</figcaption> </figure> <p>One of them has six toes!</p> <p><small><a rel="license" href="http://www.opensource.org/licenses/mit-license.php">MIT Licensed</a></small></p> <footer> <a href="/">Home</a> | <a href="../">Photo index</a> <p><small> copyright 2009 Exampl Pictures. All Rights Reserved.</small></p> </footer> </body> </html> In this case the license applies to just the photo (the main
content of the document), not the whole document. In particular not the design of the page itself, which is covered by the copyright given at the bottom of the document. This could be made
clearer in the styling (e.g. making the license link prominently positioned near the photograph,
while having the page copyright in light small text at the foot of the page.

http://developers.whatwg.org/links.html[4/16/2014 9:28:48 PM]

4.8 Links HTML: The Living Standard - Edition for Web Developers

Link type "nofollow "


The nofollow keyword may be used with a and
area elements. This keyword does not create a hyperlink, but annotates any other hyperlinks created by the element (the
implied hyperlink, if no other keywords create one). The nofollow keyword indicates that the link is not endorsed
by the original author or publisher of the page, or that the link to the referenced document was
included primarily because of a commercial relationship between people affiliated with the two
pages.

Link type "noreferrer"


The noreferrer keyword may be used with a and
area elements. This keyword does not create a hyperlink, but annotates any other hyperlinks created by the element (the
implied hyperlink, if no other keywords create one). It indicates that no referrer information is to be leaked when following the link.

Link type "pingback "


The pingback keyword may be used with link
elements. This keyword creates an external resource
link. For the semantics of the pingback keyword, see the Pingback
1.0 specification.

Link type "prefetch "


The prefetch keyword may be used with link,
a , and area elements. This keyword creates an external resource link. The prefetch keyword indicates that preemptively fetching and
caching the specified resource is likely to be beneficial, as it is highly likely that the user will require this resource.

http://developers.whatwg.org/links.html[4/16/2014 9:28:48 PM]

4.8 Links HTML: The Living Standard - Edition for Web Developers

There is no default type for resources given by the prefetch


keyword.

Link type "search "


The search keyword may be used with link,
a , and area elements. This keyword creates a hyperlink. The search keyword indicates that the referenced document
provides an interface specifically for searching the document and its related resources. OpenSearch description documents can be used with link elements and
the search link type to enable user agents to autodiscover search
interfaces.

Link type "sidebar "


The sidebar keyword may be used with link,
a , and area elements. This keyword creates a hyperlink. The sidebar keyword indicates that the referenced document, if
retrieved, is intended to be shown in a secondary browsing context (if possible),
instead of in the current browsing context. A hyperlink with the sidebar keyword specified is
a sidebar hyperlink.

Link type "stylesheet"


The stylesheet keyword may be used with link
elements. This keyword creates an external resource
link that contributes to the styling processing model. The specified resource is a resource that describes how to present the document. Exactly how
the resource is to be processed depends on the actual type of the resource. If the alternate keyword is also specified on the
link element, then the link is an alternative stylesheet; in this case,
the title attribute must be specified on the link
element, with a non-empty value. The default type for resources given by the stylesheet
keyword is text/css.

http://developers.whatwg.org/links.html[4/16/2014 9:28:48 PM]

4.8 Links HTML: The Living Standard - Edition for Web Developers

Link type "tag "


The tag keyword may be used with a and
area elements. This keyword creates a hyperlink. The tag keyword indicates that the tag that the
referenced document represents applies to the current document. Since it indicates that the tag applies to the current document, it would
be inappropriate to use this keyword in the markup of a tag cloud, which
lists the popular tags across a set of pages. This document is about some gems, and so it is tagged with " http://en.wikipedia.org/wiki/Gemstone " to unambiguously categorise it as applying
to the "jewel" kind of gems, and not to, say, the towns in the US, the Ruby package format, or
the Swiss locomotive class: <!DOCTYPE HTML> <html> <head> <title>My Precious</title> </head> <body> <header><h1>My precious</h1> <p>Summer 2012</p></header> <p>Recently I managed to dispose of a red gem that had been bothering me. I now have a much nicer blue sapphire.</p> <p>The red gem had been found in a bauxite stone while I was digging out the office level, but nobody was willing to haul it away. The same red gem stayed there for literally years.</p> <footer> Tags: <a rel=tag href="http://en.wikipedia.org/wiki/Gemstone">Gemstone</a> </footer> </body> </html> In this document, there are two articles. The "tag "
link, however, applies to the whole page (and would do so wherever it was placed, including if it
was
http://developers.whatwg.org/links.html[4/16/2014 9:28:48 PM]

4.8 Links HTML: The Living Standard - Edition for Web Developers

within the article elements). <!DOCTYPE HTML> <html> <head> <title>Gem 4/4</title> </head> <body> <article> <h1>801: Steinbock</h1> <p>The number 801 Gem 4/4 electro-diesel has an ibex and was rebuilt in 2002.</p> </article> <article> <h1>802: Murmeltier</h1> <figure> <img src="http://upload.wikimedia.org/wikipedia/commons/b/b0/Train s_de_la_Bernina_en_hiver_2.jpg" alt="The 802 was red with pantographs and tall vents on the side."> <figcaption>The 802 in the 1980s, above Lago Bianco. </figcaption> </figure> <p>The number 802 Gem 4/4 electro-diesel has a marmot and was rebuilt in 2003.</p> </article> <p class="topic"><a rel=tag href="http://en.wikipedia.org/wiki/Rhaetian_Railway_Gem_4/4"> Gem 4/4</a></p> </body> </html>

Sequential link types


Some documents form part of a sequence of documents. A sequence of documents is one where each document can have a previous sibling and a
next sibling. A document with no previous sibling is the start of

http://developers.whatwg.org/links.html[4/16/2014 9:28:48 PM]

4.8 Links HTML: The Living Standard - Edition for Web Developers

its sequence, a
document with no next sibling is the end of its sequence. A document may be part of multiple sequences.

Link type "next" The next keyword may be used with link,
a , and area elements. This keyword creates a hyperlink. The next keyword indicates that the document is part of a
sequence, and that the link is leading to the document that is the next logical document in the sequence.

Link type "prev" The prev keyword may be used with link,
a , and area elements. This keyword creates a hyperlink. The prev keyword indicates that the document is part of a
sequence, and that the link is leading to the document that is the previous logical document in the sequence.

Other link types


Extensions to the predefined set of link types may be
registered in the microformats
wiki existing-rel-values page. Anyone is free to edit the microformats wiki existing-rel-values page at
any time to add a type. Extension types must be specified with the following information: Keyword The actual value being defined. The value should not be confusingly similar to any other
defined value (e.g. differing only in case). If the value contains a U+003A COLON character (:), it must also be an absolute
URL. Effect on... link One of the following:

http://developers.whatwg.org/links.html[4/16/2014 9:28:48 PM]

4.8 Links HTML: The Living Standard - Edition for Web Developers

Not allowed The keyword must not be specified on link elements. Hyperlink The keyword may be specified on a link element; it creates a
hyperlink. External Resource The keyword may be specified on a link element; it creates an external resource link. Effect on... a and area One of the following: Not allowed The keyword must not be specified on a and area elements. Hyperlink The keyword may be specified on a and area elements; it creates a
hyperlink. External Resource The keyword may be specified on a and area elements; it creates
an external resource link. Hyperlink Annotation The keyword may be specified on a and area elements; it annotates other hyperlinks
created by the element. Brief description A short non-normative description of what the keyword's meaning is. Specification A link to a more detailed description of the keyword's semantics and requirements. It
could be another page on the Wiki, or a link to an external page. Synonyms A list of other keyword values that have exactly the same processing requirements. Authors
should not use the values defined to be synonyms, they are only intended to allow user agents to
support legacy content. Anyone may remove synonyms that are not used in practice; only names that
need to be processed as synonyms for compatibility with legacy content are to be registered in
this way. Status One of the following:

http://developers.whatwg.org/links.html[4/16/2014 9:28:48 PM]

4.8 Links HTML: The Living Standard - Edition for Web Developers

Proposed The keyword has not received wide peer review and approval. Someone has proposed it and is,
or soon will be, using it. Ratified The keyword has received wide peer review and approval. It has a specification that
unambiguously defines how to handle pages that use the keyword, including when they use it in
incorrect ways. Discontinued The keyword has received wide peer review and it has been found wanting. Existing pages are
using this keyword, but new pages should avoid it. The "brief description" and "specification"
entries will give details of what authors should use instead, if anything. If a keyword is found to be redundant with existing values, it should be removed and listed
as a synonym for the existing value. If a keyword is registered in the "proposed" state for a period of a month or more without
being used or specified, then it may be removed from the registry. If a keyword is added with the "proposed" status and found to be redundant with existing
values, it should be removed and listed as a synonym for the existing value. If a keyword is
added with the "proposed" status and found to be harmful, then it should be changed to
"discontinued" status. Anyone can change the status at any time, but should only do so in accordance with the
definitions above. Types defined as extensions in the microformats
wiki existing-rel-values page with the status "proposed" or "ratified" may be used with the
rel attribute on link, a, and area
elements in accordance to the "Effect on..." field. [MFREL]

Up next

4.9 Tabular data

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/links.html[4/16/2014 9:28:48 PM]

4.9 Tabular data HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
Tabular data
The table element
Techniques for describing tables
Techniques for table design
The caption element
The colgroup element
The col element
The tbody element
The thead element
The tfoot element
The tr element
The td element
The th element
Attributes common to td and th elements
Table sorting model
Examples

Tabular data

The table element


Categories: Flow content. Palpable content. Contexts in which this element can be used: Where flow content is expected.

http://developers.whatwg.org/tabular-data.html[4/16/2014 9:28:55 PM]

4.9 Tabular data HTML: The Living Standard - Edition for Web Developers

Content model: In this order: optionally a caption element,


followed by zero or more colgroup elements, followed
optionally by a thead element, followed optionally by
a tfoot element, followed by either zero or more
tbody elements or one or more tr
elements, followed optionally by a tfoot element (but
there can only be one tfoot element child in
total), optionally intermixed with one or more script-supporting elements. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes sortable DOM interface: The table element represents data with more than one dimension, in
the form of a table. Tables have rows, columns, and cells given by their descendants. The rows and
columns form a grid; a table's cells must completely cover that grid without overlap. Authors are encouraged to provide information describing how to interpret complex tables.
Guidance on how to provide such information is given
below. Tables must not be used as layout aids. Historically, some Web authors have misused tables in
HTML as a way to control their page layout. This usage is non-conforming, because tools attempting
to extract tabular data from such documents would obtain very confusing results. In particular,
users of accessibility tools like screen readers are likely to find it very difficult to navigate
pages with tables used for layout. There are a variety of alternatives to using HTML tables for layout, primarily using CSS positioning and the CSS table model. Authors are encouraged to consider
using some of the table design techniques described below
to make tables easier to navigate for users. The sortable attribute is used in the table
sorting model. table . caption [ = value ]

http://developers.whatwg.org/tabular-data.html[4/16/2014 9:28:55 PM]

4.9 Tabular data HTML: The Living Standard - Edition for Web Developers

Returns the table's caption element. Can be set, to replace the caption element. If the new value is not a
caption element, throws a HierarchyRequestError exception. caption = table . createCaption () Ensures the table has a caption element, and returns it. table . deleteCaption () Ensures the table does not have a caption element. table . tHead [ = value ] Returns the table's thead element. Can be set, to replace the thead element. If the new value is not a
thead element, throws a HierarchyRequestError exception. thead = table . createTHead() Ensures the table has a thead element, and returns it. table . deleteTHead() Ensures the table does not have a thead element. table . tFoot [ = value ] Returns the table's tfoot element. Can be set, to replace the tfoot element. If the new value is not a
tfoot element, throws a HierarchyRequestError exception. tfoot = table . createTFoot() Ensures the table has a tfoot element, and returns it. table . deleteTFoot() Ensures the table does not have a tfoot element. table . tBodies Returns an HTMLCollection of the tbody elements of the table. tbody = table . createTBody() Creates a tbody element, inserts it into the table, and returns it. table . rows Returns an HTMLCollection of the tr elements of the table. tr = table . insertRow( [ index ] )

http://developers.whatwg.org/tabular-data.html[4/16/2014 9:28:55 PM]

4.9 Tabular data HTML: The Living Standard - Edition for Web Developers

Creates a tr element, along with a tbody if required, inserts them


into the table at the position given by the argument, and returns the tr . The position is relative to the rows in the table. The index 1, which is the default
if the argument is omitted, is equivalent to inserting at the end of the table. If the given position is less than 1 or greater than the number of rows, throws an
IndexSizeError exception. table . deleteRow (index) Removes the tr element with the given position in the table. The position is relative to the rows in the table. The index 1 is equivalent to deleting the last row of the table. If the given position is less than 1 or greater than the index of the last row, or if
there are no rows, throws an IndexSizeError exception. Here is an example of a table being used to mark up a Sudoku puzzle. Observe the lack of
headers, which are not necessary in such a table. <section> <style scoped> table { border-collapse: collapse; border: solid thick; } colgroup, tbody { border: solid medium; } td { border: solid thin; height: 1.4em; width: 1.4em; textalign: center; padding: 0; } </style> <h1>Today's Sudoku</h1> <table> <colgroup><col><col><col> <colgroup><col><col><col> <colgroup><col><col><col> <tbody> <tr> <td> 1 <td> <td> 9 <tr> <td> 1 <td> <tr> <td> 7 <td> <td> 6 <tbody> <td> <td> <td> <td> <td> <td> <td> 2 <td> <td> <td> 9 <td> <td> <td> <td> 3 <td> 6 <td> <td> 4 <td> 7 <td>

http://developers.whatwg.org/tabular-data.html[4/16/2014 9:28:55 PM]

4.9 Tabular data HTML: The Living Standard - Edition for Web Developers

<tr> <td> 2 <td> <td> 8 <tr> <td> <td> <tr> <td> 5 <td> <td> 1 <tbody> <tr> <td> 6 <td> <td> 2 <tr> <td> <td> <tr> <td> 9 <td> <td> 5 </table> </section> <td> <td>

<td> 4 <td> <td> <td> <td>

<td> 3 <td> <td> <td>

<td> 9 <td> <td> <td> <td>

<td> 9 <td>

<td> 7 <td>

<td> <td> <td>

<td> <td>

<td> 5 <td> <td> 7 <td>

<td> <td>

<td> <td> <td>

<td> 8 <td>

<td> 2 <td>

Techniques for describing tables


For tables that consist of more than just a grid of cells with headers
in the first row and headers in the first column, and for any table in general where the reader
might have difficulty understanding the content, authors should include explanatory information
introducing the table. This information is useful for all users, but is especially useful for
users who cannot see the table, e.g. users of screen readers. Such explanatory information should introduce the purpose of the table, outline its basic cell
structure, highlight any trends or patterns, and generally teach the user how to use the
table. For instance, the following table: Characteristics with positive and negative sides Negative Characteristic Positive Sad Failing Mood Grade Happy Passing

...might benefit from a description explaining the way the table is laid out, something like
"Characteristics are given in the second column, with the negative side in the left column and the
positive side in the right column".
http://developers.whatwg.org/tabular-data.html[4/16/2014 9:28:55 PM]

4.9 Tabular data HTML: The Living Standard - Edition for Web Developers

There are a variety of ways to include this information, such as: In prose, surrounding the table <p>In the following table, characteristics are given in the second column, with the negative side in the left column and the positive side in the right column.</p> <table> <caption>Characteristics with positive and negative sides</caption> <thead> <tr> <th id="n"> Negative <th> Characteristic <th> Positive <tbody> <tr> <td headers="n r1"> Sad <th id="r1"> Mood <td> Happy <tr> <td headers="n r2"> Failing <th id="r2"> Grade <td> Passing </table> In the table's caption <table> <caption> <strong>Characteristics with positive and negative sides. </strong> <p>Characteristics are given in the second column, with the negative side in the left column and the positive side in the right column.</p> </caption> <thead>

http://developers.whatwg.org/tabular-data.html[4/16/2014 9:28:55 PM]

4.9 Tabular data HTML: The Living Standard - Edition for Web Developers

<tr> <th id="n"> Negative <th> Characteristic <th> Positive <tbody> <tr> <td headers="n r1"> Sad <th id="r1"> Mood <td> Happy <tr> <td headers="n r2"> Failing <th id="r2"> Grade <td> Passing </table> In the table's caption , in a details element <table> <caption> <strong>Characteristics with positive and negative sides. </strong> <details> <summary>Help</summary> <p>Characteristics are given in the second column, with the negative side in the left column and the positive side in the right column.</p> </details> </caption> <thead> <tr> <th id="n"> Negative <th> Characteristic <th> Positive <tbody> <tr> <td headers="n r1"> Sad <th id="r1"> Mood <td> Happy <tr>
http://developers.whatwg.org/tabular-data.html[4/16/2014 9:28:55 PM]

4.9 Tabular data HTML: The Living Standard - Edition for Web Developers

<td headers="n r2"> Failing <th id="r2"> Grade <td> Passing </table> Next to the table, in the same figure <figure> <figcaption>Characteristics with positive and negative sides</figcaption> <p>Characteristics are given in the second column, with the negative side in the left column and the positive side in the right column.</p> <table> <thead> <tr> <th id="n"> Negative <th> Characteristic <th> Positive <tbody> <tr> <td headers="n r1"> Sad <th id="r1"> Mood <td> Happy <tr> <td headers="n r2"> Failing <th id="r2"> Grade <td> Passing </table> </figure> Next to the table, in a figure's figcaption <figure> <figcaption> <strong>Characteristics with positive and negative sides</strong> <p>Characteristics are given in the second column, with the negative side in the left column and the positive side in the right

http://developers.whatwg.org/tabular-data.html[4/16/2014 9:28:55 PM]

4.9 Tabular data HTML: The Living Standard - Edition for Web Developers

column.</p> </figcaption> <table> <thead> <tr> <th id="n"> Negative <th> Characteristic <th> Positive <tbody> <tr> <td headers="n r1"> Sad <th id="r1"> Mood <td> Happy <tr> <td headers="n r2"> Failing <th id="r2"> Grade <td> Passing </table> </figure>

Authors may also use other techniques, or combinations of the above techniques, as
appropriate. The best option, of course, rather than writing a description explaining the way the table is
laid out, is to adjust the table such that no explanation is needed. In the case of the table used in the examples above, a simple rearrangement of the table so
that the headers are on the top and left sides removes the need for an explanation as well as
removing the need for the use of headers attributes: <table> <caption>Characteristics with positive and negative sides</caption> <thead> <tr> <th> Characteristic <th> Negative <th> Positive <tbody>

http://developers.whatwg.org/tabular-data.html[4/16/2014 9:28:55 PM]

4.9 Tabular data HTML: The Living Standard - Edition for Web Developers

<tr> <th> Mood <td> Sad <td> Happy <tr> <th> Grade <td> Failing <td> Passing </table>

Techniques for table design


Good table design is key to making tables more readable and usable. In visual media, providing column and row borders and alternating row backgrounds can be very
effective to make complicated tables more readable. For tables with large volumes of numeric content, using monospaced fonts can help users see
patterns, especially in situations where a user agent does not render the borders. (Unfortunately,
for historical reasons, not rendering borders on tables is a common default.) In speech media, table cells can be distinguished by reporting the corresponding headers before
reading the cell's contents, and by allowing users to navigate the table in a grid fashion, rather
than serializing the entire contents of the table in source order. Authors are encouraged to use CSS to achieve these effects.

The caption element


Categories: None. Contexts in which this element can be used: As the first element child of a table element. Content model: Flow content, but with no descendant table elements. Tag omission in text/html:

http://developers.whatwg.org/tabular-data.html[4/16/2014 9:28:55 PM]

4.9 Tabular data HTML: The Living Standard - Edition for Web Developers

Neither tag is omissible. Content attributes: Global attributes DOM interface: The caption element represents the title of the table
that is its parent, if it has a parent and that is a table element. When a table element is the only content in a figure element other
than the figcaption , the caption element should be omitted in favor of
the figcaption . A caption can introduce context for a table, making it significantly easier to understand. Consider, for instance, the following table: 1 1 2 2 3 3 4 4 5 5 6 6 7 2 3 4 5 6 7 8 3 4 5 6 7 8 9 4 5 6 7 8 9 10 5 6 7 8 9 10 11 6 7 8 9 10 11 12

In the abstract, this table is not clear. However, with a caption giving the table's number
(for reference in the main prose) and explaining its use, it makes more sense: <caption> <p>Table 1. <p>This table shows the total score obtained from rolling two six-sided dice. The first row represents the value of the first die, the first column the value of the second die. The total is given in the cell that corresponds to the values of the two dice. </caption>

http://developers.whatwg.org/tabular-data.html[4/16/2014 9:28:55 PM]

4.9 Tabular data HTML: The Living Standard - Edition for Web Developers

This provides the user with more context: Table 1. This table shows the total score obtained from rolling two
sixsided dice. The first row represents the value of the first die, the first column the value of the second die. The total is
given in the cell that corresponds to the values of the two dice. 1 1 2 2 3 3 4 4 5 5 6 6 7 2 3 4 5 6 7 8 3 4 5 6 7 8 9 4 5 6 7 8 9 10 5 6 7 8 9 10 11 6 7 8 9 10 11 12

The colgroup element


Categories: None. Contexts in which this element can be used: As a child of a table element, after any
caption elements and before any thead ,
tbody, tfoot , and tr
elements. Content model: If the span attribute is present: Empty. If the span attribute is absent: Zero or more col and template elements. Tag omission in text/html: A colgroup element's start tag can be
omitted if the first thing inside the colgroup element is a col element,
and if the element is not immediately preceded by another colgroup element whose
end tag has been omitted. (It can't be omitted if the element
is empty.)

http://developers.whatwg.org/tabular-data.html[4/16/2014 9:28:55 PM]

4.9 Tabular data HTML: The Living Standard - Edition for Web Developers

A colgroup element's end tag can be omitted if


the colgroup element is not immediately followed by a space character or
a comment. Content attributes: Global attributes span Number of columns spanned by the element DOM interface: The colgroup element represents a group of one or more columns in the table that is its parent, if it has a
parent and that is a table element. If the colgroup element contains no col elements, then the element
may have a span content attribute specified,
whose value must be a valid nonnegative integer greater than zero.

The col element


Categories: None. Contexts in which this element can be used: As a child of a colgroup element that doesn't have
a span attribute. Content model: Empty. Tag omission in text/html: No end tag. Content attributes: Global attributes span Number of columns spanned by the element DOM interface: HTMLTableColElement, same as for
colgroup elements. This interface defines one member,
span. If a col element has a parent and that is a colgroup element that
itself has a parent that is a table element, then the col element
represents one or more columns in the column group represented by that colgroup. The element may have a content attribute
specified, whose value must be

http://developers.whatwg.org/tabular-data.html[4/16/2014 9:28:55 PM]

4.9 Tabular data HTML: The Living Standard - Edition for Web Developers

span a valid non-negative integer greater than zero.

The tbody element


Categories: None. Contexts in which this element can be used: As a child of a table element, after any
caption, colgroup, and
thead elements, but only if there are no
tr elements that are children of the
table element. Content model: Zero or more tr and script-supporting elements Tag omission in text/html: A tbody element's start tag can be omitted
if the first thing inside the tbody element is a tr element, and if the
element is not immediately preceded by a tbody , thead, or
tfoot element whose end tag has been omitted. (It
can't be omitted if the element is empty.) A tbody element's end tag can be omitted if
the tbody element is immediately followed by a tbody or
tfoot element, or if there is no more content in the parent element. Content attributes: Global attributes DOM interface: The HTMLTableSectionElement interface is also
used for thead and tfoot elements. The tbody element represents a block of rows that consist of a
body of data for the parent table element, if the tbody element has a
parent and it is a table . tbody . rows Returns an HTMLCollection of the tr elements of the table
section. tr = tbody . insertRow ( [ index ] ) Creates a tr element, inserts it into the table section at the position given by

http://developers.whatwg.org/tabular-data.html[4/16/2014 9:28:55 PM]

4.9 Tabular data HTML: The Living Standard - Edition for Web Developers

the argument, and returns the tr . The position is relative to the rows in the table section. The index 1, which is the
default if the argument is omitted, is equivalent to inserting at the end of the table
section. If the given position is less than 1 or greater than the number of rows, throws an
IndexSizeError exception. tbody . deleteRow (index) Removes the tr element with the given position in the table section. The position is relative to the rows in the table section. The index 1 is equivalent
to deleting the last row of the table section. If the given position is less than 1 or greater than the index of the last row, or if
there are no rows, throws an IndexSizeError exception.

The thead element


Categories: None. Contexts in which this element can be used: As a child of a table element, after any
caption, and colgroup
elements and before any tbody, tfoot , and
tr elements, but only if there are no other thead elements that are children of the
table element. Content model: Zero or more tr and script-supporting elements Tag omission in text/html: A thead element's end tag can be omitted if
the thead element is immediately followed by a tbody or
tfoot element. Content attributes: Global attributes DOM interface: HTMLTableSectionElement, as defined for
tbody elements. The thead element represents the block of rows that consist of
the column labels (headers) for the parent table element, if the thead
element has a

http://developers.whatwg.org/tabular-data.html[4/16/2014 9:28:55 PM]

4.9 Tabular data HTML: The Living Standard - Edition for Web Developers

parent and it is a table . This example shows a thead element being used. Notice the use of both
th and td elements in the thead element: the first row is
the headers, and the second row is an explanation of how to fill in the table. <table> <caption> School auction sign-up sheet </caption> <thead> <tr> <th><label for=e1>Name</label> <th><label for=e2>Product</label> <th><label for=e3>Picture</label> <th><label for=e4>Price</label> <tr> <td>Your name here <td>What are you selling? <td>Link to a picture <td>Your reserve price <tbody> <tr> <td>Ms Danus <td>Doughnuts <td><img src="http://example.com/mydoughnuts.png" title="Doughnuts from Ms Danus"> <td>$45 <tr> <td><input id=e1 type=text name=who required form=f> <td><input id=e2 type=text name=what required form=f> <td><input id=e3 type=url name=pic form=f> <td><input id=e4 type=number step=0.01 min=0 value=0 required form=f> </table> <form id=f action="/auction.cgi"> <input type=button name=add value="Submit"> </form>

The tfoot element

http://developers.whatwg.org/tabular-data.html[4/16/2014 9:28:55 PM]

4.9 Tabular data HTML: The Living Standard - Edition for Web Developers

Categories: None. Contexts in which this element can be used: As a child of a table element, after any
caption, colgroup, and thead elements and before any tbody and tr
elements, but only if there are no other tfoot
elements that are children of the table element. As a child of a table element, after any
caption, colgroup, thead,
tbody , and tr elements, but only if there
are no other tfoot elements that are children of the
table element. Content model: Zero or more tr and script-supporting elements Tag omission in text/html: A tfoot element's end tag can be omitted if
the tfoot element is immediately followed by a tbody element, or if
there is no more content in the parent element. Content attributes: Global attributes DOM interface: HTMLTableSectionElement, as defined for
tbody elements. The tfoot element represents the block of rows that consist of
the column summaries (footers) for the parent table element, if the
tfoot element has a parent and it is a table .

The tr element
Categories: None. Contexts in which this element can be used: As a child of a thead element. As a child of a tbody element. As a child of a tfoot element. As a child of a table element, after any
caption, colgroup, and thead elements, but only if there are no tbody elements that
are children of the table element.

http://developers.whatwg.org/tabular-data.html[4/16/2014 9:28:55 PM]

4.9 Tabular data HTML: The Living Standard - Edition for Web Developers

Content model: Zero or more td , th , and script-supporting elements Tag omission in text/html: A tr element's end tag can be omitted if the
tr element is immediately followed by another tr element, or if there is
no more content in the parent element. Content attributes: Global attributes DOM interface: The tr element represents a row of
cells in a table. tr . rowIndex Returns the position of the row in the table's rows
list. Returns 1 if the element isn't in a table. tr . sectionRowIndex Returns the position of the row in the table section's rows list. Returns 1 if the element isn't in a table section. tr . cells Returns an HTMLCollection of the td and th elements of
the row. cell = tr . insertCell ( [ index ] ) Creates a td element, inserts it into the table row at the position given by the argument, and returns the td . The position is relative to the cells in the row. The index 1, which is the default
if the argument is omitted, is equivalent to inserting at the end of the row. If the given position is less than 1 or greater than the number of cells, throws an
IndexSizeError exception. tr . deleteCell(index) Removes the td or th element with the given position in the
row. The position is relative to the cells in the row. The index 1 is equivalent to deleting the last cell of the row.

http://developers.whatwg.org/tabular-data.html[4/16/2014 9:28:55 PM]

4.9 Tabular data HTML: The Living Standard - Edition for Web Developers

If the given position is less than 1 or greater than the index of the last cell, or if there are no cells, throws an IndexSizeError exception.

The td element
Categories: Sectioning root. Contexts in which this element can be used: As a child of a tr element. Content model: Flow content. Tag omission in text/html: A td element's end tag can be omitted if the
td element is immediately followed by a td or th element,
or if there is no more content in the parent element. Content attributes: Global attributes colspan Number of columns that the cell is to span rowspan Number of rows that the cell is to span headers The header cells for this cell DOM interface: The td element represents a data cell in a table.

The th element
Categories: If the th element is a sorting interface th element: Interactive content. Otherwise: None. Contexts in which this element can be used: As a child of a tr element. Content model: Flow content, but with no header , footer , sectioning content, or heading

http://developers.whatwg.org/tabular-data.html[4/16/2014 9:28:55 PM]

4.9 Tabular data HTML: The Living Standard - Edition for Web Developers

content descendants, and if the th element is a sorting interface th element, no interactive content descendants. Tag omission in text/html: A th element's end tag can be omitted if the
th element is immediately followed by a td or th element,
or if there is no more content in the parent element. Content attributes: Global attributes colspan Number of columns that the cell is to span rowspan Number of rows that the cell is to span headers The header cells for this cell scope Specifies which cells the header cell applies to abbr Alternative label to use for the header cell when referencing the cell in other contexts sorted Column sort direction and ordinality DOM interface: The th element represents a header cell in a table. The th element may have a scope
content attribute specified. The scope attribute is an
enumerated attribute with five states, four of which have explicit keywords: The row keyword, which maps to the
row state The row state means the header cell applies to some of the subsequent cells in the
same row(s). The col keyword, which maps to the
column state The column state means the header cell applies to some of the subsequent cells in the
same column(s). The rowgroup keyword, which maps to
the row group state The row group state means the header cell applies to all the remaining cells in the
row group. A th element's scope attribute must
not be in the row group state if the element is not
anchored in a row group. The colgroup keyword, which maps to
the column group state The column group state means the header cell applies to all the remaining cells in the
column group. A th element's scope attribute must
not be in the

http://developers.whatwg.org/tabular-data.html[4/16/2014 9:28:55 PM]

4.9 Tabular data HTML: The Living Standard - Edition for Web Developers

column group state if the element is


not anchored in a column group. The auto state The auto state makes the header cell apply to a set of cells selected based on context. The scope attribute's missing value default is the
auto state. The th element may have an abbr
content attribute specified. Its value must be an alternative label for the header cell, to be
used when referencing the cell in other contexts (e.g. when describing the header cells that apply
to a data cell). It is typically an abbreviated form of the full header cell, but can also be an
expansion, or merely a different phrasing. The sorted attribute is used in the table
sorting model. The following example shows how the scope attribute's rowgroup value affects which data cells a header cell
applies to. Here is a markup fragment showing a table: <table> <thead> <tr> <th> ID <th> Measurement <th> Average <th> Maximum <tbody> <tr> <td> <th scope=rowgroup> Cats <td> <td> <tr> <td> 93 <th scope=row> Legs <td> 3.5 <td> 4 <tr> <td> 10 <th scope=row> Tails <td> 1 <td> 1 <tbody> <tr> <td> <th scope=rowgroup> English speakers <td> <td> <tr> <td> 32 <th scope=row> Legs <td> 2.67 <td> 4 <tr> <td> 35 <th scope=row> Tails <td> 0.33 <td> 1 </table> This would result in the following table: ID Measurement Cats 93 10 Legs Tails English
http://developers.whatwg.org/tabular-data.html[4/16/2014 9:28:55 PM]

Average Maximum

3.5 1

4 1

4.9 Tabular data HTML: The Living Standard - Edition for Web Developers

speakers 32 35 Legs Tails 2.67 0.33 4 1

The headers in the first row all apply directly down to the rows in their column. The headers with the explicit scope attributes apply to all
the cells in their row group other than the cells in the first column. The remaining headers apply just to the cells to the right of them.

Attributes common to td and th elements


The td and th elements may have a colspan content attribute specified, whose value must
be a valid non-negative integer greater than zero. The td and th elements may also have a rowspan content attribute specified, whose value must
be a valid non-negative integer. For this attribute, the value zero means that the
cell is to span all the remaining rows in the row group. These attributes give the number of columns and rows respectively that the cell is to span.
These attributes must not be used to overlap cells. The td and th element may have a headers content attribute specified. The headers attribute, if specified, must contain a string consisting
of an unordered set of unique space-separated tokens that are
case-sensitive, each of which must have the value of an ID of a th element taking part in the same table as the td or th element.

http://developers.whatwg.org/tabular-data.html[4/16/2014 9:28:55 PM]

4.9 Tabular data HTML: The Living Standard - Edition for Web Developers

A th element with ID id is
said to be directly targeted by all td and th elements in the
same table that have headers attributes whose values include as one of their tokens
the ID id. A th element A is said to be targeted by a th or td element
B if either A is directly targeted by B or if there exists an element C that is itself
targeted by the element B and A is directly
targeted by C. A th element must not be targeted by itself. The td and th elements implement interfaces that inherit from the HTMLTableCellElement interface: cell . cellIndex Returns the position of the cell in the row's cells list.
This does not necessarily correspond to the x-position of the cell in the
table, since earlier cells might cover multiple rows or columns. Returns 1 if the element isn't in a row.

Table sorting model


The sortable attribute on
table elements is a boolean attribute. When present, it indicates that
the user agent is to allow the user to sort the table . To make a column sortable in a table with a thead , the column needs
to have th element that does not span multiple
columns in a thead above any rows that it is to sort. To make a column sortable in a table without a thead , the column
needs to have th element that does not span multiple
columns in the first tr element of the table , where that
tr element is not in a tfoot . When the user selects a column by which to sort, the user agent sets the th element's sorted attribute. This attribute can also
be set manually, to indicate that the table should be automatically sorted, even when scripts modify the page on when the page is loaded. The sorted attribute, if specified, must have a value that
is a set of spaceseparated tokens consisting of optionally a token whose value is an
ASCII case-insensitive match for the string "reversed", and optionally a token

http://developers.whatwg.org/tabular-data.html[4/16/2014 9:28:55 PM]

4.9 Tabular data HTML: The Living Standard - Edition for Web Developers

whose value
is a valid non-negative integer greater than zero, in either order. In other words, ignoring spaces and case, the sorted attribute's value can be empty, "reversed", "1 ", "reversed 1 ", or
"1 reversed", where "1" is any number equal to or greater than 1. While one or more th elements in the table have a sorted attribute, the user agent will keep the table's data rows
sorted. The value of the attribute controls how the column is used in determining the sort order.
The reversed keyword means that the column sort
direction is reversed, rather than normal, which is the default if the keyword
is omitted. The number, if present, indicates the column key ordinality; if the number
is omitted, the column is the primary key, as if the value 1 had been specified. Thus, sorted="1" indicates the table's primary key, sorted="2" its secondary key, and so forth. A sorting-capable th element is a th element that matches
all the following conditions simultaneously:

It corresponds to a cell whose width is 1.


(Specifically, a header cell, since this
is a th element.)

There is no cell that corresponds to another


sorting-capable th element that
covers slots in the same column but on a higher (earlier) row.

If the cell's table has


a row group corresponding to a thead
element, the cell is
in a row
group that corresponds to the first thead element of the cell's table. Otherwise: the cell is not in a row group corresponding to a tfoot element, and
the cell is in the first row
of the table. In other words, each column can have one
sorting-capable th element; this will be the highest th in
a thead that spans no other columns, or, if there is no thead , the
th in the first row (that is not in a tfoot), assuming it spans no
columns. The sorting-capable th elements of the table element table are the sortingcapable
th elements whose cell's table is table. A table element table is a sorting-capable
table element if there are one or more sorting-capable th
elements of the table element table.

http://developers.whatwg.org/tabular-data.html[4/16/2014 9:28:55 PM]

4.9 Tabular data HTML: The Living Standard - Edition for Web Developers

A th element is a sorting-enabled th element if it is a


sorting-capable th element and it has a sorted attribute. The sorting-enabled th elements of the table element table are the sortingenabled
th elements whose cell's table is table. A table element table is a sorting-enabled
table element if there are one or more sorting-capable th
elements of the table element table, and at least one of
them is a sorting-enabled th element (i.e. at least one has a sorted attribute). A table element is a table element with a user-agent exposed
sorting interface if it is a sorting-capable table element and has
a sortable attribute specified. A sorting interface th element is a sorting-capable
th element whose cell's table is a table element with a user-agent exposed
sorting interface. Each table element has a currently-sorting flag, which must initially
be false. The sorted attribute must not be specified on
th elements that are not sorting-capable
th elements. The sortable attribute
must not be specified on table elements that are not sorting-capable table elements. A table must not have two th elements whose sorted attribute have the same column key
ordinality. th . sort() Act as if the user had indicated that this was to be the new primary sort column. The table won't actually be sorted until the script terminates. table . stopSorting() Removes all the sorted attributes that are causing the
table to automatically sort its contents, if any.

Examples
The following shows how might one mark up the bottom part of table 45 of the Smithsonian
physical tables, Volume 71:
http://developers.whatwg.org/tabular-data.html[4/16/2014 9:28:55 PM]

4.9 Tabular data HTML: The Living Standard - Edition for Web Developers

<table> <caption>Specification values: <b>Steel</b>, <b>Castings</b>, Ann. A.S.T.M. A27-16, Class B;* P max. 0.06; S max. 0.05. </caption> <thead> <tr> <th rowspan=2>Grade.</th> <th rowspan=2>Yield Point.</th> <th colspan=2>Ultimate tensile strength</th> <th rowspan=2>Per cent elong. 50.8mm or 2 in.</th> <th rowspan=2>Per cent reduct. area.</th> </tr> <tr> <th>kg/mm<sup>2</sup></th> <th>lb/in<sup>2</sup></th> </tr> </thead> <tbody> <tr> <td>Hard</td> <td>0.45 ultimate</td> <td>56.2</td> <td>80,000</td> <td>15</td> <td>20</td> </tr> <tr> <td>Medium</td> <td>0.45 ultimate</td> <td>49.2</td> <td>70,000</td> <td>18</td> <td>25</td> </tr> <tr> <td>Soft</td> <td>0.45 ultimate</td> <td>42.2</td>

http://developers.whatwg.org/tabular-data.html[4/16/2014 9:28:55 PM]

4.9 Tabular data HTML: The Living Standard - Edition for Web Developers

<td>60,000</td> <td>22</td> <td>30</td> </tr> </tbody> </table> This table could look like this: Specification values: Steel, Castings,
Ann. A.S.T.M. A27-16, Class B;* P max. 0.06; S max. 0.05. Grade. Yield Point. Ultimate tensile strength kg/mm2 lb/in2 Hard 0.45 ultimate Medium 0.45 ultimate Soft 0.45 ultimate The following shows how one might mark up the gross margin table on page 46 of Apple, Inc's
10-K filing for fiscal year 2008: <table> <thead> <tr> <th> <th>2008 <th>2007 <th>2006 <tbody> <tr> <th>Net sales <td>$ 32,479 <td>$ 24,006 <td>$ 19,315 <tr> <th>Cost of sales <td> 21,334 42.2 60,000 22 30 49.2 70,000 18 25 56.2 80,000 Per cent elong. Per cent 50.8mm or2in. 15 reduct. area. 20

http://developers.whatwg.org/tabular-data.html[4/16/2014 9:28:55 PM]

4.9 Tabular data HTML: The Living Standard - Edition for Web Developers

<td> <td> <tbody> <tr>

15,852 13,717

<th>Gross margin <td>$ 11,145 <td>$ <td>$ <tfoot> <tr> <th>Gross margin percentage <td>34.3% <td>34.0% <td>29.0% </table> This table could look like this: 2008 Net sales Cost of sales Gross margin $ 32,479 21,334 $ 11,145 2007 $ 24,006 15,852 $ 8,154 34.0% 2006 $ 19,315 13,717 $ 5,598 29.0% 8,154 5,598

Gross margin percentage 34.3%

The following shows how one might mark up the operating expenses table from lower on the same
page of that document: <table> <colgroup> <col> <colgroup> <col> <col> <col> <thead> <tr> <th> <th>2008 <th>2007 <th>2006 <tbody> <tr> <th scope=rowgroup> Research and development <td> $ 1,109 <td> $ 782 <td> $ 712 <tr> <th scope=row> Percentage of net sales <td> 3.4% <td> 3.3% <td> 3.7% <tbody> <tr> <th scope=rowgroup> Selling, general, and

http://developers.whatwg.org/tabular-data.html[4/16/2014 9:28:55 PM]

4.9 Tabular data HTML: The Living Standard - Edition for Web Developers

administrative <td> $ 3,761 <td> $ 2,963 <td> $ 2,433 <tr> <th scope=row> Percentage of net sales <td> 11.6% <td> 12.3% <td> 12.6% </table> This table could look like this: 2008 Research and development $ 1,109 Percentage of net sales Selling, general, and administrative Percentage of net sales 3.4% $ 3,761 11.6% 3.3% $ 2,963 12.3% 3.7% $ 2,433 12.6% 2007 $ 782 2006 $ 712

Up next

4.10 Forms

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/tabular-data.html[4/16/2014 9:28:55 PM]

4.10 Forms HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
Forms
Introduction
Writing a form's user interface
Implementing the server-side processing for a form
Configuring a form to communicate with a server
Client-side form validation
Enabling client-side automatic filling of form controls
Improving the user experience on mobile devices
The difference between the field type, the autofill field name, and the input modality
Date, time, and number formats
Categories
The form element
The label element

Forms

Introduction
A form is a component of a Web page that has form controls, such as text fields, buttons,
checkboxes, range controls, or color pickers. A user can interact with such a form, providing data
that can then be sent to the server for further processing (e.g. returning the results of a search
or calculation). No client-side scripting is needed in many cases, though an API is available so
that scripts can augment the user experience or use forms for purposes other than submitting data
to a server. Writing a form consists of several steps, which can be performed in any order:

http://developers.whatwg.org/forms.html[4/16/2014 9:29:10 PM]

4.10 Forms HTML: The Living Standard - Edition for Web Developers

writing the user


interface, implementing the server-side processing, and configuring the user interface to
communicate with the server.

Writing a form's user interface


For the purposes of this brief introduction, we will create a pizza ordering form. Any form starts with a form element, inside which are placed the controls. Most
controls are represented by the input element, which by default provides a one-line
text field. To label a control, the label element is used; the label text and the
control itself go inside the label element. Each part of a form is considered a
paragraph, and is typically separated from other parts using p elements.
Putting this together, here is how one might ask for the customer's name: <form> <p><label>Customer name: <input></label></p> </form> To let the user select the size of the pizza, we can use a set of radio buttons. Radio buttons
also use the input element, this time with a type attribute with the value radio . To make the radio buttons work as a group, they are given a common name using the name attribute. To group a batch
of controls together, such as, in this case, the radio buttons, one can use the
fieldset element. The title of such a group of controls is given by the first element
in the fieldset, which has to be a legend element. <form> <p><label>Customer name: <input></label></p> <fieldset> <legend> Pizza Size </legend> <p><label> <input type=radio name=size> Small </label></p> <p><label> <input type=radio name=size> Medium </label></p> <p><label> <input type=radio name=size> Large </label></p> </fieldset> </form> Changes from the previous step are highlighted.

http://developers.whatwg.org/forms.html[4/16/2014 9:29:10 PM]

4.10 Forms HTML: The Living Standard - Edition for Web Developers

To pick toppings, we can use checkboxes. These use the input element with a type attribute with the value checkbox: <form> <p><label>Customer name: <input></label></p> <fieldset> <legend> Pizza Size </legend> <p><label> <input type=radio name=size> Small </label></p> <p><label> <input type=radio name=size> Medium </label></p> <p><label> <input type=radio name=size> Large </label></p> </fieldset> <fieldset> <legend> Pizza Toppings </legend> <p><label> <input type=checkbox> Bacon </label></p> <p><label> <input type=checkbox> Extra Cheese </label></p> <p><label> <input type=checkbox> Onion </label></p> <p><label> <input type=checkbox> Mushroom </label></p> </fieldset> </form> The pizzeria for which this form is being written is always making mistakes, so it needs a way
to contact the customer. For this purpose, we can use form controls specifically for telephone
numbers (input elements with their type attribute set to tel) and e-mail addresses
( input elements with their type attribute set to
email): <form> <p><label>Customer name: <input></label></p> <p><label>Telephone: <input type=tel></label></p> <p><label>E-mail address: <input type=email></label></p> <fieldset> <legend> Pizza Size </legend> <p><label> <input type=radio name=size> Small </label></p> <p><label> <input type=radio name=size> Medium </label></p> <p><label> <input type=radio name=size> Large </label></p> </fieldset> <fieldset> <legend> Pizza Toppings </legend> <p><label> <input type=checkbox> Bacon </label></p> <p><label> <input type=checkbox> Extra Cheese </label></p> <p><label> <input type=checkbox> Onion </label></p>

http://developers.whatwg.org/forms.html[4/16/2014 9:29:10 PM]

4.10 Forms HTML: The Living Standard - Edition for Web Developers

<p><label> <input type=checkbox> Mushroom </label></p> </fieldset> </form> We can use an input element with its type
attribute set to time to ask for a delivery time. Many
of these form controls have attributes to control exactly what values can be specified; in this
case, three attributes of particular interest are min, max , and step. These set the
minimum time, the maximum time, and the interval between allowed values (in seconds). This
pizzeria only delivers between 11am and 9pm, and doesn't promise anything better than 15 minute
increments, which we can mark up as follows: <form> <p><label>Customer name: <input></label></p> <p><label>Telephone: <input type=tel></label></p> <p><label>E-mail address: <input type=email></label></p> <fieldset> <legend> Pizza Size </legend> <p><label> <input type=radio name=size> Small </label></p> <p><label> <input type=radio name=size> Medium </label></p> <p><label> <input type=radio name=size> Large </label></p> </fieldset> <fieldset> <legend> Pizza Toppings </legend> <p><label> <input type=checkbox> Bacon </label></p> <p><label> <input type=checkbox> Extra Cheese </label></p> <p><label> <input type=checkbox> Onion </label></p> <p><label> <input type=checkbox> Mushroom </label></p> </fieldset> <p><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900"></label></p> </form> The textarea element can be used to provide a free-form text field. In this instance, we are going to use it to provide a space for the customer to give delivery
instructions: <form> <p><label>Customer name: <input></label></p> <p><label>Telephone: <input type=tel></label></p> <p><label>E-mail address: <input type=email></label></p>

http://developers.whatwg.org/forms.html[4/16/2014 9:29:10 PM]

4.10 Forms HTML: The Living Standard - Edition for Web Developers

<fieldset> <legend> Pizza Size </legend> <p><label> <input type=radio name=size> Small </label></p> <p><label> <input type=radio name=size> Medium </label></p> <p><label> <input type=radio name=size> Large </label></p> </fieldset> <fieldset> <legend> Pizza Toppings </legend> <p><label> <input type=checkbox> Bacon </label></p> <p><label> <input type=checkbox> Extra Cheese </label></p> <p><label> <input type=checkbox> Onion </label></p> <p><label> <input type=checkbox> Mushroom </label></p> </fieldset> <p><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900"></label></p> <p><label>Delivery instructions: <textarea></textarea> </label></p> </form> Finally, to make the form submittable we use the button element: <form> <p><label>Customer name: <input></label></p> <p><label>Telephone: <input type=tel></label></p> <p><label>E-mail address: <input type=email></label></p> <fieldset> <legend> Pizza Size </legend> <p><label> <input type=radio name=size> Small </label></p> <p><label> <input type=radio name=size> Medium </label></p> <p><label> <input type=radio name=size> Large </label></p> </fieldset> <fieldset> <legend> Pizza Toppings </legend> <p><label> <input type=checkbox> Bacon </label></p> <p><label> <input type=checkbox> Extra Cheese </label></p> <p><label> <input type=checkbox> Onion </label></p> <p><label> <input type=checkbox> Mushroom </label></p> </fieldset> <p><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900"></label></p> <p><label>Delivery instructions: <textarea></textarea>
http://developers.whatwg.org/forms.html[4/16/2014 9:29:10 PM]

4.10 Forms HTML: The Living Standard - Edition for Web Developers

</label></p> <p><button>Submit order</button></p> </form>

Implementing the server-side processing for a form


The exact details for writing a server-side processor are out of scope for this specification.
For the purposes of this introduction, we will assume that the script at https://pizza.example.com/order.cgi is configured to accept submissions using the
application/x-www-form-urlencoded format, expecting the following parameters sent in an HTTP POST body: custname Customer's name custtel Customer's telephone number custemail Customer's e-mail address size The pizza size, either small , medium , or large topping A topping, specified once for each selected topping, with the allowed values being bacon , cheese , onion , and mushroom delivery The requested delivery time comments The delivery instructions

Configuring a form to communicate with a server


Form submissions are exposed to servers in a variety of ways, most commonly as HTTP GET or POST
requests. To specify the exact method used, the method
attribute is specified on the form element. This doesn't specify how the form data is
encoded, though; to specify that, you use the enctype attribute. You also have to specify the URL of the service that will handle the

http://developers.whatwg.org/forms.html[4/16/2014 9:29:10 PM]

4.10 Forms HTML: The Living Standard - Edition for Web Developers

submitted data, using the action attribute. For each form control you want submitted, you then have to give a name that will be used to
refer to the data in the submission. We already specified the name for the group of radio buttons;
the same attribute (name ) also specifies the submission name.
Radio buttons can be distinguished from each other in the submission by giving them different
values, using the value attribute. Multiple controls can have the same name; for example, here we give all the checkboxes the same
name, and the server distinguishes which checkbox was checked by seeing which values are submitted
with that name like the radio buttons, they are also given unique values with the value attribute. Given the settings in the previous section, this all becomes: <form method="post" enctype="application/x-www-form-urlencoded" action="https://pizza.example.com/order.cgi"> <p><label>Customer name: <input name="custname"></label></p> <p><label>Telephone: <input type=tel name="custtel"></label> </p> <p><label>E-mail address: <input type=email name="custemail"></label></p> <fieldset> <legend> Pizza Size </legend> <p><label> <input type=radio name=size value="small"> Small </label></p> <p><label> <input type=radio name=size value="medium"> Medium </label></p> <p><label> <input type=radio name=size value="large"> Large </label></p> </fieldset> <fieldset> <legend> Pizza Toppings </legend> <p><label> <input type=checkbox name="topping" value="bacon"> Bacon </label></p> <p><label> <input type=checkbox name="topping" value="cheese"> Extra Cheese </label></p> <p><label> <input type=checkbox name="topping" value="onion"> Onion </label></p> <p><label> <input type=checkbox name="topping" value="mushroom"> Mushroom </label></p>
http://developers.whatwg.org/forms.html[4/16/2014 9:29:10 PM]

4.10 Forms HTML: The Living Standard - Edition for Web Developers

</fieldset> <p><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900" name="delivery"></label> </p> <p><label>Delivery instructions: <textarea name="comments"> </textarea></label></p> <p><button>Submit order</button></p> </form> There is no particular significance to the way some of the attributes have their
values quoted and others don't. The HTML syntax allows a variety of equally valid ways to specify
attributes, as discussed in the syntax section. For example, if the customer entered "Denise Lawrence" as their name, "555321-8642" as their
telephone number, did not specify an e-mail address, asked for a medium-sized pizza, selected the
Extra Cheese and Mushroom toppings, entered a delivery time of 7pm, and left the delivery
instructions text field blank, the user agent would submit the following to the online Web
service: custname=Denise+Lawrence&custtel=555-3218624&custemail=&size=medium&topping=cheese&topping=mushroom&d elivery=19%3A00&comments=

Client-side form validation


Forms can be annotated in such a way that the user agent will check the user's input before the
form is submitted. The server still has to verify the input is valid (since hostile users can
easily bypass the form validation), but it allows the user to avoid the wait incurred by having
the server be the sole checker of the user's input. The simplest annotation is the required attribute,
which can be specified on input elements to indicate that the form is not to be
submitted until a value is given. By adding this attribute to the customer name, pizza size, and
delivery time fields, we allow the user agent to notify the user when the user submits the form
without filling in those fields: <form method="post" enctype="application/x-www-form-urlencoded" action="https://pizza.example.com/order.cgi">

http://developers.whatwg.org/forms.html[4/16/2014 9:29:10 PM]

4.10 Forms HTML: The Living Standard - Edition for Web Developers

<p><label>Customer name: <input name="custname" required> </label></p> <p><label>Telephone: <input type=tel name="custtel"></label> </p> <p><label>E-mail address: <input type=email name="custemail"></label></p> <fieldset> <legend> Pizza Size </legend> <p><label> <input type=radio name=size required value="small"> Small </label></p> <p><label> <input type=radio name=size required value="medium"> Medium </label></p> <p><label> <input type=radio name=size required value="large"> Large </label></p> </fieldset> <fieldset> <legend> Pizza Toppings </legend> <p><label> <input type=checkbox name="topping" value="bacon"> Bacon </label></p> <p><label> <input type=checkbox name="topping" value="cheese"> Extra Cheese </label></p> <p><label> <input type=checkbox name="topping" value="onion"> Onion </label></p> <p><label> <input type=checkbox name="topping" value="mushroom"> Mushroom </label></p> </fieldset> <p><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900" name="delivery" required> </label></p> <p><label>Delivery instructions: <textarea name="comments"> </textarea></label></p> <p><button>Submit order</button></p> </form> It is also possible to limit the length of the input, using the maxlength attribute. By adding this to the textarea
element, we can limit users to 1000 characters, preventing them from writing huge essays to the
busy delivery drivers instead of staying focused and to the point: <form method="post" enctype="application/x-www-form-urlencoded"
http://developers.whatwg.org/forms.html[4/16/2014 9:29:10 PM]

4.10 Forms HTML: The Living Standard - Edition for Web Developers

action="https://pizza.example.com/order.cgi"> <p><label>Customer name: <input name="custname" required> </label></p> <p><label>Telephone: <input type=tel name="custtel"></label> </p> <p><label>E-mail address: <input type=email name="custemail"></label></p> <fieldset> <legend> Pizza Size </legend> <p><label> <input type=radio name=size required value="small"> Small </label></p> <p><label> <input type=radio name=size required value="medium"> Medium </label></p> <p><label> <input type=radio name=size required value="large"> Large </label></p> </fieldset> <fieldset> <legend> Pizza Toppings </legend> <p><label> <input type=checkbox name="topping" value="bacon"> Bacon </label></p> <p><label> <input type=checkbox name="topping" value="cheese"> Extra Cheese </label></p> <p><label> <input type=checkbox name="topping" value="onion"> Onion </label></p> <p><label> <input type=checkbox name="topping" value="mushroom"> Mushroom </label></p> </fieldset> <p><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900" name="delivery" required> </label></p> <p><label>Delivery instructions: <textarea name="comments" maxlength=1000></textarea></label></p> <p><button>Submit order</button></p> </form> When a form is submitted, invalid events are
fired at each form control that is invalid, and then at the form element itself. This
can be useful for displaying a summary of the problems with the form, since typically the browser
itself will only report one problem at a time.

http://developers.whatwg.org/forms.html[4/16/2014 9:29:10 PM]

4.10 Forms HTML: The Living Standard - Edition for Web Developers

Enabling client-side automatic filling of form controls


Some browsers attempt to aid the user by automatically filling form controls rather than having
the user reenter their information each time. For example, a field asking for the user's telephone
number can be automatically filled with the user's phone number. To help the user agent with this, we can tell it what the field is using the autocomplete attribute. In the case of this form, we have
three fields that can be usefully annotated in this way: the information about who the pizza is to
be delivered to. Adding this information looks like this: <form method="post" enctype="application/x-www-form-urlencoded" action="https://pizza.example.com/order.cgi"> <p><label>Customer name: <input name="custname" required autocomplete="shipping name"></label></p> <p><label>Telephone: <input type=tel name="custtel" autocomplete="shipping tel"></label></p> <p><label>E-mail address: <input type=email name="custemail" autocomplete="shipping email"></label></p> <fieldset> <legend> Pizza Size </legend> <p><label> <input type=radio name=size required value="small"> Small </label></p> <p><label> <input type=radio name=size required value="medium"> Medium </label></p> <p><label> <input type=radio name=size required value="large"> Large </label></p> </fieldset> <fieldset> <legend> Pizza Toppings </legend> <p><label> <input type=checkbox name="topping" value="bacon"> Bacon </label></p> <p><label> <input type=checkbox name="topping" value="cheese"> Extra Cheese </label></p> <p><label> <input type=checkbox name="topping" value="onion"> Onion </label></p> <p><label> <input type=checkbox name="topping" value="mushroom"> Mushroom </label></p>

http://developers.whatwg.org/forms.html[4/16/2014 9:29:10 PM]

4.10 Forms HTML: The Living Standard - Edition for Web Developers

</fieldset> <p><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900" name="delivery" required> </label></p> <p><label>Delivery instructions: <textarea name="comments" maxlength=1000></textarea></label></p> <p><button>Submit order</button></p> </form>

Improving the user experience on mobile devices


Some devices, in particular those with on-screen keyboards and those in locales with languages
with many characters (e.g. Japanese), can provide the user with multiple input modalities. For
example, when typing in a credit card number the user may wish to only see keys for digits 0-9,
while when typing in their name they may wish to see a form field that by default capitalises each
word. Using the inputmode attribute we can select appropriate
input modalities: <form method="post" enctype="application/x-www-form-urlencoded" action="https://pizza.example.com/order.cgi"> <p><label>Customer name: <input name="custname" required autocomplete="shipping name" inputmode="latin-name"></label> </p> <p><label>Telephone: <input type=tel name="custtel" autocomplete="shipping tel"></label></p> <p><label>E-mail address: <input type=email name="custemail" autocomplete="shipping email"></label></p> <fieldset> <legend> Pizza Size </legend> <p><label> <input type=radio name=size required value="small"> Small </label></p> <p><label> <input type=radio name=size required value="medium"> Medium </label></p> <p><label> <input type=radio name=size required value="large"> Large </label></p> </fieldset> <fieldset>
http://developers.whatwg.org/forms.html[4/16/2014 9:29:10 PM]

4.10 Forms HTML: The Living Standard - Edition for Web Developers

<legend> Pizza Toppings </legend> <p><label> <input type=checkbox name="topping" value="bacon"> Bacon </label></p> <p><label> <input type=checkbox name="topping" value="cheese"> Extra Cheese </label></p> <p><label> <input type=checkbox name="topping" value="onion"> Onion </label></p> <p><label> <input type=checkbox name="topping" value="mushroom"> Mushroom </label></p> </fieldset> <p><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900" name="delivery" required> </label></p> <p><label>Delivery instructions: <textarea name="comments" maxlength=1000 inputmode="latin-prose"></textarea></label> </p> <p><button>Submit order</button></p> </form>

The difference between the field type, the autofill field name, and the input modality
The type, autocomplete, and inputmode attributes can seem confusingly similar. For instance,
in all three cases, the string "email " is a valid value. This section
attempts to illustrate the difference between the three attributes and provides advice suggesting
how to use them. The type attribute on input elements decides
what kind of control the user agent will use to expose the field. Choosing between different
values of this attribute is the same choice as choosing whether to use an input
element, a textarea element, a select element, a keygen
element, etc. The autocomplete attribute, in contrast, describes
what the value that the user will enter actually represents. Choosing between different values of
this attribute is the same choice as choosing what the label for the element will be. First, consider telephone numbers. If a page is asking for a telephone number from the user,
the right form control to use is <input type=tel>.
However, which autocomplete value to use depends on
which phone number the page is asking for, whether they expect a telephone number in the
international

http://developers.whatwg.org/forms.html[4/16/2014 9:29:10 PM]

4.10 Forms HTML: The Living Standard - Edition for Web Developers

format or just the local format, and so forth. For example, a page that forms part of a checkout process on an e-commerce site for a customer
buying a gift to be shipped to a friend might need both the buyer's telephone number (in case of
payment issues) and the friend's telephone number (in case of delivery issues). If the site
expects international phone numbers (with the country code prefix), this could thus look like
this: <p><label>Your phone number: <input type=tel name=custtel autocomplete="billing tel"></label> <p><label>Recipient's phone number: <input type=tel name=shiptel autocomplete="shipping tel"></label> <p>Please enter complete phone numbers including the country code prefix, as in "+1 555 123 4567". But if the site only supports British customers and recipients, it might instead look like this
(notice the use of tel-national rather than
tel): <p><label>Your phone number: <input type=tel name=custtel autocomplete="billing tel-national"></label> <p><label>Recipient's phone number: <input type=tel name=shiptel autocomplete="shipping tel-national"></label> <p>Please enter complete UK phone numbers, as in "(01632) 960 123". Now, consider a person's preferred languages. The right autocomplete value is language. However, there could be a number of
different form controls used for the purpose: a free text field ( <input type=text>), a drop-down list (<select>), radio buttons (<input
type=radio> ), etc. It only depends on what kind of interface is desired. The inputmode decides what kind of input modality (e.g.
keyboard) to use, when the control is a free-form text field. Consider names. If a page just wants one name from the user, then the relevant control is <input type=text> . If the page is asking for the user's full name, then the relevant autocomplete value is name. But if the user is Japanese, and the page is asking
for the user's Japanese name and the user's romanized name, then it would be helpful to the user
if the first field defaulted to a Japanese input modality, while the second defaulted to a Latin input modality (ideally with automatic capitalization of each word). This is where the inputmode attribute can help:

http://developers.whatwg.org/forms.html[4/16/2014 9:29:10 PM]

4.10 Forms HTML: The Living Standard - Edition for Web Developers

<p><label>Japanese name: <input name="j" type="text" autocomplete="section-jp name" inputmode="kana"></label> <label>Romanized name: <input name="e" type="text" autocomplete="section-en name" inputmode="latin-name"> </label> In this example, the "section-* " keywords in
the autocomplete attributes' values tell the user agent
that the two fields expect different names. Without them, the user agent could
automatically fill the second field with the value given in the first field when the user gave a
value to the first field. The "-jp" and "-en" parts of the
keywords are opaque to the user agent; the user agent cannot guess, from those, that the two names
are expected to be in Japanese and English respectively.

Date, time, and number formats


In this pizza delivery example, the times are specified in the format "HH:MM": two digits for
the hour, in 24-hour format, and two digits for the time. (Seconds could also be specified, though
they are not necessary in this example.) In some locales, however, times are often expressed differently when presented to users. For
example, in the United States, it is still common to use the 12-hour clock with an am/pm
indicator, as in "2pm". In France, it is common to separate the hours from the minutes using an
"h" character, as in "14h00". Similar issues exist with dates, with the added complication that even the order of the
components is not always consistent for example, in Cyprus the first of February 2003
would typically be written "1/2/03", while that same date in Japan would typically be written as
"20030201" and even with numbers, where locales differ, for
example, in what punctuation is used as the decimal separator and the thousands separator. It is therefore important to distinguish the time, date, and number formats used in HTML and in
form submissions, which are always the formats defined in this specification (and based on the
well-established ISO 8601 standard for computer-readable date and time formats), from the time,
date, and number formats presented to the user by the browser and accepted as input from the

http://developers.whatwg.org/forms.html[4/16/2014 9:29:10 PM]

4.10 Forms HTML: The Living Standard - Edition for Web Developers

user
by the browser. The format used "on the wire", i.e. in HTML markup and in form submissions, is intended to be
computer-readable and consistent irrespective of the user's locale. Dates, for instance, are
always written in the format "YYYY-MM-DD", as in "2003-02-01". Users are not expected to ever see
this format. The time, date, or number given by the page in the wire format is then translated to the user's
preferred presentation (based on user preferences or on the locale of the page itself), before
being displayed to the user. Similarly, after the user inputs a time, date, or number using their
preferred format, the user agent converts it back to the wire format before putting it in the DOM
or submitting it. This allows scripts in pages and on servers to process times, dates, and numbers in a
consistent manner without needing to support dozens of different formats, while still supporting
the users' needs.

Categories
Mostly for historical reasons, elements in this section fall into several overlapping (but
subtly different) categories in addition to the usual ones like flow content,
phrasing content, and interactive content. A number of the elements are form-associated
elements, which means they can have a form owner.

button fieldset input keygen label object output select textarea img
The form-associated elements fall into several
subcategories: Listed elements

http://developers.whatwg.org/forms.html[4/16/2014 9:29:10 PM]

4.10 Forms HTML: The Living Standard - Edition for Web Developers

Denotes elements that are listed in the form.elements and fieldset.elements APIs.

button fieldset input keygen object output select textarea


Submittable elements Denotes elements that can be used for constructing the
form data set when a form element is submitted.

button input keygen object select textarea


Some submittable elements can be, depending on their
attributes, buttons. The prose below defines when an element
is a button. Some buttons are specifically submit
buttons. Resettable elements Denotes elements that can be affected when a form element is reset.

input keygen output select textarea


Reassociateable elements Denotes elements that have a form content attribute, and a
matching form IDL attribute, that allow authors to specify an
explicit form owner.

button fieldset
http://developers.whatwg.org/forms.html[4/16/2014 9:29:10 PM]

4.10 Forms HTML: The Living Standard - Edition for Web Developers

input keygen label object output select textarea


Some elements, not all of them form-associated,
are categorized as labelable elements. These are elements that
can be associated with a label element.

button input (if the type attribute is not in the Hidden state) keygen meter output progress select textarea

The form element


Categories: Flow content. Palpable content. Contexts in which this element can be used: Where flow content is expected. Content model: Flow content, but with no form element descendants. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes accept-charset Character encodings to use for form submission action URL to use for form submission Default setting for autofill feature for controls in the form
http://developers.whatwg.org/forms.html[4/16/2014 9:29:10 PM]

4.10 Forms HTML: The Living Standard - Edition for Web Developers

autocomplete enctype Form data set encoding type to use for form submission method HTTP method to use for form submission name Name of form to use in the document.forms API novalidate Bypass form control validation for form submission target Browsing context for form submission DOM interface: The form element represents a collection of form-associated elements, some of which can represent
editable values that can be submitted to a server for processing. The accept-charset attribute gives the
character encodings that are to be used for the submission. If specified, the value must be an
ordered set of unique space-separated tokens that are ASCII
case-insensitive, and each token must be an ASCII case-insensitive match for
one of the labels of an ASCII-compatible character
encoding. The name attribute represents the
form's name within the forms collection. The
value must not be the empty string, and the value must be unique amongst the form
elements in the forms collection that it is in, if
any. The autocomplete attribute is an
enumerated attribute. The attribute has two states. The on keyword maps to the on state, and the off keyword maps to the off state. The attribute may also be omitted. The
missing value default is the on state.
The off state indicates that by default,
form controls in the form will have their autofill field name set to "off"; the on state indicates that by default, form controls
in the form will have their autofill field name set to "on ". The action, enctype,
method , novalidate,
and target attributes are attributes for form
submission. form . elements Returns an HTMLCollection of the form controls in the form (excluding image
buttons for historical reasons). form . length Returns the number of form controls in the form (excluding image buttons for

http://developers.whatwg.org/forms.html[4/16/2014 9:29:10 PM]

4.10 Forms HTML: The Living Standard - Edition for Web Developers

historical
reasons). form[index] Returns the indexth element in the form (excluding image buttons for historical reasons). form[name] Returns the form control (or, if there are several, a RadioNodeList of the form
controls) in the form with the given ID or name (excluding image buttons for historical reasons); or, if there
are none, returns the img element with the given ID. Once an element has been referenced using a particular name, that name will continue being
available as a way to reference that element in this method, even if the element's actual ID or name changes, for as long as
the element remains in the Document. If there are multiple matching items, then a RadioNodeList object containing all
those elements is returned. form . submit() Submits the form. form . reset () Resets the form. form . checkValidity () Returns true if the form's controls are all valid; otherwise, returns false. form . reportValidity() Returns true if the form's controls are all valid; otherwise, returns false and informs the user. This example shows two search forms: <form action="http://www.google.com/search" method="get"> <label>Google: <input type="search" name="q"></label> <input type="submit" value="Search..."> </form> <form action="http://www.bing.com/search" method="get"> <label>Bing: <input type="search" name="q"></label> <input type="submit" value="Search..."> </form>

http://developers.whatwg.org/forms.html[4/16/2014 9:29:10 PM]

4.10 Forms HTML: The Living Standard - Edition for Web Developers

The label element


Categories: Flow content. Phrasing content. Interactive content. Reassociateable form-associated element. Palpable content. Contexts in which this element can be used: Where phrasing content is expected. Content model: Phrasing content, but with no descendant labelable elements unless it is the element's labeled control, and no descendant label elements. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes form Associates the control with a form element for Associate the label with form control DOM interface: The label element represents a caption in a user interface. The
caption can be associated with a specific form control, either using the for attribute, or by putting the form control inside the
label element itself. The for attribute may be specified to indicate a
form control with which the caption is to be associated. If the attribute is specified, the
attribute's value must be the ID of a labelable element in the same Document as the
label element. The form attribute is used to explicitly associate the
label element with its form owner. The following example shows three form controls each with a label, two of which have small
text showing the right format for users to use.

http://developers.whatwg.org/forms.html[4/16/2014 9:29:10 PM]

4.10 Forms HTML: The Living Standard - Edition for Web Developers

<p><label>Full name: <input name=fn> <small>Format: First Last</small></label></p> <p><label>Age: <input name=age type=number min=0></label></p> <p><label>Post code: <input name=pc> <small>Format: AB12 3CD</small></label></p>

label . control Returns the form control that is associated with this element. control . labels Returns a NodeList of all the label elements that the form control
is associated with.

Up next

4.10.5 The input element

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/forms.html[4/16/2014 9:29:10 PM]

4.11 Interactive elements HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
Interactive elements
The details element
The summary element
The menu element
The menuitem element
Context menus
Declaring a context menu
Event definitions

Interactive elements

The details element


Categories: Flow content. Sectioning root. Interactive content. Palpable content. Contexts in which this element can be used: Where flow content is expected. Content model: One summary element followed by flow content. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes

http://developers.whatwg.org/interactive-elements.html[4/16/2014 9:29:16 PM]

4.11 Interactive elements HTML: The Living Standard - Edition for Web Developers

open Whether the details are visible DOM interface: The details element represents a disclosure widget from which the
user can obtain additional information or controls. The details element is not appropriate for footnotes. Please see the section on footnotes for details on how to mark up footnotes. The summary element child of the element, if any,
represents the summary or legend of the details. The rest of the element's contents represents the additional information or controls. The open content attribute is a boolean
attribute. If present, it indicates that both the summary and the additional information is
to be shown to the user. If the attribute is absent, only the summary is to be shown. The following example shows the details element being used to hide technical
details in a progress report. <section class="progress window"> <h1>Copying "Really Achieving Your Childhood Dreams"</h1> <details> <summary>Copying... <progress max="375505392" value="97543282"></progress> 25%</summary> <dl> <dt>Transfer rate:</dt> <dd>452KB/s</dd> <dt>Local filename:</dt> <dd>/home/rpausch/raycd.m4v</dd> <dt>Remote filename:</dt> <dd>/var/www/lectures/raycd.m4v</dd> <dt>Duration:</dt> <dd>01:16:27</dd> <dt>Color profile:</dt> <dd>SD (6-1-6)</dd> <dt>Dimensions:</dt> <dd>320240</dd> </dl> </details> </section> The following shows how a details element can be used to hide some controls by
default:

http://developers.whatwg.org/interactive-elements.html[4/16/2014 9:29:16 PM]

4.11 Interactive elements HTML: The Living Standard - Edition for Web Developers

<details> <summary><label for=fn>Name & Extension:</label></summary> <p><input type=text id=fn name=fn value="Pillar Magazine.pdf"> <p><label><input type=checkbox name=ext checked> Hide extension</label> </details> One could use this in conjunction with other details in a list to allow the user
to collapse a set of fields down to a small set of headings, with the ability to open each
one.

http://developers.whatwg.org/interactive-elements.html[4/16/2014 9:29:16 PM]

4.11 Interactive elements HTML: The Living Standard - Edition for Web Developers

In these examples, the summary really just summarises what the controls can change, and not
the actual values, which is less than ideal. Because the open attribute is added and removed
automatically as the user interacts with the control, it can be used in CSS to style the element differently based on its state. Here, a stylesheet is used to animate the color of the summary
when the element is opened or closed: <style> details > summary { transition: color 1s; color: black; } details[open] > summary { color: red; } </style>

http://developers.whatwg.org/interactive-elements.html[4/16/2014 9:29:16 PM]

4.11 Interactive elements HTML: The Living Standard - Edition for Web Developers

<details> <summary>Automated Status: Operational</summary> <p>Velocity: 12m/s</p> <p>Direction: North</p> </details>

The summary element


Categories: None. Contexts in which this element can be used: As the first child of a details element. Content model: Phrasing content. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes DOM interface: Uses HTMLElement. The summary element represents a summary, caption, or legend for the
rest of the contents of the summary element's parent details
element.

The menu element


Categories: Flow content. If the element's type attribute is in the toolbar state: Palpable content. Contexts in which this element can be used: Where flow content is expected. If the element's type attribute is in the popup menu state: as the child of a menu element whose type attribute is in the popup menu state. Content model:

http://developers.whatwg.org/interactive-elements.html[4/16/2014 9:29:16 PM]

4.11 Interactive elements HTML: The Living Standard - Edition for Web Developers

If the element's type attribute is in the toolbar state: either zero or more li and script-supporting elements, or, flow content. If the element's type attribute is in the popup menu state: in any order, zero or more menuitem elements, zero or more hr elements, zero or more menu elements whose type attributes are in the popup menu state, and zero or more script-supporting elements. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes type Type of menu label User-visible label DOM interface: The menu element represents a list of commands. The type attribute is an enumerated
attribute indicating the kind of menu being declared. The attribute has two states. The
popup keyword maps to the popup menu state, in which the element is declaring a context menu or the menu for a
menu button. The toolbar keyword maps to the toolbar state, in which the element is declaring a toolbar. The attribute may also be
omitted. The missing value default is the popup menu
state if the parent element is a menu element whose type attribute is in the popup
menu state; otherwise, it is the toolbar state. If a menu element's type attribute is in the
popup menu state, then the element represents
the commands of a popup menu, and the user can only examine and interact with the commands if that
popup menu is activated through some other element, either via the contextmenu attribute or the button element's menu attribute. If a menu element's type attribute is in the
toolbar state, then the element represents a
toolbar consisting of its contents, in the form of either an unordered list of items (represented
by li elements), each of which represents a command that the user can perform or
activate, or, if the element has no li element children, flow content
describing available commands. The label attribute gives the label of the
menu. It is used by user agents to display nested menus in the UI: a context menu containing
another menu

http://developers.whatwg.org/interactive-elements.html[4/16/2014 9:29:16 PM]

4.11 Interactive elements HTML: The Living Standard - Edition for Web Developers

would use the nested menu's label attribute for


the submenu's menu label. The label attribute must only be
specified on menu elements whose parent element is a menu element whose
type attribute is in the popup
menu state. In this example, the menu element is used to describe a toolbar with three menu
buttons on it, each of which has a dropdown menu with a series of options: <menu> <li> <button type=menu value="File" menu="filemenu"> <menu id="filemenu" type="popup"> <menuitem onclick="fnew()" label="New..."> <menuitem onclick="fopen()" label="Open..."> <menuitem onclick="fsave()" label="Save"> <menuitem onclick="fsaveas()" label="Save as..."> </menu> </li> <li> <button type=menu value="Edit" menu="editmenu"> <menu id="editmenu" type="popup"> <menuitem onclick="ecopy()" label="Copy"> <menuitem onclick="ecut()" label="Cut"> <menuitem onclick="epaste()" label="Paste"> </menu> </li> <li> <button type=menu value="Help" menu="helpmenu"> <menu id="helpmenu" type="popup"> <menuitem onclick="location='help.html'" label="Help"> <menuitem onclick="location='about.html'" label="About"> </menu> </li> </menu> In a supporting user agent, this might look like this (assuming the user has just activated the
second button):

http://developers.whatwg.org/interactive-elements.html[4/16/2014 9:29:16 PM]

4.11 Interactive elements HTML: The Living Standard - Edition for Web Developers

The menuitem element


Categories: None. Contexts in which this element can be used: As a child of a menu element whose type attribute is in the popup menu state. Content model: Empty. Tag omission in text/html: No end tag. Content attributes: Global attributes type Type of command label User-visible label icon Icon for the command disabled Whether the form control is disabled checked Whether the command or control is checked radiogroup Name of group of commands to treat as a radio button group default Mark the command as being a default command command Command definition Also, the title attribute has special semantics on this element. Hint describing the command DOM interface: The menuitem element represents a command that the user can invoke from a popup
menu (either a context menu or the menu of a menu button). A menuitem element that uses one or more of the
type,
label ,
icon, disabled,
checked, and
radiogroup
attributes defines a new command.
http://developers.whatwg.org/interactive-elements.html[4/16/2014 9:29:16 PM]

4.11 Interactive elements HTML: The Living Standard - Edition for Web Developers

A menuitem element that uses the command attribute defines a command by reference to another
one. This allows authors to define a command once, and set its state (e.g. whether it is active or
disabled) in one place, and have all references to that command in the user interface change at
the same time. If the command attribute is specified, the element
is in the indirect command mode. If it is not specified, it is in the explicit
command mode. When the element is in the indirect command mode, the element
must not have any of the following attributes specified:
type,
label ,
icon,
disabled,
checked , radiogroup . The type attribute indicates the kind of
command: either a normal command with an associated action, or a state or option that can be
toggled, or a selection of one item from a list of items. The attribute is an enumerated attribute with three keywords and states. The " command" keyword maps to the Command state, the "checkbox" keyword maps to the Checkbox state, and the "radio " keyword maps to the Radio state. The missing value default is the
Command state. The Command state The element represents a normal command with an associated action. The Checkbox state The element represents a state or option that can be toggled. The Radio state The element represents a selection of one item from a list of items. The label attribute gives the name of the
command, as shown to the user. The label attribute must
be specified if the element is in the explicit command mode. If the attribute is
specified, it must have a value that is not the empty string. The icon attribute gives a picture that
represents the command. If the attribute is specified, the attribute's value must contain a
valid non-empty URL potentially surrounded by spaces. The disabled attribute is a
boolean attribute that, if present, indicates that the command is not available in
the current state.

http://developers.whatwg.org/interactive-elements.html[4/16/2014 9:29:16 PM]

4.11 Interactive elements HTML: The Living Standard - Edition for Web Developers

The distinction between disabled and


hidden is subtle. A command would be disabled if, in the same
context, it could be enabled if only certain aspects of the situation were changed. A command
would be marked as hidden if, in that situation, the command will never be enabled. For example,
in the context menu for a water faucet, the command "open" might be disabled if the faucet is
already open, but the command "eat" would be marked hidden since the faucet could never be
eaten. The checked attribute is a boolean
attribute that, if present, indicates that the command is selected. The attribute must be
omitted unless the type attribute is in either the Checkbox state or the Radio state. The radiogroup attribute gives the
name of the group of commands that will be toggled when the command itself is toggled, for
commands whose type attribute has the value "radio ". The scope of the name is the child list of the parent element. The
attribute must be omitted unless the type attribute is in the Radio state. When specified, the
attribute's value must be a non-empty string. If a menuitem element slave has a command attribute, and there is an element in
slave's home subtree whose ID has
a value equal to the value of slave's command attribute, and the first such element in tree
order, hereafter master, itself defines a
command and either is not a menuitem element or does not itself have a command attribute, then the master command of slave is master. A menuitem element with a command
attribute must have a master command. This effectively defines the syntax of the attribute's value as being the ID of another element that defines a command. The title attribute gives a hint describing
the command, which might be shown to the user to help him. The default attribute indicates, if
present, that the command is the one that would have been invoked if the user had directly
activated the menu's subject instead of using the menu. The default attribute is a boolean attribute. In this trivial example, a submit button is given a context menu that has two options, one to
reset the form, and one to submit the form. The submit command is marked as being the default. <form action="dosearch.pl"> <p><label>Enter search terms: <input type="text"
http://developers.whatwg.org/interactive-elements.html[4/16/2014 9:29:16 PM]

4.11 Interactive elements HTML: The Living Standard - Edition for Web Developers

name="terms"></label></p> <p><input type=submit contextmenu=formmenu id="submitbutton"></p> <p hidden><input type=reset id="resetbutton"></p> <menu type=popup id=formmenu> <menuitem command="submitbutton" default> <menuitem command="resetbutton"> </menu> </form> The menuitem element is not rendered except as part of a popup menu. Here is an example of a pop-up menu button with three options that let the user toggle between
left, center, and right alignment. One could imagine such a toolbar as part of a text editor. The
menu also has a separator followed by another menu item labeled "Publish", though that menu item
is disabled. <button type=menu menu=editmenu>Commands...</button> <menu type="popup" id="editmenu"> <menuitem type="radio" radiogroup="alignment" checked="checked" label="Left" icon="icons/alL.png" onclick="setAlign('left')"> <menuitem type="radio" radiogroup="alignment" label="Center" icon="icons/alC.png" onclick="setAlign('center')"> <menuitem type="radio" radiogroup="alignment" label="Right" icon="icons/alR.png" onclick="setAlign('right')"> <hr> <menuitem type="command" disabled label="Publish" icon="icons/pub.png" onclick="publish()"> </menu>

Context menus

http://developers.whatwg.org/interactive-elements.html[4/16/2014 9:29:16 PM]

4.11 Interactive elements HTML: The Living Standard - Edition for Web Developers

Declaring a context menu


The contextmenu attribute gives the element's
context menu. The value must be the ID of a menu
element in the same home subtree whose type
attribute is in the popup menu state. When a user right-clicks on an element with a contextmenu attribute, the user agent will first fire a contextmenu event at the element, and then, if that event is not
canceled, a show event at the menu element. Here is an example of a context menu for an input control: <form name="npc"> <label>Character name: <input name=char type=text contextmenu=namemenu required></label> <menu type=popup id=namemenu> <menuitem label="Pick random name" onclick="document.forms.npc.elements.char.value = getRandomName()"> <menuitem label="Prefill other fields based on name" onclick="prefillFields(document.forms.npc.elements.char.value )"> </menu> </form> This adds two items to the control's context menu, one called "Pick random name", and one
called "Prefill other fields based on name". They invoke scripts that are not shown in the
example above. In this example, an image of cats is given a context menu with four possible commands: <img src="cats.jpeg" alt="Cats" contextmenu=catsmenu> <menu type="popup" id="catsmenu"> <menuitem label="Pet the kittens" onclick="kittens.pet()"> <menuitem label="Cuddle with the kittens" onclick="kittens.cuddle()"> <menu label="Feed the kittens"> <menuitem label="Fish" onclick="kittens.feed(fish)"> <menuitem label="Chicken" onclick="kittens.feed(chicken)"> </menu> </menu>

http://developers.whatwg.org/interactive-elements.html[4/16/2014 9:29:16 PM]

4.11 Interactive elements HTML: The Living Standard - Edition for Web Developers

When a user of a mouse-operated visual Web browser right-clicks on the image, the browser
might pop up a context menu like this:

When the user clicks the disclosure triangle, such a user agent would expand the context menu
in place, to show the browser's own commands:

Event definitions
event . relatedTarget Returns the other event target involved in this event. For example, when a show event fires on a menu element, the other event
target involved in the event would be the element for which the menu is being shown.

http://developers.whatwg.org/interactive-elements.html[4/16/2014 9:29:16 PM]

4.11 Interactive elements HTML: The Living Standard - Edition for Web Developers

Up next

4.11.6 Commands

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/interactive-elements.html[4/16/2014 9:29:16 PM]

4.12 Scripting HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
Scripting
The script element
Scripting languages
Restrictions for contents of script elements
Inline documentation for external scripts
The noscript element
The template element

Scripting
Scripts allow authors to add interactivity to their documents. Authors are encouraged to use declarative alternatives to scripting where possible, as
declarative mechanisms are often more maintainable, and many users disable scripting. For example, instead of using script to show or hide a section to show more details, the
details element could be used. Authors are also encouraged to make their applications degrade gracefully in the absence of
scripting support. For example, if an author provides a link in a table header to dynamically resort the table,
the link could also be made to function without scripts by requesting the sorted table from the
server.

The script element


Categories:

http://developers.whatwg.org/scripting-1.html[4/16/2014 9:29:22 PM]

4.12 Scripting HTML: The Living Standard - Edition for Web Developers

Metadata content. Flow content. Phrasing content. Script-supporting element. Contexts in which this element can be used: Where metadata content is expected. Where phrasing content is expected. Where script-supporting elements are expected. Content model: If there is no src
attribute, depends on the value of the type attribute, but must match
script content restrictions. If there is a src
attribute, the element must be either empty or contain only script documentation that also matches script
content restrictions. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes src Address of the resource type Type of embedded resource charset Character encoding of the external script resource async Execute script asynchronously defer Defer script execution crossorigin How the element handles crossorigin requests DOM interface: The script element allows authors to include dynamic script and data blocks in
their documents. The element does not represent content for the
user. When used to include dynamic scripts, the scripts may either be embedded inline or may be
imported from an external file using the src attribute. If
the language is not that described by "text/javascript ", then the type attribute must be present, as described below. Whatever
language is used, the contents of the script element must conform with the
requirements of that language's specification.

http://developers.whatwg.org/scripting-1.html[4/16/2014 9:29:22 PM]

4.12 Scripting HTML: The Living Standard - Edition for Web Developers

When used to include data blocks (as opposed to scripts), the data must be embedded inline, the
format of the data must be given using the type attribute,
the src attribute must not be specified, and the contents of
the script element must conform to the requirements defined for the format used. The type attribute gives the language of the
script or format of the data. If the attribute is present, its value must be a valid MIME
type. The charset parameter must not be specified. The default, which
is used if the attribute is absent, is "text/javascript". The src attribute, if specified, gives the
address of the external script resource to use. The value of the attribute must be a valid
non-empty URL potentially surrounded by spaces identifying a script resource of the type
given by the type attribute, if the attribute is present, or
of the type "text/javascript", if the attribute is absent. A resource is a
script resource of a given type if that type identifies a scripting language and the resource
conforms with the requirements of that language's specification. The charset attribute gives the character
encoding of the external script resource. The attribute must not be specified if the src attribute is not present. If the attribute is set, its value
must be an ASCII case-insensitive match for one of the labels of an encoding, and must specify the same encoding as
the charset parameter of the Content-Type
metadata of the external file, if any. The async and defer attributes are boolean attributes that indicate how the script should be executed. The defer and async attributes
must not be specified if the src attribute is not
present. There are three possible modes that can be selected using these attributes. If the async attribute is present, then the script will be executed asynchronously, as soon as it is available. If the async
attribute is not present but the defer attribute is
present, then the script is executed when the page has finished parsing. If neither attribute is
present, then the script is fetched and executed immediately, before the user agent continues
parsing the page. The exact processing details for these attributes are, for mostly historical reasons, somewhat non-trivial, involving a number of aspects of HTML. The implementation
requirements are therefore by necessity scattered throughout the specification. The algorithms
below (in this section) describe the core of this processing, but these algorithms reference and
are referenced

http://developers.whatwg.org/scripting-1.html[4/16/2014 9:29:22 PM]

4.12 Scripting HTML: The Living Standard - Edition for Web Developers

by the parsing rules for script start and end tags in HTML, in foreign content,
and in XML, the rules for the document.write() method, the handling of scripting, etc. The defer attribute may be specified even if the async attribute is specified, to cause legacy Web browsers that
only support defer (and not async ) to fall back to the defer behavior instead of the synchronous blocking behavior that
is the default. The crossorigin attribute is a
CORS settings attribute. It controls, for scripts that are obtained from other origins, whether error information will be exposed. Changing the src, type, charset, async, defer , and crossorigin attributes dynamically has no direct effect;
these attribute are only used at specific times described below. script . text [ = value ] Returns the contents of the element, ignoring child nodes that aren't Text nodes. Can be set, to replace the element's children with the given value. When inserted using the document.write()
method, script elements execute (typically synchronously), but when inserted using
innerHTML and outerHTML
attributes, they do not execute at all. In this example, two script elements are used. One embeds an external script, and
the other includes some data. <script src="game-engine.js"></script> <script type="text/x-game-map"> ........U.........e o............A....e .....A.....AAA....e .A..AAA...AAAAA...e </script> The data in this case might be used by the script to generate the map of a video game. The
data doesn't have to be used that way, though; maybe the map data is actually embedded in other
parts of the page's markup, and the

http://developers.whatwg.org/scripting-1.html[4/16/2014 9:29:22 PM]

4.12 Scripting HTML: The Living Standard - Edition for Web Developers

data block here is just used by the site's search engine to


help users who are looking for particular features in their game maps. The following sample shows how a script element can be used to define a function that is then
used by other parts of the document. It also shows how a script element can be used
to invoke script while the document is being parsed, in this case to initialize the form's
output. <script> function calculate(form) { var price = 52000; if (form.elements.brakes.checked) price += 1000; if (form.elements.radio.checked) price += 2500; if (form.elements.turbo.checked) price += 5000; if (form.elements.sticker.checked) price += 250; form.elements.result.value = price; } </script> <form name="pricecalc" onsubmit="return false" onchange="calculate(this)"> <fieldset> <legend>Work out the price of your car</legend> <p>Base cost: 52000.</p> <p>Select additional options:</p> <ul> <li><label><input type=checkbox name=brakes> Ceramic brakes (1000)</label></li> <li><label><input type=checkbox name=radio> Satellite radio (2500)</label></li> <li><label><input type=checkbox name=turbo> Turbo charger (5000)</label></li> <li><label><input type=checkbox name=sticker> "XZ" sticker (250)</label></li> </ul> <p>Total: <output name=result></output></p> </fieldset> <script>

http://developers.whatwg.org/scripting-1.html[4/16/2014 9:29:22 PM]

4.12 Scripting HTML: The Living Standard - Edition for Web Developers

calculate(document.forms.pricecalc); </script> </form>

Scripting languages
The following lists the MIME type strings that user agents must recognize, and the
languages to which they refer: "application/ecmascript" "application/javascript" "application/x-ecmascript" "application/x-javascript" "text/ecmascript" "text/javascript" "text/javascript1.0" "text/javascript1.1" "text/javascript1.2" "text/javascript1.3" "text/javascript1.4" "text/javascript1.5" "text/jscript" "text/livescript" "text/x-ecmascript" "text/x-javascript" JavaScript.

Restrictions for contents of script elements


The easiest and safest way to avoid the rather strange restrictions described in
this section is to always escape "<!--" as "<\!-- ", "<script " as " <\script", and "</script" as "<\/script " when these sequences appear in scripts (e.g. in strings or in
comments). Doing so avoids the pitfalls that the restrictions in this section are prone to
triggering: namely, that, for historical reasons, parsing of script blocks in HTML is
a strange and exotic practice that acts unintuitively in the face of these strings.

http://developers.whatwg.org/scripting-1.html[4/16/2014 9:29:22 PM]

4.12 Scripting HTML: The Living Standard - Edition for Web Developers

The textContent of a script element must match the script production in the following ABNF, the character set for which is Unicode. script escape data2 ) data1 not-data1 data2 not-data2 data3 not-data3 script-start script-end lt slash s s c c r r i i p p t t tag-end tag-end = < any string that doesn't contain a substring = "<!--" = < any string that doesn't contain a substring = script-start / "-->" = < any string that doesn't contain a substring = script-end / "-->" = lt s c r i p t tag-end = data1 *( escape [ script-start data3 ] "-->" = "<!--" data2 *( script-start data3 script-end

data1 ) [ escape ]

that matches not-data1 >

that matches not-data2 >

that matches not-data3 >

= lt slash s c r i p t tag-end = = = = = = = = %x003C ; U+003C LESS-THAN SIGN character (<) %x002F ; U+002F SOLIDUS character (/) %x0053 ; U+0053 LATIN CAPITAL LETTER S %x0043 ; U+0043 LATIN CAPITAL LETTER C %x0052 ; U+0052 LATIN CAPITAL LETTER R %x0049 ; U+0049 LATIN CAPITAL LETTER I %x0050 ; U+0050 LATIN CAPITAL LETTER P %x0054 ; U+0054 LATIN CAPITAL LETTER T

=/ %x0073 ; U+0073 LATIN SMALL LETTER S =/ %x0063 ; U+0063 LATIN SMALL LETTER C =/ %x0072 ; U+0072 LATIN SMALL LETTER R =/ %x0069 ; U+0069 LATIN SMALL LETTER I =/ %x0070 ; U+0070 LATIN SMALL LETTER P =/ %x0074 ; U+0074 LATIN SMALL LETTER T = %x0009 ; U+0009 CHARACTER TABULATION (tab)

=/ %x000A ; U+000A LINE FEED (LF)

http://developers.whatwg.org/scripting-1.html[4/16/2014 9:29:22 PM]

4.12 Scripting HTML: The Living Standard - Edition for Web Developers

tag-end tag-end tag-end tag-end

=/ %x000C ; U+000C FORM FEED (FF) =/ %x0020 ; U+0020 SPACE =/ %x002F ; U+002F SOLIDUS (/) =/ %x003E ; U+003E GREATER-THAN SIGN (>)

When a script element contains script documentation, there are


further restrictions on the contents of the element, as described in the section below. The following script illustrates this issue. Suppose you have a script that contains a string,
as in: var example = 'Consider this string: <!-- <script>'; console.log(example); If one were to put this string directly in a script block, it would violate the restrictions above: <script> var example = 'Consider this string: <!-- <script>'; console.log(example); </script> The bigger problem, though, and the reason why it would violate those restrictions, is that
actually the script would get parsed weirdly: the script block above is not terminated.
That is, what looks like a "</script> " end tag in this snippet is
actually still part of the script block. The script doesn't execute (since it's not
terminated); if it somehow were to execute, as it might if the markup looked as follows, it would
fail because the script (highlighted here) is not valid JavaScript: <script> var example = 'Consider this string: <!-- <script>'; console.log(example); </script> <!-- despite appearances, this is actually part of the script still! --> <script> ... // this is the same script block still... </script> What is going on here is that for legacy reasons, "<!--" and "<script " strings in script elements in HTML need to be balanced
in order for the
http://developers.whatwg.org/scripting-1.html[4/16/2014 9:29:22 PM]

4.12 Scripting HTML: The Living Standard - Edition for Web Developers

parser to consider closing the block. By escaping the problematic strings as mentioned at the top of this section, the problem is
avoided entirely: <script> var example = 'Consider this string: <\!-- <\script>'; console.log(example); </script> <!-- this is just a comment between script blocks --> <script> ... // this is a new script block </script>

Inline documentation for external scripts


If a script element's src attribute is
specified, then the contents of the script element, if any, must be such that the
value of the text IDL attribute, which is derived from the
element's contents, matches the documentation production in the following
ABNF, the character set for which is Unicode. [ABNF] documentation = *( *( space / tab / comment ) [ line-comment ] newline ) comment 1*star slash line-comment ; characters tab newline space star slash not-newline FEED (LF) not-star ASTERISK (*)
http://developers.whatwg.org/scripting-1.html[4/16/2014 9:29:22 PM]

= slash star *( not-star / star not-slash ) = slash slash *not-newline

= %x0009 ; U+0009 CHARACTER TABULATION (tab) = %x000A ; U+000A LINE FEED (LF) = %x0020 ; U+0020 SPACE = %x002A ; U+002A ASTERISK (*) = %x002F ; U+002F SOLIDUS (/) = %x0000-0009 / %x000B-10FFFF ; a Unicode character other than U+000A LINE = %x0000-0029 / %x002B-10FFFF ; a Unicode character other than U+002A

4.12 Scripting HTML: The Living Standard - Edition for Web Developers

not-slash SOLIDUS (/)

= %x0000-002E / %x0030-10FFFF ; a Unicode character other than U+002F

This corresponds to putting the contents of the element in JavaScript comments. This requirement is in addition to the earlier restrictions on the syntax of contents of script elements. This allows authors to include documentation, such as license information or API information,
inside their documents while still referring to external script files. The syntax is constrained
so that authors don't accidentally include what looks like valid script while also providing a
src attribute. <script src="cool-effects.js"> // create new instances using: // // // var e = new Effect(); e.play(); e.stop(); // start the effect using .play, stop using .stop:

</script>

The noscript element


Categories: Metadata content. Flow content. Phrasing content. Contexts in which this element can be used: In a head element of an HTML document, if there are no ancestor noscript elements. Where phrasing content is expected in HTML documents, if there are no ancestor noscript elements. Content model: When scripting is disabled, in a head element: in any order, zero or more link elements, zero or more style elements, and zero or more meta elements.

http://developers.whatwg.org/scripting-1.html[4/16/2014 9:29:22 PM]

4.12 Scripting HTML: The Living Standard - Edition for Web Developers

When scripting is disabled, not in a head element: transparent, but there must be no noscript element descendants. Otherwise: text that conforms to the requirements given in the prose. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes DOM interface: Uses HTMLElement. The noscript element represents nothing if scripting is enabled, and represents its children if
scripting is disabled. It is used to present different markup to user agents that support scripting and those that don't support scripting, by affecting
how the document is parsed. When used in HTML documents, the allowed content model is as follows: In a head element, if scripting is
disabled for the noscript element The noscript element must contain only link, style ,
and meta elements. In a head element, if scripting is enabled
for the noscript element The noscript element must contain only text, except that invoking the
HTML fragment parsing algorithm with
the noscript element as the context element and the text contents as the input must result in a list of nodes
that consists only of link, style , and meta elements that
would be conforming if they were children of the noscript element, and no parse errors. Outside of head elements, if scripting is
disabled for the noscript element The noscript element's content model is transparent, with the
additional restriction that a noscript element must not have a noscript
element as an ancestor (that is, noscript can't be nested). Outside of head elements, if scripting is
enabled for the noscript element The noscript element must contain only text, except that the text must be such
that running the following algorithm results in a conforming document with no
noscript elements and no script elements, and such that no step in the
algorithm causes an HTML parser to flag a parse error:

http://developers.whatwg.org/scripting-1.html[4/16/2014 9:29:22 PM]

4.12 Scripting HTML: The Living Standard - Edition for Web Developers

1. Remove every script element from the document. 2. Make a list of every noscript element in the document. For every
noscript element in that list, perform the following steps: 1. Let the parent element be the parent element of the
noscript element. 2. Take all the children of the parent element that come before the
noscript element, and call these elements the before
children. 3. Take all the children of the parent element that come after
the noscript element, and call these elements the after
children. 4. Let s be the concatenation of all the Text node children
of the noscript element. 5. Set the innerHTML attribute of the parent element to the value of s. (This, as a side-effect,
causes the noscript element to be removed from the document.) 6. Insert the before children at the start of the parent
element, preserving their original relative order. 7. Insert the after children at the end of the parent
element, preserving their original relative order.

All these contortions are required because, for historical reasons, the noscript element is handled differently by the HTML parser based on whether scripting was enabled or not when the parser was
invoked. The noscript element must not be used in XML documents. The noscript element is only effective in the HTML
syntax, it has no effect in the XHTML syntax. This is because the way it works
is by essentially "turning off" the parser when scripts are enabled, so that the contents of the element are treated as pure text and not as real elements. XML does not define a mechanism by
which to do this. In the following example, a noscript element is
used to provide fallback for a script. <form action="calcSquare.php"> <p> <label for=x>Number</label>: <input id="x" name="x" type="number"> </p> <script> var x = document.getElementById('x');

http://developers.whatwg.org/scripting-1.html[4/16/2014 9:29:22 PM]

4.12 Scripting HTML: The Living Standard - Edition for Web Developers

var output = document.createElement('p'); output.textContent = 'Type a number; it will be squared right then!'; x.form.appendChild(output); x.form.onsubmit = function () { return false; } x.oninput = function () { var v = x.valueAsNumber; output.textContent = v + ' squared is ' + v * v; }; </script> <noscript> <input type=submit value="Calculate Square"> </noscript> </form> When script is disabled, a button appears to do the calculation on the server side. When
script is enabled, the value is computed on-the-fly instead. The noscript element is a blunt instrument. Sometimes, scripts might be enabled,
but for some reason the page's script might fail. For this reason, it's generally better to avoid
using noscript, and to instead design the script to change the page from being a
scriptless page to a scripted page on the fly, as in the next example: <form action="calcSquare.php"> <p> <label for=x>Number</label>: <input id="x" name="x" type="number"> </p> <input id="submit" type=submit value="Calculate Square"> <script> var x = document.getElementById('x'); var output = document.createElement('p'); output.textContent = 'Type a number; it will be squared right then!'; x.form.appendChild(output); x.form.onsubmit = function () { return false; } x.oninput = function () { var v = x.valueAsNumber; output.textContent = v + ' squared is ' + v * v; };

http://developers.whatwg.org/scripting-1.html[4/16/2014 9:29:22 PM]

4.12 Scripting HTML: The Living Standard - Edition for Web Developers

var submit = document.getElementById('submit'); submit.parentNode.removeChild(submit); </script> </form> The above technique is also useful in XHTML, since noscript is not supported in
the XHTML syntax.

The template element


Categories: Metadata content. Flow content. Phrasing content. Script-supporting element. Contexts in which this element can be used: Where metadata content is expected. Where phrasing content is expected. Where script-supporting elements are expected. As a child of a colgroup element that doesn't have a span attribute. Content model: Either: Metadata content. Or: Flow content. Or: The content model of ol and ul elements. Or: The content model of dl elements. Or: The content model of figure elements. Or: The content model of ruby elements. Or: The content model of object elements. Or: The content model of video and audio elements. Or: The content model of table elements. Or: The content model of colgroup elements. Or: The content model of thead , tbody, and tfoot elements. Or: The content model of tr elements.

http://developers.whatwg.org/scripting-1.html[4/16/2014 9:29:22 PM]

4.12 Scripting HTML: The Living Standard - Edition for Web Developers

Or: The content model of fieldset elements. Or: The content model of select elements. Or: The content model of details elements. Or: The content model of menu elements whose type attribute is in the popup menu state. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes DOM interface: The template element is used to declare fragments of HTML that can be cloned and
inserted in the document by script. In a rendering, the template element represents nothing. template . content Returns the contents of the template, which are stored in a DocumentFragment associated with a different Document so as to avoid
the template contents interfering with the main Document. (For
example, this avoids form controls from being submitted, scripts from executing, and so forth.) In this example, a script populates a table with data from a data structure, using a
template to provide the element structure instead of manually generating the
structure from markup. <!DOCTYPE html> <title>Cat data</title> <script> // Data is hard-coded here, but could come from the server var data = [ { name: 'Pillar', color: 'Ticked Tabby', sex: 'Female (neutered)', legs: 3 }, { name: 'Hedral', color: 'Tuxedo', sex: 'Male (neutered)', legs: 4 }, ]; </script>

http://developers.whatwg.org/scripting-1.html[4/16/2014 9:29:22 PM]

4.12 Scripting HTML: The Living Standard - Edition for Web Developers

<table> <thead> <tr> <th>Name <th>Color <th>Sex <th>Legs <tbody> <template id="row"> <tr><td><td><td><td> </template> </table> <script> var template = document.querySelector('#row'); for (var i = 0; i < data.length; i += 1) { var cat = data[i]; var clone = template.content.cloneNode(true); var cells = clone.querySelectorAll('td'); cells[0].textContent = cat.name; cells[1].textContent = cat.color; cells[2].textContent = cat.sex; cells[3].textContent = cat.legs; template.parentNode.appendChild(clone); } </script>

Up next

4.12.4 The canvas element

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/scripting-1.html[4/16/2014 9:29:22 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
The canvas element
Proxying canvases to workers
The 2D rendering context
Implementation notes
The canvas state
DrawingStyle objects
Line styles
Text styles
Building paths
Path objects
Transformations
Image sources for 2D rendering contexts
Fill and stroke styles
Drawing rectangles to the bitmap
Drawing text to the bitmap
Drawing paths to the canvas
Drawing images
Hit regions
Pixel manipulation
Compositing
Image smoothing
Shadows
Best practices
Examples
Pixel density
Serializing bitmaps to a file
Common idioms without dedicated elements
The main part of the content
Bread crumb navigation
Tag clouds

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

Conversations
Footnotes
Disabled elements

The canvas element


Categories: Flow content. Phrasing content. Embedded content. Palpable content. Contexts in which this element can be used: Where embedded content is expected. Content model: Transparent, but with no interactive content descendants except for a elements, button elements, input elements whose type attribute are in the Checkbox or Radio Button states, and input elements that are buttons. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes width Horizontal dimension height Vertical dimension DOM interface: The canvas element provides scripts with a resolution-dependent bitmap canvas,
which can be used for rendering graphs, game graphics, art, or other visual images on the fly. Authors should not use the canvas element in a document when a more suitable
element is available. For example, it is inappropriate to use a canvas element to
render a page heading: if the desired presentation of the heading is graphically intense, it
should be marked up using appropriate elements (typically h1) and then styled using
CSS and supporting technologies such as XBL.

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

When authors use the canvas element, they must also provide content that, when
presented to the user, conveys essentially the same function or purpose as the
canvas ' bitmap. This content may be placed as content of the canvas element. The contents of the canvas element, if any, are the element's fallback
content. In interactive visual media, if scripting is enabled for
the canvas element, and if support for canvas elements has been enabled,
the canvas element represents embedded content consisting
of a dynamically created image, the element's bitmap. In non-interactive, static, visual media, if the canvas element has been previously associated with a rendering context (e.g. if the page was viewed in an interactive
visual medium and is now being printed, or if some script that ran during the page layout process
painted on the element), then the canvas element represents
embedded content with the element's current bitmap and size. Otherwise, the element
represents its fallback content instead. In non-visual media, and in visual media if scripting is
disabled for the canvas element or if support for canvas elements
has been disabled, the canvas element represents its fallback
content instead. When a canvas element represents embedded content, the
user can still focus descendants of the canvas element (in the fallback
content). When an element is focused, it is the target of keyboard interaction events (even
though the element itself is not visible). This allows authors to make an interactive canvas
keyboard-accessible: authors should have a one-to-one mapping of interactive regions to focusable
elements in the fallback content. (Focus has no effect on mouse interaction events.) The canvas element has two attributes to control the size of the element's bitmap:
width and height. These attributes, when specified, must have values that are valid non-negative integers. The width
attribute defaults to 300, and the height attribute
defaults to 150. The intrinsic dimensions of the canvas element when it represents
embedded content are equal to the dimensions of the element's bitmap. A canvas element can be sized arbitrarily by a style sheet, its
bitmap is then subject to the 'object-fit' CSS property. The bitmaps used with canvas elements can have arbitrary pixel
densities.

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

Typically, the density will match that of the user's screen. context = canvas . getContext (contextId [, ... ]) Returns an object that exposes an API for drawing on the canvas. The first argument specifies
the desired API, either "2d " or "webgl ". Subsequent arguments are handled by that API. This specification defines the "2d " context below.
There is also a specification that defines a "webgl"
context. Returns null if the given context ID is not supported, if the canvas has already been
initialized with the other context type (e.g. trying to get a "2d " context after getting a "webgl " context). Throws an InvalidStateError exception if the setContext() or transferControlToProxy() methods have been
used. supported = canvas . probablySupportsContext(contextId [, ... ]) Returns false if calling getContext() with the
same arguments would definitely return null, and true otherwise. This return value is not a guarantee that getContext() will or will not return an object, as
conditions (e.g. availability of system resources) can vary over time. Throws an InvalidStateError exception if the setContext() or transferControlToProxy() methods have been
used. canvas . setContext(context) Sets the canvas' rendering context to the given object. Throws an InvalidStateError exception if the getContext() or transferControlToProxy() methods have been
used. url = canvas . toDataURL ( [ type, ... ] ) url = canvas . toDataURLHD ( [ type, ... ] ) Returns a data: URL for the image in
the canvas. The first argument, if provided, controls the type of the image to be returned (e.g. PNG or
JPEG). The default is image/png ; that type is also used if the given type
isn't supported. The other arguments are specific to the type, and control the way that the
image is generated, as given in the table
below.

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

When trying to use types other than "image/png ", authors can check if the image
was really returned in the requested format by checking to see if the returned string starts
with one of the exact strings "data:image/png, " or " data:image/png;". If it does, the image is PNG, and thus the requested type was
not supported. (The one exception to this is if the canvas has either no height or no width, in
which case the result might simply be "data:,".) The toDataURL() method returns the data at a
resolution of 96dpi. The toDataURLHD() method
returns it at the native canvas bitmap resolution. canvas . toBlob(callback [, type, ... ]) canvas . toBlobHD(callback [, type, ... ]) Creates a Blob object representing a file containing the image in the canvas, and invokes a callback with a handle to that object. The second argument, if provided, controls the type of the image to be returned (e.g. PNG or
JPEG). The default is image/png ; that type is also used if the given type
isn't supported. The other arguments are specific to the type, and control the way that the
image is generated, as given in the table
below. The toBlob() method provides the data at a resolution
of 96dpi. The toBlobHD() method provides it at the
native canvas bitmap resolution.

Proxying canvases to workers


Since DOM nodes cannot be accessed across worker boundaries, a proxy object is needed to enable
workers to render to canvas elements in Document s. canvasProxy = canvas . transferControlToProxy() Returns a CanvasProxy object that can be used to transfer control for this canvas over to another document (e.g. an iframe from another origin)
or to a worker. Throws an InvalidStateError exception if the getContext() or setContext() methods have been used. canvasProxy . setContext(context) Sets the CanvasProxy object's canvas element's rendering context to
the given object.

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

Throws an InvalidStateError exception if the CanvasProxy has been transfered. The transferControlToProxy()
method of the canvas element, when invoked, must run the following steps: 1. If the canvas element's canvas
context mode is not none, throw an InvalidStateError exception and abort these steps. 2. Set the canvas element's context
mode to proxied. 3. Return a CanvasProxy object bound to this canvas
element. A CanvasProxy object can be neutered (like any Transferable object), meaning it can no longer be transferred, and
can be disabled, meaning it can no longer be bound
to rendering contexts. When first created, a CanvasProxy object must be neither. A CanvasProxy is created with a link to a canvas element. A
CanvasProxy object that has not been disabled must have a strong reference to its canvas element. The setContext(context) method of CanvasProxy objects, when invoked, must run the following steps: 1. If the CanvasProxy object has been disabled, throw an InvalidStateError exception and abort these steps. 2. If the CanvasProxy object has not been neutered, then neuter it. 3. If context's context
bitmap mode is fixed, then throw an
InvalidStateError exception and abort these steps. 4. If context's context
bitmap mode is bound, then run context's unbinding steps and
set its context's context
bitmap mode to unbound. 5. Run context's binding
steps to bind it to this CanvasProxy object's canvas element. 6. Set the context's context bitmap mode to bound. To transfer a
CanvasProxy object old to a new owner owner,
a user agent must create a new CanvasProxy object linked to the same
canvas element as old, thus obtaining new,
must neuter and disable the old object, and must

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

finally return new. Here is a clock implemented on a worker. First, the main page: <!DOCTYPE HTML> <title>Clock</title> <canvas></canvas> <script> var canvas = document.getElementsByTagName('canvas')[0]; var proxy = canvas.transferControlToProxy(); var worker = new Worker('clock.js'); worker.postMessage(proxy, [proxy]); </script> Second, the worker: onmessage = function (event) { var context = new CanvasRenderingContext2D(); event.data.setContext(context); // event.data is the CanvasProxy object setInterval(function () { context.clearRect(0, 0, context.width, context.height); context.fillText(new Date(), 0, 100); context.commit(); }, 1000); };

The 2D rendering context


context = canvas . getContext ('2d') Returns a CanvasRenderingContext2D object that is permanently bound to a
particular canvas element. context = new CanvasRenderingContext2D( [ width, height ] ) Returns an unbound CanvasRenderingContext2D object with an implied bitmap with
the given dimensions in CSS pixels (300x150, if the arguments are omitted). context . canvas Returns the canvas element, if the rendering context was obtained using the

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

getContext() method. context . width context . height Return the dimensions of the bitmap, in CSS pixels. Can be set, to update the bitmap's dimensions. If the rendering context is bound to a canvas,
this will also update the canvas' intrinsic dimensions. context . commit () If the rendering context is bound to a canvas , display the current frame. The CanvasFillRule enumeration is used to select the fill rule
algorithm by which to determine if a point is inside or outside a path. The value "nonzero" value
indicates the non-zero winding rule, wherein
a point is considered to be outside a shape if the number of times a half-infinite straight
line drawn from that point crosses the shape's path going in one direction is equal to the
number of times it crosses the path going in the other direction. The "evenodd" value indicates
the even-odd rule, wherein
a point is considered to be outside a shape if the number of times a half-infinite straight
line drawn from that point crosses the shape's path is even. If a point is not outside a shape, it is inside the shape.

Implementation notes Although the way the specification is written it might sound like an implementation needs to
track up to four bitmaps per canvas or rendering context one scratch bitmap,
one output bitmap for the rendering context, one bitmap for the canvas,
and one bitmap for the actually currently rendered image user agents can in fact generally
optimise this to only one or two. The scratch bitmap, when it isn't the same bitmap as the output
bitmap, is only directly observable if it is read, and therefore implementations can, instead of updating this bitmap, merely remember the sequence of drawing operations that have been
applied to it until such time as the bitmap's actual data is needed (for example because of a call
to commit(), drawImage(), or the createImageBitmap()
factory method). In many cases, this will be more

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

memory efficient. The bitmap of a canvas element is the one bitmap that's pretty much always going
to be needed in practice. The output bitmap of a rendering context, when it has one,
is always just an alias to a canvas element's bitmap. Additional bitmaps are sometimes needed, e.g. to enable fast drawing when the canvas is being
painted at a different size than its intrinsic size, or to enable double buffering so that the
rendering commands from the scratch bitmap can be applied without the rendering being
updated midway.

The canvas state Each CanvasRenderingContext2D rendering context maintains a stack of drawing
states. Drawing states consist of:

The current transformation matrix. The current clipping region. The current values of the following attributes: strokeStyle, fillStyle,
globalAlpha, lineWidth, lineCap , lineJoin, miterLimit, lineDashOffset , shadowOffsetX, shadowOffsetY , shadowBlur , shadowColor, globalCompositeOperation, font, textAlign , textBaseline, direction, imageSmoothingEnabled .

The current dash list.


The current default path and the rendering context's bitmaps are not
part of the drawing state. The current default path is persistent, and can only be reset using the beginPath() method. The bitmaps
depend on whether and how the rendering context is bound to a canvas element.

context . save() Pushes the current state onto the stack. context . restore() Pops the top state on the stack, restoring the context to that state.

DrawingStyle objects All the line styles (line width, caps, joins, and dash patterns) and text styles (fonts)
described in the next two sections apply to

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

CanvasRenderingContext2D objects and to


DrawingStyle objects. This section defines the constructor used to obtain a
DrawingStyle object. This object is then used by methods on Path objects
to control how text and paths are rasterised and stroked. styles = new DrawingStyle( [ element ] ) Creates a new DrawingStyle object, optionally using a specific element for resolving relative keywords and sizes in font specifications.

Line styles context . lineWidth [ = value ] styles . lineWidth [ = value ] Returns the current line width. Can be set, to change the line width. Values that are not finite values greater than zero are
ignored. context . lineCap [ = value ] styles . lineCap [ = value ] Returns the current line cap style. Can be set, to change the line cap style. The possible line cap styles are butt, round , and
square. Other values are ignored. context . lineJoin [ = value ] styles . lineJoin [ = value ] Returns the current line join style. Can be set, to change the line join style. The possible line join styles are bevel , round , and
miter . Other values are ignored. context . miterLimit [ = value ] styles . miterLimit [ = value ] Returns the current miter limit ratio. Can be set, to change the miter limit ratio. Values that are not finite values greater than
zero are ignored.
http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

context . setLineDash(segments) styles . setLineDash(segments) Sets the current line dash pattern (as used when stroking). The argument is a list of
distances for which to alternately have the line on and the line off. segments = context . getLineDash() segments = styles . getLineDash() Returns a copy of the current line dash pattern. The array returned will always have an even
number of entries (i.e. the pattern is normalized). context . lineDashOffset styles . lineDashOffset Returns the phase offset (in the same units as the line dash pattern). Can be set, to change the phase offset. Values that are not finite values are ignored.

Text styles context . font [ = value ] styles . font [ = value ] Returns the current font settings. Can be set, to change the font. The syntax is the same as for the CSS 'font' property; values
that cannot be parsed as CSS font values are ignored. Relative keywords and lengths are computed relative to the font of the canvas element. context . textAlign [ = value ] styles . textAlign [ = value ] Returns the current text alignment settings. Can be set, to change the alignment. The possible values are and their meanings are given
below. Other values are ignored. The default is start . context . textBaseline [ = value ] styles . textBaseline [ = value ] Returns the current baseline alignment settings. Can be set, to change the baseline alignment. The possible values and their

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

meanings are
given below. Other values are ignored. The default is alphabetic . context . direction [ = value ] styles . direction [ = value ] Returns the current directionality. Can be set, to change the directionality. The possible values and their meanings are given
below. Other values are ignored. The default is inherit. The textAlign attribute's allowed keywords are
as follows: start Align to the start edge of the text (left side in left-to-right text, right side in right-to-left text). end Align to the end edge of the text (right side in left-to-right text, left side in right-to-left text). left Align to the left. right Align to the right. center Align to the center. The textBaseline
attribute's allowed keywords correspond to alignment points in the
font:

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

The keywords map to these alignment points as follows: top The top of the em square hanging The hanging baseline middle The middle of the em square alphabetic The alphabetic baseline ideographic The ideographic baseline bottom The bottom of the em square The direction attribute's allowed keywords are
as follows: ltr Treat input to the text preparation algorithm as left-to-right text. rtl Treat input to the text preparation algorithm as right-to-left text. inherit Default to the directionality of the canvas element or Document
as appropriate. The text preparation algorithm is as follows. It takes as input a string text, a CanvasDrawingStyles object target, and an
optional length maxWidth. It returns an array of glyph shapes, each positioned
on a common coordinate space, a physical alignment whose value is one of
left, right, and center, and an inline box. (Most callers of this
algorithm ignore the physical alignment and the inline box.) 1. If maxWidth was provided but is less than or equal to zero, return an
empty array. 2. Replace all the space characters in text with U+0020 SPACE characters.

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

3. Let font be the current font of target, as given


by that object's font attribute. 4. Apply the appropriate step from the following list to determine the value of direction: If the target object's direction attribute has the value "ltr" Let direction be 'ltr'. If the target object's direction attribute has the value "rtl" Let direction be 'rtl'. If the target object's font style source object is an
element Let direction be the directionality of the target object's font style source object. If the target object's font style source object is a
Document and that Document has a root element child Let direction be the directionality of the target object's font style source object's root element child. Otherwise Let direction be 'ltr'. 5. Form a hypothetical infinitely-wide CSS line box containing a single inline box containing
the text text, with all the properties at their initial values except the
'font' property of the inline box set to font, the 'direction' property of
the inline box set to direction, and the 'white-space' property set to 'pre'. 6. If maxWidth was provided and the hypothetical width of the inline box
in the hypothetical line box is greater than maxWidth CSS pixels, then change
font to have a more condensed font (if one is available or if a reasonably
readable one can be synthesized by applying a horizontal scale factor to the font) or a smaller
font, and return to the previous step. 7. The anchor point is a point on the inline box, and the physical alignment is one of the values left, right, and center. These variables are determined by the textAlign and textBaseline values as follows: Horizontal position: If textAlign is left If textAlign is start and direction is
'ltr' If textAlign is end and direction is 'rtl' Let the anchor point's horizontal position be the left edge of the
inline box, and let physical alignment be left.

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

If textAlign is right If textAlign is end and direction is 'ltr' If textAlign is start and direction is
'rtl' Let the anchor point's horizontal position be the right edge of the
inline box, and let physical alignment be right. If textAlign is center Let the anchor point's horizontal position be half way between the left
and right edges of the inline box, and let physical alignment be center. Vertical position: If textBaseline is top Let the anchor point's vertical position be the top of the em box of
the first available font of the inline box. If textBaseline is hanging Let the anchor point's vertical position be the hanging baseline of the
first available font of the inline box. If textBaseline is middle Let the anchor point's vertical position be half way between the bottom
and the top of the em box of the first available font of the inline box. If textBaseline is alphabetic Let the anchor point's vertical position be the alphabetic baseline of
the first available font of the inline box. If textBaseline is ideographic Let the anchor point's vertical position be the ideographic baseline of
the first available font of the inline box. If textBaseline is bottom Let the anchor point's vertical position be the bottom of the em box of
the first available font of the inline box. 8. Let result be an array constructed by iterating over each glyph in the
inline box from left to right (if any), adding to the array, for each glyph, the shape of the
glyph as it is in the inline box, positioned on a coordinate space using CSS pixels with its
origin is at the anchor point. 9. Return result, physical alignment, and the inline
box.

Building paths

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

Each object implementing the CanvasPathMethods interface has a path. A path has a list of zero or
more subpaths. Each subpath consists of a list of one or more points, connected by straight or
curved lines, and a flag indicating whether the subpath is closed or not. A closed subpath is one
where the last point of the subpath is connected to the first point of the subpath by a straight
line. Subpaths with only one point are ignored when painting the path. When an object implementing the CanvasPathMethods interface is created, its path must be initialized to zero subpaths. context . moveTo (x, y) path . moveTo(x, y) Creates a new subpath with the given point. context . closePath () path . closePath () Marks the current subpath as closed, and starts a new subpath with a point the same as the
start and end of the newly closed subpath. context . lineTo (x, y) path . lineTo(x, y) Adds the given point to the current subpath, connected to the previous one by a straight
line. context . quadraticCurveTo(cpx, cpy, x, y) path . quadraticCurveTo(cpx, cpy, x, y) Adds the given point to the current subpath, connected to the previous one by a quadratic
Bzier curve with the given control point. context . bezierCurveTo (cp1x, cp1y, cp2x, cp2y, x, y) path . bezierCurveTo (cp1x, cp1y, cp2x, cp2y, x, y) Adds the given point to the current subpath, connected to the previous one by a cubic
Bzier curve with the given control points. context . arcTo (x1, y1, x2, y2, radiusX [, radiusY, rotation ]) path . arcTo (x1, y1, x2, y2, radiusX [, radiusY, rotation ]) Adds an arc with the given control points and radius to the current subpath, connected to the
previous point by a straight line. If two radii are provided, the first controls the width of the arc's ellipse, and the second
controls the height. If only one is provided, or if they are the same, the arc is from a circle.
In the case of an ellipse, the rotation argument

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

controls the clockwise inclination of the


ellipse relative to the x-axis. Throws an IndexSizeError exception if the given radius is negative.

context . arc(x, y, radius, startAngle, endAngle [, anticlockwise ] ) path . arc(x, y, radius, startAngle, endAngle [, anticlockwise ] ) Adds points to the subpath such that the arc described by the circumference of the circle
described by the arguments, starting at the given start angle and

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

ending at the given end angle,


going in the given direction (defaulting to clockwise), is added to the path, connected to the
previous point by a straight line. Throws an IndexSizeError exception if the given radius is negative.

context . ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle [, anticlockwise] ) path . ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle [, anticlockwise] ) Adds points to the subpath such that the arc described by the circumference of the ellipse
described by the arguments, starting at the given start angle and ending at the given end angle,
going in the given direction (defaulting to clockwise), is added to the path, connected to the
previous point by a straight line. Throws an IndexSizeError exception if the given radius is negative. context . rect(x, y, w, h) path . rect(x, y, w, h) Adds a new closed subpath to the path, representing the given rectangle.

Path objects Path objects can be used to declare paths that are then later used on CanvasRenderingContext2D objects. In addition to many of the APIs described in
earlier sections, Path objects have methods to combine paths, and to add text to
paths. path = new Path() Creates a new empty Path object.

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

path = new Path(path) Creates a new Path object that is a copy of the argument. path = new Path(d) Creates a new path with the path described by the argument, interpreted as SVG path data. path . addPath(path, transform) path . addPathByStrokingPath (path, styles, transform) Adds to the path the path given by the argument. In the case of the stroking variants, the line styles are taken from the styles argument, which can be either a DrawingStyle object or a CanvasRenderingContext2D object. path . addText(text, styles, transform, x, y [, maxWidth ]) path . addText(text, styles, transform, path [, maxWidth ]) path . addPathByStrokingText (text, styles, transform, x, y [, maxWidth ]) path . addPathByStrokingText (text, styles, transform, path [, maxWidth ]) Adds to the path a series of subpaths corresponding to the given text. If the arguments give
a coordinate, the text is drawn horizontally at the given coordinates. If the arguments give a
path, the text is drawn along the path. If a maximum width is provided, the text will be scaled
to fit that width if necessary. The font, and in the case of the stroking variants, the line styles, are taken from the styles argument, which can be either a DrawingStyle object or a CanvasRenderingContext2D object.

Transformations Each CanvasRenderingContext2D object has a current transformation matrix,


as well as methods (described in this section) to manipulate it. When a
CanvasRenderingContext2D object is created, its transformation matrix must be
initialized to the identity transform. The transformation matrix is applied to coordinates when creating the current default
path, and when painting text, shapes, and Path objects, on CanvasRenderingContext2D objects.

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

Most of the API uses SVGMatrix objects rather than this API. This API remains mostly for historical reasons. context . currentTransform [ = value ] Returns the transformation matrix, as an SVGMatrix object. Can be set, to change the transformation matrix. context . scale (x, y) Changes the transformation matrix to apply a scaling transformation with the given characteristics. context . rotate (angle) Changes the transformation matrix to apply a rotation transformation with the given characteristics. The angle is in radians. context . translate (x, y) Changes the transformation matrix to apply a translation transformation with the given characteristics. context . transform (a, b, c, d, e, f) Changes the transformation matrix to apply the matrix given by the arguments as described below. context . setTransform(a, b, c, d, e, f) Changes the transformation matrix to the matrix given by the arguments as described below. context . resetTransform () Changes the transformation matrix to the identity transform.

a b 0

c d 0

e f 1

The arguments a, b, c,
d, e, and f are sometimes called m11, m12, m21, m22, dx, and dy or m11, m21, m12, m22, dx, and
dy. Care should be taken in particular with the order of the second and third
arguments (b and c) as their order varies from API to API
and APIs sometimes use the notation m12/m21 and sometimes
m21/m12 for those positions.

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

Image sources for 2D rendering contexts Several methods in the CanvasRenderingContext2D API take the union type CanvasImageSource as an argument. This union type allows objects implementing any of the following interfaces to be used as image
sources:

HTMLImageElement (img elements) HTMLVideoElement (video elements) HTMLCanvasElement (canvas elements) CanvasRenderingContext2D ImageBitmap
The ImageBitmap interface can be created from a number of other
imagerepresenting types, including ImageData . When a user agent is required to check the usability of the image
argument, where image is a CanvasImageSource object, the
user agent must run these steps, which return either good, bad, or
aborted: 1. If the image argument is an HTMLImageElement object that
is in the broken state, then throw an
InvalidStateError exception, return aborted, and abort these steps. 2. If the image argument is an HTMLImageElement object that
is not fully decodable, or if the image
argument is an HTMLVideoElement object whose readyState attribute is either HAVE_NOTHING or HAVE_METADATA, then return bad and abort these
steps. 3. If the image argument is an HTMLImageElement object with
an intrinsic width or intrinsic height (or both) equal to zero, then return bad and abort
these steps. 4. If the image argument is an HTMLCanvasElement object with
either a horizontal dimension or a vertical dimension equal to zero, then return bad and
abort these steps. 5. Return good. When a CanvasImageSource object represents an HTMLImageElement, the element's image must be used as the source image.

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

Specifically, when a CanvasImageSource object represents an animated image in an


HTMLImageElement, the user agent must use the default image of the animation (the
one that the format defines is to be used when animation is not supported or is disabled), or, if
there is no such image, the first frame of the animation, when rendering the image for
CanvasRenderingContext2D APIs. When a CanvasImageSource object represents an HTMLVideoElement, then the frame at the current playback position when the method with the argument is
invoked must be used as the source image when rendering the image for
CanvasRenderingContext2D APIs, and the source image's dimensions must be the intrinsic width and intrinsic height of the media resource
(i.e. after any aspect-ratio correction has been applied). When a CanvasImageSource object represents an HTMLCanvasElement , the element's bitmap must be used as the source image. When a CanvasImageSource object represents a CanvasRenderingContext2D, the
object's scratch bitmap must be used as the source image. When a CanvasImageSource object represents an element that is being rendered and that element has been resized, the original image data of the source image
must be used, not the image as it is rendered (e.g. width and height attributes on the source element have no effect on how
the object is interpreted when rendering the image for CanvasRenderingContext2D APIs). When a CanvasImageSource object represents an ImageBitmap, the
object's bitmap image data must be used as the source image. The image argument is not origin-clean if it is an
HTMLImageElement or HTMLVideoElement whose origin is not
the same as the entry script's origin, or if it is an HTMLCanvasElement whose bitmap's origin-clean flag is false, or if it is a
CanvasRenderingContext2D object whose scratch bitmap's originclean flag is false.

Fill and stroke styles context . fillStyle [ = value ] Returns the current style used for filling shapes.
http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

Can be set, to change the fill style. The style can be either a string containing a CSS color, or a
CanvasGradient or CanvasPattern
object. Invalid values are ignored. context . strokeStyle [ = value ] Returns the current style used for stroking shapes. Can be set, to change the stroke style. The style can be either a string containing a CSS color, or a
CanvasGradient or CanvasPattern
object. Invalid values are ignored. There are two types of gradients, linear gradients and radial gradients, both represented by
objects implementing the opaque CanvasGradient interface. Once a gradient has been created (see below), stops are placed along it to define how the colors are distributed along the gradient. gradient . addColorStop(offset, color) Adds a color stop with the given color to the gradient at the given offset. 0.0 is the offset
at one end of the gradient, 1.0 is the offset at the other end. Throws an IndexSizeError exception if the offset is out of range. Throws a SyntaxError exception if the color cannot be parsed. gradient = context . createLinearGradient(x0, y0, x1, y1) Returns a CanvasGradient object that represents a
linear gradient that paints along the line given by the
coordinates represented by the arguments. gradient = context . createRadialGradient(x0, y0, r0, x1, y1, r1) Returns a CanvasGradient object that represents a
radial gradient that paints along the cone given by the circles
represented by the arguments. If either of the radii are negative, throws an
IndexSizeError exception. Patterns are represented by objects implementing the opaque CanvasPattern
interface. pattern = context . createPattern (image, repetition) Returns a CanvasPattern object that uses the given image and repeats in the

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

direction(s) given by the repetition argument. The allowed values for repetition are repeat (both
directions), repeat-x (horizontal only), repeat-y
(vertical only), and no-repeat (neither). If the repetition argument is empty, the value repeat is used. If the image isn't yet fully decoded, then nothing is drawn. If the image is a canvas with no
data, throws an InvalidStateError exception. pattern . setTransform(transform) Sets the transformation matrix that will be used when rendering the pattern during a fill or
stroke painting operation.

Drawing rectangles to the bitmap There are three methods that immediately draw rectangles to the bitmap. They each take four
arguments; the first two give the x and y coordinates of the top left of the rectangle, and the second two give the width w and height
h of the rectangle, respectively. context . clearRect (x, y, w, h) Clears all pixels on the bitmap in the given rectangle to transparent black. context . fillRect(x, y, w, h) Paints the given rectangle onto the bitmap, using the current fill style. context . strokeRect (x, y, w, h) Paints the box that outlines the given rectangle onto the bitmap, using the current stroke
style.

Drawing text to the bitmap context . fillText(text, x, y [, maxWidth ] ) context . strokeText (text, x, y [, maxWidth ] ) Fills or strokes (respectively) the given text at the given position. If a maximum width is
provided, the text will be scaled to fit that width if necessary. metrics = context . measureText(text) Returns a TextMetrics object with the metrics of the given text in the current

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

font. metrics . width metrics . actualBoundingBoxLeft metrics . actualBoundingBoxRight metrics . fontBoundingBoxAscent metrics . fontBoundingBoxDescent metrics . actualBoundingBoxAscent metrics . actualBoundingBoxDescent metrics . emHeightAscent metrics . emHeightDescent metrics . hangingBaseline metrics . alphabeticBaseline metrics . ideographicBaseline Returns the measurement described below. width attribute The width of that inline box, in CSS pixels. (The text's advance width.) actualBoundingBoxLeft attribute The distance parallel to the baseline from the alignment point given by the textAlign attribute to the left side of the bounding
rectangle of the given text, in CSS pixels; positive numbers indicating a distance going left
from the given alignment point. The sum of this value and the next (actualBoundingBoxRight ) can be wider than
the width of the inline box (width ), in particular
with slanted fonts where characters overhang their advance width. actualBoundingBoxRight attribute The distance parallel to the baseline from the alignment point given by the textAlign attribute to the right side of the bounding
rectangle of the given text, in CSS pixels; positive numbers indicating a distance going right
from the given alignment point. fontBoundingBoxAscent attribute The distance from the horizontal line indicated by the textBaseline attribute to the top of the highest
bounding rectangle of all the fonts used to render the text, in CSS pixels; positive numbers
indicating a distance going up from the given baseline.

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

This value and the next are useful when rendering a background that must have a
consistent height even if the exact text being rendered changes. The actualBoundingBoxAscent attribute (and
its corresponding attribute for the descent) are useful when drawing a bounding box around
specific text. fontBoundingBoxDescent attribute The distance from the horizontal line indicated by the textBaseline attribute to the bottom of the lowest
bounding rectangle of all the fonts used to render the text, in CSS pixels; positive numbers
indicating a distance going down from the given baseline. actualBoundingBoxAscent attribute The distance from the horizontal line indicated by the textBaseline attribute to the top of the bounding
rectangle of the given text, in CSS pixels; positive numbers indicating a distance going up from
the given baseline. This number can vary greatly based on the input text, even if the first font specified covers all the characters in the input. For example, the actualBoundingBoxAscent of a lowercase
"o" from an alphabetic baseline would be less than that of an uppercase "F". The value can
easily be negative; for example, the distance from the top of the em box (textBaseline value " top") to the top of the bounding rectangle when
the given text is just a single comma ", " would likely (unless the font is
quite unusual) be negative. actualBoundingBoxDescent attribute The distance from the horizontal line indicated by the textBaseline attribute to the bottom of the bounding
rectangle of the given text, in CSS pixels; positive numbers indicating a distance going down
from the given baseline. emHeightAscent attribute The distance from the horizontal line indicated by the textBaseline attribute to the top of the em square in
the line box, in CSS pixels; positive numbers indicating that the given baseline is below the top
of the em square (so this value will usually be positive). Zero if the given baseline is the top
of the em square; half the font size if the given baseline is the middle of the em
square. emHeightDescent attribute The distance from the horizontal line indicated by the textBaseline attribute to the bottom of the em square
in the line box, in CSS pixels; positive numbers indicating that the given baseline is below the
bottom of the em square (so this value will usually be negative). (Zero if the given baseline is
the top of the em square.)
http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

hangingBaseline attribute The distance from the horizontal line indicated by the textBaseline attribute to the hanging baseline of the
line box, in CSS pixels; positive numbers indicating that the given baseline is below the hanging
baseline. (Zero if the given baseline is the hanging baseline.) alphabeticBaseline attribute The distance from the horizontal line indicated by the textBaseline attribute to the alphabetic baseline of
the line box, in CSS pixels; positive numbers indicating that the given baseline is below the
alphabetic baseline. (Zero if the given baseline is the alphabetic baseline.) ideographicBaseline attribute The distance from the horizontal line indicated by the textBaseline attribute to the ideographic baseline of
the line box, in CSS pixels; positive numbers indicating that the given baseline is below the
ideographic baseline. (Zero if the given baseline is the ideographic baseline.) Glyphs rendered using fillText() and
strokeText() can spill out of the box given by the
font size (the em square size) and the width returned by measureText() (the text width). Authors are encouraged
to use the bounding box values described above if this is an issue. A future version of the 2D context API may provide a way to render fragments of
documents, rendered using CSS, straight to the canvas. This would be provided in preference to a
dedicated way of doing multiline layout.

Drawing paths to the canvas The context always has a current default path. There is only one current default path, it is not part of the drawing state. The current default
path is a path, as described above. context . beginPath () Resets the current default path. context . fill() context . fill(path) Fills the subpaths of the current default path or the given path with the

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

current fill style. context . stroke () context . stroke (path) Strokes the subpaths of the current default path or the given path with the current stroke style. context . drawSystemFocusRing(element) context . drawSystemFocusRing(path, element) If the given element is focused, draws a focus ring around the current default path or the given path, following the platform conventions for focus rings. shouldDraw = context . drawCustomFocusRing(element) shouldDraw = context . drawCustomFocusRing(path, element) If the given element is focused, and the user has configured his system to draw focus rings
in a particular manner (for example, high contrast focus rings), draws a focus ring around the
current default path or the given path and returns false. Otherwise, returns true if the given element is focused, and false otherwise. This can thus
be used to determine when to draw a focus ring (see the example below). context . scrollPathIntoView () context . scrollPathIntoView (path) Scrolls the current default path or the given path into view. This is especially useful on devices with small screens, where the whole canvas might not be visible at once. context . clip() context . clip(path) Further constrains the clipping region to the current default path or the given path. context . resetClip () Unconstrains the clipping region. context . isPointInPath (x, y) context . isPointInPath (path, x, y) Returns true if the given point is in the current default path or the given
path. context . isPointInStroke(x, y) context . isPointInStroke(path, x, y)

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

Returns true if the given point would be in the region covered by the stroke of the
current default path or the given path, given the current stroke style. This canvas element has a couple of checkboxes. The path-related commands are
highlighted: <canvas height=400 width=750> <label><input type=checkbox id=showA> Show As</label> <label><input type=checkbox id=showB> Show Bs</label> <!-- ... --> </canvas> <script> function drawCheckbox(context, element, x, y, paint) { context.save(); context.font = '10px sans-serif'; context.textAlign = 'left'; context.textBaseline = 'middle'; var metrics = context.measureText(element.labels[0].textContent); if (paint) { context.beginPath(); context.strokeStyle = 'black'; context.rect(x-5, y-5, 10, 10); context.stroke(); if (element.checked) { context.fillStyle = 'black'; context.fill(); } context.fillText(element.labels[0].textContent, x+5, y); } context.beginPath(); context.rect(x-7, y-7, 12 + metrics.width+2, 14); if (paint && context.drawCustomFocusRing(element)) { context.strokeStyle = 'silver'; context.stroke(); } context.restore(); } function drawBase() { /* ... */ } function drawAs() { /* ... */ }

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

function drawBs() { /* ... */ } function redraw() { var canvas = document.getElementsByTagName('canvas')[0]; var context = canvas.getContext('2d'); context.clearRect(0, 0, canvas.width, canvas.height); drawCheckbox(context, document.getElementById('showA'), 20, 40, true); drawCheckbox(context, document.getElementById('showB'), 20, 60, true); drawBase(); if (document.getElementById('showA').checked) drawAs(); if (document.getElementById('showB').checked) drawBs(); } function processClick(event) { var canvas = document.getElementsByTagName('canvas')[0]; var context = canvas.getContext('2d'); var x = event.clientX; var y = event.clientY; var node = event.target; while (node) { x -= node.offsetLeft - node.scrollLeft; y -= node.offsetTop - node.scrollTop; node = node.offsetParent; } drawCheckbox(context, document.getElementById('showA'), 20, 40, false); if (context.isPointInPath(x, y)) document.getElementById('showA').checked = ! (document.getElementById('showA').checked); drawCheckbox(context, document.getElementById('showB'), 20, 60, false); if (context.isPointInPath(x, y)) document.getElementById('showB').checked = ! (document.getElementById('showB').checked); redraw(); } document.getElementsByTagName('canvas') [0].addEventListener('focus', redraw, true);

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

document.getElementsByTagName('canvas') [0].addEventListener('blur', redraw, true); document.getElementsByTagName('canvas') [0].addEventListener('change', redraw, true); document.getElementsByTagName('canvas') [0].addEventListener('click', processClick, false); redraw(); </script>

Drawing images To draw images, the drawImage method


can be used. context . drawImage (image, dx, dy) context . drawImage (image, dx, dy, dw, dh) context . drawImage (image, sx, sy, sw, sh, dx, dy, dw, dh) Draws the given image onto the canvas. The arguments are
interpreted as follows:

If the image isn't yet fully decoded, then nothing is drawn. If the image is a canvas with no
data, throws an InvalidStateError exception.

Hit regions

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

A hit region list is a list of hit regions for a


bitmap. Each hit region consists of the following information:

A set of pixels on the bitmap for which this


region is responsible. A bounding circumference on the
bitmap that surrounds the hit region's set of
pixels as they stood when it was
created.

Optionally, a non-empty string representing an ID for


distinguishing the
region from others.

Optionally, a reference to another region that acts as the parent for this one. A count of regions that have this one as their parent, known as the hit region's
child count.

A cursor specification, in the form


of either a CSS cursor value, or the string "
inherit" meaning that the
cursor of the hit region's parent, if any, or of the canvas element, if
not, is to be used instead.

Optionally, either a control, or an unbacked region description.


A control is just a reference to an
Element node, to which, in certain conditions, the user agent will route events,
and from which the user agent will determine the state of the hit region for the purposes of
accessibility tools. (The control is ignored when it is not a descendant of the
canvas element.) An unbacked region description
consists of the following:

Optionally, a label. An ARIA role, which, if the unbacked region description also has a label,
could be the empty string. context . addHitRegion(options) Adds a hit region to the bitmap. The argument is an object with the following members: path (default null) A Path object that describes the pixels that form part of the region. If this member is not provided or is set to null, the current default path is used instead. fillRule (default "nonzero")

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

The fill rule to use when determining which pixels are inside the path. id (default empty string) The ID to use for this region. This is used in MouseEvent events on the canvas (event.region) and as a way to
reference this region in later calls to addHitRegion() . parentID (default null) The ID of the parent region, for purposes of navigation by accessibility tools and for
cursor fallback. cursor (default "inherit") The cursor to use when the mouse is over this region. The value " inherit" means to use the cursor for the parent region (as specified by the
parentID member), if any, or to use the
canvas element's cursor if the region has no parent. control (default null) An element (that is a descendant of the canvas ) to which events are to be routed, and which accessibility tools are to use as a surrogate for describing and interacting
with this region. label (default null) A text label for accessibility tools to use as a description of this region, if there is no
control. role (default null) An ARIA role for accessibility tools to use to determine how to represent this region, if
there is no control. Hit regions can be used for a variety of purposes:

With an ID, they can make hit detection easier by having the user agent check
which region
the mouse is over and include the ID in the mouse events.

With a control, they can make routing events to DOM elements automatic,
allowing e.g.
clicks on a canvas to automatically submit a form via a button element.

With a label, they can make it easier for users to explore a canvas without
seeing it, e.g. by touch on a mobile device.

With a cursor, they can make it easier for different regions of the canvas to
have different cursors, with the user agent automatically switching between them. context . removeHitRegion(id) Removes a hit region (and all its descendants) from the canvas bitmap. The

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

argument is the ID
of a region added using addHitRegion() . The pixels that were covered by this region and its descendants are effectively cleared by
this operation, leaving the regions non-interactive. In particular, regions that occupied the
same pixels before the removed regions were added, overlapping them, do not resume their
previous role. The MouseEvent interface is extended to support hit
regions: event . region If the mouse was over a hit region, then this returns the hit region's ID, if it has one. Otherwise, returns null.

Pixel manipulation imagedata = context . createImageData(sw, sh) Returns an ImageData object with the given dimensions. All the pixels in the returned object are transparent black. Throws an IndexSizeError exception if the either of the width or height arguments are zero. imagedata = context . createImageData(imagedata) Returns an ImageData object with the same dimensions as the argument. All the
pixels in the returned object are transparent black. imagedata = context . createImageDataHD (sw, sh) Returns an ImageData object whose dimensions equal the dimensions given in the
arguments, multiplied by the number of pixels in the canvas bitmap that correspond to each
coordinate space unit. All the pixels in the returned object are transparent black. Throws an IndexSizeError exception if the either of the width or height arguments are zero. imagedata = context . getImageData(sx, sy, sw, sh) Returns an ImageData object containing the image data for the given rectangle of
the bitmap.

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

Throws an IndexSizeError exception if the either of the width or height arguments are zero. The data will be returned with one pixel of image data for each coordinate space unit on the
canvas (ignoring transforms). imagedata = context . getImageDataHD(sx, sy, sw, sh) Returns an ImageData object containing the image data for the given rectangle of
the bitmap. Throws an IndexSizeError exception if the either of the width or height arguments are zero. The data will be returned at the same resolution as the canvas bitmap. imagedata . width imagedata . height Returns the actual dimensions of the data in the ImageData object, in pixels. For objects returned by the non-HD variants of the methods in this API, this will correspond to
the dimensions given to the methods. For the HD variants, the number of pixels might be
different than the number of corresponding coordinate space units. imagedata . resolution Returns the theoretical number of pixels in the ImageData object's data per corresponding coordinate space unit. This value is automatically determined from the source
image when the ImageData object is created. It is only used to ensure that
ImageBitmap objects have the right pixel density when generated from
ImageData objects. imagedata . data Returns the one-dimensional array containing the data in RGBA order, as integers in the range
0 to 255. context . putImageData(imagedata, dx, dy [, dirtyX, dirtyY, dirtyWidth, dirtyHeight ]) Paints the data from the given ImageData object onto the bitmap. If a dirty rectangle is provided, only the pixels from that rectangle are painted. The globalAlpha and globalCompositeOperation attributes, as well as the shadow attributes, are ignored for the purposes of this method call; pixels in the
canvas are replaced wholesale, with no composition, alpha blending, no shadows, etc.

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

Throws a NotSupportedError exception if any of the arguments are not finite. Each pixel in the image data is mapped to one coordinate space unit on the bitmap, regardless
of the value of the resolution attribute. context . putImageDataHD (imagedata, dx, dy [, dirtyX, dirtyY, dirtyWidth, dirtyHeight ]) Paints the data from the given ImageData object onto the bitmap, at the bitmap's
native pixel density (regardless of the value of the ImageData object's resolution attribute). If a dirty rectangle is provided,
only the pixels from that rectangle are painted. The globalAlpha and globalCompositeOperation attributes, as
well as the shadow attributes, are ignored for the purposes of this method call; pixels in the
canvas are replaced wholesale, with no composition, alpha blending, no shadows, etc. Throws a NotSupportedError exception if any of the arguments are not finite. In the following example, the script generates an ImageData object so that it can
draw onto it. // canvas is a reference to a <canvas> element var context = canvas.getContext('2d'); // create a blank slate var data = context.createImageDataHD(canvas.width, canvas.height); // create some plasma FillPlasma(data, 'green'); // green plasma // add a cloud to the plasma AddCloud(data, data.width/2, data.height/2); // put a cloud in the middle // paint the plasma+cloud on the canvas context.putImageDataHD(data, 0, 0);

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

// support methods function FillPlasma(data, color) { ... } function AddCloud(data, x, y) { ... } Here is an example of using getImageDataHD() and putImageDataHD() to implement an edge detection
filter. <!DOCTYPE HTML> <html> <head> <title>Edge detection demo</title> <script> var image = new Image(); function init() { image.onload = demo; image.src = "image.jpeg"; } function demo() { var canvas = document.getElementsByTagName('canvas')[0]; var context = canvas.getContext('2d'); // draw the image onto the canvas context.drawImage(image, 0, 0); // get the image data to manipulate var input = context.getImageDataHD(0, 0, canvas.width, canvas.height); // get an empty slate to put the data into var output = context.createImageDataHD(canvas.width, canvas.height); // alias some variables for convenience // notice that we are using input.width and input.height here // as they might not be the same as canvas.width and canvas.height // (in particular, they might be different on high-res displays) var w = input.width, h = input.height; var inputData = input.data;
http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

var outputData = output.data; // edge detection for (var y = 1; y < h-1; y += 1) { for (var x = 1; x < w-1; x += 1) { for (var c = 0; c < 3; c += 1) { var i = (y*w + x)*4 + c; outputData[i] = 127 + -inputData[i - w*4 - 4] inputData[i - w*4] - inputData[i - w*4 + 4] + -inputData[i - 4] 8*inputData[i] - inputData[i + 4] + -inputData[i + w*4 - 4] inputData[i + w*4] - inputData[i + w*4 + 4]; } outputData[(y*w + x)*4 + 3] = 255; // alpha } } // put the image data back after manipulation context.putImageDataHD(output, 0, 0); } </script> </head> <body onload="init()"> <canvas></canvas> </body> </html> +

Compositing context . globalAlpha [ = value ] Returns the current alpha value applied to rendering operations. Can be set, to change the alpha value. Values outside of the range 0.0 .. 1.0 are ignored. context . globalCompositeOperation [ = value ] Returns the current composition operation, from the values defined in the Compositing and
Blending specification. .

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

Can be set, to change the composition operation. Unknown values are ignored.

Image smoothing context . imageSmoothingEnabled [ = value ] Returns whether pattern fills and the drawImage() method will attempt to smooth images if
their pixels don't line up exactly with the display, when scaling images up. Can be set, to change whether images are smoothed (true) or not (false).

Shadows All drawing operations are affected by the four global shadow attributes. context . shadowColor [ = value ] Returns the current shadow color. Can be set, to change the shadow color. Values that cannot be parsed as CSS colors are ignored. context . shadowOffsetX [ = value ] context . shadowOffsetY [ = value ] Returns the current shadow offset. Can be set, to change the shadow offset. Values that are not finite numbers are ignored. context . shadowBlur [ = value ] Returns the current level of blur applied to shadows. Can be set, to change the blur level. Values that are not finite numbers greater than or
equal to zero are ignored. If the current composition operation is copy, shadows
effectively won't render (since the shape will overwrite the shadow).

Best practices When a canvas is interactive, authors should include focusable elements in the
http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

element's
fallback content corresponding to each focusable part of the canvas, as in the example above. To indicate which focusable part of the canvas is currently focused, authors should use the
drawSystemFocusRing() method, passing it
the element for which a ring is being drawn. This method only draws the focus ring if the element
is focused, so that it can simply be called whenever drawing the element, without checking whether
the element is focused or not first. Authors should avoid implementing text editing controls using the canvas element.
Doing so has a large number of disadvantages:

Mouse placement of the caret has to be reimplemented. Keyboard movement of the caret has to be reimplemented (possibly across
lines, for multiline
text input).

Scrolling of the text field has to be implemented (horizontally for long lines,
vertically
for multiline input).

Native features such as copy-and-paste have to be reimplemented. Native features such as spell-checking have to be reimplemented. Native features such as drag-and-drop have to be reimplemented. Native features such as page-wide text search have to be reimplemented. Native features specific to the user, for example custom text services, have to
be
reimplemented. This is close to impossible since each user might have different services
installed, and there is an unbounded set of possible such services.

Bidirectional text editing has to be reimplemented. For multiline text editing, line wrapping has to be implemented for all relevant

languages.

Text selection has to be reimplemented. Dragging of bidirectional text selections has to be reimplemented. Platform-native keyboard shortcuts have to be reimplemented. Platform-native input method editors (IMEs) have to be reimplemented. Undo and redo functionality has to be reimplemented. Accessibility features such as magnification following the caret or selection
have to be
reimplemented. This is a huge amount of work, and authors are most strongly encouraged to avoid doing any of
it by instead using the input element, the textarea element, or the
contenteditable attribute.

Examples
http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

Here is an example of a script that uses canvas to draw pretty glowing lines. <canvas width="800" height="450"></canvas> <script> var context = document.getElementsByTagName('canvas') [0].getContext('2d'); var lastX = context.canvas.width * Math.random(); var lastY = context.canvas.height * Math.random(); var hue = 0; function line() { context.save(); context.translate(context.canvas.width/2, context.canvas.height/2); context.scale(0.9, 0.9); context.translate(-context.canvas.width/2, context.canvas.height/2); context.beginPath(); context.lineWidth = 5 + Math.random() * 10; context.moveTo(lastX, lastY); lastX = context.canvas.width * Math.random(); lastY = context.canvas.height * Math.random(); context.bezierCurveTo(context.canvas.width * Math.random(), context.canvas.height * Math.random(), context.canvas.width * Math.random(), context.canvas.height * Math.random(), lastX, lastY); hue = hue + 10 * Math.random(); context.strokeStyle = 'hsl(' + hue + ', 50%, 50%)'; context.shadowColor = 'white'; context.shadowBlur = 10; context.stroke(); context.restore(); }
http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

setInterval(line, 50); function blank() { context.fillStyle = 'rgba(0,0,0,0.1)'; context.fillRect(0, 0, context.canvas.width, context.canvas.height); } setInterval(blank, 40); </script> The 2D rendering context for canvas is often used for sprite-based games. The
following example demonstrates this:

Here is the source for this example: <!DOCTYPE HTML> <title>Blue Robot Demo</title> <base href="http://www.whatwg.org/demos/canvas/blue-robot/"> <style> html { overflow: hidden; min-height: 200px; min-width: 380px; } body { height: 200px; position: relative; margin: 8px; } .buttons { position: absolute; bottom: 0px; left: 0px; margin: 4px; } </style> <canvas width="380" height="200"></canvas> <script> var Landscape = function (context, width, height) { this.offset = 0; this.width = width;

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

this.advance = function (dx) { this.offset += dx; }; this.horizon = height * 0.7; // This creates the sky gradient (from a darker blue to white at the bottom) this.sky = context.createLinearGradient(0, 0, 0, this.horizon); this.sky.addColorStop(0.0, 'rgb(55,121,179)'); this.sky.addColorStop(0.7, 'rgb(121,194,245)'); this.sky.addColorStop(1.0, 'rgb(164,200,214)'); // this creates the grass gradient (from a darker green to a lighter green) this.earth = context.createLinearGradient(0, this.horizon, 0, height); this.earth.addColorStop(0.0, 'rgb(81,140,20)'); this.earth.addColorStop(1.0, 'rgb(123,177,57)'); this.paintBackground = function (context, width, height) { // first, paint the sky and grass rectangles context.fillStyle = this.sky; context.fillRect(0, 0, width, this.horizon); context.fillStyle = this.earth; context.fillRect(0, this.horizon, width, heightthis.horizon); // then, draw the cloudy banner // we make it cloudy by having the draw text off the top of the // canvas, and just having the blurred shadow shown on the canvas context.save(); context.translate(width-((this.offset+(this.width*3.2)) % (this.width*4.0))+0, 0); context.shadowColor = 'white'; context.shadowOffsetY = 30+this.horizon/3; // offset down on canvas context.shadowBlur = '5'; context.fillStyle = 'white'; context.textAlign = 'left'; context.textBaseline = 'top'; context.font = '20px sans-serif';

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

context.fillText('WHATWG ROCKS', 10, -30); // text up above canvas context.restore(); // then, draw the background tree context.save(); context.translate(width-((this.offset+(this.width*0.2)) % (this.width*1.5))+30, 0); context.beginPath(); context.fillStyle = 'rgb(143,89,2)'; context.lineStyle = 'rgb(10,10,10)'; context.lineWidth = 2; context.rect(0, this.horizon+5, 10, -50); // trunk context.fill(); context.stroke(); context.beginPath(); context.fillStyle = 'rgb(78,154,6)'; context.arc(5, this.horizon-60, 30, 0, Math.PI*2); // leaves context.fill(); context.stroke(); context.restore(); }; this.paintForeground = function (context, width, height) { // draw the box that goes in front context.save(); context.translate(width-((this.offset+(this.width*0.7)) % (this.width*1.1))+0, 0); context.beginPath(); context.rect(0, this.horizon - 5, 25, 25); context.fillStyle = 'rgb(220,154,94)'; context.lineStyle = 'rgb(10,10,10)'; context.lineWidth = 2; context.fill(); context.stroke(); context.restore(); }; }; </script> <script> var BlueRobot = function () {

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

this.sprites = new Image(); this.sprites.src = 'blue-robot.png'; // this sprite sheet has 8 cells this.targetMode = 'idle'; this.walk = function () { this.targetMode = 'walk'; }; this.stop = function () { this.targetMode = 'idle'; }; this.frameIndex = { 'idle': [0], // first cell is the idle frame 'walk': [1,2,3,4,5,6], // the walking animation is cells 1-6 'stop': [7], // last cell is the stopping animation }; this.mode = 'idle'; this.frame = 0; // index into frameIndex this.tick = function () { // this advances the frame and the robot // the return value is how many pixels the robot has moved this.frame += 1; if (this.frame >= this.frameIndex[this.mode].length) { // we've reached the end of this animation cycle this.frame = 0; if (this.mode != this.targetMode) { // switch to next cycle if (this.mode == 'walk') { // we need to stop walking before we decide what to do next this.mode = 'stop'; } else if (this.mode == 'stop') { if (this.targetMode == 'walk') this.mode = 'walk'; else this.mode = 'idle'; } else if (this.mode == 'idle') { if (this.targetMode == 'walk') this.mode = 'walk';

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

} } } if (this.mode == 'walk') return 8; return 0; }, this.paint = function (context, x, y) { if (!this.sprites.complete) return; // draw the right frame out of the sprite sheet onto the canvas // we assume each frame is as high as the sprite sheet // the x,y coordinates give the position of the bottom center of the sprite context.drawImage(this.sprites, this.frameIndex[this.mode][this.frame] * this.sprites.height, 0, this.sprites.height, this.sprites.height, x-this.sprites.height/2, ythis.sprites.height, this.sprites.height, this.sprites.height); }; }; </script> <script> var canvas = document.getElementsByTagName('canvas')[0]; var context = canvas.getContext('2d'); var landscape = new Landscape(context, canvas.width, canvas.height); var blueRobot = new BlueRobot(); // paint when the browser wants us to, using requestAnimationFrame() function paint() { context.clearRect(0, 0, canvas.width, canvas.height); landscape.paintBackground(context, canvas.width, canvas.height); blueRobot.paint(context, canvas.width/2, landscape.horizon*1.1); landscape.paintForeground(context, canvas.width, canvas.height);

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

requestAnimationFrame(paint); } paint(); // but tick every 150ms, so that we don't slow down when we don't paint setInterval(function () { var dx = blueRobot.tick(); landscape.advance(dx); }, 100); </script> <p class="buttons"> <input type=button value="Walk" onclick="blueRobot.walk()"> <input type=button value="Stop" onclick="blueRobot.stop()"> <footer> <small> Blue Robot Player Sprite by <a href="http://johncolburn.deviantart.com/">JohnColburn</a>. Licensed under the terms of the Creative Commons Attribution Share-Alike 3.0 Unported license.</small> <small> This work is itself licensed under a <a rel="license" href="http://creativecommons.org/licenses/bysa/3.0/">Creative Commons Attribution-ShareAlike 3.0 Unported License</a>. </small> </footer>

Pixel density
The user agent may use any square pixel density for the bitmaps of a canvas and
its rendering contexts. Once a canvas has a bitmap, that canvas must keep its
resolution for its lifetime. In general, user agents are encouraged to use a pixel density equal to the screen
pixel density. Ideally, the number of device pixels per CSS pixel would be a multiple of two.
Several factors can affect the screen pixel density: most prominently the actual display pixel
density, but also important is the current zoom level. All the bitmaps created during a single task for
canvas elements and CanvasRenderingContext2D objects must have the same
pixel density.

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

window . screen . canvasResolution Returns the pixel density that has been, or will be, used for bitmaps during this task.

Serializing bitmaps to a file


JPEG File Interchange Format, E. Hamilton. Arguments for serialization methods Type image/jpeg Other arguments The second argument is a number in the range 0.0 to 1.0
inclusive treated as the desired quality level. Reference [JPEG]

Common idioms without dedicated elements

The main part of the content


The main content of a page not including headers and footers, navigation links,
sidebars, advertisements, and so forth can be marked up in a variety of ways, depending on
the needs of the author. The simplest solution is to not mark up the main content at all, and just leave it as implicit.
Another way to think of this is that the body elements marks up the main content of
the page, and the bits that aren't main content are excluded through the use of more appropriate
elements like aside and nav. Here is a short Web page marked up along this minimalistic school of thought. The main content
is highlighted. Notice how all the other content in the body is marked up
with elements to indicate that it's not part of the main content, in this case
header , nav, and footer . <!DOCTYPE HTML>

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

<html> <head> <title> My Toys </title> </head> <body> <header> <h1>My toys</h1> </header> <nav> <p><a href="/">Home</a></p> <p><a href="/contact">Contact</a></p> </nav> <p>I really like my chained book and my telephone. I'm not such a fan of my big ball.</p> <p>Another toy I like is my mirror.</p> <footer> <p> copyright 2010 by the boy</p> </footer> </body> </html> If the main content is an independent unit of content that one could imagine syndicating
independently, then the article element would be appropriate to mark up the main
content of the document. The document in the previous example is here recast as a blog post: <!DOCTYPE HTML> <html> <head> <title> The Boy Blog: My Toys </title> </head> <body> <header> <h1>The Boy Blog</h1> </header> <nav> <p><a href="/">Home</a></p> <p><a href="/contact">Contact</a></p> </nav>

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

<article> <header> <h1>My toys</h1> <p>Published August 4th</p> </header> <p>I really like my chained book and my telephone. I'm not such a fan of my big ball.</p> <p>Another toy I like is my mirror.</p> </article> <footer> <p> copyright 2010 by the boy</p> </footer> </body> </html> If the main content is not an independent unit of content so much as a section of a larger
work, for instance a chapter, then the section element would be appropriate to mark
up the main content of the document. Here is the same document, but as a chapter in an online book: <!DOCTYPE HTML> <html> <head> <title> Chapter 2: My Toys The Book of the Boy </title> </head> <body> <header> <hgroup> <h1>The Book of the Boy</h1> <h2>A book about boy stuff</h2> </hgroup> </header> <nav> <p><a href="/">Front Page</a></p> <p><a href="/toc">Table of Contents</a></p> <p><a href="/c1">Chapter 1</a> <a href="/c3">Chapter 3</a></p> </nav> <section>

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

<h1>Chapter 2: My Toys</h1> <p>I really like my chained book and my telephone. I'm not such a fan of my big ball.</p> <p>Another toy I like is my mirror.</p> </section> </body> </html> If neither article nor section would be appropriate, but the main
content still needs an explicit element, for example for styling purposes, then the
main element can be used. This is the same as the original example, but using main for the main content instead of leaving it implied: <!DOCTYPE HTML> <html> <head> <title> My Toys </title> <style> body > main { background: navy; color: yellow; } </style> </head> <body> <header> <h1>My toys</h1> </header> <nav> <p><a href="/">Home</a></p> <p><a href="/contact">Contact</a></p> </nav> <main> <p>I really like my chained book and my telephone. I'm not such a fan of my big ball.</p> <p>Another toy I like is my mirror.</p> </main> <footer> <p> copyright 2010 by the boy</p> </footer>

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

</body> </html>

Bread crumb navigation


This specification does not provide a machine-readable way of describing bread-crumb navigation
menus. Authors are encouraged to just use a series of links in a paragraph. The nav
element can be used to mark the section containing these paragraphs as being navigation
blocks. In the following example, the current page can be reached via two paths. (" &gt;" is the "> " character.) <nav> <p> <a href="/">Main</a> &gt; <a href="/products/">Products</a> &gt; <a href="/products/dishwashers/">Dishwashers</a> &gt; <a>Second hand</a> </p> <p> <a href="/">Main</a> &gt; <a href="/second-hand/">Second hand</a> &gt; <a>Dishwashers</a> </p> </nav>

Tag clouds
This specification does not define any markup specifically for marking up lists of keywords that apply to a group of pages (also known as tag clouds). In general, authors
are encouraged to either mark up such lists using ul elements with explicit inline
counts that are then hidden and turned into a presentational effect using a style sheet, or to use
SVG. Here, three tags are included in a short tag cloud: <style> @media screen, print, handheld, tv {

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

/* should be ignored by non-visual browsers */ .tag-cloud > li > span { display: none; } .tag-cloud > li { display: inline; } .tag-cloud-1 { font-size: 0.7em; } .tag-cloud-2 { font-size: 0.9em; } .tag-cloud-3 { font-size: 1.1em; } .tag-cloud-4 { font-size: 1.3em; } .tag-cloud-5 { font-size: 1.5em; } } </style> ... <ul class="tag-cloud"> <li class="tag-cloud-4"><a title="28 instances" href="/t/apple">apple</a> <span>(popular)</span> <li class="tag-cloud-2"><a title="6 instances" href="/t/kiwi">kiwi</a> <span>(rare)</span> <li class="tag-cloud-5"><a title="41 instances" href="/t/pear">pear</a> <span>(very popular)</span> </ul> The actual frequency of each tag is given using the title
attribute. A CSS style sheet is provided to convert the markup into a cloud of differently-sized
words, but for user agents that do not support CSS or are not visual, the markup contains
annotations like "(popular)" or "(rare)" to categorize the various tags by frequency, thus
enabling all users to benefit from the information. The ul element is used (rather than ol ) because the order is not
particularly important: while the list is in fact ordered alphabetically, it would convey the
same information if ordered by, say, the length of the tag. The tag rel-keyword is
not used on these a elements because they do not represent tags that apply
to the page itself; they are just part of an index listing the tags themselves.

Conversations
This specification does not define a specific element for marking up conversations, meeting
minutes, chat transcripts, dialogues in screenplays, instant message logs, and other situations
where different players take turns

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

in discourse. Instead, authors are encouraged to mark up conversations using p elements and
punctuation. Authors who need to mark the speaker for styling purposes are encouraged to use
span or b . Paragraphs with their text wrapped in the i element can be used for marking up stage directions. This example demonstrates this using an extract from Abbot and Costello's famous sketch,
Who's on first: <p> Costello: Look, you gotta first baseman? <p> Abbott: Certainly. <p> Costello: Who's playing first? <p> Abbott: That's right. <p> Costello becomes exasperated. <p> Costello: When you pay off the first baseman every month, who gets the money? <p> Abbott: Every dollar of it. The following extract shows how an IM conversation log could be marked up, using the
data element to provide Unix timestamps for each line. Note that the timestamps are
provided in a format that the time element does not support, so the
data element is used instead (namely, Unix time_t timestamps).
Had the author wished to mark up the data using one of the date and time formats supported by the
time element, that element could have been used instead of data. This
could be advantageous as it would allow data analysis tools to detect the timestamps
unambiguously, without coordination with the page author. <p> <data value="1319898155">14:22</data> <b>egof</b> I'm not that nerdy, I've only seen 30% of the star trek episodes <p> <data value="1319898192">14:23</data> <b>kaj</b> if you know what percentage of the star trek episodes you have seen, you are inarguably nerdy <p> <data value="1319898200">14:23</data> <b>egof</b> it's unarguably <p> <data value="1319898228">14:23</data> <i>* kaj blinks</i> <p> <data value="1319898260">14:24</data> <b>kaj</b> you are not helping your case HTML does not have a good way to mark up graphs, so descriptions of interactive conversations
from games are more difficult to mark up. This
http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

example shows one possible convention using


dl elements to list the possible responses at each point in the conversation.
Another option to consider is describing the conversation in the form of a DOT file, and
outputting the result as an SVG image to place in the document. <p> Next, you meet a fisherman. You can say one of several greetings: <dl> <dt> "Hello there!" <dd> <p> He responds with "Hello, how may I help you?"; you can respond with: <dl> <dt> "I would like to buy a fish." <dd> <p> He sells you a fish and the conversation finishes. <dt> "Can I borrow your boat?" <dd> <p> He is surprised and asks "What are you offering in return?". <dl> <dt> "Five gold." (if you have enough) <dt> "Ten gold." (if you have enough) <dt> "Fifteen gold." (if you have enough) <dd> <p> He lends you his boat. The conversation ends. <dt> "A fish." (if you have one) <dt> "A newspaper." (if you have one) <dt> "A pebble." (if you have one) <dd> <p> "No thanks", he replies. Your conversation options at this point are the same as they were after asking to borrow his boat, minus any options you've suggested before. </dl> </dd> </dl> </dd> <dt> "Vote for me in the next election!" <dd> <p> He turns away. The conversation finishes. <dt> "Sir, are you aware that your fish are running away?"

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

<dd> <p> He looks at you skeptically and says "Fish cannot run, sir". <dl> <dt> "You got me!" <dd> <p> The fisherman sighs and the conversation ends. <dt> "Only kidding." <dd> <p> "Good one!" he retorts. Your conversation options at this point are the same as those following "Hello there!" above. <dt> "Oh, then what are they doing?" <dd> <p> He looks at his fish, giving you an opportunity to steal his boat, which you do. The conversation ends. </dl> </dd> </dl> In some games, conversations are simpler: each character merely has a fixed set of lines that
they say. In this example, a game FAQ/walkthrough lists some of the known possible responses for
each character: <section> <h1>Dialogue</h1> <p><small>Some characters repeat their lines in order each time you interact with them, others randomly pick from amongst their lines. Those who respond in order have numbered entries in the lists below.</small> <h2>The Shopkeeper</h2> <ul> <li>How may I help you? <li>Fresh apples! <li>A loaf of bread for madam? </ul> <h2>The pilot</h2> <p>Before the accident: <ul> </li>I'm about to fly out, sorry! </li>Sorry, I'm just waiting for flight clearance and then

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

I'll be off! </ul> <p>After the accident: <ol> <li>I'm about to fly out, sorry! <li>Ok, I'm not leaving right now, my plane is being cleaned. <li>Ok, it's not being cleaned, it needs a minor repair first. <li>Ok, ok, stop bothering me! Truth is, I had a crash. </ol> <h2>Clan Leader</h2> <p>During the first clan meeting: <ul> <li>Hey, have you seen my daughter? I bet she's up to something nefarious again... <li>Nice weather we're having today, eh? <li>The name is Bailey, Jeff Bailey. How can I help you today? <li>A glass of water? Fresh from the well! </ul> <p>After the earthquake: <ol> <li>Everyone is safe in the shelter, we just have to put out the fire! <li>I'll go and tell the fire brigade, you keep hosing it down! </ol> </section>

Footnotes
HTML does not have a dedicated mechanism for marking up footnotes. Here are the suggested
alternatives. For short inline annotations, the title attribute could be used. In this example, two parts of a dialogue are annotated with footnote-like content using the
title attribute.

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

<p> <b>Customer</b>: Hello! I wish to register a complaint. Hello. Miss? <p> <b>Shopkeeper</b>: <span title="Colloquial pronunciation of 'What do you'" >Watcha</span> mean, miss? <p> <b>Customer</b>: Uh, I'm sorry, I have a cold. I wish to make a complaint. <p> <b>Shopkeeper</b>: Sorry, <span title="This is, of course, a lie.">we're closing for lunch</span>. Unfortunately, relying on the title attribute is
currently discouraged as many user agents do not expose the attribute in an accessible manner as required by this specification (e.g. requiring a pointing device such as a mouse to cause a
tooltip to appear, which excludes keyboard-only users and touch-only users, such as anyone with a
modern phone or tablet). If the title attribute is used, CSS can used to
draw the reader's attention to the elements with the attribute. For example, the following CSS places a dashed line below elements that have a title attribute. [title] { border-bottom: thin dashed; } For longer annotations, the a element should be used, pointing to an element later
in the document. The convention is that the contents of the link be a number in square
brackets. In this example, a footnote in the dialogue links to a paragraph below the dialogue. The
paragraph then reciprocally links back to the dialogue, allowing the user to return to the
location of the footnote. <p> Announcer: Number 16: The <i>hand</i>. <p> Interviewer: Good evening. I have with me in the studio tonight Mr Norman St John Polevaulter, who for the past few years has been contradicting people. Mr Polevaulter, why <em>do</em> you contradict people? <p> Norman: I don't. <sup><a href="#fn1" id="r1">[1]</a> </sup>
http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

<p> Interviewer: You told me you did! ... <section> <p id="fn1"><a href="#r1">[1]</a> This is, naturally, a lie, but paradoxically if it were true he could not say so without contradicting the interviewer and thus making it false.</p> </section> For side notes, longer annotations that apply to entire sections of the text rather than just
specific words or sentences, the aside element should be used. In this example, a sidebar is given after a dialogue, giving it some context. <p> <span class="speaker">Customer</span>: I will not buy this record, it is scratched. <p> <span class="speaker">Shopkeeper</span>: I'm sorry? <p> <span class="speaker">Customer</span>: I will not buy this record, it is scratched. <p> <span class="speaker">Shopkeeper</span>: No no no, this's'a tobacconist's. <aside> <p>In 1970, the British Empire lay in ruins, and foreign nationalists frequented the streets many of them Hungarians (not the streets the foreign nationals). Sadly, Alexander Yalt has been publishing incompetently-written phrase books. </aside> For figures or tables, footnotes can be included in the relevant figcaption or caption element, or in surrounding prose. In this example, a table has cells with footnotes that are given in prose. A figure element is used to give a single legend to the combination of the table and
its footnotes. <figure> <figcaption>Table 1. Alternative activities for knights. </figcaption> <table> <tr>
http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

<th> Activity <th> Location <th> Cost <tr> <td> Dance <td> Wherever possible <td> 0<sup><a href="#fn1">1</a></sup> <tr> <td> Routines, chorus scenes<sup><a href="#fn2">2</a> </sup> <td> Undisclosed <td> Undisclosed <tr> <td> Dining<sup><a href="#fn3">3</a></sup> <td> Camelot <td> Cost of ham, jam, and spam<sup><a href="#fn4">4</a> </sup> </table> <p id="fn1">1. Assumed.</p> <p id="fn2">2. Footwork impeccable.</p> <p id="fn3">3. Quality described as "well".</p> <p id="fn4">4. A lot.</p> </figure>

Disabled elements
An element is said to be actually disabled if it
falls into one of the following categories:

button elements that are disabled input elements that are disabled select elements that are disabled textarea elements that are disabled optgroup elements that have a disabled attribute option elements that are disabled menuitem elements that have a disabled attribute fieldset elements that have a disabled attribute
This definition is used to determine what elements can be focused and which
http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

4.12.4 The canvas element HTML: The Living Standard - Edition for Web Developers

elements match the :disabled pseudo-class.

Up next

5 Microdata

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/the-canvas-element.html[4/16/2014 9:29:30 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
Microdata
Introduction
Overview
The basic syntax
Typed items
Global identifiers for items
Selecting names when defining vocabularies
Using the microdata DOM API
Encoding microdata
The microdata model
Items
Names: the itemprop attribute
Values
Microdata and other namespaces
Microdata DOM API
Sample microdata vocabularies
vCard
Conversion to vCard
Examples
vEvent
Conversion to iCalendar
Examples
Licensing works
Examples

5 MICRODATA

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

Introduction

Overview
Sometimes, it is desirable to annotate content with specific machine-readable labels, e.g. to
allow generic scripts to provide services that are customised to the page, or to enable content
from a variety of cooperating authors to be processed by a single script in a consistent
manner. For this purpose, authors can use the microdata features described in this section. Microdata
allows nested groups of name-value pairs to be added to documents, in parallel with the existing
content.

The basic syntax


At a high level, microdata consists of a group of name-value pairs. The groups are called items, and each name-value pair is a property. Items and properties
are represented by regular elements. To create an item, the itemscope attribute is used. To add a property to an item, the itemprop attribute is used
on one of the item's descendants. Here there are two items, each of which has the property "name": <div itemscope> <p>My name is <span itemprop="name">Elizabeth</span>.</p> </div> <div itemscope> <p>My name is <span itemprop="name">Daniel</span>.</p> </div> Markup without microdata attributes has no effect on microdata. These two examples are exactly equivalent, at a microdata level, as the previous two examples
respectively: <div itemscope>

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

<p>My <em>name</em> is <span itemprop="name">E<strong>liz</strong>abeth</span>.</p> </div> <section> <div itemscope> <aside> <p>My name is <span itemprop="name"><a href="/? user=daniel">Daniel</a></span>.</p> </aside> </div> </section> Properties generally have values that are strings. Here the item has three properties: <div itemscope> <p>My name is <span itemprop="name">Neil</span>.</p> <p>My band is called <span itemprop="band">Four Parts Water</span>.</p> <p>I am <span itemprop="nationality">British</span>.</p> </div> When a string value is a URL, it is expressed using the a element and
its href attribute, the img element and its
src attribute, or other elements that link to or embed external
resources. In this example, the item has one property, "image", whose value is a URL: <div itemscope> <img itemprop="image" src="google-logo.png" alt="Google"> </div> When a string value is in some machine-readable format unsuitable for human consumption, it is
expressed using the value attribute of the data element, with the human-readable version given in the element's contents. Here, there is an item with a property whose value is a product ID. The ID is not
human-friendly, so the product's name is used the human-visible text instead of the ID. <h1 itemscope>
http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

<data itemprop="product-id" value="9678AOU879">The Instigator 2000</data> </h1> For numeric data, the meter element and its value attribute can be used instead. Here a rating is given using a meter element. <div itemscope itemtype="http://schema.org/Product"> <span itemprop="name">Panasonic White 60L Refrigerator</span> <img src="panasonic-fridge-60l-white.jpg" alt=""> <div itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating"> <meter itemprop="ratingValue" min=0 value=3.5 max=5>Rated 3.5/5</meter> (based on <span itemprop="reviewCount">11</span> customer reviews) </div> </div> Similarly, for date- and time-related data, the time element and its datetime attribute can be used instead. In this example, the item has one property, "birthday", whose value is a date: <div itemscope> I was born on <time itemprop="birthday" datetime="2009-0510">May 10th 2009</time>. </div> Properties can also themselves be groups of name-value pairs, by putting the itemscope attribute on the element that declares the property. Items that are not part of others are called top-level microdata items. In this example, the outer item represents a person, and the inner one represents a band: <div itemscope> <p>Name: <span itemprop="name">Amanda</span></p>
http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

<p>Band: <span itemprop="band" itemscope> <span itemprop="name">Jazz Band</span> (<span itemprop="size">12</span> players)</span></p> </div> The outer item here has two properties, "name" and "band". The "name" is "Amanda", and the
"band" is an item in its own right, with two properties, "name" and "size". The "name" of the
band is "Jazz Band", and the "size" is "12". The outer item in this example is a top-level microdata item. Properties that are not descendants of the element with the itemscope attribute can be associated with the item using the itemref attribute.
This attribute takes a list of IDs of elements to crawl in addition to crawling the children of
the element with the itemscope attribute. This example is the same as the previous one, but all the properties are separated from their
items: <div itemscope id="amanda" itemref="a b"></div> <p id="a">Name: <span itemprop="name">Amanda</span></p> <div id="b" itemprop="band" itemscope itemref="c"></div> <div id="c"> <p>Band: <span itemprop="name">Jazz Band</span></p> <p>Size: <span itemprop="size">12</span> players</p> </div> This gives the same result as the previous example. The first item has two properties, "name",
set to "Amanda", and "band", set to another item. That second item has two further properties,
"name", set to "Jazz Band", and "size", set to "12". An item can have multiple properties with the same name and
different values. This example describes an ice cream, with two flavors: <div itemscope> <p>Flavors in my favorite ice cream:</p> <ul> <li itemprop="flavor">Lemon sorbet</li> <li itemprop="flavor">Apricot sorbet</li>

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

</ul> </div> This thus results in an item with two properties, both "flavor", having the values "Lemon
sorbet" and "Apricot sorbet". An element introducing a property can also introduce multiple properties at once, to avoid
duplication when some of the properties have the same value. Here we see an item with two properties, "favorite-color" and "favoritefruit", both set to
the value "orange": <div itemscope> <span itemprop="favorite-color favorite-fruit">orange</span> </div> It's important to note that there is no relationship between the microdata and the content of
the document where the microdata is marked up. There is no semantic difference, for instance, between the following two examples: <figure> <img src="castle.jpeg"> <figcaption><span itemscope><span itemprop="name">The Castle</span></span> (1986)</figcaption> </figure> <span itemscope><meta itemprop="name" content="The Castle"> </span> <figure> <img src="castle.jpeg"> <figcaption>The Castle (1986)</figcaption> </figure> Both have a figure with a caption, and both, completely unrelated to the figure, have an item
with a name-value pair with the name "name" and the value "The Castle". The only difference is
that if the user drags the caption out of the document, in the former case, the item will be
included in the dragand-drop data. In neither case is the image in any way associated with the item.

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

Typed items
The examples in the previous section show how information could be marked up on a page that
doesn't expect its microdata to be re-used. Microdata is most useful, though, when it is used in
contexts where other authors and readers are able to cooperate to make new uses of the markup. For this purpose, it is necessary to give each item a type,
such as "http://example.com/person", or "http://example.org/cat", or "http://band.example.net/".
Types are identified as URLs. The type for an item is given as the value of an itemtype attribute on the same element as the itemscope attribute. Here, the item's type is "http://example.org/animals#cat": <section itemscope itemtype="http://example.org/animals#cat"> <h1 itemprop="name">Hedral</h1> <p itemprop="desc">Hedral is a male american domestic shorthair, with a fluffy black fur with white paws and belly.</p> <img itemprop="img" src="hedral.jpeg" alt="" title="Hedral, age 18 months"> </section> In this example the "http://example.org/animals#cat" item has three properties, a "name"
("Hedral"), a "desc" ("Hedral is..."), and an "img" ("hedral.jpeg"). The type gives the context for the properties, thus selecting a vocabulary: a property named
"class" given for an item with the type "http://census.example/person" might refer to the economic
class of an individual, while a property named "class" given for an item with the type "http://example.com/school/teacher" might refer to the classroom a teacher has been assigned.
Several types can share a vocabulary. For example, the types "http://example.org/people/teacher " and " http://example.org/people/engineer " could be defined to use the same vocabulary
(though maybe some properties would not be especially useful in both cases, e.g. maybe the "http://example.org/people/engineer" type might not typically be used with the
"classroom " property). Multiple types defined to use the same vocabulary can
be given for a single item by listing the URLs as a space-separated list in the attribute' value.
An item cannot be given
http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

two types if they do not use the same vocabulary, however.

Global identifiers for items


Sometimes, an item gives information about a topic that has a
global identifier. For example, books can be identified by their ISBN number. Vocabularies (as identified by the itemtype attribute) can
be designed such that items get associated with their global
identifier in an unambiguous way by expressing the global identifiers as URLs given in an itemid attribute. The exact meaning of the URLs given in itemid attributes depends on the vocabulary used. Here, an item is talking about a particular book: <dl itemscope itemtype="http://vocab.example.net/book" itemid="urn:isbn:0-330-34032-8"> <dt>Title <dd itemprop="title">The Reality Dysfunction <dt>Author <dd itemprop="author">Peter F. Hamilton <dt>Publication date <dd><time itemprop="pubdate" datetime="1996-01-26">26 January 1996</time> </dl> The "http://vocab.example.net/book" vocabulary in this example would define that the itemid attribute takes a urn: URL pointing to the ISBN of the book.

Selecting names when defining vocabularies


Using microdata means using a vocabulary. For some purposes, an ad-hoc vocabulary is adequate.
For others, a vocabulary will need to be designed. Where possible, authors are encouraged to
re-use existing vocabularies, as this makes content re-use easier. When designing new vocabularies, identifiers can be created either using

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

URLs, or, for properties, as plain words (with no dots or colons). For URLs, conflicts with other vocabularies can be avoided by only using identifiers that correspond to
pages that the author has control over. For instance, if Jon and Adam both write content at example.com, at http://example.com/~jon/... and http://example.com/~adam/... respectively, then
they could select identifiers of the form "http://example.com/~jon/name" and "http://example.com/~adam/name"
respectively. Properties whose names are just plain words can only be used within the context of the types
for which they are intended; properties named using URLs can be reused in items of any type. If an
item has no type, and is not part of another item, then if its properties have names that are just
plain words, they are not intended to be globally unique, and are instead only intended for
limited use. Generally speaking, authors are encouraged to use either properties with globally
unique names (URLs) or ensure that their items are typed. Here, an item is an "http://example.org/animals#cat", and most of the properties have names
that are words defined in the context of that type. There are also a few additional properties
whose names come from other vocabularies. <section itemscope itemtype="http://example.org/animals#cat"> <h1 itemprop="name http://example.com/fn">Hedral</h1> <p itemprop="desc">Hedral is a male american domestic shorthair, with a fluffy <span itemprop="http://example.com/color">black</span> fur with <span itemprop="http://example.com/color">white</span> paws and belly.</p> <img itemprop="img" src="hedral.jpeg" alt="" title="Hedral, age 18 months"> </section> This example has one item with the type "http://example.org/animals#cat" and the following
properties: Property name Value Hedral

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

http://example.com/fn desc

Hedral Hedral is a male american domestic shorthair, with a fluffy black fur with white paws and belly.

http://example.com/color http://example.com/color img

black white .../hedral.jpeg

Using the microdata DOM API


The microdata becomes even more useful when scripts can use it to expose information to the
user, for example offering it in a form that can be used by other applications. The document.getItems(typeNames)
method provides access to the toplevel microdata items. It returns a
NodeList containing the items with the specified types, or all types if no argument
is specified. Each item is represented in the DOM by the element on which
the relevant itemscope attribute is found. These elements have
their element.itemScope IDL attribute set to true. The type(s) of items can be obtained using the element.itemType IDL attribute on the element with the itemscope attribute. This sample shows how the getItems() method can be
used to obtain a list of all the top-level microdata items of a particular type given in the document: var cats = document.getItems("http://example.com/feline"); Once an element representing an item has been obtained, its
properties can be extracted using the properties IDL
attribute. This attribute returns an HTMLPropertiesCollection, which can be
enumerated to go through each element that adds one or more properties to the item. It can also be
indexed by name, which will return an object with a list of the elements that add properties with
that name. Each element that adds a property also has an itemValue IDL
attribute that

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

returns its value. This sample gets the first item of type "http://example.net/user" and then pops up an alert
using the "name" property from that item. var user = document.getItems('http://example.net/user')[0]; alert('Hello ' + user.properties['name'][0].itemValue + '!'); The HTMLPropertiesCollection object, when indexed by name in this way, actually
returns a PropertyNodeList object with all the matching properties. The
PropertyNodeList object can be used to obtain all the values at once using
its getValues method, which returns
an array of all the values. In an earlier example, a "http://example.org/animals#cat" item had two "http://example.com/color" values. This script looks up the first such item and then lists all
its values. var cat = document.getItems('http://example.org/animals#cat') [0]; var colors = cat.properties['http://example.com/color'].getValues(); var result; if (colors.length == 0) { result = 'Color unknown.'; } else if (colors.length == 1) { result = 'Color: ' + colors[0]; } else { result = 'Colors:'; for (var i = 0; i < colors.length; i += 1) result += ' ' + colors[i]; } It's also possible to get a list of all the property names using the object's
names IDL attribute. This example creates a big list with a nested list for each item on the page, each with all of
the property names used in that item. var outer = document.createElement('ul'); var items = document.getItems(); for (var item = 0; item < items.length; item += 1) { var itemLi = document.createElement('li');

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

var inner = document.createElement('ul'); for (var name = 0; name < items[item].properties.names.length; name += 1) { var propLi = document.createElement('li'); propLi.appendChild(document.createTextNode(items[item].proper ties.names[name])); inner.appendChild(propLi); } itemLi.appendChild(inner); outer.appendChild(itemLi); } document.body.appendChild(outer); If faced with the following from an earlier example: <section itemscope itemtype="http://example.org/animals#cat"> <h1 itemprop="name http://example.com/fn">Hedral</h1> <p itemprop="desc">Hedral is a male american domestic shorthair, with a fluffy <span itemprop="http://example.com/color">black</span> fur with <span itemprop="http://example.com/color">white</span> paws and belly.</p> <img itemprop="img" src="hedral.jpeg" alt="" title="Hedral, age 18 months"> </section> ...it would result in the following output:

name http://example.com/fn desc http://example.com/color img


(The duplicate occurrence of "http://example.com/color" is not included in the list.)

Encoding microdata
http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

The microdata model


The microdata model consists of groups of name-value pairs known as items. Each group is known as an item. Each item can have item types, a global identifier (if the vocabulary specified by the item types support global identifiers for items), and a list of name-value pairs. Each name in the namevalue pair is
known as a property, and each property has one or more values. Each value is either a string or itself a group of name-value
pairs (an item). The names are unordered relative to each other,
but if a particular name has multiple values, they do have a relative order.

Items
Every HTML element may have an itemscope attribute specified. The itemscope attribute is a boolean attribute. An element with the itemscope attribute specified creates a
new item, a group of name-value pairs. Elements with an itemscope attribute may have an itemtype attribute specified, to give the item
types of the item. The itemtype attribute, if specified, must have a value that
is an unordered set of unique space-separated tokens that are
case-sensitive, each of which is a valid URL that is an absolute
URL, and all of which are defined to use the same vocabulary. The attribute's value must
have at least one token. The item types of an item are the tokens obtained
by splitting the element's itemtype attribute's value on spaces. If the itemtype attribute is missing or parsing it in this way finds no
tokens, the item is said to have no item types. The item types must all be types defined in applicable specifications and must all be defined to use the same
vocabulary. The itemtype attribute must not be specified on elements
that do not have an itemscope attribute specified. An item is said to be a typed item when either it
has an item type, or it is the value of a property of a typed item. The relevant types for a
typed item is the

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

item's item types,


if it has any, or else is the relevant types of the item for which it is a property's value. Elements with an itemscope attribute and an itemtype attribute that references a vocabulary that is defined to
support global identifiers for items may also have an itemid attribute specified, to give a global identifier for
the item, so that it can be related to other items on pages elsewhere on the Web. The itemid attribute, if specified, must have a value that is
a valid URL potentially surrounded by spaces. The global identifier of an item is the value of
its element's itemid attribute, if it has one, resolved relative to the element on which the attribute is specified. If the itemid attribute is missing or if resolving it fails, it
is said to have no global identifier. The itemid attribute must not be specified on elements that do
not have both an itemscope attribute and an itemtype attribute specified, and must not be specified on elements
with an itemscope attribute whose itemtype attribute specifies a vocabulary that does not support
global identifiers for items, as defined by that vocabulary's specification. The exact meaning of a global identifier is determined by the vocabulary's specification. It is up to such specifications to define whether multiple items with the same
global identifier (whether on the same page or on different pages) are allowed to exist, and what
the processing rules for that vocabulary are with respect to handling the case of multiple items
with the same ID. Elements with an itemscope attribute may have an itemref attribute specified, to give a list of additional
elements to crawl to find the name-value pairs of the item. The itemref attribute, if specified, must have a value that
is an unordered set of unique space-separated tokens that are
case-sensitive, consisting of IDs of elements in the
same home subtree. The itemref attribute must not be specified on elements that
do not have an itemscope attribute specified. The itemref attribute is not part of the
microdata data model. It is merely a syntactic construct to aid authors in adding annotations to
pages where the data to be annotated does not follow a convenient tree structure. For example, it
allows authors to mark up data in a table so that each column

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

defines a separate item, while keeping the properties in the cells. This example shows a simple vocabulary used to describe the products of a model railway
manufacturer. The vocabulary has just five property names: product-code An integer that names the product in the manufacturer's catalog. name A brief description of the product. scale One of "HO", "1", or "Z" (potentially with leading or trailing
whitespace), indicating the scale of the product. digital If present, one of "Digital", "Delta", or "Systems"
(potentially with leading or trailing whitespace) indicating that
the product has a digital decoder of the given type. track-type For track-specific products, one of "K", "M", "C" (potentially
with leading or trailing whitespace) indicating the type of track
for which the product is intended. This vocabulary has four defined item types: http://md.example.com/loco Rolling stock with an engine http://md.example.com/passengers Passenger rolling stock http://md.example.com/track Track pieces http://md.example.com/lighting Equipment with lighting Each item that uses this vocabulary can be given one or more
of these types, depending on what the product is. Thus, a locomotive might be marked up as: <dl itemscope itemtype="http://md.example.com/loco http://md.example.com/lighting"> <dt>Name: <dd itemprop="name">Tank Locomotive (DB 80)
http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

<dt>Product code: <dd itemprop="product-code">33041 <dt>Scale: <dd itemprop="scale">HO <dt>Digital: <dd itemprop="digital">Delta </dl> A turnout lantern retrofit kit might be marked up as: <dl itemscope itemtype="http://md.example.com/track http://md.example.com/lighting"> <dt>Name: <dd itemprop="name">Turnout Lantern Kit <dt>Product code: <dd itemprop="product-code">74470 <dt>Purpose: <dd>For retrofitting 2 <span itemprop="track-type">C</span> Track turnouts. <meta itemprop="scale" content="HO"> </dl> A passenger car with no lighting might be marked up as: <dl itemscope itemtype="http://md.example.com/passengers"> <dt>Name: <dd itemprop="name">Express Train Passenger Car (DB Am 203) <dt>Product code: <dd itemprop="product-code">8710 <dt>Scale: <dd itemprop="scale">Z </dl> Great care is necessary when creating new vocabularies. Often, a hierarchical approach to
types can be taken that results in a vocabulary where each item only ever has a single type,
which is generally much simpler to manage.

Names: the itemprop attribute

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

Every HTML element may have an itemprop attribute specified, if doing so adds one or more properties to one or more items (as defined below). The itemprop attribute, if specified, must have a value that
is an unordered set of unique space-separated tokens that are
case-sensitive, representing the names of the name-value pairs that it adds. The
attribute's value must have at least one token. Each token must be either:

If the item is a typed item: a defined property name allowed in this


situation
according to the specification that defines the relevant types for the
item, or

A valid URL that is an absolute URL defined as an item property


name
allowed in this situation by a vocabulary specification, or

A valid URL that is an absolute URL, used as a proprietary item


property
name (i.e. one used by the author for private purposes, not defined in a public
specification), or

If the item is not a typed item: a string that contains no U+002E FULL STOP
characters (.) and no U+003A COLON characters (:), used as a proprietary item property name (i.e.
one used by the author for private purposes, not defined in a public specification). Specifications that introduce defined property names
must ensure all such property names contain no U+002E FULL STOP characters (.), no U+003A COLON
characters (:), and no space characters. When an element with an itemprop attribute adds a property to multiple items,
the requirement above regarding the tokens applies for each item individually. The property names of an element are the tokens that the element's itemprop attribute is found to contain when its value is split on spaces, with the order preserved but with
duplicates removed (leaving only the first occurrence of each name). Within an item, the properties are unordered with respect to
each other, except for properties with the same name, which are ordered in the order they are
given by the algorithm that defines the properties of an item. In the following example, the "a" property has the values "1" and "2", in that order,
but whether the "a" property comes before the "b" property or not is not important:

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

<div itemscope> <p itemprop="a">1</p> <p itemprop="a">2</p> <p itemprop="b">test</p> </div> Thus, the following is equivalent: <div itemscope> <p itemprop="b">test</p> <p itemprop="a">1</p> <p itemprop="a">2</p> </div> As is the following: <div itemscope> <p itemprop="a">1</p> <p itemprop="b">test</p> <p itemprop="a">2</p> </div> And the following: <div id="x"> <p itemprop="a">1</p> </div> <div itemscope itemref="x"> <p itemprop="b">test</p> <p itemprop="a">2</p> </div>

Values
The property value of a name-value pair added by an
element with an itemprop attribute is as given for the first
matching case in the following list: If the element also has an itemscope attribute The value is the item created by the element.

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

If the element is a meta element The value is the value of the element's content attribute,
if any, or the empty string if there is no such attribute. If the element is an audio , embed , iframe,
img , source , track , or video element The value is the absolute URL that results from resolving the value of the element's src attribute relative to
the element at the time the attribute is set, or the empty string if there is no such attribute
or if resolving it results in an error. If the element is an a , area, or link element The value is the absolute URL that results from resolving the value of the element's href attribute relative
to the element at the time the attribute is set, or the empty string if there is no such
attribute or if resolving it results in an error. If the element is an object element The value is the absolute URL that results from resolving the value of the element's data attribute relative
to the element at the time the attribute is set, or the empty string if there is no such
attribute or if resolving it results in an error. If the element is a data element The value is the value of the element's value attribute,
if it has one, or the empty string otherwise. If the element is a meter element The value is the value of the element's value attribute,
if it has one, or the empty string otherwise. If the element is a time element The value is the element's datetime value. Otherwise The value is the element's textContent. The URL property elements are the a , area,
audio , embed , iframe, img , link ,
object, source , track , and video elements. If a property's value, as defined by the property's
definition, is an absolute URL, the property must be specified using a URL property element.

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

These requirements do not apply just because a property value happens to match the
syntax for a URL. They only apply if the property is explicitly defined as taking such a
value. For example, a book about the first moon landing could be
called "mission:moon". A "title" property from a vocabulary that defines a title as being a string
would not expect the title to be given in an a element, even though it looks like a
URL. On the other hand, if there was a (rather narrowly scoped!) vocabulary for
"books whose titles look like URLs" which had a "title" property defined to take a URL, then the
property would expect the title to be given in an a element (or one of the
other URL property elements), because of the requirement above.

Microdata and other namespaces


Currently, the itemscope , itemprop, and other microdata attributes are only defined for
HTML elements. This means that attributes with the literal names "itemscope ", "itemprop", etc, do not cause microdata
processing to occur on elements in other namespaces, such as SVG. Thus, in the following example there is only one item, not
two. <p itemscope></p> <!-- this is an item (with no properties and no type) --> <svg itemscope></svg> <!-- this is not, it's just an svg element with an invalid unknown attribute -->

Microdata DOM API


document . getItems( [ types ] ) Returns a NodeList of the elements in the Document that create
items, that are not part of other items, and that are of the types given in the argument, if any are
listed. The types argument is interpreted as a space-separated list of types. element . properties If the element has an itemscope attribute, returns an

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

HTMLPropertiesCollection object with all the element's properties. Otherwise, an


empty HTMLPropertiesCollection object. element . itemValue [ = value ] Returns the element's value. Can be set, to change the element's value.
Setting the value when the element has no itemprop attribute or when the element's value is an item throws an InvalidAccessError exception. In this example, a script checks to see if a particular element element is declaring a particular property, and if it is, it increments a counter: if (element.itemProp.contains('color')) count += 1; This script iterates over each of the values of an element's itemref attribute, calling a function for each referenced
element: for (var index = 0; index < element.itemRef.length; index += 1) process(document.getElementById(element.itemRef[index]));

Sample microdata vocabularies


The vocabularies in this section are primarily intended to demonstrate how a vocabulary is
specified, though they are also usable in their own right.

vCard
An item with the item type http://microformats.org/profile/hcard represents a person's or
organization's contact information. This vocabulary does not support global identifiers for items. The following are the type's defined property names.
They are based on the vocabulary defined in the vCard 4.0 specification and its extensions, where more information on how to interpret the values can be found.

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

kind Describes what kind of contact the item represents. The value must be text that, when compared in a
case-sensitive manner, is equal to one of the kind strings. A single property with the name kind may be present within
each item with the type http://microformats.org/profile/hcard . fn Gives the formatted text corresponding to the name of the person or organization. The value must be text. Exactly one property with the name fn must be present within
each item with the type http://microformats.org/profile/hcard . n Gives the structured name of the person or organization. The value must be an item with zero or more of each of the family-name, given-name , additional-name, honorific-prefix, and honorific-suffix properties. Exactly one property with the name n must be present within
each item with the type http://microformats.org/profile/hcard . family-name (inside n ) Gives the family name of the person, or the full name of the organization. The value must be text. Any number of properties with the name family-name may be present within the item that forms the value of the n property of
an item with the type http://microformats.org/profile/hcard . given-name (inside n ) Gives the given-name of the person. The value must be text. Any number of properties with the name given-name
may be present within the item that forms the value of the n property of
an item with the type http://microformats.org/profile/hcard .

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

additional-name (inside n ) Gives the any additional names of the person. The value must be text. Any number of properties with the name additional-name may be present within the item that forms the value of the n property of
an item with the type http://microformats.org/profile/hcard . honorific-prefix (inside n ) Gives the honorific prefix of the person. The value must be text. Any number of properties with the name honorific-prefix may be present within the item that forms the value of the n property of
an item with the type http://microformats.org/profile/hcard . honorific-suffix (inside n ) Gives the honorific suffix of the person. The value must be text. Any number of properties with the name honorific-suffix may be present within the item that forms the value of the n property of
an item with the type http://microformats.org/profile/hcard . nickname Gives the nickname of the person or organization. The nickname is the descriptive name given instead of or in addition to the one
belonging to a person, place, or thing. It can also be used to specify a familiar form of a
proper name specified by the fn or n properties. The value must be text. Any number of properties with the name nickname may be
present within each item with the type http://microformats.org/profile/hcard . photo Gives a photograph of the person or organization. The value must be an absolute
URL.

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

Any number of properties with the name photo may be


present within each item with the type http://microformats.org/profile/hcard . bday Gives the birth date of the person or organization. The value must be a valid date
string. A single property with the name bday may be present within
each item with the type http://microformats.org/profile/hcard . anniversary Gives the birth date of the person or organization. The value must be a valid date
string. A single property with the name anniversary may be
present within each item with the type http://microformats.org/profile/hcard . sex Gives the biological sex of the person. The value must be one of
F , meaning "female",
M , meaning "male",
N , meaning "none or not applicable", O, meaning "other", or
U , meaning "unknown". A single property with the name sex may be present within
each item with the type http://microformats.org/profile/hcard. gender-identity Gives the gender identity of the person. The value must be text. A single property with the name gender-identity
may be present within each item with the type http://microformats.org/profile/hcard . adr Gives the delivery address of the person or organization. The value must be an item with zero or more type,
post-office-box , extended-address, and street-address properties, and optionally a locality property, optionally a region property, optionally a postal-code property, and optionally a country-name property. If no type properties are present within an item that forms the value of an adr

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

property
of an item with the type http://microformats.org/profile/hcard , then the address type string work is
implied. Any number of properties with the name adr may be present
within each item with the type http://microformats.org/profile/hcard . type (inside adr ) Gives the type of delivery address. The value must be text that, when compared in a
case-sensitive manner, is equal to one of the address type
strings. Any number of properties with the name type may be
present within the item that forms the value of an adr property
of an item with the type http://microformats.org/profile/hcard , but within each such adr property item there must only
be one type property per distinct value. post-office-box (inside adr ) Gives the post office box component of the delivery address of the person or organization. The value must be text. Any number of properties with the name post-office-box may be present within the item that forms the value of an adr property
of an item with the type http://microformats.org/profile/hcard. The vCard specification urges authors not to use this field. extended-address (inside adr ) Gives an additional component of the delivery address of the person or organization. The value must be text. Any number of properties with the name extended-address may be present within the item that forms the value of an adr property
of an item with the type http://microformats.org/profile/hcard. The vCard specification urges authors not to use this field. street-address (inside adr ) Gives the street address component of the delivery address of the person or

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

organization. The value must be text. Any number of properties with the name street-address may be present within the item that forms the value of an adr property
of an item with the type http://microformats.org/profile/hcard. locality (inside adr ) Gives the locality component (e.g. city) of the delivery address of the person or
organization. The value must be text. A single property with the name locality may be
present within the item that forms the value of an adr property
of an item with the type http://microformats.org/profile/hcard . region (inside adr ) Gives the region component (e.g. state or province) of the delivery address of the person or
organization. The value must be text. A single property with the name region may be
present within the item that forms the value of an adr property
of an item with the type http://microformats.org/profile/hcard . postal-code (inside adr ) Gives the postal code component of the delivery address of the person or organization. The value must be text. A single property with the name postal-code may
be present within the item that forms the value of an adr property
of an item with the type http://microformats.org/profile/hcard . country-name (inside adr ) Gives the country name component of the delivery address of the person or organization. The value must be text. A single property with the name country-name
may be present within the

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

item that forms the value of an adr property


of an item with the type http://microformats.org/profile/hcard . tel Gives the telephone number of the person or organization. The value must be either text that can be
interpreted as a telephone number as defined in the CCITT specifications E.163 and X.121, or an
item with zero or more type properties and exactly one value property. If no type properties are present within an item that forms the value of a tel property
of an item with the type http://microformats.org/profile/hcard , or if the value of such a tel property is text, then the telephone type string
voice is implied. Any number of properties with the name tel may be present
within each item with the type http://microformats.org/profile/hcard . type (inside tel ) Gives the type of telephone number. The value must be text that, when compared in a
case-sensitive manner, is equal to one of the telephone type
strings. Any number of properties with the name type may be
present within the item that forms the value of a tel property
of an item with the type http://microformats.org/profile/hcard , but within each such tel property item there must only
be one type property per distinct value. value (inside tel ) Gives the actual telephone number of the person or organization. The value must be text that can be interpreted as
a telephone number as defined in the CCITT specifications E.163 and X.121. Exactly one property with the name value must be
present within the item that forms the value of a tel property
of an item with the type http://microformats.org/profile/hcard . email Gives the e-mail address of the person or organization. The value must be text.

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

Any number of properties with the name email may be


present within each item with the type http://microformats.org/profile/hcard . impp Gives a URL for instant messaging and presence protocol communications with the
person or organization. The value must be an absolute
URL. Any number of properties with the name impp may be present
within each item with the type http://microformats.org/profile/hcard . lang Gives a language understood by the person or organization. The value must be a valid BCP 47 language tag. . Any number of properties with the name lang may be present
within each item with the type http://microformats.org/profile/hcard . tz Gives the time zone of the person or organization. The value must be text and must match the
following syntax: 1. Either a U+002B PLUS SIGN character (+) or a U+002D HYPHEN-MINUS character (-). 2. A valid non-negative integer that is exactly two digits long and that
represents a number in the range 00..23. 3. A U+003A COLON character (:). 4. A valid non-negative integer that is exactly two digits long and that
represents a number in the range 00..59. Any number of properties with the name tz may be present
within each item with the type http://microformats.org/profile/hcard . geo Gives the geographical position of the person or organization. The value must be text and must match the
following syntax: 1. Optionally, either a U+002B PLUS SIGN character (+) or a U+002D HYPHEN-MINUS character
(-). 2. One or more ASCII digits. 3. Optionally*, a U+002E FULL STOP character (.) followed by one or more
http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

ASCII
digits. 4. A U+003B SEMICOLON character (;). 5. Optionally, either a U+002B PLUS SIGN character (+) or a U+002D HYPHEN-MINUS character
(-). 6. One or more ASCII digits. 7. Optionally*, a U+002E FULL STOP character (.) followed by one or more ASCII
digits. The optional components marked with an asterisk (*) should be included, and should have six
digits each. The value specifies latitude and longitude, in that order (i.e., "LAT LON" ordering), in decimal degrees. The longitude represents the location east and west of the prime
meridian as a positive or negative real number, respectively. The latitude represents the
location north and south of the equator as a positive or negative real number, respectively. Any number of properties with the name geo may be present
within each item with the type http://microformats.org/profile/hcard . title Gives the job title, functional position or function of the person or organization. The value must be text. Any number of properties with the name title may be
present within each item with the type http://microformats.org/profile/hcard . role Gives the role, occupation, or business category of the person or organization. The value must be text. Any number of properties with the name role may be present
within each item with the type http://microformats.org/profile/hcard . logo Gives the logo of the person or organization. The value must be an absolute
URL. Any number of properties with the name logo may be present
within each item with the type http://microformats.org/profile/hcard .

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

agent Gives the contact information of another person who will act on behalf of the person or
organization. The value must be either an item with the type http://microformats.org/profile/hcard , or an absolute URL,
or text. Any number of properties with the name agent may be
present within each item with the type http://microformats.org/profile/hcard . org Gives the name and units of the organization. The value must be either text or an item with one organization-name property and zero or more organization-unit properties. Any number of properties with the name org may be present
within each item with the type http://microformats.org/profile/hcard . organization-name (inside org ) Gives the name of the organization. The value must be text. Exactly one property with the name organization-name must be present within the item that forms the value of an org property
of an item with the type http://microformats.org/profile/hcard. organization-unit (inside org ) Gives the name of the organization unit. The value must be text. Any number of properties with the name organization-unit may be present within the item that forms the value of the org
property of an item with the type http://microformats.org/profile/hcard. member Gives a URL that represents a member of the group. The value must be an absolute
URL. Any number of properties with the name member may be
present within each item with the type http://microformats.org/profile/hcard if the item

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

also has a property with the name kind whose value is "group ". related Gives a relationship to another entity. The value must an item with one url
property and one rel properties. Any number of properties with the name orrelated may be
present within each item with the type http://microformats.org/profile/hcard . url (inside related ) Gives the URL for the related entity. The value must be an absolute
URL. Exactly one property with the name url must be present
within the item that forms the value of a related
property of an item with the type http://microformats.org/profile/hcard . rel (inside related ) Gives the relationship between the entity and the related entity. The value must be text that, when compared in a
case-sensitive manner, is equal to one of the relationship
strings. Exactly one property with the name rel must be present
within the item that forms the value of a related
property of an item with the type http://microformats.org/profile/hcard . categories Gives the name of a category or tag that the person or organization could be classified
as. The value must be text. Any number of properties with the name categories
may be present within each item with the type http://microformats.org/profile/hcard . note Gives supplemental information or a comment about the person or organization. The value must be text. Any number of properties with the name note may be present
within each

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

item with the type http://microformats.org/profile/hcard . rev Gives the revision date and time of the contact information. The value must be text that is a valid
global date and time string. The value distinguishes the current revision of the information for other renditions of the information. Any number of properties with the name rev may be present
within each item with the type http://microformats.org/profile/hcard . sound Gives a sound file relating to the person or organization. The value must be an absolute
URL. Any number of properties with the name sound may be
present within each item with the type http://microformats.org/profile/hcard . uid Gives a globally unique identifier corresponding to the person or organization. The value must be text. A single property with the name uid may be present within
each item with the type http://microformats.org/profile/hcard. url Gives a URL relating to the person or organization. The value must be an absolute
URL. Any number of properties with the name url may be present
within each item with the type http://microformats.org/profile/hcard . The kind strings are: individual Indicates a single entity (e.g. a person). group Indicates multiple entities (e.g. a mailing list).

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

org Indicates a single entity that is not a person (e.g. a company). location Indicates a geographical place (e.g. an office building). The address type strings are: home Indicates a delivery address for a residence. work Indicates a delivery address for a place of work. The telephone type strings are: home Indicates a residential number. work Indicates a telephone number for a place of work. text Indicates that the telephone number supports text messages (SMS). voice Indicates a voice telephone number. fax Indicates a facsimile telephone number. cell Indicates a cellular telephone number. video Indicates a video conferencing telephone number. pager Indicates a paging device telephone number. textphone Indicates a telecommunication device for people with hearing or speech

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

difficulties. The relationship strings are: emergency An emergency contact. agent Another entity that acts on behalf of this entity. contact acquaintance friend met worker colleague resident neighbor child parent sibling spouse kin muse crush date sweetheart me Has the meaning defined in XFN.

Conversion to vCard
Given a list of nodes nodes in a Document, a user agent must
run the following algorithm to extract any vCard data represented
by those nodes (only the first vCard is returned): 1. If none of the nodes in nodes are items with the item type http://microformats.org/profile/hcard , then there is no vCard. Abort the
algorithm, returning nothing.

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

2. Let node be the first node in nodes that is an


item with the item type http://microformats.org/profile/hcard . 3. Let output be an empty string. 4. Add a vCard line with the type "BEGIN " and the value
"VCARD" to output. 5. Add a vCard line with the type "PROFILE " and the value
"VCARD" to output. 6. Add a vCard line with the type "VERSION " and the value
"4.0" to output. 7. Add a vCard line with the type "SOURCE " and the result
of escaping the vCard text string that is the document's address as the
value to output. 8. If the title element is not null, add a vCard line
with the type " NAME" and with the result of escaping the vCard text
string obtained from the textContent of the title
element as the value to output. 9. Let sex be the empty string. 10. Let gender-identity be the empty string. 11. For each element element that is a property of the item node: for each name name in element's property names, run the
following substeps: 1. Let parameters be an empty set of name-value pairs. 2. Run the appropriate set of substeps from the following list. The steps will set a variable
value, which is used in the next step. If the property's value is an item subitem and name is
n 1. Let value be the empty string. 2. Append to value the result of collecting the first vCard
subproperty named family-name in subitem. 3. Append a U+003B SEMICOLON character (;) to value. 4. Append to value the result of collecting the first vCard
subproperty named given-name in subitem. 5. Append a U+003B SEMICOLON character (;) to value. 6. Append to value the result of collecting the first vCard
subproperty named additional-name in
subitem. 7. Append a U+003B SEMICOLON character (;) to value. 8. Append to value the result of collecting the first vCard
subproperty

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

named honorific-prefix
in subitem. 9. Append a U+003B SEMICOLON character (;) to value. 10. Append to value the result of collecting the first vCard
subproperty named honorific-suffix
in subitem. If the property's value is an item subitem and name is
adr 1. Let value be the empty string. 2. Append to value the result of collecting vCard
subproperties named post-office-box in subitem. 3. Append a U+003B SEMICOLON character (;) to value. 4. Append to value the result of collecting vCard
subproperties named extended-address in subitem. 5. Append a U+003B SEMICOLON character (;) to value. 6. Append to value the result of collecting vCard
subproperties named street-address
in subitem. 7. Append a U+003B SEMICOLON character (;) to value. 8. Append to value the result of collecting the first vCard
subproperty named locality in subitem. 9. Append a U+003B SEMICOLON character (;) to value. 10. Append to value the result of collecting the first vCard
subproperty named region in subitem. 11. Append a U+003B SEMICOLON character (;) to value. 12. Append to value the result of collecting the first vCard
subproperty named postal-code in subitem. 13. Append a U+003B SEMICOLON character (;) to value. 14. Append to value the result of collecting the first vCard
subproperty named country-name in
subitem. 15. If there is a property named type in subitem, and the first such property has a value that is not an item and whose value consists only of alphanumeric ASCII
characters, then add a parameter named "TYPE" whose value is
the value of that property to parameters. If the property's value is an item subitem and name is
org 1. Let value be the empty string.

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

2. Append to value the result of collecting the first vCard


subproperty named organization-name in subitem. 3. For each property named organization-unit in subitem, run the following steps: 1. If the value of the property is an
item, then skip this property. 2. Append a U+003B SEMICOLON character (;) to value. 3. Append the result of escaping the vCard text string given by the
value of the property to value. If the property's value is an item subitem with the item type http://microformats.org/profile/hcard
and name is related 1. Let value be the empty string. 2. If there is a property named url in subitem, and its element is a URL property element, then append the result of escaping the vCard text string given by the value of the first
such property to value, and add a parameter with the name " VALUE" and the value "URI" to parameters. 3. If there is a property named rel in subitem, and the first such property has a value that is not an item and whose value consists only of alphanumeric ASCII
characters, then add a parameter named " RELATION" whose value
is the value of that property to parameters. If the property's value is an item and name is none of the above 1. Let value be the result of collecting the first vCard
subproperty named value in subitem. 2. If there is a property named type in subitem, and the first such property has a value that is not an item and whose value consists only of alphanumeric ASCII
characters, then add a parameter named "TYPE" whose value is
the value of that property to parameters. If the property's value is not an item and its name is sex If this is the first such property to be found, set sex to the
property's value. If the property's value is not an item and its name is gender-identity If this is the first such property to be found, set gender-identity
to the property's value.

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

Otherwise (the property's value is not an


item) 1. Let value be the property's value. 2. If element is one of the URL property elements, add
a parameter with the name "VALUE " and the value "URI " to parameters. 3. Otherwise, if name is bday or
anniversary and the value is
a valid date string, add a parameter with the name "VALUE " and the value "DATE" to parameters. 4. Otherwise, if name is rev and
the value is a valid global date and time string, add a
parameter with the name "VALUE " and the value " DATE-TIME " to parameters. 5. Prefix every U+005C REVERSE SOLIDUS character (\) in value with another U+005C REVERSE SOLIDUS character (\). 6. Prefix every U+002C COMMA character (,) in value with a U+005C REVERSE SOLIDUS character (\). 7. Unless name is geo, prefix
every U+003B SEMICOLON character (;) in value with a U+005C REVERSE
SOLIDUS character (\). 8. Replace every U+000D CARRIAGE RETURN U+000A LINE FEED character pair (CRLF) in value with a U+005C REVERSE SOLIDUS character (\) followed by a U+006E LATIN
SMALL LETTER N character (n). 9. Replace every remaining U+000D CARRIAGE RETURN (CR) or U+000A LINE FEED (LF)
character in value with a U+005C REVERSE SOLIDUS character (\) followed
by a U+006E LATIN SMALL LETTER N character (n). 3. Add a vCard line with the type name, the parameters parameters, and the value value to output. 12. If either sex or gender-identity has a value that
is not the empty string, add a vCard line with the type "GENDER " and the value consisting of the concatenation of sex,
a U+003B SEMICOLON character (;), and genderidentity to output. 13. Add a vCard line with the type "END " and the value
"VCARD" to output. When the above algorithm says that the user agent is to add a vCard line

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

consisting
of a type type, optionally some parameters, and a value value to a string output, it must run the following steps: 1. Let line be an empty string. 2. Append type, converted to ASCII uppercase, to line. 3. If there are any parameters, then for each parameter, in the order that they were added, run
these substeps: 1. Append a U+003B SEMICOLON character (;) to line. 2. Append the parameter's name to line. 3. Append a U+003D EQUALS SIGN character (=) to line. 4. Append the parameter's value to line. 4. Append a U+003A COLON character (:) to line. 5. Append value to line. 6. Let maximum length be 75. 7. If and while line is longer than maximum length
Unicode code points long, run the following substeps: 1. Append the first maximum length Unicode code points of line to output. 2. Remove the first maximum length Unicode code points from line. 3. Append a U+000D CARRIAGE RETURN character (CR) to output. 4. Append a U+000A LINE FEED character (LF) to output. 5. Append a U+0020 SPACE character to output. 6. Let maximum length be 74. 8. Append (what remains of) line to output. 9. Append a U+000D CARRIAGE RETURN character (CR) to output. 10. Append a U+000A LINE FEED character (LF) to output. When the steps above require the user agent to obtain the result of collecting vCard
subproperties named subname in subitem, the user
agent must run the following steps:

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

1. Let value be the empty string. 2. For each property named subname in the item subitem,
run the following substeps: 1. If the value of the property is itself an
item, then skip this property. 2. If this is not the first property named subname in subitem (ignoring any that were skipped by the previous step), then append a
U+002C COMMA character (,) to value. 3. Append the result of escaping the vCard text string given by the value of the property to value. 3. Return value. When the steps above require the user agent to obtain the result of collecting the first
vCard subproperty named subname in subitem, the user
agent must run the following steps: 1. If there are no properties named subname in subitem, then abort these substeps, returning the empty string. 2. If the value of the first property named subname in subitem is an item, then abort these substeps, returning the empty string. 3. Return the result of escaping the vCard text string given by the value of the first property named subname in subitem. When the above algorithms say the user agent is to escape the vCard text string value, the user agent must use the
following steps: 1. Prefix every U+005C REVERSE SOLIDUS character (\) in value with
another U+005C REVERSE SOLIDUS character (\). 2. Prefix every U+002C COMMA character (,) in value with a U+005C REVERSE
SOLIDUS character (\). 3. Prefix every U+003B SEMICOLON character (;) in value with a U+005C REVERSE SOLIDUS character (\). 4. Replace every U+000D CARRIAGE RETURN U+000A LINE FEED character pair (CRLF) in value with a U+005C REVERSE SOLIDUS character (\) followed by a U+006E LATIN SMALL
LETTER N character (n). 5. Replace every remaining U+000D CARRIAGE RETURN (CR) or U+000A

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

LINE FEED (LF) character in


value with a U+005C REVERSE SOLIDUS character (\) followed by a U+006E LATIN
SMALL LETTER N character (n). 6. Return the mutated value. This algorithm can generate invalid vCard output, if the input does not conform to
the rules described for the http://microformats.org/profile/hcard
item type and defined property
names.

Examples
Here is a long example vCard for a fictional character called "Jack Bauer": <section id="jack" itemscope itemtype="http://microformats.org/profile/hcard"> <h1 itemprop="fn"> <span itemprop="n" itemscope> <span itemprop="given-name">Jack</span> <span itemprop="family-name">Bauer</span> </span> </h1> <img itemprop="photo" alt="" src="jack-bauer.jpg"> <p itemprop="org" itemscope> <span itemprop="organization-name">Counter-Terrorist Unit</span> (<span itemprop="organization-unit">Los Angeles Division</span>) </p> <p> <span itemprop="adr" itemscope> <span itemprop="street-address">10201 W. Pico Blvd.</span> <br> <span itemprop="locality">Los Angeles</span>, <span itemprop="region">CA</span> <span itemprop="postal-code">90064</span><br> <span itemprop="country-name">United States</span><br> </span> <span itemprop="geo">34.052339;-118.410623</span> </p>

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

<h2>Assorted Contact Methods</h2> <ul> <li itemprop="tel" itemscope> <span itemprop="value">+1 (310) 597 3781</span> <span itemprop="type">work</span> <meta itemprop="type" content="voice"> </li> <li><a itemprop="url" href="http://en.wikipedia.org/wiki/Jack_Bauer">I'm on Wikipedia</a> so you can leave a message on my user talk page.</li> <li><a itemprop="url" href="http://www.jackbauerfacts.com/">Jack Bauer Facts</a> </li> <li itemprop="email"><a href="mailto:j.bauer@la.ctu.gov.invalid">j.bauer@la.ctu.gov.i nvalid</a></li> <li itemprop="tel" itemscope> <span itemprop="value">+1 (310) 555 3781</span> <span> <meta itemprop="type" content="cell">mobile phone</span> </li> </ul> <ins datetime="2008-07-20 21:00:00+01:00"> <meta itemprop="rev" content="2008-07-20 21:00:00+01:00"> <p itemprop="tel" itemscope><strong>Update!</strong> My new <span itemprop="type">home</span> phone number is <span itemprop="value">01632 960 123</span>.</p> </ins> </section> The odd line wrapping is needed because newlines are meaningful in microdata: newlines would
be preserved in a conversion to, for example, the vCard format. This example shows a site's contact details (using the address element) containing an address with two street components: <address itemscope itemtype="http://microformats.org/profile/hcard"> <strong itemprop="fn"><span itemprop="n" itemscope><span itemprop="given-name">Alfred</span>

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

<span itemprop="family-name">Person</span></span></strong> <br> <span itemprop="adr" itemscope> <span itemprop="street-address">1600 Amphitheatre Parkway</span> <br> <span itemprop="street-address">Building 43, Second Floor</span> <br> <span itemprop="locality">Mountain View</span>, <span itemprop="region">CA</span> <span itemprop="postalcode">94043</span> </span> </address> The vCard vocabulary can be used to just mark up people's names: <span itemscope itemtype="http://microformats.org/profile/hcard" ><span itemprop=fn><span itemprop="n" itemscope><span itemprop="given-name" >George</span> <span itemprop="family-name">Washington</span> </span ></span></span> This creates a single item with a two name-value pairs, one with the name "fn" and the value
"George Washington", and the other with the name "n" and a second item as its value, the second
item having the two name-value pairs "given-name" and "family-name" with the values "George" and "Washington" respectively. This is defined to map to the following vCard: BEGIN:VCARD PROFILE:VCARD VERSION:4.0 SOURCE:document's address FN:George Washington N:Washington;George;;; END:VCARD

vEvent
An item with the item type

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

http://microformats.org/profile/hcalendar#vevent represents
an event. This vocabulary does not support global identifiers for items. The following are the type's defined property names.
They are based on the vocabulary defined in the iCalendar specification, where more information on
how to interpret the values can be found. Only the parts of the iCalendar vocabulary relating to events are used here; this
vocabulary cannot express a complete iCalendar instance.

attach Gives the address of an associated document for the event. The value must be an absolute
URL. Any number of properties with the name attach may be
present within each item with the type http://microformats.org/profile/hcalendar#vevent. categories Gives the name of a category or tag that the event could be classified as. The value must be text. Any number of properties with the name categories
may be present within each item with the type http://microformats.org/profile/hcalendar#vevent. class Gives the access classification of the information regarding the event. The value must be text with one of the following
values:

public private confidential


This is merely advisory and cannot be considered a confidentiality
measure. A single property with the name class may be present
within each item with the type http://microformats.org/profile/hcalendar#vevent.

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

comment Gives a comment regarding the event. The value must be text. Any number of properties with the name comment may be
present within each item with the type http://microformats.org/profile/hcalendar#vevent. description Gives a detailed description of the event. The value must be text. A single property with the name description may be
present within each item with the type http://microformats.org/profile/hcalendar#vevent. geo Gives the geographical position of the event. The value must be text and must match the
following syntax: 1. Optionally, either a U+002B PLUS SIGN character (+) or a U+002D HYPHEN-MINUS character
(-). 2. One or more ASCII digits. 3. Optionally*, a U+002E FULL STOP character (.) followed by one or more ASCII
digits. 4. A U+003B SEMICOLON character (;). 5. Optionally, either a U+002B PLUS SIGN character (+) or a U+002D HYPHEN-MINUS character
(-). 6. One or more ASCII digits. 7. Optionally*, a U+002E FULL STOP character (.) followed by one or more ASCII
digits. The optional components marked with an asterisk (*) should be included, and should have six
digits each. The value specifies latitude and longitude, in that order (i.e., "LAT LON" ordering), in decimal degrees. The longitude represents the location east and west of the prime
meridian as a positive or negative real number, respectively. The latitude represents the
location north and south of the equator as a positive or negative real number, respectively.

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

A single property with the name geo may be present within


each item with the type http://microformats.org/profile/hcalendar#vevent. location Gives the location of the event. The value must be text. A single property with the name location may be
present within each item with the type http://microformats.org/profile/hcalendar#vevent. resources Gives a resource that will be needed for the event. The value must be text. Any number of properties with the name resources may
be present within each item with the type http://microformats.org/profile/hcalendar#vevent. status Gives the confirmation status of the event. The value must be text with one of the following
values:

tentative confirmed cancelled


A single property with the name status may be present
within each item with the type http://microformats.org/profile/hcalendar#vevent. summary Gives a short summary of the event. The value must be text. User agents should replace U+000A LINE FEED (LF) characters in the value by U+0020 SPACE characters when using the value. A single property with the name summary may be present
within each item with the type http://microformats.org/profile/hcalendar#vevent. dtend Gives the date and time by which the event ends.

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

If the property with the name dtend is present within an


item with the type http://microformats.org/profile/hcalendar#vevent that has a property
with the name dtstart whose value is a valid date
string, then the value of the property with
the name dtend must be text that is a valid date string also. Otherwise, the value of the
property must be text that is a valid global date and time string. In either case, the value be later in time than
the value of the dtstart property of the same item. The time given by the dtend property is not
inclusive. For day-long events, therefore, the dtend
property's value will be the day after the
end of the event. A single property with the name dtend may be present
within each item with the type http://microformats.org/profile/hcalendar#vevent, so long as that http://microformats.org/profile/hcalendar#vevent does not have a
property with the name duration. dtstart Gives the date and time at which the event starts. The value must be text that is either a
valid date string or a valid global date and time string. Exactly one property with the name dtstart must be
present within each item with the type http://microformats.org/profile/hcalendar#vevent. duration Gives the duration of the event. The value must be text that is a valid
vevent duration string. The duration represented is the sum of all the durations represented by integers in the
value. A single property with the name duration may be
present within each item with the type http://microformats.org/profile/hcalendar#vevent, so long as that http://microformats.org/profile/hcalendar#vevent does not have a
property with the name dtend . transp

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

Gives whether the event is to be considered as consuming time on a calendar, for the purpose
of free-busy time searches. The value must be text with one of the following
values:

opaque transparent
A single property with the name transp may be present
within each item with the type http://microformats.org/profile/hcalendar#vevent. contact Gives the contact information for the event. The value must be text. Any number of properties with the name contact may be
present within each item with the type http://microformats.org/profile/hcalendar#vevent. url Gives a URL for the event. The value must be an absolute
URL. A single property with the name url may be present within
each item with the type http://microformats.org/profile/hcalendar#vevent. uid Gives a globally unique identifier corresponding to the event. The value must be text. A single property with the name uid may be present within
each item with the type http://microformats.org/profile/hcalendar#vevent. exdate Gives a date and time at which the event does not occur despite the recurrence rules. The value must be text that is either a
valid date string or a valid global date and time string. Any number of properties with the name exdate may be
present within each item with the type

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

http://microformats.org/profile/hcalendar#vevent. exrule Gives a rule for finding dates and times at which the event does not occur despite the
recurrence rules. The value must be text that matches the RECUR
value type defined in the iCalendar specification. [RFC2445] Any number of properties with the name exrule may be
present within each item with the type http://microformats.org/profile/hcalendar#vevent. rdate Gives a date and time at which the event recurs. The value must be text that is one of the
following:

A valid date string. A valid global date and time string. A valid global date and time string followed by a U+002F SOLIDUS character
(/)
followed by a second valid global date and time string representing a later time.

A valid global date and time string followed by a U+002F SOLIDUS character
(/)
followed by a valid vevent duration string. Any number of properties with the name rdate may be
present within each item with the type http://microformats.org/profile/hcalendar#vevent. rrule Gives a rule for finding dates and times at which the event occurs. The value must be text that matches the RECUR
value type defined in the iCalendar specification. [RFC2445] Any number of properties with the name rrule may be
present within each item with the type http://microformats.org/profile/hcalendar#vevent. created Gives the date and time at which the event information was first created in a calendaring
system.

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

The value must be text that is a valid


global date and time string. A single property with the name created may be present
within each item with the type http://microformats.org/profile/hcalendar#vevent. last-modified Gives the date and time at which the event information was last modified in a calendaring
system. The value must be text that is a valid
global date and time string. A single property with the name last-modified
may be present within each item with the type http://microformats.org/profile/hcalendar#vevent. sequence Gives a revision number for the event information. The value must be text that is a valid
non-negative integer. A single property with the name sequence may be
present within each item with the type http://microformats.org/profile/hcalendar#vevent. A string is a valid vevent duration string if it matches the following pattern: 1. A U+0050 LATIN CAPITAL LETTER P character (P). 2. One of the following:

A valid non-negative integer followed by a U+0057 LATIN CAPITAL


LETTER W
character (W). The integer represents a duration of that number of weeks.

At least one, and possible both in this order, of the following: A valid non-negative integer followed by a U+0044 LATIN CAPITAL
LETTER D
character (D). The integer represents a duration of that number of days.

A U+0054 LATIN CAPITAL LETTER T character (T) followed by any


one of the following, or
the first and second of the following in that order, or the second and third of the following
in that order, or all three of the following in this order:

A valid non-negative integer followed by a U+0048 LATIN CAPITAL


LETTER H
character (H). The integer represents a duration of that number of hours.

A valid non-negative integer followed by a U+004D LATIN CAPITAL


LETTER M
character (M). The integer represents a duration of that

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

number of minutes.

A valid non-negative integer followed by a U+0053 LATIN CAPITAL


LETTER S
character (S). The integer represents a duration of that number of seconds.

Conversion to iCalendar
Given a list of nodes nodes in a Document, a user agent must
run the following algorithm to extract any vEvent data
represented by those nodes: 1. If none of the nodes in nodes are items with the type http://microformats.org/profile/hcalendar#vevent, then there is no vEvent data. Abort the algorithm, returning nothing. 2. Let output be an empty string. 3. Add an iCalendar line with the type "BEGIN " and the
value "VCALENDAR " to output. 4. Add an iCalendar line with the type "PRODID " and the
value equal to a useragent-specific string representing the user agent to output. 5. Add an iCalendar line with the type "VERSION " and the
value "2.0 " to output. 6. For each node node in nodes that is an item with the type http://microformats.org/profile/hcalendar#vevent, run the following
steps: 1. Add an iCalendar line with the type "BEGIN " and the
value "VEVENT " to output. 2. Add an iCalendar line with the type "DTSTAMP " and a
value consisting of an iCalendar DATE-TIME string representing the current date and time, with the annotation "VALUE=DATE-TIME", to output. [RFC2445] 3. For each element element that is a property of the item node: for each name name in element's property names, run the
appropriate set of substeps from the following list: If the property's value is an item Skip the property. If the property is dtend

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

If the property is dtstart If the property is exdate If the property is rdate If the property is created If the property is last-modified Let value be the result of stripping all U+002D HYPHEN-MINUS (-) and U+003A COLON (:) characters from the property's value. If the property's value is a valid date
string then add an iCalendar line with the type name
and the value value to output, with the annotation
" VALUE=DATE ". Otherwise, if the property's value is a
valid global date and time string then add an iCalendar line with
the type name and the value value to output, with the annotation "VALUE=DATE-TIME". Otherwise skip the property. Otherwise Add an iCalendar line with the type name and the
property's value to output. 4. Add an iCalendar line with the type "END " and the
value "VEVENT " to output. 7. Add an iCalendar line with the type "END " and the value
"VCALENDAR " to output. When the above algorithm says that the user agent is to add an iCalendar line consisting of a type type, a value value, and optionally
an annotation, to a string output, it must run the following steps: 1. Let line be an empty string. 2. Append type, converted to ASCII uppercase, to line. 3. If there is an annotation: 1. Append a U+003B SEMICOLON character (;) to line. 2. Append the annotation to line. 4. Append a U+003A COLON character (:) to line. 5. Prefix every U+005C REVERSE SOLIDUS character (\) in value with
another U+005C REVERSE SOLIDUS character (\).

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

6. Prefix every U+002C COMMA character (,) in value with a U+005C REVERSE
SOLIDUS character (\). 7. Prefix every U+003B SEMICOLON character (;) in value with a U+005C REVERSE SOLIDUS character (\). 8. Replace every U+000D CARRIAGE RETURN U+000A LINE FEED character pair (CRLF) in value with a U+005C REVERSE SOLIDUS character (\) followed by a U+006E LATIN SMALL
LETTER N character (n). 9. Replace every remaining U+000D CARRIAGE RETURN (CR) or U+000A LINE FEED (LF) character in
value with a U+005C REVERSE SOLIDUS character (\) followed by a U+006E LATIN
SMALL LETTER N character (n). 10. Append value to line. 11. Let maximum length be 75. 12. If and while line is longer than maximum length
Unicode code points long, run the following substeps: 1. Append the first maximum length Unicode code points of line to output. 2. Remove the first maximum length Unicode code points from line. 3. Append a U+000D CARRIAGE RETURN character (CR) to output. 4. Append a U+000A LINE FEED character (LF) to output. 5. Append a U+0020 SPACE character to output. 6. Let maximum length be 74. 13. Append (what remains of) line to output. 14. Append a U+000D CARRIAGE RETURN character (CR) to output. 15. Append a U+000A LINE FEED character (LF) to output. This algorithm can generate invalid iCalendar output, if the input does not conform to the rules described for the http://microformats.org/profile/hcalendar#vevent item type and defined property names.

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

Examples
Here is an example of a page that uses the vEvent vocabulary to mark up an event: <body itemscope itemtype="http://microformats.org/profile/hcalendar#vevent"> ... <h1 itemprop="summary">Bluesday Tuesday: Money Road</h1> ... <time itemprop="dtstart" datetime="2009-05-05T19:00:00Z">May 5th @ 7pm</time> (until <time itemprop="dtend" datetime="2009-0505T21:00:00Z">9pm</time>) ... <a href="http://livebrum.co.uk/2009/05/05/bluesday-tuesdaymoney-road" rel="bookmark" itemprop="url">Link to this page</a> ... <p>Location: <span itemprop="location">The RoadHouse</span> </p> ... <p><input type=button value="Add to Calendar" onclick="location = getCalendar(this)"></p> ... <meta itemprop="description" content="via livebrum.co.uk"> </body> The "getCalendar()" method could look like
this: function getCalendar(node) { // This function assumes the content is valid. // It is not a compliant implementation of the algorithm for extracting vEvent data. while (node && (!node.itemScope || !node.itemType.contains('http://microformats.org/profile/hcal endar#vevent'))) node = node.parentNode; if (!node) { alert('No event data found.'); return;

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

} var stamp = new Date(); var stampString = '' + stamp.getUTCFullYear() + (stamp.getUTCMonth() + 1) + stamp.getUTCDate() + 'T' + stamp.getUTCHours() + stamp.getUTCMinutes() + stamp.getUTCSeconds() + 'Z'; var calendar = 'BEGIN:VCALENDAR\r\nPRODID:HTML\r\nVERSION:2.0\r\nBEGIN:VEVEN T\r\nDTSTAMP:' + stampString + '\r\n'; for (var propIndex = 0; propIndex < node.properties.length; propIndex += 1) { var prop = node.properties[propIndex]; var value = prop.itemValue; var parameters = ''; if (prop.localName == 'time') { value = value.replace(/[:-]/g, ''); if (value.match(/T/)) parameters = ';VALUE=DATE'; else parameters = ';VALUE=DATE-TIME'; } else { value = value.replace(/\\/g, '\\n'); value = value.replace(/;/g, '\\;'); value = value.replace(/,/g, '\\,'); value = value.replace(/\n/g, '\\n'); } for (var nameIndex = 0; nameIndex < prop.itemProp.length; nameIndex += 1) { var name = prop.itemProp[nameIndex]; if (!name.match(/:/) && !name.match(/\./)) calendar += name.toUpperCase() + parameters + ':' + value + '\r\n'; } } calendar += 'END:VEVENT\r\nEND:VCALENDAR\r\n'; return 'data:text/calendar;component=vevent,' + encodeURI(calendar); } The same page could offer some markup, such as the following,
for copyand-pasting into blogs:
http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

<div itemscope itemtype="http://microformats.org/profile/hcalendar#vevent"> <p>I'm going to <strong itemprop="summary">Bluesday Tuesday: Money Road</strong>, <time itemprop="dtstart" datetime="2009-05-05T19:00:00Z">May 5th at 7pm</time> to <time itemprop="dtend" datetime="2009-0505T21:00:00Z">9pm</time>, at <span itemprop="location">The RoadHouse</span>!</p> <p><a href="http://livebrum.co.uk/2009/05/05/bluesdaytuesday-money-road" itemprop="url">See this event on livebrum.co.uk</a>. </p> <meta itemprop="description" content="via livebrum.co.uk"> </div>

Licensing works
An item with the item type http://n.whatwg.org/work represents a work (e.g. an article, an
image, a video, a song, etc). This type is primarily intended to allow authors to include
licensing information for works. The following are the type's defined property
names. work Identifies the work being described. The value must be an absolute
URL. Exactly one property with the name work must be present
within each item with the type http://n.whatwg.org/work. title Gives the name of the work. A single property with the name title may be present
within each item with the type http://n.whatwg.org/work. author

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

Gives the name or contact information of one of the authors or creators of the work. The value must be either an item with the type http://microformats.org/profile/hcard , or text. Any number of properties with the name author may be
present within each item with the type http://n.whatwg.org/work. license Identifies one of the licenses under which the work is available. The value must be an absolute
URL. Any number of properties with the name license may be
present within each item with the type http://n.whatwg.org/work.

Examples
This example shows an embedded image entitled My Pond, licensed under the
Creative Commons Attribution-Share Alike 3.0 United States License and the MIT license
simultaneously. <figure itemscope itemtype="http://n.whatwg.org/work"> <img itemprop="work" src="mypond.jpeg"> <figcaption> <p><cite itemprop="title">My Pond</cite></p> <p><small>Licensed under the <a itemprop="license" href="http://creativecommons.org/licenses/bysa/3.0/us/">Creative Commons Attribution-Share Alike 3.0 United States License</a> and the <a itemprop="license" href="http://www.opensource.org/licenses/mitlicense.php">MIT license</a>.</small> </figcaption> </figure>

Up next

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

5 Microdata HTML: The Living Standard - Edition for Web Developers

6 Loading Web pages

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/microdata.html[4/16/2014 9:29:42 PM]

6 Loading Web pages HTML: The Living Standard - Edition for Web Developers

W HATW G

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
Loading Web pages
Browsing contexts
Nested browsing contexts
Navigating nested browsing contexts in the DOM
Auxiliary browsing contexts
Navigating auxiliary browsing contexts in the DOM
Secondary browsing contexts
Browsing context names
The Window object
APIs for creating and navigating browsing contexts by name
Accessing other browsing contexts
Named access on the Window object
Closing browsing contexts
Browser interface elements

LOADING WEB PAGES

Browsing contexts
A browsing context is an environment in which Document objects are presented to the user. A tab or window in a Web browser typically contains a browsing
context, as does an iframe. Each browsing context has a corresponding WindowProxy object. A browsing context has a session history, which lists the
Document objects that that browsing context has presented, is
presenting, or will present. At any time, one Document in each browsing
context is designated the active document. A Document's
browsing context is that browsing context whose session
history contains the Document, if any. (A Document created using
an API such as createDocument() has no
browsing context.) Each Document in a browsing context is associated with a Window object. A browsing context's WindowProxy object forwards everything to the
browsing context's active document's Window object.

http://developers.whatwg.org/browsers.html[4/16/2014 9:29:53 PM]

6 Loading Web pages HTML: The Living Standard - Edition for Web Developers

In general, there is a 1-to-1 mapping from the Window object to the


Document object. There are two exceptions. First, a Window can be reused
for the presentation of a second Document in the same browsing context,
such that the mapping is then 1-to-2. This occurs when a browsing context is navigated from the initial about:blank Document
to another, with replacement enabled. Second, a Document can end up
being reused for several Window objects when the document.open() method is used, such that the mapping is then
many-to-1. A Document does not necessarily have a browsing context
associated with it. In particular, data mining tools are likely to never instantiate browsing contexts. A browsing context can have a creator browsing context, the
browsing context that was responsible for its creation. If a browsing
context has a parent browsing context, then that is its creator browsing
context. Otherwise, if the browsing context has an opener browsing
context, then that is its creator browsing context. Otherwise, the
browsing context has no creator browsing context. If a browsing context A has a creator browsing
context, then the Document that was the active document of that
creator browsing context at the time A was created is the
creator Document.

Nested browsing contexts


Certain elements (for example, iframe elements) can instantiate further browsing contexts. These are called nested browsing contexts. If a browsing context P has a
Document D with an element E that nests
another browsing context C inside it, then C is said to be
nested through D, and E is said to be the browsing context container of C.
If the browsing context container element E is in the Document D, then P is
said to be the parent browsing context of C and C is said to be a child browsing context of P.
Otherwise, the nested browsing context C has no parent
browsing context. A browsing context A is said to be an ancestor of a browsing context B if there exists a browsing
context A' that is a child browsing context of A and that is itself an ancestor of
B, or if the browsing context A is the
parent browsing context of B. A browsing context that is not a nested browsing context has no parent browsing context, and is the top-level browsing context of all the browsing contexts for which it is an ancestor browsing context. The transitive closure of parent browsing contexts
for a nested browsing context gives the list of ancestor browsing contexts. The list of the descendant browsing contexts of a Document d is the (ordered) list returned by the following algorithm:

http://developers.whatwg.org/browsers.html[4/16/2014 9:29:53 PM]

6 Loading Web pages HTML: The Living Standard - Edition for Web Developers

1. Let list be an empty list. 2. For each child browsing context of d that is nested through an element that is in the Document d, in the tree
order of the elements nesting those browsing contexts, run these substeps: 1. Append that child browsing context to the list list. 2. Append the list of the descendant browsing contexts of the active
document of that child browsing context to the list list. 3. Return the constructed list. A Document is said to be fully active when it is the active
document of its browsing context, and either its browsing context is a
top-level browsing context, or it has a parent browsing context and the
Document through which it is
nested is itself fully active. Because they are nested through an element, child browsing
contexts are always tied to a specific Document in their parent browsing
context. User agents must not allow the user to interact with child browsing contexts of elements that are in Documents that are
not themselves fully active. A nested browsing context can have a seamless browsing context flag
set, if it is embedded through an iframe element with a seamless attribute. A nested browsing context can be put into a delaying load events mode. This is used when it is navigated, to delay the load event of the browsing
context container iframe element before the new Document is
created. The document family of a browsing context consists of the union of all
the Document objects in that browsing context's session
history and the document families of all those
Document objects. The document family of a Document object
consists of the union of all the document families of the
browsing contexts that are nested through the Document object.

Navigating nested browsing contexts in the DOM


window . top Returns the WindowProxy for the top-level browsing context. window . parent Returns the WindowProxy for the parent browsing context. window . frameElement Returns the Element for the browsing context container. Returns null if there isn't one. Throws a SecurityError exception in cross-origin situations.

http://developers.whatwg.org/browsers.html[4/16/2014 9:29:53 PM]

6 Loading Web pages HTML: The Living Standard - Edition for Web Developers

Auxiliary browsing contexts


It is possible to create new browsing contexts that are related to a top-level browsing
context without being nested through an element. Such browsing contexts are called auxiliary browsing contexts. Auxiliary browsing contexts are always top-level browsing contexts. An auxiliary browsing context has an opener browsing context, which is
the browsing context from which the auxiliary browsing context was
created.

Navigating auxiliary browsing contexts in the DOM


The opener IDL attribute on the Window
object, on getting, must return the WindowProxy object of the browsing
context from which the current browsing context was created (its opener
browsing context), if there is one, if it is still available, and if the current
browsing context has not disowned its opener; otherwise, it must return null.
On setting, if the new value is null then the current browsing context must disown its opener; if the new value is anything else then the
user agent must
call the [[DefineOwnProperty]] internal method of the Window object, passing the
property name "opener " as the property key, and the Property Descriptor {
[[Value]]: value, [[Writable]]: true, [[Enumerable]]: true,
[[Configurable]]: true } as the property descriptor, where value is the new value.

Secondary browsing contexts


User agents may support secondary browsing
contexts, which are browsing contexts that form part
of the user agent's interface, apart from the main content area. The sidebar link type uses secondary browsing contexts.

Browsing context names


Browsing contexts can have a browsing context name. By default, a browsing context
has no name (its name is not set). A valid browsing context name is any string with at least one character that does
not start with a U+005F LOW LINE character. (Names starting with an underscore are reserved for
special keywords.) A valid browsing context name or keyword is any string that is either a valid browsing context name or that is an ASCII case-insensitive match for one of: _blank , _self, _parent , or _top. These values have different meanings based on whether the page is sandboxed or not, as
summarized in the following (non-normative) table. In this table,

http://developers.whatwg.org/browsers.html[4/16/2014 9:29:53 PM]

6 Loading Web pages HTML: The Living Standard - Edition for Web Developers

"current" means the


browsing context that the link or script is in, "parent" means the parent
browsing context of the one the link or script is in, "master" means the nearest
ancestor browsing context of the one the link or script is in that is not itself in a
seamless iframe, "top" means the top-level
browsing context of the one the link or script is in, "new" means a new top-level browsing context or auxiliary browsing context is to be created, subject to various user preferences and user agent policies, "none" means that nothing will happen, and
"maybe new" means the same as "new" if the " allow-popups" keyword is also specified on the
sandbox attribute (or if the user overrode the
sandboxing), and the same as "none" otherwise. Keyword Ordinary effect Effect in an iframe with... seamless="" sandbox="" sandbox="" sandbox="allow- sandbox="allowseamless="" none specified, for links and form submissions empty string _blank _self _parent if there isn't a parent _parent if parent is also top _parent if there is one and it's not top _top if top is current _top if top is not current name that doesn't exist name that exists and specified descendant specified descendant specified descendant specified descendant specified descendant specified descendant new new maybe new maybe new maybe new maybe new top top none none top top current current current current current current parent parent none none none none parent/top parent/top none none parent/top parent/top new current current new current current maybe new current current maybe new current current maybe new current current maybe new current current current master current master current master current master current master current master

seamless="" top-navigation" top-navigation"

http://developers.whatwg.org/browsers.html[4/16/2014 9:29:53 PM]

6 Loading Web pages HTML: The Living Standard - Edition for Web Developers

is a descendant name that exists and is current name that exists and is an ancestor that is top name that exists and is an ancestor that is not top other name that exists with common top name that exists with different top, if familiar and one permitted sandboxed navigator name that exists with different top, if familiar but not one permitted sandboxed navigator name that exists with different top, not familiar
Most of the restrictions on sandboxed browsing contexts are applied by
other algorithms, e.g. the navigation algorithm, not the rules
for choosing a browsing context given a

current

current

current

current

current

current

specified ancestor

specified ancestor

none

none

specified ancestor/top

specified ancestor/top

specified ancestor

specified ancestor

none

none

none

none

specified

specified

none

none

none

none

specified

specified

specified

specified

specified

specified

specified

specified

none

none

none

none

new

new

maybe new

maybe new

maybe new

maybe new

http://developers.whatwg.org/browsers.html[4/16/2014 9:29:53 PM]

6 Loading Web pages HTML: The Living Standard - Edition for Web Developers

browsing context name given below.

The Window object


window . window window . frames window . self These attributes all return window. window . document Returns the Document associated with window. document . defaultView Returns the Window object of the active document.

APIs for creating and navigating browsing contexts by name


window = window . open( [ url [, target [, features [, replace ] ] ] ] ) Opens a window to show url (defaults to about:blank), and
returns it. The target argument gives the name of the new window. If a
window exists with that name already, it is reused. The replace attribute,
if true, means that whatever page is currently open in that window will be removed from the window's session history. The features argument is ignored. window . name [ = value ] Returns the name of the window. Can be set, to change the name. window . close () Closes the window. window . closed Returns true if the window has been closed, false otherwise. window . stop() Cancels the document load.

Accessing other browsing contexts


window . length Returns the number of child browsing
contexts. window[index] Returns the indicated child browsing context.

http://developers.whatwg.org/browsers.html[4/16/2014 9:29:53 PM]

6 Loading Web pages HTML: The Living Standard - Edition for Web Developers

Named access on the Window object


window[name] Returns the indicated element or collection of elements.

Closing browsing contexts


When the user agent is required to close a browsing context, it must run the following steps: 1. Let specified browsing context be the browsing context
being closed. 2. Prompt to unload the active
document of the specified browsing context. If the user refused
to allow the document to be unloaded, then abort these steps. 3. Unload the active document of the specified browsing context with the recycle parameter set to
false. 4. Remove the specified browsing context from the user interface (e.g.
close or hide its tab in a tabbed browser). 5. Discard the specified
browsing context. User agents should offer users the ability to arbitrarily close any top-level browsing context.

Browser interface elements


To allow Web pages to integrate with Web browsers, certain Web browser interface elements are
exposed in a limited way to scripts in Web pages. Each interface element is represented by a BarProp object: window . locationbar . visible Returns true if the location bar is visible; otherwise, returns false. window . menubar . visible Returns true if the menu bar is visible; otherwise, returns false. window . personalbar . visible Returns true if the personal bar is visible; otherwise, returns false. window . scrollbars . visible Returns true if the scroll bars are visible; otherwise, returns false. window . statusbar . visible Returns true if the status bar is visible; otherwise, returns false. window . toolbar . visible

http://developers.whatwg.org/browsers.html[4/16/2014 9:29:53 PM]

6 Loading Web pages HTML: The Living Standard - Edition for Web Developers

Returns true if the toolbar is visible; otherwise, returns false.

Up next

6.3 Origin

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/browsers.html[4/16/2014 9:29:53 PM]

6.3 Origin HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
Origin
Relaxing the same-origin restriction
Sandboxing

Origin
Origins are the fundamental currency of the Web's security model. Two actors in the Web
platform that share an origin are assumed to trust each other and to have the same authority.
Actors with differing origins are considered potentially hostile versus each other, and are
isolated from each other to varying degrees. For example, if Example Bank's Web site, hosted at bank.example.com, tries to examine the DOM of Example Charity's Web site, hosted
at charity.example.org, a SecurityError exception will be
raised. The origin of a resource and the effective script origin of a resource
are both either opaque identifiers or tuples consisting of a scheme component, a host component, a
port component, and optionally extra data. The extra data could include the certificate of the site when using encrypted connections, to ensure that if the site's secure certificate changes, the origin is considered to
change as well.

Relaxing the same-origin restriction


document . domain [ = domain ] Returns the current domain used for security checks.

http://developers.whatwg.org/origin-0.html[4/16/2014 9:30:02 PM]

6.3 Origin HTML: The Living Standard - Edition for Web Developers

Can be set to a value that removes subdomains, to change the effective script origin to allow pages on other subdomains of the same domain (if they do the same thing)
to access each other. The domain attribute is used to enable
pages on different hosts of a domain to access each others' DOMs. Do not use the document.domain
attribute when using shared hosting. If an untrusted third party is able to host an HTTP server at
the same IP address but on a different port, then the same-origin protection that normally protects two different sites on the same host will fail, as the ports are ignored when comparing
origins after the document.domain attribute has been
used.

Sandboxing
A sandboxing flag set is a set of zero or more of the following flags, which are used to restrict the abilities that potentially untrusted resources have: The sandboxed navigation browsing context flag This flag prevents content from navigating browsing contexts other
than the sandboxed browsing context itself (or browsing contexts further nested inside it),
auxiliary browsing contexts (which are protected
by the sandboxed auxiliary navigation browsing context flag defined next), and the
top-level browsing context (which is protected by the sandboxed top-level
navigation browsing context flag defined below). If the sandboxed auxiliary navigation browsing context flag is not set, then in certain cases the restrictions nonetheless allow popups (new top-level browsing contexts) to be opened. These browsing contexts always have one permitted sandboxed navigator, set
when the browsing context is created, which allows the browsing context that
created them to actually navigate them. (Otherwise, the sandboxed navigation browsing
context flag would prevent them from being navigated even if they were opened.) The sandboxed auxiliary navigation browsing context flag This flag prevents content from creating new auxiliary browsing
contexts, e.g. using the target attribute, the
window.open() method, or the

http://developers.whatwg.org/origin-0.html[4/16/2014 9:30:02 PM]

6.3 Origin HTML: The Living Standard - Edition for Web Developers

showModalDialog() method. The sandboxed top-level navigation browsing context flag This flag prevents content from navigating their top-level
browsing context and prevents content from closing their
top-level browsing context. When the sandboxed top-level navigation browsing context flag is not
set, content can navigate its top-level browsing context, but other browsing contexts are still protected by the sandboxed
navigation browsing context flag and possibly the sandboxed auxiliary navigation
browsing context flag. The sandboxed plugins browsing context flag This flag prevents content from instantiating plugins, whether
using the embed element, the object element, the applet element, or through navigation of a nested browsing context, unless
those plugins can be secured. The sandboxed seamless iframes flag This flag prevents content from using the seamless
attribute on descendant iframe elements. This prevents a page inserted using the allow-same-origin keyword from using a
CSS-selector-based method of probing the DOM of other pages on the same site (in particular,
pages that contain user-sensitive information). The sandboxed origin browsing context flag This flag forces content into a unique origin, thus preventing
it from accessing other content from the same origin. This flag also prevents script from reading from or writing to the document.cookie IDL attribute, and blocks access to
localStorage. The sandboxed forms browsing context flag This flag blocks form submission. The sandboxed pointer lock browsing context flag This flag disables the Pointer Lock API. The sandboxed scripts browsing context flag This flag blocks script execution. The sandboxed automatic features browsing context flag This flag blocks features that trigger automatically, such as automatically playing a video or automatically focusing a form control.

http://developers.whatwg.org/origin-0.html[4/16/2014 9:30:02 PM]

6.3 Origin HTML: The Living Standard - Edition for Web Developers

The sandboxed fullscreen browsing context flag This flag prevents content from using the requestFullscreen() method. When the user agent is to parse a sandboxing directive, given a string input, a sandboxing flag set output, and
optionally an allow fullscreen flag, it must run the following steps: 1. Split input on spaces,
to obtain tokens. 2. Let output be empty. 3. Add the following flags to output:

The sandboxed navigation browsing context flag. The sandboxed auxiliary navigation browsing context flag, unless tokens
contains the allow-popups keyword.

The sandboxed top-level navigation browsing context flag, unless tokens


contains the allow-top-navigation
keyword.

The sandboxed plugins browsing context flag. The sandboxed seamless iframes flag. The sandboxed origin browsing context flag, unless the tokens contains the
allow-same-origin
keyword. The allow-same-origin keyword
is intended for two cases. First, it can be used to allow content from the same site to be sandboxed to disable
scripting, while still allowing access to the DOM of the sandboxed content. Second, it can be used to embed content from a third-party site, sandboxed to prevent that
site from opening pop-up windows, etc, without preventing the embedded page from
communicating back to its originating site, using the database APIs to store data, etc.

The sandboxed forms browsing context flag, unless tokens contains the
allow-forms keyword.

The sandboxed pointer lock browsing context flag, unless tokens contains
the allow-pointer-lock
keyword.

http://developers.whatwg.org/origin-0.html[4/16/2014 9:30:02 PM]

6.3 Origin HTML: The Living Standard - Edition for Web Developers

The sandboxed scripts browsing context flag, unless tokens contains the
allow-scripts keyword.

The sandboxed automatic features browsing context flag, unless tokens


contains the allow-scripts keyword (defined above). This flag is relaxed by the same keyword as scripts, because when scripts are
enabled these features are trivially possible anyway, and it would be unfortunate to force
authors to use script to do them when sandboxed rather than allowing them to use the
declarative features.

The sandboxed fullscreen browsing context flag, unless the allow fullscreen
flag was passed to the parse a sandboxing
directive flag. Every top-level browsing context has a popup sandboxing flag set, which
is a sandboxing flag set. When a browsing context is created, its
popup sandboxing flag set must be empty. It is populated by the rules for
choosing a browsing context given a browsing context name. Every nested browsing context has an iframe sandboxing flag
set, which is a sandboxing flag set. Which flags in a nested browsing
context's iframe sandboxing flag set are set at any particular
time is determined by the iframe element's sandbox attribute. Every Document has an active sandboxing flag set, which is a
sandboxing flag set. When the Document is created, its active
sandboxing flag set must be empty. It is populated by the navigation
algorithm. Every resource that is obtained by the navigation algorithm has a
forced sandboxing flag set, which is a sandboxing flag set. A resource by
default has no flags set in its forced sandboxing flag set, but other specifications
can define that certain flags are set. In particular, the forced sandboxing flag set is used by the Content
Security Policy specification. When a user agent is to implement the sandboxing for a Document, it
must populate Document's active sandboxing flag set with the union of
the flags that are present in the following sandboxing flag
sets at the time the Document object is created:

If the Document's browsing context is a top-level browsing


context, then: the
flags set on the browsing context's popup sandboxing
flag set.

http://developers.whatwg.org/origin-0.html[4/16/2014 9:30:02 PM]

6.3 Origin HTML: The Living Standard - Edition for Web Developers

If the Document's browsing context is a nested browsing


context, then: the
flags set on the browsing context's
iframe sandboxing flag set.

If the Document's browsing context is a nested browsing


context, then: the
flags set on the browsing context's parent browsing
context's active document's active sandboxing flag set.

The flags set on the Document's resource's forced sandboxing flag


set, if it has
one.

Up next

6.5 Session history and navigation

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/origin-0.html[4/16/2014 9:30:02 PM]

6.5 Session history and navigation HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
Session history and navigation
The session history of browsing contexts
The History interface
The Location interface
Browsing the Web
History traversal
Unloading documents

Session history and navigation

The session history of browsing contexts


The sequence of Documents in a browsing context is its session
history. History objects provide a representation of the pages in the session history of
browsing contexts. Each browsing context,
including nested browsing contexts, has a distinct
session history. Each Document object in a browsing context's session
history is associated with a unique instance of the History object, although
they all must model the same underlying session history. History objects represent their browsing context's session history as
a flat list of session history entries. Each
session history entry consists of a URL and optionally a state
object. Titles associated with session history
entries need not have any relation with the current title of the
Document. The title of a session history entry is intended to explain
the state of the document at that point, so that the user

http://developers.whatwg.org/history.html[4/16/2014 9:30:14 PM]

6.5 Session history and navigation HTML: The Living Standard - Edition for Web Developers

can navigate the document's history. URLs without associated state objects are added to the
session history as the user (or script) navigates from page to page. A state object is an object representing a user interface state. Pages can add state
objects to the session history. These are then returned to the
script when the user (or script) goes back in the history, thus enabling authors to use the
"navigation" metaphor even in one-page applications. State objects are intended to be used for two main purposes:
first, storing a preparsed description of the state in the URL so that in the simple
case an author doesn't have to do the parsing (though one would still need the parsing for
handling URLs passed around by users, so it's only a minor optimization), and second, so that the author can store state that one wouldn't store in the URL
because it only applies to the current Document instance and it would have to be
reconstructed if a new Document were opened. An example of the latter would be something like keeping track of the precise coordinate from
which a pop-up div was made to animate, so that if the user goes back, it can be
made to animate to the same location. Or alternatively, it could be used to keep a pointer into a
cache of data that would be fetched from the server based on the information in the
URL, so that when going back and forward, the information doesn't have to be fetched
again. At any point, one of the entries in the session history is the current entry. This
is the entry representing the active document of the browsing context.
Which entry is the current entry is changed by the algorithms defined in this specification, e.g. during session history
traversal. The current entry is usually an entry for the address of the Document. However, it can also be one of
the entries for state objects added to the history by that
document. An entry with persisted user state is one that also has user-agent defined state.
This specification does not specify what kind of state can be stored. For example, some user agents might want to persist the scroll position, or the
values of form controls. User agents that persist the value of form controls are encouraged to also

http://developers.whatwg.org/history.html[4/16/2014 9:30:14 PM]

6.5 Session history and navigation HTML: The Living Standard - Edition for Web Developers

persist
their directionality (the value of the element's dir attribute).
This prevents values from being displayed incorrectly after a history traversal when the user had
originally entered the values with an explicit, non-default directionality. Entries that consist of state objects share the same
Document as the entry for the page that was active when they were added. Contiguous entries that differ just by fragment identifier also share the same Document. All entries that share the same Document (and that are therefore
merely different states of one particular document) are contiguous by definition. Each Document in a browsing context can also have a latest
entry. This is the entry or that Document that was most the recently traversed
to. When a Document is created, it initially has no latest entry.

The History interface


window . history . length Returns the number of entries in the joint session history. window . history . state Returns the current state object. window . history . go ( [ delta ] ) Goes back or forward the specified number of steps in the joint session history. A zero delta will reload the current page. If the delta is out of range, does nothing. window . history . back() Goes back one step in the joint session history. If there is no previous page, does nothing. window . history . forward () Goes forward one step in the joint session history.

http://developers.whatwg.org/history.html[4/16/2014 9:30:14 PM]

6.5 Session history and navigation HTML: The Living Standard - Edition for Web Developers

If there is no next page, does nothing. window . history . pushState (data, title [, url ] ) Pushes the given data onto the session history, with the given title, and, if provided and
not null, the given URL. window . history . replaceState(data, title [, url ] ) Updates the current entry in the session history to have the given data, title, and, if
provided and not null, URL. The joint session history of a top-level browsing context is the union
of all the session histories of all browsing contexts of all the fully active Document objects that share that top-level browsing context, with all the entries that are current entries in their respective session histories removed except for the current entry of the joint session
history. The current entry of the joint session history is the entry that most recently became a current entry in its session history. Entries in the joint session history are ordered chronologically by the time they
were added to their respective session histories. Each entry
has an index; the earliest entry has index 0, and the subsequent entries are numbered with consecutively increasing integers (1, 2, 3, etc). Since each Document in a browsing context might have a
different event loop, the actual state of the joint session history can
be someone nebulous. For example, two sibling iframe elements could both traverse from one unique origin to another at the same time,
so their precise order might not be welldefined; similarly, since they might only find out about
each other later, they might disagree about the length of the joint session
history. Consider a game where the user can navigate along a line, such that the user is always at some
coordinate, and such that the user can bookmark the page corresponding to a particular
coordinate, to return to it later. A static page implementing the x=5 position in such a game could look like the following: <!DOCTYPE HTML> <!-- this is http://example.com/line?x=5 --> <title>Line Game - 5</title> <p>You are at coordinate 5 on the line.</p>

http://developers.whatwg.org/history.html[4/16/2014 9:30:14 PM]

6.5 Session history and navigation HTML: The Living Standard - Edition for Web Developers

<p> <a href="?x=6">Advance to 6</a> or <a href="?x=4">retreat to 4</a>? </p> The problem with such a system is that each time the user clicks, the whole page has to be
reloaded. Here instead is another way of doing it, using script: <!DOCTYPE HTML> <!-- this starts off as http://example.com/line?x=5 --> <title>Line Game - 5</title> <p>You are at coordinate <span id="coord">5</span> on the line.</p> <p> <a href="?x=6" onclick="go(1); return false;">Advance to 6</a> or <a href="?x=4" onclick="go(-1); return false;">retreat to 4</a>? </p> <script> var currentPage = 5; // prefilled by server function go(d) { setupPage(currentPage + d); history.pushState(currentPage, document.title, '?x=' + currentPage); } onpopstate = function(event) { setupPage(event.state); } function setupPage(page) { currentPage = page; document.title = 'Line Game - ' + currentPage; document.getElementById('coord').textContent = currentPage; document.links[0].href = '?x=' + (currentPage+1); document.links[0].textContent = 'Advance to ' + (currentPage+1); document.links[1].href = '?x=' + (currentPage-1); document.links[1].textContent = 'retreat to ' + (currentPage-1);

http://developers.whatwg.org/history.html[4/16/2014 9:30:14 PM]

6.5 Session history and navigation HTML: The Living Standard - Edition for Web Developers

} </script> In systems without script, this still works like the previous example. However, users that
do have script support can now navigate much faster, since there is no network access
for the same experience. Furthermore, contrary to the experience the user would have with just a
nave scriptbased approach, bookmarking and navigating the session history still work. In the example above, the data argument to the pushState() method is the same information as would be sent
to the server, but in a more convenient form, so that the script doesn't have to parse the URL
each time the user navigates. Applications might not use the same title for a session history entry as the value of the document's title element at that time. For example, here is a simple
page that shows a block in the title element. Clearly, when navigating backwards to
a previous state the user does not go back in time, and therefore it would be inappropriate to
put the time in the session history title. <!DOCTYPE HTML> <TITLE>Line</TITLE> <SCRIPT> setInterval(function () { document.title = 'Line - ' + new Date(); }, 1000); var i = 1; function inc() { set(i+1); history.pushState(i, 'Line - ' + i); } function set(newI) { i = newI; document.forms.F.I.value = newI; } </SCRIPT> <BODY ONPOPSTATE="set(event.state)"> <FORM NAME=F> State: <OUTPUT NAME=I>1</OUTPUT> <INPUT VALUE="Increment" TYPE=BUTTON ONCLICK="inc()"> </FORM>

http://developers.whatwg.org/history.html[4/16/2014 9:30:14 PM]

6.5 Session history and navigation HTML: The Living Standard - Edition for Web Developers

The Location interface


Each Document object in a browsing context's session history is
associated with a unique instance of a Location object. document . location [ = value ] window . location [ = value ] Returns a Location object with the current page's location. Can be set, to navigate to another page. Location objects provide a representation of the address of the active document of their Document's
browsing context, and allow the current entry of the browsing
context's session history to be changed, by adding or replacing entries in the history object. location . assign (url) Navigates to the given page. location . replace(url) Removes the current page from the session history and navigates to the given page. location . reload () Reloads the current page. The Location interface also supports the URLUtils interface.

Browsing the Web

History traversal
The popstate event is fired in certain cases
when navigating to a session history entry.

http://developers.whatwg.org/history.html[4/16/2014 9:30:14 PM]

6.5 Session history and navigation HTML: The Living Standard - Edition for Web Developers

event . state Returns a copy of the information that was provided to pushState() or replaceState() . The hashchange event is fired when navigating
to a session history entry whose URL differs from that of the previous
one only in the fragment identifier. event . oldURL Returns the URL of the session history entry that was previously
current. event . newURL Returns the URL of the session history entry that is now
current. The pageshow event is fired when traversing to a session history entry.
The pagehide event is fired when traversing
from a session history entry. The specification uses the page
showing flag to ensure that scripts receive these events in a consistent manner (e.g. that
they never receive two pagehide events in a row without an
intervening pageshow , or vice versa). event . persisted For the pageshow event, returns false if the page is
newly being loaded (and the load event will fire). Otherwise,
returns true. For the pagehide event, returns false if the page is
going away for the last time. Otherwise, returns true, meaning that (if nothing conspires to
make the page unsalvageable) the page might be reused if the user navigates back to this
page. Things that can cause the page to be unsalvageable include:

document.open() Listening for beforeunload events Listening for unload events Having iframes that are not salvageable Active WebSocket objects Aborting a Document

Unloading documents
http://developers.whatwg.org/history.html[4/16/2014 9:30:14 PM]

6.5 Session history and navigation HTML: The Living Standard - Edition for Web Developers

event . returnValue [ = value ] Returns the current return value of the event (the message to show the user). Can be set, to update the message. There are no BeforeUnloadEvent -specific initialization methods.

Up next

6.7 Offline Web applications

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/history.html[4/16/2014 9:30:14 PM]

6.7 Offline Web applications HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
Offline Web applications
Introduction
Supporting offline caching for legacy applications
Event summary
The cache manifest syntax
Some sample manifests
Writing cache manifests
Application cache API
Browser state

Offline Web applications

Introduction
In order to enable users to continue interacting with Web applications and documents even when
their network connection is unavailable for instance, because they are traveling outside
of their ISP's coverage area authors can provide a manifest which lists the files that are
needed for the Web application to work offline and which causes the user's browser to keep a copy
of the files for use offline. To illustrate this, consider a simple clock applet consisting of an HTML page " clock.html ", a CSS style sheet "clock.css ", and a JavaScript
script " clock.js". Before adding the manifest, these three files might look like this: <!-- clock.html -->

http://developers.whatwg.org/offline.html[4/16/2014 9:30:20 PM]

6.7 Offline Web applications HTML: The Living Standard - Edition for Web Developers

<!DOCTYPE HTML> <html> <head> <title>Clock</title> <script src="clock.js"></script> <link rel="stylesheet" href="clock.css"> </head> <body> <p>The time is: <output id="clock"></output></p> </body> </html> /* clock.css */ output { font: 2em sans-serif; } /* clock.js */ setInterval(function () { document.getElementById('clock').value = new Date(); }, 1000); If the user tries to open the " clock.html" page while offline, though,
the user agent (unless it happens to have it still in the local cache) will fail with an error. The author can instead provide a manifest of the three files, say " clock.appcache ": CACHE MANIFEST clock.html clock.css clock.js With a small change to the HTML file, the manifest (served as text/cache-manifest)
is linked to the application: <!-- clock.html --> <!DOCTYPE HTML> <html manifest="clock.appcache"> <head> <title>Clock</title> <script src="clock.js"></script>

http://developers.whatwg.org/offline.html[4/16/2014 9:30:20 PM]

6.7 Offline Web applications HTML: The Living Standard - Edition for Web Developers

<link rel="stylesheet" href="clock.css"> </head> <body> <p>The time is: <output id="clock"></output></p> </body> </html> Now, if the user goes to the page, the browser will cache the files and make them available
even when the user is offline. Authors are encouraged to include the main page in the manifest also, but in practice the page that referenced the manifest is automatically cached even if it isn't explicitly
mentioned. With the exception of "no-store" directive, HTTP cache headers and restrictions on
caching pages served over TLS (encrypted, using https: ) are overridden by
manifests. Thus, pages will not expire from an application cache before the user agent has updated
it, and even applications served over TLS can be made to work offline. View this example online.

Supporting offline caching for legacy applications


The application cache feature works best if the application logic is separate from the
application and user data, with the logic (markup, scripts, style sheets, images, etc) listed in
the manifest and stored in the application cache, with a finite number of static HTML pages for
the application, and with the application and user data stored in Web Storage or a client-side
Indexed Database, updated dynamically using Web Sockets, XMLHttpRequest , serversent
events, or some other similar mechanism. This model results in a fast experience for the user: the application immediately loads, and
fresh data is obtained as fast as the network will allow it (possibly while stale data shows). Legacy applications, however, tend to be designed so that the user data and the logic are mixed
together in the HTML, with each operation resulting in a new HTML page from the server. For example, consider a news application. The typical architecture of such an

http://developers.whatwg.org/offline.html[4/16/2014 9:30:20 PM]

6.7 Offline Web applications HTML: The Living Standard - Edition for Web Developers

application,
when not using the application cache feature, is that the user fetches the main page, and the
server returns a dynamically-generated page with the current headlines and the user interface
logic mixed together. A news application designed for the application cache feature, however, would instead have the
main page just consist of the logic, and would then have the main page fetch the data separately
from the server, e.g. using XMLHttpRequest . The mixed-content model does not work well with the application cache feature: since the
content is cached, it would result in the user always seeing the stale data from the previous time
the cache was updated. While there is no way to make the legacy model work as fast as the separated model, it
can at least be retrofitted for offline use using the prefer-online application cache mode. To do so, list all the static
resources used by the HTML page you want to have work offline in an application cache manifest, use the manifest attribute to select that manifest from the HTML file,
and then add the following line at the bottom of the manifest: SETTINGS: prefer-online NETWORK: * This causes the application cache to only be used for master entries when the user is offline, and causes the
application cache to be used as an atomic HTTP cache (essentially pinning resources listed in the
manifest), while allowing all resources not listed in the manifest to be accessed normally when
the user is online.

Event summary
When the user visits a page that declares a manifest, the browser will try to update the cache.
It does this by fetching a copy of the manifest and, if the manifest has changed since the user
agent last saw it, redownloading all the resources it mentions and caching them anew. As this is going on, a number of events get fired on the ApplicationCache object
to keep the script updated as to the state of the cache update, so that the user can be notified
appropriately. The events are as follows:

http://developers.whatwg.org/offline.html[4/16/2014 9:30:20 PM]

6.7 Offline Web applications HTML: The Living Standard - Edition for Web Developers

Event name checking

Interface Event

Fired when... The user agent is checking for an update, or attempting to download the manifest for the
first time. This is always the first event in the sequence.

Next events noupdate, downloading , obsolete, error

noupdate downloading

Event Event

The manifest hadn't changed. The user agent has found an update and is fetching it, or is downloading the resources
listed by the manifest for the first time.

Last event in sequence. progress, error , cached , updateready

progress

ProgressEvent

The user agent is downloading resources listed by the manifest.


The event object's total attribute returns the total number of files to be downloaded. The event object's loaded attribute returns the number of files processed so far.

progress, error , cached , updateready

cached

Event

The resources listed in the manifest have been downloaded, and the application is now cached.

Last event in sequence.

http://developers.whatwg.org/offline.html[4/16/2014 9:30:20 PM]

6.7 Offline Web applications HTML: The Living Standard - Edition for Web Developers

updateready

Event

The resources listed in the manifest have been newly redownloaded, and the script can use swapCache() to switch to the new cache.

Last event in sequence.

obsolete

Event

The manifest was found to have become a 404 or 410 page, so the application cache is being deleted.

Last event in sequence.

error

Event

The manifest was a 404 or 410 page, so the attempt to cache the application has been aborted. The manifest hadn't changed, but the page referencing the manifest failed to download properly. A fatal error occurred while fetching the resources listed in the manifest. The manifest changed while the update was being run.

Last event in sequence.

The user agent will try fetching the files again momentarily.

These events are cancelable; their default action is for the user agent to show download
progress information. If the page shows its own update UI, canceling the events will prevent the
user agent from showing redundant progress information.
http://developers.whatwg.org/offline.html[4/16/2014 9:30:20 PM]

6.7 Offline Web applications HTML: The Living Standard - Edition for Web Developers

The cache manifest syntax

Some sample manifests


This example manifest requires two images and a style sheet to be cached and whitelists a CGI
script. CACHE MANIFEST # the above line is required # this is a comment # there can be as many of these anywhere in the file # they are all ignored # comments can have spaces before them # but must be alone on the line # blank lines are ignored too # these are files that need to be cached they can either be listed # first, or a "CACHE:" header could be put before them, as is done # lower down. images/sound-icon.png images/background.png # note that each file has to be put on its own line # here is a file for the online whitelist -- it isn't cached, and # references to this file will bypass the cache, always hitting the # network (or trying to, if the user is offline). NETWORK: comm.cgi # here is another set of files to cache, this time just the CSS file.

http://developers.whatwg.org/offline.html[4/16/2014 9:30:20 PM]

6.7 Offline Web applications HTML: The Living Standard - Edition for Web Developers

CACHE: style/default.css It could equally well be written as follows: CACHE MANIFEST NETWORK: comm.cgi CACHE: style/default.css images/sound-icon.png images/background.png Offline application cache manifests can use absolute paths or even absolute URLs: CACHE MANIFEST /main/home /main/app.js /settings/home /settings/app.js http://img.example.com/logo.png http://img.example.com/check.png http://img.example.com/cross.png The following manifest defines a catch-all error page that is displayed for any page on the
site while the user is offline. It also specifies that the online whitelist wildcard flag is open, meaning that accesses to resources on other sites will not be blocked.
(Resources on the same site are already not blocked because of the catch-all fallback
namespace.) So long as all pages on the site reference this manifest, they will get cached locally as they
are fetched, so that subsequent hits to the same page will load the page immediately from the
cache. Until the manifest is changed, those pages will not be fetched from the server again. When
the manifest changes, then all the files will be redownloaded. Subresources, such as style sheets, images, etc, would only be cached using the regular HTTP
caching semantics, however. CACHE MANIFEST

http://developers.whatwg.org/offline.html[4/16/2014 9:30:20 PM]

6.7 Offline Web applications HTML: The Living Standard - Edition for Web Developers

FALLBACK: / /offline.html NETWORK: *

Writing cache manifests


Manifests must be served using the text/cache-manifest MIME type. All resources served using the text/cache-manifest MIME type must follow the
syntax of application cache manifests, as described in this section. An application cache manifest is a text file, whose text is encoded using UTF8. Data in
application cache manifests is line-based. Newlines must be represented by U+000A LINE FEED (LF)
characters, U+000D CARRIAGE RETURN (CR) characters, or U+000D CARRIAGE RETURN (CR) U+000A LINE
FEED (LF) pairs. This is a willful violation of RFC 2046, which requires all text/* types to only allow CRLF line breaks. This requirement, however, is
outdated; the use of CR, LF, and CRLF line breaks is commonly supported and indeed sometimes CRLF
is not supported by text editors. The first line of an application cache manifest must consist of the string "CACHE", a single
U+0020 SPACE character, the string "MANIFEST", and either a U+0020 SPACE character, a U+0009
CHARACTER TABULATION (tab) character, a U+000A LINE FEED (LF) character, or a U+000D CARRIAGE
RETURN (CR) character. The first line may optionally be preceded by a U+FEFF BYTE ORDER MARK (BOM)
character. If any other text is found on the first line, it is ignored. Subsequent lines, if any, must all be one of the following: A blank line Blank lines must consist of zero or more U+0020 SPACE and
U+0009 CHARACTER TABULATION (tab) characters only. A comment Comment lines must consist of zero or more U+0020 SPACE and U+0009 CHARACTER TABULATION (tab)
characters, followed by a single U+0023 NUMBER SIGN character (#), followed by zero or more
characters other than

http://developers.whatwg.org/offline.html[4/16/2014 9:30:20 PM]

6.7 Offline Web applications HTML: The Living Standard - Edition for Web Developers

U+000A LINE FEED (LF) and U+000D CARRIAGE RETURN (CR) characters. Comments must be on a line on their own. If they were to be included on a line
with a URL, the "#" would be mistaken for part of a fragment identifier. A section header Section headers change the current section. There are four possible section headers: CACHE: Switches to the explicit section. FALLBACK: Switches to the fallback section. NETWORK: Switches to the online whitelist section. SETTINGS: Switches to the settings section. Section header lines must consist of zero or more U+0020 SPACE and U+0009 CHARACTER
TABULATION (tab) characters, followed by one of the names above (including the U+003A COLON
character (:)) followed by zero or more U+0020 SPACE and U+0009 CHARACTER TABULATION (tab) characters. Ironically, by default, the current section is the explicit section. Data for the current section The format that data lines must take depends on the current section. When the current section is the explicit
section, data lines must consist of zero or more U+0020 SPACE and U+0009 CHARACTER
TABULATION (tab) characters, a valid URL identifying a resource other than the
manifest itself, and then zero or more U+0020 SPACE and U+0009 CHARACTER TABULATION (tab)
characters. When the current section is the fallback
section, data lines must consist of zero or more U+0020 SPACE and U+0009 CHARACTER
TABULATION (tab) characters, a valid URL identifying a resource other than the
manifest itself, one or more U+0020 SPACE and U+0009 CHARACTER TABULATION (tab) characters,
another valid URL identifying a resource other than the manifest itself, and then
zero or more U+0020 SPACE and U+0009 CHARACTER

http://developers.whatwg.org/offline.html[4/16/2014 9:30:20 PM]

6.7 Offline Web applications HTML: The Living Standard - Edition for Web Developers

TABULATION (tab) characters. When the current section is the online


whitelist section, data lines must consist of zero or more U+0020 SPACE and U+0009
CHARACTER TABULATION (tab) characters, either a single U+002A ASTERISK character (*) or a valid URL identifying a resource
other than the manifest itself, and then zero or more U+0020 SPACE and U+0009 CHARACTER
TABULATION (tab) characters. When the current section is the settings
section, data lines must consist of zero or more U+0020 SPACE and U+0009 CHARACTER
TABULATION (tab) characters, a setting,
and then zero or more U+0020 SPACE and U+0009 CHARACTER TABULATION (tab) characters. Currently only one setting is
defined: The cache mode setting This consists of the string "prefer-online ". It sets the cache mode to preferonline. (The cache mode defaults to fast.) Within a settings section, each setting must occur no more than once. Manifests may contain sections more than once. Sections may be empty. URLs that are to be fallback pages associated with fallback namespaces, and those namespaces themselves,
must be given in fallback sections, with
the namespace being the first URL of the data line, and the corresponding fallback page being the
second URL. All the other pages to be cached must be listed in explicit sections. Fallback namespaces and fallback entries must have the same origin
as the manifest itself. A fallback namespace must not be listed more
than once. Namespaces that the user agent is to put into the online whitelist must all be specified in online whitelist sections. (This is needed for
any URL that the page is intending to use to communicate back to the server.) To specify that all
URLs are automatically whitelisted in this way, a U+002A ASTERISK character (*) may be specified
as one of the URLs. Authors should not include namespaces in the online whitelist for which another namespace in
the online whitelist is a prefix
match.

http://developers.whatwg.org/offline.html[4/16/2014 9:30:20 PM]

6.7 Offline Web applications HTML: The Living Standard - Edition for Web Developers

Relative URLs must be given relative to the manifest's own


URL. All URLs in the manifest must have the same scheme as
the manifest itself (either explicitly or implicitly, through the use of relative URLs). URLs in manifests must not have fragment identifiers (i.e. the U+0023 NUMBER SIGN character
isn't allowed in URLs in manifests). Fallback namespaces and namespaces in the
online whitelist are matched by prefix
match.

Application cache API


cache = window . applicationCache (In a window.) Returns the ApplicationCache object that applies to the active document of that Window . cache = self . applicationCache (In a shared worker.) Returns the ApplicationCache object that applies to the
current shared worker. cache . status Returns the current status of the application cache, as given by the constants defined
below. cache . update () Invokes the application cache download process. Throws an InvalidStateError exception if there is no application cache to update. Calling this method is not usually necessary, as user agents will generally take care of
updating application caches automatically. The method can be useful in situations such as long-lived applications. For example, a Web
mail application might stay open in a browser tab for weeks at a time. Such an application could
want to test for updates each day. cache . abort () Cancels the application cache download process. This method is intended to be used by Web application showing their own caching progress UI,
in case the user wants to stop the update (e.g. because

http://developers.whatwg.org/offline.html[4/16/2014 9:30:20 PM]

6.7 Offline Web applications HTML: The Living Standard - Edition for Web Developers

bandwidth is limited). cache . swapCache () Switches to the most recent application cache, if there is a newer one. If there isn't,
throws an InvalidStateError exception. This does not cause previously-loaded resources to be reloaded; for example, images do not
suddenly get reloaded and style sheets and scripts do not get reparsed or reevaluated. The only
change is that subsequent requests for cached resources will obtain the newer copies. The updateready event will fire before this
method can be called. Once it fires, the Web application can, at its leisure, call this method
to switch the underlying cache to the one with the more recent updates. To make proper use of
this, applications have to be able to bring the new features into play; for example, reloading
scripts to enable new features. An easier alternative to swapCache() is just to
reload the entire page at a time suitable for the user, using location.reload() . UNCACHED (numeric value 0) The ApplicationCache object's cache host is not associated with
an application cache at this time. IDLE (numeric value 1) The ApplicationCache object's cache host is associated with an
application cache whose application cache group's update status is idle, and that application
cache is the newest cache in its
application cache group, and the application cache group is not marked
as obsolete. CHECKING (numeric value 2) The ApplicationCache object's cache host is associated with an
application cache whose application cache group's update status is checking. DOWNLOADING (numeric value 3) The ApplicationCache object's cache host is associated with an
application cache whose application cache group's update status is downloading. UPDATEREADY (numeric value 4) The ApplicationCache object's cache host is associated with an
application cache whose application cache group's update status is idle, and whose application
cache group is not marked as obsolete, but
that application cache

http://developers.whatwg.org/offline.html[4/16/2014 9:30:20 PM]

6.7 Offline Web applications HTML: The Living Standard - Edition for Web Developers

is not the newest cache in its group. OBSOLETE (numeric value 5) The ApplicationCache object's cache host is associated with an
application cache whose application cache group is marked as obsolete.

Browser state
window . navigator . onLine Returns false if the user agent is definitely offline (disconnected from the network).
Returns true if the user agent might be online. The events online and offline are fired when the value of this attribute changes.

This attribute is inherently unreliable. A computer can be connected to a network


without having Internet access. In this example, an indicator is updated as the browser goes online and offline. <!DOCTYPE HTML> <html> <head> <title>Online status</title> <script> function updateIndicator() { document.getElementById('indicator').textContent = navigator.onLine ? 'online' : 'offline'; } </script> </head> <body onload="updateIndicator()" ononline="updateIndicator()" onoffline="updateIndicator()"> <p>The network is: <span id="indicator">(state unknown) </span> </body> </html>

http://developers.whatwg.org/offline.html[4/16/2014 9:30:20 PM]

6.7 Offline Web applications HTML: The Living Standard - Edition for Web Developers

Up next

7 Web application APIs

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/offline.html[4/16/2014 9:30:20 PM]

7 Web application APIs HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
Web application APIs
Scripting
Introduction
The ErrorEvent interface
Events
Event handlers
Event handlers on elements, Document objects, and Window objects
IDL definitions
Base64 utility methods
Dynamic markup insertion
Opening the input stream
Closing the input stream
document.write()
document.writeln()

WEB APPLICATION APIS

Scripting

Introduction
Various mechanisms can cause author-provided executable code to run in the context of a
document. These mechanisms include, but are probably not limited to:

Processing of script elements. Processing of inline javascript: URLs (e.g. the


src attribute of img
http://developers.whatwg.org/webappapis.html[4/16/2014 9:30:26 PM]

7 Web application APIs HTML: The Living Standard - Edition for Web Developers

elements, or an @import rule in a CSS style element block).

Event handlers, whether registered through the DOM using


addEventListener() , by explicit event handler content attributes, by
event handler IDL attributes, or otherwise.

Processing of technologies like XBL or SVG that have their own scripting
features.

The ErrorEvent interface The message attribute must return the


value it was initialized to. When the object is created, this attribute must be initialized to the
empty string. It represents the error message. The filename attribute must return the
value it was initialized to. When the object is created, this attribute must be initialized to the
empty string. It represents the absolute URL of the script in which the error
originally occurred. The lineno attribute must return the
value it was initialized to. When the object is created, this attribute must be initialized to
zero. It represents the line number where the error occurred in the script. The colno attribute must return the value
it was initialized to. When the object is created, this attribute must be initialized to zero. It
represents the column number where the error occurred in the script. The error attribute must return the value
it was initialized to. When the object is created, this attribute must be initialized to null.
Where appropriate, it is set to the object representing the error (e.g. the exception object in
the case of an uncaught DOM exception).

Events

Event handlers
Many objects can have event handlers specified. These act as non-capture event
listeners for the object on which they are specified. An event handler has a name, which always starts with
"on " and is followed by

http://developers.whatwg.org/webappapis.html[4/16/2014 9:30:26 PM]

7 Web application APIs HTML: The Living Standard - Edition for Web Developers

the name of the event for which it is intended. An event handler can either have the value null or be set
to a callback object. This is defined using the EventHandler callback function type. Event handlers are exposed in one of two ways. The first way, common to all event handlers, is as an event handler IDL attribute. The second way is as an event handler content
attribute. Event handlers on HTML elements and some of the event handlers on
Window objects are exposed in this way. An event handler content attribute is a
content attribute for a specific event handler. The name of
the content attribute is the same as the name of the event
handler. Event handler content attributes, when specified, must contain valid JavaScript
code which, when parsed, would match the FunctionBody production after
automatic semicolon insertion. When an event handler content
attribute is set on an element owned by a Document that is not in a
browsing context, the corresponding event handler is not changed. This example demonstrates the order in which event listeners are invoked. If the button in
this example is clicked by the user, the page will show four alerts, with the text "ONE", "TWO",
"THREE", and "FOUR" respectively. <button id="test">Start Demo</button> <script> var button = document.getElementById('test'); button.addEventListener('click', function () { alert('ONE') }, false); button.setAttribute('onclick', "alert('NOT CALLED')"); // event handler listener is registered here button.addEventListener('click', function () { alert('THREE') }, false); button.onclick = function () { alert('TWO'); }; button.addEventListener('click', function () { alert('FOUR') }, false); </script>

http://developers.whatwg.org/webappapis.html[4/16/2014 9:30:26 PM]

7 Web application APIs HTML: The Living Standard - Edition for Web Developers

The EventHandler callback function type represents a callback used for event handlers. It is represented in Web IDL as follows: In JavaScript, any Function object implements this interface. For example, the following document fragment: <body onload="alert(this)" onclick="alert(this)"> ...leads to an alert saying "[objectWindow]" when the document is
loaded, and an alert saying "[objectHTMLBodyElement]" whenever the
user clicks something in the page. The return value of the function affects whether the event is canceled or not: if the return value is false, the event is canceled
(except for mouseover events, where the return value has to
be true to cancel the event). With beforeunload events,
the value is instead used to determine the message to show the user. For historical reasons, the onerror handler has different
arguments: Similarly, the onbeforeunload handler has a
different return value:

Event handlers on elements, Document objects, and Window objects


The following are the event handlers (and their corresponding event handler event types) supported by all HTML elements, as both event handler content attributes
and event handler IDL attributes; and supported by all Document and Window objects, as event handler IDL
attributes: Event handler onabort oncancel oncanplay oncanplaythrough onchange onclick Event handler event type abort cancel canplay canplaythrough change click

http://developers.whatwg.org/webappapis.html[4/16/2014 9:30:26 PM]

7 Web application APIs HTML: The Living Standard - Edition for Web Developers

onclose oncontextmenu oncuechange ondblclick ondrag ondragend ondragenter ondragexit ondragleave ondragover ondragstart ondrop ondurationchange onemptied onended oninput oninvalid onkeydown onkeypress onkeyup onloadeddata onloadedmetadata onloadstart onmousedown onmouseenter onmouseleave onmousemove onmouseout

close contextmenu cuechange dblclick drag dragend dragenter dragexit dragleave dragover dragstart drop durationchange emptied ended input invalid keydown keypress keyup loadeddata loadedmetadata loadstart mousedown mouseenter mouseleave mousemove mouseout

http://developers.whatwg.org/webappapis.html[4/16/2014 9:30:26 PM]

7 Web application APIs HTML: The Living Standard - Edition for Web Developers

onmouseover onmouseup onmousewheel onpause onplay onplaying onprogress onratechange onreset onseeked onseeking onselect onshow onsort onstalled onsubmit onsuspend ontimeupdate ontoggle onvolumechange onwaiting

mouseover mouseup mousewheel pause play playing progress ratechange reset seeked seeking select show sort stalled submit suspend timeupdate toggle volumechange waiting

The following are the event handlers (and their corresponding event handler event types) supported by all HTML elements other than body and frameset elements, as both event handler content attributes and event handler IDL attributes; supported by all Document
objects, as event handler IDL attributes; and supported by all Window objects, as event handler IDL attributes on the
Window objects themselves, and with corresponding event handler content
attributes and event handler IDL attributes exposed on all body
and frameset elements that are owned by that
Window object's Documents: Event handler Event handler event type
http://developers.whatwg.org/webappapis.html[4/16/2014 9:30:26 PM]

7 Web application APIs HTML: The Living Standard - Edition for Web Developers

onblur onerror onfocus onload onscroll

blur error focus load scroll

The following are the event handlers (and their corresponding event handler event types) supported by Window objects, as event handler IDL attributes on the
Window objects themselves, and with corresponding event handler content
attributes and event handler IDL attributes exposed on all body
and frameset elements that are owned by that
Window object's Documents: Event handler onafterprint onbeforeprint onbeforeunload onhashchange onmessage onoffline ononline onpagehide onpageshow onpopstate onresize onstorage onunload Event handler event type afterprint beforeprint beforeunload hashchange message offline online pagehide pageshow popstate resize storage unload

The following are the event handlers (and their corresponding event handler event types) supported on Document objects as event handler IDL attributes: Event handler onreadystatechange Event handler event type readystatechange

http://developers.whatwg.org/webappapis.html[4/16/2014 9:30:26 PM]

7 Web application APIs HTML: The Living Standard - Edition for Web Developers

IDL definitions

Base64 utility methods


The atob() and btoa() methods allow authors to transform content to and from
the base64 encoding. In these APIs, for mnemonic purposes, the "b" can be considered to stand for "binary", and the "a" for "ASCII". In practice, though, for primarily historical reasons, both the
input and output of these functions are Unicode strings. result = window . btoa( data ) Takes the input data, in the form of a Unicode string containing only characters in the range
U+0000 to U+00FF, each representing a binary byte with values 0x00 to 0xFF respectively, and
converts it to its base64 representation, which it returns. Throws an InvalidCharacterError exception if the input string contains any
out-of-range characters. result = window . atob( data ) Takes the input data, in the form of a Unicode string containing base64encoded binary data,
decodes it, and returns a string consisting of characters in the range U+0000 to U+00FF, each
representing a binary byte with values 0x00 to 0xFF respectively, corresponding to that binary
data. Throws an InvalidCharacterError exception if the input string is not valid base64 data.

Dynamic markup insertion


APIs for dynamically inserting markup into the document interact with the parser,
and thus their behavior varies depending on whether they are used with HTML documents
(and the HTML parser) or XHTML in XML documents (and the XML
parser).

http://developers.whatwg.org/webappapis.html[4/16/2014 9:30:26 PM]

7 Web application APIs HTML: The Living Standard - Edition for Web Developers

Opening the input stream


The open() method comes in several variants
with different numbers of arguments. document = document . open( [ type [, replace ] ] ) Causes the Document to be replaced in-place, as if it was a new
Document object, but reusing the previous object, which is then returned. If the type argument is omitted or has the value
"text/html ", then the resulting Document has an HTML parser associated
with it, which can be given data to parse using document.write() . Otherwise, all content passed to document.write() will be parsed as plain text. If the replace argument is present and has the value "replace", the existing entries in the session history for the
Document object are removed. The method has no effect if the Document is still being parsed. Throws an InvalidStateError exception if the Document is an XML document. window = document . open( url, name, features [, replace ] ) Works like the window.open() method.

Closing the input stream


document . close () Closes the input stream that was opened by the document.open() method. Throws an InvalidStateError exception if the
Document is an XML document.

document.write()
document . write (text...) In general, adds the given string(s) to the Document's input stream. This method has very idiosyncratic behavior. In some cases, this method
http://developers.whatwg.org/webappapis.html[4/16/2014 9:30:26 PM]

7 Web application APIs HTML: The Living Standard - Edition for Web Developers

can
affect the state of the HTML parser while the parser is running, resulting in a DOM
that does not correspond to the source of the document (e.g. if the string written is the string
"<plaintext> " or "<!--"). In other cases,
the call can clear the current page first, as if document.open() had been called. In yet more cases, the method
is simply ignored, or throws an exception. To make matters worse, the exact behavior of this
method can in some cases be dependent on network latency, which can lead to failures that are very hard to debug. For all these reasons, use
of this method is strongly discouraged. This method throws an InvalidStateError exception when invoked on XML
documents.

document.writeln()
document . writeln (text...) Adds the given string(s) to the Document's input stream, followed by a newline
character. If necessary, calls the open() method
implicitly first. This method throws an InvalidStateError exception when invoked on XML
documents.

Up next

7.4 Timers

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/webappapis.html[4/16/2014 9:30:26 PM]

7.4 Timers HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
Timers
User prompts
Simple dialogs
Printing
Dialogs implemented using separate documents
System state and capabilities
The Navigator object
Client identification
Language preferences
Custom scheme and content handlers
Manually releasing the storage mutex
Plugins
The External interface
Images

Timers
The setTimeout()
and setInterval()
methods allow authors to schedule timer-based callbacks. handle = window . setTimeout ( handler [, timeout [, arguments... ] ]) Schedules a timeout to run handler after timeout
milliseconds. Any arguments are passed straight through to the handler. handle = window . setTimeout ( code [, timeout ] ) Schedules a timeout to compile and run code after timeout milliseconds.

http://developers.whatwg.org/timers.html[4/16/2014 9:30:32 PM]

7.4 Timers HTML: The Living Standard - Edition for Web Developers

window . clearTimeout( handle ) Cancels the timeout set with setTimeout()


identified by handle. handle = window . setInterval( handler [, timeout [, arguments... ]]) Schedules a timeout to run handler every timeout
milliseconds. Any arguments are passed straight through to the handler. handle = window . setInterval( code [, timeout ] ) Schedules a timeout to compile and run code every timeout milliseconds. window . clearInterval ( handle ) Cancels the timeout set with setInterval() identified by handle.

Timers can be nested; after five such nested timers, however, the interval is forced to be at least four milliseconds. This API does not guarantee that timers will run exactly on schedule. Delays due
to CPU load, other tasks, etc, are to be expected. To run tasks of several milliseconds back to back without any delay, while still yielding back
to the browser to avoid starving the user interface (and to avoid the browser killing the script
for hogging the CPU), simply queue the next timer before performing work: function doExpensiveWork() { var done = false; // ... // this part of the function takes up to five milliseconds // set done to true if we're done // ... return done; } function rescheduleWork() { var handle = setTimeout(rescheduleWork, 0); // preschedule next iteration if (doExpensiveWork()) clearTimeout(handle); // clear the timeout if we don't need it }

http://developers.whatwg.org/timers.html[4/16/2014 9:30:32 PM]

7.4 Timers HTML: The Living Standard - Edition for Web Developers

function scheduleWork() { setTimeout(rescheduleWork, 0); } scheduleWork(); // queues a task to do lots of work

User prompts

Simple dialogs
window . alert (message) Displays a modal alert with the given message, and waits for the user to dismiss it. A call to the navigator.yieldForStorageUpdates() method is
implied when this method is invoked. result = window . confirm(message) Displays a modal OK/Cancel prompt with the given message, waits for the user to dismiss it,
and returns true if the user clicks OK and false if the user clicks Cancel. A call to the navigator.yieldForStorageUpdates() method is
implied when this method is invoked. result = window . prompt (message [, default] ) Displays a modal text field prompt with the given message, waits for the user to dismiss it,
and returns the value that the user entered. If the user cancels the prompt, then returns null
instead. If the second argument is present, then the given value is used as a default. A call to the navigator.yieldForStorageUpdates() method is
implied when this method is invoked.

Printing
window . print ()
http://developers.whatwg.org/timers.html[4/16/2014 9:30:32 PM]

7.4 Timers HTML: The Living Standard - Edition for Web Developers

Prompts the user to print the page. A call to the navigator.yieldForStorageUpdates() method is
implied when this method is invoked.

Dialogs implemented using separate documents


result = window . showModalDialog(url [, argument] ) Prompts the user with the given page, waits for that page to
close, and returns the return value. A call to the navigator.yieldForStorageUpdates()
method is implied when this method is invoked. window . dialogArguments Returns the argument argument that was passed to the showModalDialog() method. window . returnValue [ = value ] Returns the current return value for the window. Can be set, to change the value that will be returned by the showModalDialog() method.

The window.close() method can be used to


close the browsing context.

System state and capabilities

The Navigator object

Client identification
In certain cases, despite the best efforts of the entire industry, Web browsers have bugs and
limitations that Web authors are forced to work around.

http://developers.whatwg.org/timers.html[4/16/2014 9:30:32 PM]

7.4 Timers HTML: The Living Standard - Edition for Web Developers

This section defines a collection of attributes that can be used to determine, from script, the
kind of user agent in use, in order to work around these issues. Client detection should always be limited to detecting known current versions; future versions
and unknown versions should always be assumed to be fully compliant. window . navigator . appCodeName Returns the string "Mozilla". window . navigator . appName Returns the name of the browser. window . navigator . appVersion Returns the version of the browser. window . navigator . platform Returns the name of the platform. window . navigator . product Returns the string "Gecko ". window . navigator . taintEnabled() Returns false. window . navigator . userAgent Returns the complete User-Agent header.

Language preferences
window . navigator . language Returns a language tag representing the user's preferred language.

Custom scheme and content handlers


The registerProtocolHandler() method
allows Web sites to register themselves as possible handlers for particular schemes. For example,
an online telephone messaging service could register itself as a handler of the sms:
scheme, so that if the user clicks on such a link, he is given the
http://developers.whatwg.org/timers.html[4/16/2014 9:30:32 PM]

7.4 Timers HTML: The Living Standard - Edition for Web Developers

opportunity to use that Web


site. Analogously, the registerContentHandler() method
allows Web sites to register themselves as possible handlers for content in a particular
MIME type. For example, the same online telephone messaging service could register
itself as a handler for text/vcard files, so that if the user has no native
application capable of handling vCards, his Web browser can instead suggest he use that site to
view contact information stored on vCards that he opens. window . navigator . registerProtocolHandler (scheme, url, title) window . navigator . registerContentHandler (mimeType, url, title) Registers a handler for the given scheme or content type, at the given URL, with the given
title. The string "%s " in the URL is used as a placeholder for where to put
the URL of the content to be handled. Throws a SecurityError exception if the user agent blocks the registration (this
might happen if trying to register as a handler for "http", for instance). Throws a SyntaxError exception if the "%s" string is
missing in the URL. In addition to the registration methods, there are also methods for determining if particular
handlers have been registered, and for unregistering handlers. state = window . navigator . isProtocolHandlerRegistered(scheme, url) state = window . navigator . isContentHandlerRegistered (mimeType, url) Returns one of the following strings describing the state of the handler given by the
arguments: new Indicates that no attempt has been made to register the given handler (or that the handler
has been unregistered). It would be appropriate to promote the availability of the handler or
to just automatically register the handler. registered Indicates that the given handler has been registered or that the site is blocked from
registering the handler. Trying to register the handler again would have no effect.

http://developers.whatwg.org/timers.html[4/16/2014 9:30:32 PM]

7.4 Timers HTML: The Living Standard - Edition for Web Developers

declined Indicates that the given handler has been offered but was rejected. Trying to register the
handler again may prompt the user again. state = window . navigator . unregisterProtocolHandler (scheme, url) state = window . navigator . unregisterContentHandler(mimeType, url) Unregisters the handler given by the arguments.

Manually releasing the storage mutex


window . navigator . cookieEnabled Returns false if setting a cookie will be ignored, and true otherwise. window . navigator . yieldForStorageUpdates () If a script uses the document.cookie API, or the
localStorage API, the browser will block other scripts
from accessing cookies or storage until the first script finishes. Calling the navigator.yieldForStorageUpdates() method
tells the user agent to unblock any other scripts that may be blocked, even though the script
hasn't returned. Values of cookies and items in the Storage objects of localStorage attributes can change after calling this method,
whence its name. [WEBSTORAGE]

Plugins
window . navigator . plugins . refresh( [ refresh ] ) Updates the lists of supported plugins and MIME types for this page, and reloads the page if the lists have changed. window . navigator . plugins . length Returns the number of plugins, represented by Plugin objects, that the user agent reports. plugin = window . navigator . plugins . item(index)

http://developers.whatwg.org/timers.html[4/16/2014 9:30:32 PM]

7.4 Timers HTML: The Living Standard - Edition for Web Developers

window . navigator . plugins [index] Returns the specified Plugin object. plugin = window . navigator . plugins . item(name) window . navigator . plugins [name] Returns the Plugin object for the plugin with the given name. window . navigator . mimeTypes . length Returns the number of MIME types, represented by MimeType objects, supported by the plugins that the user agent reports. mimeType = window . navigator . mimeTypes . item(index) window . navigator . mimeTypes [index] Returns the specified MimeType object. mimeType = window . navigator . mimeTypes . item(name) window . navigator . mimeTypes [name] Returns the MimeType object for the given MIME type. plugin . name Returns the plugin's name. plugin . description Returns the plugin's description. plugin . filename Returns the plugin library's filename, if applicable on the current platform. plugin . length Returns the number of MIME types, represented by MimeType objects, supported by the plugin. mimeType = plugin . item(index) plugin[index] Returns the specified MimeType object. mimeType = plugin . item(name) plugin[name] Returns the MimeType object for the given MIME type. mimeType . type Returns the MIME type. mimeType . description

http://developers.whatwg.org/timers.html[4/16/2014 9:30:32 PM]

7.4 Timers HTML: The Living Standard - Edition for Web Developers

Returns the MIME type's description. mimeType . suffixes Returns the MIME type's typical file extensions, in a comma-separated list. mimeType . enabledPlugin Returns the Plugin object that implements this MIME type. window . navigator . javaEnabled Returns true if there's a plugin that supports the MIME type " application/x-java-vm ".

The External interface


window . external . AddSearchProvider ( url ) Adds the search engine described by the OpenSearch description document at url. The OpenSearch description document has to be on the same server as the script that calls
this method. installed = window . external . IsSearchProviderInstalled ( url ) Returns a value based on comparing url to the URLs of the results pages
of the installed search engines. 0 None of the installed search engines match url. 1 One or more installed search engines match url, but none are the user's default search engine. 2 The user's default search engine matches url. The url is compared to the URLs of the results pages of the installed
search engines using a prefix match. Only results pages on the same domain as the script that
calls this method are checked.

Another way of exposing search engines using OpenSearch description documents is


using a link element with the search link type.

http://developers.whatwg.org/timers.html[4/16/2014 9:30:32 PM]

7.4 Timers HTML: The Living Standard - Edition for Web Developers

Images
An ImageBitmap object represents a bitmap image that can be painted to a canvas
without undue latency. The exact judgement of what is undue latency of this is left up to the implementer, but in general if making use of the bitmap requires network I/O, or even local disk
I/O, then the latency is probably undue; whereas if it only requires a blocking read from a GPU or
system RAM, the latency is probably acceptable. promise = Window . createImageBitmap (image [, sx, sy, sw, sh ] ) Takes image, which can be an img element,
video , or canvas element, a Blob object, an
ImageData object, a CanvasRenderingContext2D object, or another
ImageBitmap object, and returns a Promise that is resolved when a new ImageBitmap is created. If no ImageBitmap object can be constructed, for example because the provided
image data is not actually an image, then the promise is rejected instead. If sx, sy, sw, and sh arguments are provided, the source image is cropped to the given pixels, with
any pixels missing in the original replaced by transparent black. These coordinates are in the
source image's pixel coordinate space, not in CSS pixels. Throws an InvalidStateError exception if the source image is not in a valid state (e.g. an img element that hasn't finished loading, or a CanvasRenderingContext2D object whose bitmap data has zero length along one or both
dimensions). Throws a SecurityError exception if the script is not allowed to
access the image data of the source image (e.g. a video that is CORS-cross-origin, or a canvas being drawn on by a script in a worker
from another origin). imageBitmap . width Returns the intrinsic width of the image, in CSS pixels. imageBitmap . height Returns the intrinsic height of the image, in CSS pixels. imageBitmap .
http://developers.whatwg.org/timers.html[4/16/2014 9:30:32 PM]

7.4 Timers HTML: The Living Standard - Edition for Web Developers

resolution Returns the intrinsic linear pixel density of the image, in image pixels per CSS pixels. Using this API, a sprite sheet can be precut and prepared: var sprites = {}; function loadMySprites() { var image = new Image(); image.src = 'mysprites.png'; var resolver; var promise = new Promise(function (arg) { resolver = arg }); image.onload = function () { resolver.resolve(Promise.every( createImageBitmap(image, 0, 0, 40, 40).then(function 0, 40, 40).then(function 0, 40, 40).then(function (image) { sprites.woman = image }), createImageBitmap(image, 40, (image) { sprites.man (image) { sprites.tree (image) { sprites.hut = image }), = image }), 0, 40, 40, 40).then(function = image }), createImageBitmap(image, 80, createImageBitmap(image,

createImageBitmap(image, 40, 40, 40, 40).then(function (image) { sprites.apple = image }), createImageBitmap(image, 80, 40, 40, 40).then(function (image) { sprites.snake = image }), )); }; return promise; } function runDemo() { var canvas = document.querySelector('canvas#demo'); var context = canvas.getContext('2d'); context.drawImage(sprites.tree, 30, 10); context.drawImage(sprites.snake, 70, 10); } loadMySprites().then(runDemo);

http://developers.whatwg.org/timers.html[4/16/2014 9:30:32 PM]

7.4 Timers HTML: The Living Standard - Edition for Web Developers

Up next

8 User interaction

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/timers.html[4/16/2014 9:30:32 PM]

8 User interaction HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
User interaction
The hidden attribute
Inert subtrees
The inert attribute
Activation
Focus
Sequential focus navigation and the tabindex attribute
Document-level focus APIs
Element-level focus APIs
Assigning keyboard shortcuts
Introduction
The accesskey attribute
Editing
Making document regions editable: The contenteditable content attribute
Making entire documents editable: The designMode IDL attribute
Best practices for in-page editors
Editing APIs
Spelling and grammar checking

8 USER INTERACTION

The hidden attribute


All HTML elements may have the hidden content
attribute set. The hidden attribute is a boolean
attribute. When specified on an element, it indicates that the element is not yet, or is no
longer, directly relevant to the page's current state, or that it is being used to declare content
to be reused by other

http://developers.whatwg.org/editing.html[4/16/2014 9:30:37 PM]

8 User interaction HTML: The Living Standard - Edition for Web Developers

parts of the page as opposed to being directly accessed by the user. In the following skeletal example, the attribute is used to hide the Web game's main screen
until the user logs in: <h1>The Example Game</h1> <section id="login"> <h2>Login</h2> <form> ... <!-- calls login() once the user's credentials have been checked --> </form> <script> function login() { // switch screens document.getElementById('login').hidden = true; document.getElementById('game').hidden = false; } </script> </section> <section id="game" hidden> ... </section> The hidden attribute must not be used to hide content that
could legitimately be shown in another presentation. For example, it is incorrect to use hidden to hide panels in a tabbed dialog, because the tabbed interface
is merely a kind of overflow presentation one could equally well just show all the form controls in one big page with a scrollbar. It is similarly incorrect to use this attribute to hide
content just from one presentation if something is marked hidden , it is hidden from all presentations, including, for instance,
screen readers. Elements that are not themselves hidden must not
hyperlink to elements that are hidden . The for attributes of label and output elements that are not themselves hidden must similarly not refer to elements that are
hidden . In both cases, such references would cause user
confusion. Elements and scripts may, however, refer to elements that are hidden in other contexts.

http://developers.whatwg.org/editing.html[4/16/2014 9:30:37 PM]

8 User interaction HTML: The Living Standard - Edition for Web Developers

For example, it would be incorrect to use the href


attribute to link to a section marked with the hidden attribute.
If the content is not applicable or relevant, then there is no reason to link to it. It would be fine, however, to use the ARIA aria-describedby attribute to refer to descriptions that are
themselves hidden . While hiding the descriptions implies that
they are not useful alone, they could be written in such a way that they are useful in the
specific context of being referenced from the images that they describe. Similarly, a canvas element with the hidden
attribute could be used by a scripted graphics engine as an off-screen buffer, and a form control
could refer to a hidden form element using its form attribute. Elements in a section hidden by the hidden attribute are still
active, e.g. scripts and form controls in such sections still execute and submit respectively.
Only their presentation to the user changes.

Inert subtrees
A subtree of a Document can be marked as inert. When a node or one of
its ancestors is inert, then the user agent must act as if the element was absent for
the purposes of targeting user interaction events, may ignore the node for the purposes of text
search user interfaces (commonly known as "find in page"), and may prevent the user from selecting
text in that node. User agents should allow the user to override the restrictions on search and
text selection, however. For example, consider a page that consists of just a single inert
paragraph positioned in the middle of a body. If a user moves their pointing device
from the body over to the inert paragraph and clicks on the paragraph,
no mouseover event would be fired, and the mousemove and click events would
be fired on the body element rather than the paragraph. When a node or one of its ancestors is inert, it also can't be
focusable, and it is disabled if it is a command. An entire Document can be marked as blocked by a modal dialog subject. While a Document is so marked, every node that is in the Document, with the exception of the subject element, its ancestors, and its descendants, must be

http://developers.whatwg.org/editing.html[4/16/2014 9:30:37 PM]

8 User interaction HTML: The Living Standard - Edition for Web Developers

marked
inert. (The elements excepted by this paragraph can additionally be marked
inert through other means; being part of a modal dialog does not "protect" a node
from being marked inert.) Only one element at a time can mark a Document as being blocked by a modal dialog. When a new dialog is made to block a Document, the previous element, if any, stops blocking the
Document. The dialog element's showModal() method makes use of this mechanism.

The inert attribute


The inert attribute is a boolean attribute that
indicates, by its presence, that the element is to be made inert. By default, there is no visual indication of a subtree being inert. Authors are encouraged to clearly mark what parts of their document are active and which are inert, to avoid
user confusion. In particular, it is worth remembering that not all users can see all parts of a
page at once; for example, users of screen readers, users on small devices or with magnifiers, and
even users just using particularly small windows might not be able to see the active part of a
page and may get frustrated if inert sections are not obviously inert. For individual controls,
the disabled attribute is probably more appropriate. The inert IDL attribute must reflect the
content attribute of the same name.

Activation
element . click() Acts as if the element was clicked.

Focus

Sequential focus navigation and the tabindex attribute


http://developers.whatwg.org/editing.html[4/16/2014 9:30:37 PM]

8 User interaction HTML: The Living Standard - Edition for Web Developers

The tabindex content attribute allows authors to


control whether an element is supposed to be focusable, whether it is supposed to be reachable
using sequential focus navigation, and what is to be the relative order of the element for the
purposes of sequential focus navigation. The name "tab index" comes from the common use of the
"tab" key to navigate through the focusable elements. The term "tabbing" refers to moving forward
through the focusable elements that can be reached using sequential focus navigation. The tabindex attribute, if specified, must have a value that
is a valid integer.

Document-level focus APIs


document . activeElement Returns the currently focused element. document . hasFocus() Returns true if the document has focus; otherwise, returns false. window . focus () Focuses the window. Use of this method is discouraged. Allow the user to control window focus
instead. window . blur() Unfocuses the window. Use of this method is discouraged. Allow the user to control window
focus instead.

Element-level focus APIs


element . focus() Focuses the element. element . blur() Unfocuses the element. Use of this method is discouraged. Focus another element instead. Do not use this method to hide the focus ring if you find the focus ring unsightly. Instead,
use a CSS rule to override the 'outline' property. Be aware, however, that if an alternative
focusing style isn't made available instead, the page will be significantly less usable for
people who primarily navigate pages
http://developers.whatwg.org/editing.html[4/16/2014 9:30:37 PM]

8 User interaction HTML: The Living Standard - Edition for Web Developers

using a keyboard, or those with reduced vision who use focus


outlines to help them navigate the page. For example, to hide the outline from links and instead use a yellow background, you could
use: :link:focus, :visited:focus { outline: none; background: yellow; color: black; }

Assigning keyboard shortcuts

Introduction
Each element that can be activated or focused can be assigned a single key combination to
activate it, using the accesskey attribute. The exact shortcut is determined by the user agent, based on information about the user's
keyboard, what keyboard shortcuts already exist on the platform, and what other shortcuts have
been specified on the page, using the information provided in the accesskey attribute as a guide. In order to ensure that a relevant keyboard shortcut is available on a wide variety of input
devices, the author can provide a number of alternatives in the accesskey attribute. Each alternative consists of a single character, such as a letter or digit. User agents can provide users with a list of the keyboard shortcuts, but authors are encouraged
to do so also. The accessKeyLabel IDL attribute returns a
string representing the actual key combination assigned by the user agent. In this example, an author has provided a button that can be invoked using a shortcut key. To
support full keyboards, the author has provided "C" as a possible key. To support devices
equipped only with numeric keypads, the author has provided "1" as another possibly key. <input type=button value=Collect onclick="collect()" accesskey="C 1" id=c>

http://developers.whatwg.org/editing.html[4/16/2014 9:30:37 PM]

8 User interaction HTML: The Living Standard - Edition for Web Developers

To tell the user what the shortcut key is, the author has this script here opted to explicitly
add the key combination to the button's label: function addShortcutKeyLabel(button) { if (button.accessKeyLabel != '') button.value += ' (' + button.accessKeyLabel + ')'; } addShortcutKeyLabel(document.getElementById('c')); Browsers on different platforms will show different labels, even for the same key combination,
based on the convention prevalent on that platform. For example, if the key combination is the
Control key, the Shift key, and the letter C, a Windows browser might display
"Ctrl+Shift+C ", whereas a Mac browser might display "^ C", while
an Emacs browser might just display "C-C ". Similarly, if the key combination is the
Alt key and the Escape key, Windows might use "Alt+Esc ", Mac might use
" browser might use "M-ESC " or
"ESC ESC ". In general, therefore, it is unwise to attempt to parse the value returned from the accessKeyLabel IDL attribute. ", and an Emacs

The accesskey attribute


All HTML elements may have the accesskey
content attribute set. The accesskey attribute's value is used
by the user agent as a guide for creating a keyboard shortcut that activates or focuses the
element. If specified, the value must be an ordered set of unique space-separated tokens
that are case-sensitive, each of which must be exactly one Unicode code point in
length. In the following example, a variety of links are given with access keys so that keyboard users
familiar with the site can more quickly navigate to the relevant pages: <nav> <p> <a title="Consortium Activities" accesskey="A" href="/Consortium/activities">Activities</a> | <a title="Technical Reports and Recommendations" accesskey="T" href="/TR/">Technical Reports</a> |
http://developers.whatwg.org/editing.html[4/16/2014 9:30:37 PM]

8 User interaction HTML: The Living Standard - Edition for Web Developers

<a title="Alphabetical Site Index" accesskey="S" href="/Consortium/siteindex">Site Index</a> | <a title="About This Site" accesskey="B" href="/Consortium/">About Consortium</a> | <a title="Contact Consortium" accesskey="C" href="/Consortium/contact">Contact</a> </p> </nav> In the following example, the search field is given two possible access keys, "s" and "0" (in
that order). A user agent on a device with a full keyboard might pick
Ctrl +Alt +S as the shortcut key, while a user agent on
a small device with just a numeric keypad might pick just the plain unadorned key 0: <form action="/search"> <label>Search: <input type="search" name="q" accesskey="s 0"></label> <input type="submit"> </form> In the following example, a button has possible access keys described. A script then tries to
update the button's label to advertise the key combination the user agent selected. <input type=submit accesskey="N @ 1" value="Compose"> ... <script> function labelButton(button) { if (button.accessKeyLabel) button.value += ' (' + button.accessKeyLabel + ')'; } var inputs = document.getElementsByTagName('input'); for (var i = 0; i < inputs.length; i += 1) { if (inputs[i].type == "submit") labelButton(inputs[i]); } </script> On one user agent, the button's label might become "Compose ( N)". On another, it might become "Compose (Alt+ +1)". If the user agent doesn't

http://developers.whatwg.org/editing.html[4/16/2014 9:30:37 PM]

8 User interaction HTML: The Living Standard - Edition for Web Developers

assign a key, it will be just "Compose ". The exact string depends on what the assigned access key is, and on how the user agent represents that key combination.

Editing

Making document regions editable: The contenteditable content attribute


The contenteditable attribute is an
enumerated attribute whose keywords are the empty string, true,
and false . The empty string and the true keyword map
to the true state. The false keyword maps to the false state.
In addition, there is a third state, the inherit state, which is the missing value default (and the invalid value default). The true state indicates that the element is editable. The inherit state
indicates that the element is editable if its parent is. The false state indicates that the element is not editable. element . contentEditable [ = value ] Returns "true", "false ", or "inherit", based on the state of the contenteditable attribute. Can be set, to change that state. Throws a SyntaxError exception if the new value isn't one of those strings. element . isContentEditable Returns true if the element is editable; otherwise, returns false.

Making entire documents editable: The designMode IDL attribute


document . designMode [ = value ] Returns "on" if the document is editable, and " off" if it isn't. Can be set, to change the document's current state. This focuses the document

http://developers.whatwg.org/editing.html[4/16/2014 9:30:37 PM]

8 User interaction HTML: The Living Standard - Edition for Web Developers

and resets the


selection in that document.

Best practices for in-page editors


Authors are encouraged to set the 'white-space' property on editing
hosts and on markup that was originally created through these editing mechanisms to the
value 'pre-wrap'. Default HTML whitespace handling is not well suited to WYSIWYG editing, and line
wrapping will not work correctly in some corner cases if 'white-space' is left at its default
value. As an example of problems that occur if the default 'normal' value is used instead, consider
the case of the user typing "yellow&blank;&blank;ball ", with two spaces (here
represented by "&blank;") between the words. With the editing rules in place for the default value of 'white-space' ('normal'), the resulting markup will either consist of "yellow&nbsp;ball " or "yellow&nbsp;ball "; i.e.,
there will be a non-breaking space between the two words in addition to the regular space. This
is necessary because the 'normal' value for 'white-space' requires adjacent regular spaces to be
collapsed together. In the former case, "yellow " might wrap to the next line (" "
being used here to represent a non-breaking space) even though "yellow " alone might fit at the end of the line; in the latter case, " ball", if wrapped to the
start of the line, would have visible indentation from the non-breaking space. When 'white-space' is set to 'pre-wrap', however, the editing rules will instead simply put
two regular spaces between the words, and should the two words be split at the end of a line, the
spaces would be neatly removed from the rendering.

Editing APIs
The definition of the terms active range, editing host, and
editable, the user interface requirements of elements that are editing hosts or editable, the execCommand() ,
queryCommandEnabled(),
queryCommandIndeterm() , queryCommandState(),
queryCommandSupported(), and queryCommandValue()
methods, text selections, and the delete the selection algorithm are defined in the
HTML Editing APIs specification. The interaction of editing and the undo/redo features in user
agents is defined by

http://developers.whatwg.org/editing.html[4/16/2014 9:30:37 PM]

8 User interaction HTML: The Living Standard - Edition for Web Developers

the UndoManager and DOM Transaction specification.

Spelling and grammar checking


The spellcheck attribute is an enumerated
attribute whose keywords are the empty string, true and false . The empty string and the true keyword map to the
true state. The false keyword maps to the false state. In
addition, there is a third state, the default state, which is the missing value
default (and the invalid value default). The true state indicates that the element is to have its spelling and
grammar checked. The default state indicates that the element is to act according to a default behavior, possibly based on the parent element's own spellcheck state, as defined below. The false state
indicates that the element is not to be checked. element . spellcheck [ = value ] Returns true if the element is to have its spelling and grammar checked; otherwise, returns
false. Can be set, to override the default and set the spellcheck content attribute. element . forceSpellCheck() Forces the user agent to report spelling and grammar errors on the element (if checking is
enabled), even if the user has never focused the element. (If the method is not invoked, user
agents can hide errors in text that wasn't just entered by the user.)

This specification does not define the user interface for spelling and grammar
checkers. A user agent could offer on-demand checking, could perform continuous checking while the
checking is enabled, or could use other interfaces.

Up next

8.7 Drag and drop

This document is a work in progress, if you spot something that you feel isn't quite right,

http://developers.whatwg.org/editing.html[4/16/2014 9:30:37 PM]

8 User interaction HTML: The Living Standard - Edition for Web Developers

please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/editing.html[4/16/2014 9:30:37 PM]

8.7 Drag and drop HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
Drag and drop
Introduction
The drag data store
The DataTransfer interface
The DataTransferItemList interface
The DataTransferItem interface
The DragEvent interface
Events summary
The draggable attribute
The dropzone attribute

Drag and drop


This section defines an event-based drag-and-drop mechanism. This specification does not define exactly what a drag-and-drop operation actually
is. On a visual medium with a pointing device, a drag operation could be the default action of a
mousedown event that is followed by a series of mousemove events, and the drop could be triggered by the mouse
being released. When using an input modality other than a pointing device, users would probably have to
explicitly indicate their intention to perform a drag-anddrop operation, stating what they wish
to drag and where they wish to drop it, respectively.

Introduction

http://developers.whatwg.org/dnd.html[4/16/2014 9:30:43 PM]

8.7 Drag and drop HTML: The Living Standard - Edition for Web Developers

To make an element draggable is simple: give the element a draggable attribute, and set an event listener for dragstart that stores the data being dragged. The event handler typically needs to check that it's not a text selection that is being
dragged, and then needs to store data into the DataTransfer object and set the
allowed effects (copy, move, link, or some combination). For example: <p>What fruits do you like?</p> <ol ondragstart="dragStartHandler(event)"> <li draggable="true" data-value="fruit-apple">Apples</li> <li draggable="true" data-value="fruit-orange">Oranges</li> <li draggable="true" data-value="fruit-pear">Pears</li> </ol> <script> var internalDNDType = 'text/x-example'; // set this to something specific to your site function dragStartHandler(event) { if (event.target instanceof HTMLLIElement) { // use the element's data-value="" attribute as the value to be moving: event.dataTransfer.setData(internalDNDType, event.target.dataset.value); event.dataTransfer.effectAllowed = 'move'; // only allow moves } else { event.preventDefault(); // don't allow selection to be dragged } } </script> To accept a drop, the drop target has to have a dropzone
attribute and listen to the drop event. The value of the dropzone attribute specifies what kind of
data to accept (e.g. "string:text/plain " to accept any text strings, or
"file:image/png " to accept a PNG image file) and what kind of feedback to give (e.g.
"move" to indicate that the data will be moved).

http://developers.whatwg.org/dnd.html[4/16/2014 9:30:43 PM]

8.7 Drag and drop HTML: The Living Standard - Edition for Web Developers

Instead of using the dropzone attribute, a drop


target can handle the dragenter event (to report whether or
not the drop target is to accept the drop) and the dragover
event (to specify what feedback is to be shown to the user). The drop event allows the actual drop to be performed. This
event needs to be canceled, so that the dropEffect attribute's value can be used by the source (otherwise it's reset). For example: <p>Drop your favorite fruits below:</p> <ol dropzone="move string:text/x-example" ondrop="dropHandler(event)"> <!-- don't forget to change the "text/x-example" type to something specific to your site --> </ol> <script> var internalDNDType = 'text/x-example'; // set this to something specific to your site function dropHandler(event) { var li = document.createElement('li'); var data = event.dataTransfer.getData(internalDNDType); if (data == 'fruit-apple') { li.textContent = 'Apples'; } else if (data == 'fruit-orange') { li.textContent = 'Oranges'; } else if (data == 'fruit-pear') { li.textContent = 'Pears'; } else { li.textContent = 'Unknown Fruit'; } event.target.appendChild(li); } </script> To remove the original element (the one that was dragged) from the display, the dragend event can be used. For our example here, that means updating the original markup to handle that event:
http://developers.whatwg.org/dnd.html[4/16/2014 9:30:43 PM]

8.7 Drag and drop HTML: The Living Standard - Edition for Web Developers

<p>What fruits do you like?</p> <ol ondragstart="dragStartHandler(event)" ondragend="dragEndHandler(event)"> ...as before... </ol> <script> function dragStartHandler(event) { // ...as before... } function dragEndHandler(event) { if (event.dataTransfer.dropEffect == 'move') { // remove the dragged element event.target.parentNode.removeChild(event.target); } } </script>

The drag data store


The data that underlies a drag-and-drop operation, known as the drag data store,
consists of the following information:

A drag data store item list, which is a list of items representing the dragged
data, each consisting of the following information: The drag data item kind The kind of data: Plain Unicode string Text. File Binary data with a file name. The drag data item type string A Unicode string giving the type or format of the data, generally given by a MIME
type. Some values that are not MIME types are
special-cased for legacy reasons. The API does not enforce the use of MIME types; other values can be used as well. In all cases, however, the values
are all converted to ASCII lowercase by the API.

http://developers.whatwg.org/dnd.html[4/16/2014 9:30:43 PM]

8.7 Drag and drop HTML: The Living Standard - Edition for Web Developers

Strings that contain space characters


cannot be used with the dropzone attribute, so authors are
encouraged to use only MIME types or custom strings (without
spaces). There is a limit of one Plain Unicode string item per item type string. The actual data A Unicode or binary string, in some cases with a file name (itself a Unicode string),
as per the drag data item kind. The drag data store item list is ordered in the order that the items were added to the list; most recently added last.

The following information, used to generate the UI feedback during the drag: User-agent-defined default feedback information, known as the drag data
store default
feedback.

Optionally, a bitmap image and the coordinate of a point within that image,
known as the
drag data store bitmap and drag data store hot spot coordinate.

A drag data store mode, which is one of the following:


Read/write mode For the dragstart event. New data can be added to the
drag data store. Read-only mode For the drop event. The list of items representing dragged
data can be read, including the data. No new data can be added. Protected mode For all other events. The formats and kinds in the drag data store list of
items representing dragged data can be enumerated, but the data itself is unavailable and no
new data can be added.

A drag data store allowed effects state, which is a string.


When a drag data store is created, it
must be initialized such that its drag data store item list is empty, it has no
drag data store default feedback, it has no drag data store bitmap and
drag data store hot spot coordinate, its drag data store mode is protected mode, and its drag data store allowed effects
state is the string "uninitialized ".

http://developers.whatwg.org/dnd.html[4/16/2014 9:30:43 PM]

8.7 Drag and drop HTML: The Living Standard - Edition for Web Developers

The DataTransfer interface


DataTransfer objects are used to expose the drag data store that
underlies a drag-and-drop operation. dataTransfer . dropEffect [ = value ] Returns the kind of operation that is currently selected. If the kind of operation isn't one
of those that is allowed by the effectAllowed attribute, then the operation will
fail. Can be set, to change the selected operation. The possible values are "none ", "copy ", " link", and "move". dataTransfer . effectAllowed [ = value ] Returns the kinds of operations that are to be allowed. Can be set (during the dragstart event), to change the
allowed operations. The possible values are "none ", "copy ", " copyLink", " copyMove", " link",
" linkMove", "move", "all", and
"uninitialized", dataTransfer . items Returns a DataTransferItemList object, with the drag data. dataTransfer . setDragImage(element, x, y) Uses the given element to update the drag feedback, replacing any previously specified
feedback. dataTransfer . types Returns an array listing the formats that were set in the dragstart event. In addition, if any files are being dragged,
then one of the types will be the string "Files ". data = dataTransfer . getData(format) Returns the specified data. If there is no such data, returns the empty string. dataTransfer . setData(format, data) Adds the specified data. dataTransfer . clearData ( [ format ] ) Removes the data of the specified formats. Removes all data if the argument is omitted.

http://developers.whatwg.org/dnd.html[4/16/2014 9:30:43 PM]

8.7 Drag and drop HTML: The Living Standard - Edition for Web Developers

dataTransfer . files Returns a FileList of the files being dragged, if any. DataTransfer objects are used during the drag-and-drop
events, and are only valid while those events are being fired.

The DataTransferItemList interface


Each DataTransfer object is associated with a DataTransferItemList object. items . length Returns the number of items in the drag data store. items[index] Returns the DataTransferItem object representing the indexth
entry in the drag data store. items . remove (index) Removes the indexth entry in the drag data store. items . clear () Removes all the entries in the drag data store. items . add (data) items . add (data, type) Adds a new entry for the given data to the drag data store. If the data is plain text then a type string has to be provided
also.

The DataTransferItem interface


Each DataTransferItem object is associated with a DataTransfer
object. item . kind Returns the drag data item kind, one of: "string",
"file". item . type Returns the drag data item type string.

http://developers.whatwg.org/dnd.html[4/16/2014 9:30:43 PM]

8.7 Drag and drop HTML: The Living Standard - Edition for Web Developers

item . getAsString(callback) Invokes the callback with the string data as the argument, if the drag data item
kind is Plain Unicode string. file = item . getAsFile () Returns a File object, if the drag data item kind is File.

The DragEvent interface


The drag-and-drop processing model involves several events. They all use the DragEvent interface. event . dataTransfer Returns the DataTransfer object for the event.

Although, for consistency with other event interfaces, the DragEvent interface has a constructor, it is not particularly useful. In particular, there's no way to
create a useful DataTransfer object from script, as DataTransfer objects
have a processing and security model that is coordinated by the browser during drag-and-drops.

Events summary
The following events are involved in the drag-and-drop
model. Event Name dragstart Source node &check; Cancelable Target Cancelable? Drag data store mode Read/write mode "none" dropEffect Default Action Initiate the dragand-drop operation drag Source node &check; Cancelable Protected mode "none" Continue the dragand-drop operation dragenter Immediate &check; Protected Based on Reject

http://developers.whatwg.org/dnd.html[4/16/2014 9:30:43 PM]

8.7 Drag and drop HTML: The Living Standard - Edition for Web Developers

user selection or the body element

Cancelable

mode

effectAllowed value

immediate user selection as potential target element

dragexit

Previous target element

Protected mode

"none"

None

dragleave

Previous target element

Protected mode

"none"

None

dragover

Current target element

&check; Cancelable

Protected mode

Based on effectAllowed value

Reset the current drag operation to "none"

drop

Current target element

&check; Cancelable

Read-only mode

Current drag operation

Varies

dragend

Source node

Protected mode

Current drag operation

Varies

Not shown in the above table: all these events bubble, and the effectAllowed attribute always has the value it had
after the dragstart event, defaulting to "uninitialized " in the dragstart event.

The draggable attribute


All HTML elements may have the draggable
content attribute set. The draggable attribute is an
enumerated attribute. It has three states. The first state is true and it has
the keyword true. The second state is false and it has the keyword
false. The third state is auto; it has no keywords but it is the missing value default. The true state means the element is draggable; the false state means that it is not. The auto state uses the default behavior of the user agent.

http://developers.whatwg.org/dnd.html[4/16/2014 9:30:43 PM]

8.7 Drag and drop HTML: The Living Standard - Edition for Web Developers

An element with a draggable attribute should also have a


title attribute that names the element for the purpose of
non-visual interactions. element . draggable [ = value ] Returns true if the element is draggable; otherwise, returns false. Can be set, to override the default and set the draggable
content attribute.

The dropzone attribute


All HTML elements may have the dropzone content
attribute set. When specified, its value must be an unordered set of unique space-separated tokens that are ASCII case-insensitive. The allowed values are the
following: copy Indicates that dropping an accepted item on the element will result in a copy of the
dragged data. move Indicates that dropping an accepted item on the element will result in the dragged data
being moved to the new location. link Indicates that dropping an accepted item on the element will result in a link to the
original data. Any keyword with eight characters or more, beginning with the an ASCII
case-insensitive match for the string "string:" Indicates that items with the drag data item kind Plain Unicode string
and the drag data item type string set to a value that matches the remainder of the keyword are accepted. Any keyword with six characters or more, beginning with an ASCII case-insensitive match for the string "file: " Indicates that items with the drag data item kind File and the
drag data item type string set to a value that matches the remainder of the keyword are accepted. The dropzone content attribute's values must not have more
than one of the three feedback values (copy, move, and link)
specified. If none are specified,

http://developers.whatwg.org/dnd.html[4/16/2014 9:30:43 PM]

8.7 Drag and drop HTML: The Living Standard - Edition for Web Developers

the copy value is


implied. An element with a dropzone attribute should also have a
title attribute that names the element for the purpose of
non-visual interactions. In this example, a div element is made into a drop target for image files using
the dropzone attribute. Images dropped into the target are
then displayed. <div dropzone="copy file:image/png file:image/gif file:image/jpeg" ondrop="receive(event, this)"> <p>Drop an image here to have it displayed.</p> </div> <script> function receive(event, element) { var data = event.dataTransfer.items; for (var i = 0; i < data.length; i += 1) { if ((data[i].kind == 'file') && (data[i].type.match('^image/'))) { var img = new Image(); img.src = window.createObjectURL(data[i].getAsFile()); element.appendChild(img); } } } </script>

Up next

9 Communication

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/dnd.html[4/16/2014 9:30:43 PM]

9 Communication HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
Communication
Event definitions
Server-sent events
Introduction

COMMUNICATION

Event definitions
Messages in server-sent events, Web sockets, cross-document
messaging, and channel messaging use the message event. The following interface is defined for this event: event . data Returns the data of the message. event . origin Returns the origin of the message, for server-sent events and
cross-document messaging. event . lastEventId Returns the last event ID string, for
server-sent events. event . source Returns the WindowProxy of the source window, for cross-document messaging, and the MessagePort being attached, in the connect event fired at SharedWorkerGlobalScope
objects. event . ports

http://developers.whatwg.org/comms.html[4/16/2014 9:30:48 PM]

9 Communication HTML: The Living Standard - Edition for Web Developers

Returns the MessagePort array sent with the message, for cross-document messaging and channel messaging.

Server-sent events

Introduction
To enable servers to push data to Web pages over HTTP or using dedicated server-push protocols,
this specification introduces the EventSource interface. Using this API consists of creating an EventSource object and registering an event
listener. var source = new EventSource('updates.cgi'); source.onmessage = function (event) { alert(event.data); }; On the server-side, the script ("updates.cgi" in this case) sends
messages in the following form, with the text/event-stream MIME type: data: This is the first message. data: This is the second message, it data: has two lines. data: This is the third message. Authors can separate events by using different event types. Here is a stream that has two event
types, "add" and "remove": event: add data: 73857293 event: remove data: 2153 event: add

http://developers.whatwg.org/comms.html[4/16/2014 9:30:48 PM]

9 Communication HTML: The Living Standard - Edition for Web Developers

data: 113411 The script to handle such a stream would look like this (where addHandler and removeHandler are functions that take one argument, the event): var source = new EventSource('updates.cgi'); source.addEventListener('add', addHandler, false); source.addEventListener('remove', removeHandler, false); The default event type is "message". Event streams are always decoded as UTF-8. There is no way to specify another character
encoding. Event stream requests can be redirected using HTTP 301 and 307 redirects as with normal HTTP
requests. Clients will reconnect if the connection is closed; a client can be told to stop
reconnecting using the HTTP 204 No Content response code. Using this API rather than emulating it using XMLHttpRequest or an
iframe allows the user agent to make better use of network resources in cases where the user agent implementor and the network operator are able to coordinate in advance. Amongst
other benefits, this can result in significant savings in battery life on portable devices. This
is discussed further in the section below on connectionless
push.

Up next

10 Conformance requirements

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/comms.html[4/16/2014 9:30:48 PM]

10 Conformance requirements HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
Conformance requirements
Dependencies

10 CONFORMANCE REQUIREMENTS
All diagrams, examples, and notes in this specification are
non-normative, as are all sections explicitly marked non-normative.
Everything else in this specification is normative. The key words "MUST", "MUST NOT", "REQUIRED", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and
"OPTIONAL" in the normative parts of this document are to be
interpreted as described in RFC2119. For readability, these words do
not appear in all uppercase letters in this specification. Requirements phrased in the imperative as part of algorithms
(such as "strip any leading space characters" or "return false and
abort these steps") are to be interpreted with the meaning of the
key word ("must", "should", "may", etc) used in introducing the
algorithm. Some conformance requirements are phrased as requirements on
attributes, methods or objects. Such requirements are to be
interpreted as requirements on user agents. Conformance requirements phrased as algorithms or specific steps
may be implemented in any manner, so long as the end result is
equivalent. (In particular, the algorithms defined in this
specification are intended to be easy to follow, and not intended to
be performant.) The only conformance class defined by this specification is user
agents. User agents may impose implementation-specific limits on
otherwise

http://developers.whatwg.org/conformance-requirements.html[4/16/2014 9:30:52 PM]

10 Conformance requirements HTML: The Living Standard - Edition for Web Developers

unconstrained inputs, e.g. to prevent denial of service


attacks, to guard against running out of memory, or to work around
platform-specific limitations. When support for a feature is disabled (e.g. as an emergency
measure to mitigate a security problem, or to aid in development, or
for performance reasons), user agents must act as if they had no
support for the feature whatsoever, and as if the feature was not
mentioned in this specification. For example, if a particular
feature is accessed via an attribute in a Web IDL interface, the
attribute itself would be omitted from the objects that implement
that interface leaving the attribute on the object but
making it return null or throw an exception is insufficient.

Dependencies
This specification relies on several other underlying
specifications. HTML Many fundamental concepts from HTML are used by this
specification. WebIDL The IDL blocks in this specification use the semantics of the
WebIDL specification.

Up next

11 Terminology

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/conformance-requirements.html[4/16/2014 9:30:52 PM]

11 Terminology HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
Terminology
The EventSource interface
Processing model
Parsing an event stream
Interpreting an event stream
Authoring notes
Connectionless push and other features
Garbage collection
Implementation advice
IANA considerations
text/event-stream
Last-Event-ID
Web sockets
Introduction

11 TERMINOLOGY
The construction "a Foo object", where
Foo is actually an interface, is sometimes
used instead of the more accurate "an object implementing the interface Foo". The term DOM is used to refer to the API set made available to
scripts in Web applications, and does not necessarily imply the
existence of an actual Document object or of any other
Node objects as defined in the DOM specifications. An IDL attribute is said to be getting when its value is
being retrieved (e.g. by author script), and is said to be
setting when a new value is assigned to it.

http://developers.whatwg.org/terminology-2.html[4/16/2014 9:30:57 PM]

11 Terminology HTML: The Living Standard - Edition for Web Developers

The EventSource interface


The EventSource() constructor takes one or two
arguments. The first specifies the URL to which to connect. The second specifies the
settings, if any, in the form of an EventSourceInit dictionary. When the EventSource() constructor is invoked, the UA must run these steps: 1. Resolve the URL specified in the first
argument, relative to the API base URL specified by the entry script's settings
object. 2. If the previous step failed, then throw a SyntaxError exception and abort these steps. 3. Create a new EventSource object. 4. Let CORS mode be Anonymous. 5. If the second argument is present, and the withCredentials dictionary member has the
value true, then set CORS mode to Use Credentials and initialize the new
EventSource object's withCredentials attribute to true. 6. Return the new EventSource object, but continue these steps
asynchronously. 7. Do a potentially CORS-enabled fetch of the resulting absolute
URL using the API referrer source specified by the entry script's settings
object, with the mode being CORS mode, and the origin being the entry script's origin, and process the resource obtained in this fashion, if any, as
described below. The definition of the fetching algorithm (which is
used by CORS) is such that if the browser is already fetching the resource identified by the
given absolute URL, that connection can be reused, instead of a new connection being established. All messages received up to this point are dispatched immediately, in this
case. The url attribute must return the
absolute URL that resulted from resolving the
value that was passed to the constructor. The withCredentials attribute
must return the value to which it was last initialized. When the object is created, it must be
initialized to false. The readyState attribute represents
the state of the connection. It can have the following values: CONNECTING (numeric value 0)
http://developers.whatwg.org/terminology-2.html[4/16/2014 9:30:57 PM]

11 Terminology HTML: The Living Standard - Edition for Web Developers

The connection has not yet been established, or it was closed and the user agent is
reconnecting. OPEN (numeric value 1) The user agent has an open connection and is dispatching events as it receives them. CLOSED (numeric value 2) The connection is not open, and the user agent is not trying to reconnect. Either there was a
fatal error or the close() method was invoked. When the object is created its readyState must
be set to CONNECTING (0). The rules given below
for handling the connection define when the value changes. The close() method must abort any
instances of the fetch algorithm started for this EventSource object,
and must set the readyState attribute to CLOSED . The following are the event handlers (and their corresponding event handler event types) that must be supported, as event
handler IDL attributes, by all objects implementing the EventSource
interface: Event handler Event handler event type onopen onmessage onerror open message error

In addition to the above, each EventSource object has the following associated
with it:

A reconnection time, in
milliseconds. This must initially be a user-agentdefined value, probably in the region of a few
seconds.

A last event ID string. This must


initially be the empty string.
These values are not currently exposed on the interface.

Processing model
The resource indicated in the argument to the EventSource
constructor is fetched when the constructor is run.

http://developers.whatwg.org/terminology-2.html[4/16/2014 9:30:57 PM]

11 Terminology HTML: The Living Standard - Edition for Web Developers

For HTTP connections, the Accept header may be included; if included, it must contain only formats of event framing that are supported by the user agent (one of which must
be text/event-stream , as described below). If the event source's last event ID
string is not the empty string, then a Last-Event-ID HTTP header must be included with the request,
whose value is the value of the event source's last event ID string, encoded as UTF-8. User agents should use the Cache-Control: no-cache header in requests to bypass
any caches for requests of event sources. (This header is not a custom request header, so the user agent will still use the CORS simple
cross-origin request mechanism.) User agents should ignore HTTP cache headers in the response, never caching event sources. As data is received, the tasks queued by the networking
task source to handle the data must act as follows. HTTP 200 OK responses with a Content-Type header specifying the type text/event-stream , ignoring any MIME type parameters, must be processed
line by line as described below. When a successful response with a supported MIME type is received, such that the
user agent begins parsing the contents of the stream, the user agent must announce the
connection. The task that the networking task source places
on the task queue once the fetching algorithm for such a
resource (with the correct MIME type) has completed must cause the user agent to
asynchronously reestablish the connection. This applies whether the connection is
closed gracefully or unexpectedly (but does not apply when the fetch algorithm is
canceled by the user agent, e.g. in response to window.stop() ,
since in those cases the final task is actually discarded).
It doesn't apply for the error conditions listed below except
where explicitly specified. HTTP 200 OK responses that have a Content-Type specifying an unsupported type, or
that have no Content-Type at all, must cause the user agent to fail the connection. HTTP 305 Use Proxy, 401 Unauthorized, and 407 Proxy Authentication Required should be treated
transparently as for any other subresource. HTTP 301 Moved Permanently, 302 Found, 303 See Other, and 307 Temporary Redirect responses are
handled by the fetching and CORS

http://developers.whatwg.org/terminology-2.html[4/16/2014 9:30:57 PM]

11 Terminology HTML: The Living Standard - Edition for Web Developers

algorithms. In the case of 301


redirects, the user agent must also remember the new URL so that subsequent requests for this
resource for this EventSource object start with the URL given for the last 301 seen
for requests for this object. Network errors that prevents the connection from
being established in the first place (e.g. DNS errors), must cause the user agent to
asynchronously reestablish the connection. Any other HTTP response code not listed here, as well as the
cancelation of the fetch algorithm by the user agent (e.g. in response to window.stop() or the user canceling the network connection
manually) must cause the user agent to fail the connection. For non-HTTP protocols, UAs should act in equivalent ways. When a user agent is to announce the connection, the user agent must queue a
task which, if the readyState attribute is
set to a value other than CLOSED, sets the readyState attribute to OPEN and fires a simple
event named open at the EventSource
object. When a user agent is to reestablish the connection, the user agent must run the
following steps. These steps are run asynchronously, not as part of a task. (The tasks that it queues, of course, are run like normal tasks
and not asynchronously.) 1. Queue a task to run the following steps: 1. If the readyState attribute is set to
CLOSED , abort the task. 2. Set the readyState attribute to CONNECTING . 3. Fire a simple event named error at the
EventSource object. 2. Wait a delay equal to the reconnection time of the event source. 3. Optionally, wait some more. In particular, if the previous attempt failed, then user
agents might introduce an exponential backoff delay to avoid overloading a potentially already
overloaded server. Alternatively, if the operating system has reported that there is no network
connectivity, user agents might wait for the operating system to announce that the network connection has returned before retrying. 4. Wait until the aforementioned task has run, if it has not yet run.

http://developers.whatwg.org/terminology-2.html[4/16/2014 9:30:57 PM]

11 Terminology HTML: The Living Standard - Edition for Web Developers

5. Queue a task to run the following steps: 1. If the readyState attribute is not set
to CONNECTING, abort these steps. 2. Perform a potentially CORS-enabled fetch of the absolute
URL of the event source resource, using the same referrer source, and with the
same mode and origin, as those
used in the original request triggered by the EventSource() constructor, and process the resource obtained in
this fashion, if any, as described earlier in this section. When a user agent is to fail the connection, the user agent must queue a
task which, if the readyState attribute is
set to a value other than CLOSED, sets the readyState attribute to CLOSED and fires a simple
event named error at the EventSource object.
Once the user agent has failed the connection, it does not attempt to reconnect! The task source for any tasks that are queued by EventSource objects is the remote event
task source.

Parsing an event stream


This event stream format's MIME type is text/event-stream. The event stream format is as described by the stream production of the following ABNF, the character set for which is Unicode. stream event comment field end-of-line end-of-line ; characters lf cr space colon bom name-char %x003B-10FFFF = %x000A ; U+000A LINE FEED (LF) = %x000D ; U+000D CARRIAGE RETURN (CR) = %x0020 ; U+0020 SPACE = %x003A ; U+003A COLON (:) = %xFEFF ; U+FEFF BYTE ORDER MARK = %x0000-0009 / %x000B-000C / %x000E-0039 / = ( cr lf / cr / lf ) = [ bom ] *event = *( comment / field ) end-of-line = colon *any-char end-of-line = 1*name-char [ colon [ space ] *any-char ]

http://developers.whatwg.org/terminology-2.html[4/16/2014 9:30:57 PM]

11 Terminology HTML: The Living Standard - Edition for Web Developers

; a Unicode character other than U+000A LINE FEED (LF), U+000D CARRIAGE RETURN (CR), or U+003A COLON (:) any-char = %x0000-0009 / %x000B-000C / %x000E-10FFFF ; a Unicode character other than U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) Event streams in this format must always be encoded as UTF-8. Lines must be separated by either a U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character
pair, a single U+000A LINE FEED (LF) character, or a single U+000D CARRIAGE RETURN (CR)
character. Since connections established to remote servers for such resources are expected to be
long-lived, UAs should ensure that appropriate buffering is used. In particular, while line
buffering with lines are defined to end with a single U+000A LINE FEED (LF) character is safe,
block buffering or line buffering with different expected line endings can cause delays in event dispatch.

Interpreting an event stream


Streams must be decoded using the UTF-8 decode algorithm. The UTF-8 decode algorithm strips one leading UTF-8 Byte Order Mark (BOM), if any. The stream must then be parsed by reading everything line by line, with a U+000D CARRIAGE
RETURN U+000A LINE FEED (CRLF) character pair, a single U+000A LINE FEED (LF) character not
preceded by a U+000D CARRIAGE RETURN (CR) character, and a single U+000D CARRIAGE RETURN (CR)
character not followed by a U+000A LINE FEED (LF) character being the ways in which a line can
end. When a stream is parsed, a data buffer, an event type
buffer, and a last event ID buffer must be associated with it. They must be
initialized to the empty string Lines must be processed, in the order they are received, as follows: If the line is empty (a blank line) Dispatch the event, as defined below.

http://developers.whatwg.org/terminology-2.html[4/16/2014 9:30:57 PM]

11 Terminology HTML: The Living Standard - Edition for Web Developers

If the line starts with a U+003A COLON character (:) Ignore the line. If the line contains a U+003A COLON character (:) Collect the characters on the line before the first U+003A COLON character (:), and let field be that string. Collect the characters on the line after the first U+003A COLON character (:), and let value be that string. If value starts with a U+0020 SPACE
character, remove it from value. Process the field using the steps described below, using field as the field name and value as the field value. Otherwise, the string is not empty but does not contain a U+003A COLON character (:) Process the field using the steps described below, using the
whole line as the field name, and the empty string as the field value. Once the end of the file is reached, any pending data must be discarded. (If the file ends in
the middle of an event, before the final empty line, the incomplete event is not dispatched.) The steps to process the field given a field name and a
field value depend on the field name, as given in the following list. Field names must be compared literally, with no case folding performed. If the field name is "event" Set the event type buffer to field value. If the field name is "data" Append the field value to the data buffer, then append a single U+000A
LINE FEED (LF) character to the data buffer. If the field name is "id" Set the last event ID buffer to the field value. If the field name is "retry" If the field value consists of only ASCII digits, then interpret the field
value as an integer in base ten, and set the event stream's reconnection time to that integer.
Otherwise, ignore the field. Otherwise

http://developers.whatwg.org/terminology-2.html[4/16/2014 9:30:57 PM]

11 Terminology HTML: The Living Standard - Edition for Web Developers

The field is ignored. When the user agent is required to dispatch the event,
then the user agent must act as follows: 1. Set the last event ID string of
the event source to the value of the last event ID buffer. The buffer does
not get reset, so the last event ID
string of the event source remains set to this value until the next time it is set by the
server. 2. If the data buffer is an empty string, set the data buffer and the event type buffer to the empty string and
abort these steps. 3. If the data buffer's last character is a U+000A LINE FEED (LF)
character, then remove the last character from the data buffer. 4. Create an event that uses the MessageEvent interface, with the event type message, which does not bubble, is not cancelable, and has no
default action. The data attribute must be initialized
to the value of the data buffer, the origin attribute must be initialized to the Unicode serialization of the
origin of the event stream's final URL (i.e. the URL after redirects), and the lastEventId attribute must be initialized to the
last event ID string of the event source.
This event is not trusted. 5. If the event type buffer has a value other than the empty string,
change the type of the newly created event to equal the
value of the event type buffer. 6. Set the data buffer and the event type buffer to
the empty string. 7. Queue a task which, if the readyState attribute is set to a value other than CLOSED , dispatches the newly created event at the
EventSource object. If an event doesn't have an "id" field, but an earlier event did set the event source's last event ID string, then the
event's lastEventId field will be set to the
value of whatever the last seen "id" field was. The following event stream, once followed by a blank line: data: YHOO data: +2 data: 10 ...would cause an event message with the interface
MessageEvent to be dispatched on the EventSource object. The event's
data attribute would

http://developers.whatwg.org/terminology-2.html[4/16/2014 9:30:57 PM]

11 Terminology HTML: The Living Standard - Edition for Web Developers

contain the string


YHOO\n+2\n10 (where \n represents a newline). This could be used as follows: var stocks = new EventSource("http://stocks.example.com/ticker.php"); stocks.onmessage = function (event) { var data = event.data.split('\n'); updateStocks(data[0], data[1], data[2]); }; ...where updateStocks() is a function defined as: function updateStocks(symbol, delta, value) { ... } ...or some such. The following stream contains four blocks. The first block has just a comment, and will fire
nothing. The second block has two fields with names "data" and "id" respectively; an event will
be fired for this block, with the data "first event", and will then set the last event ID to "1"
so that if the connection died between this block and the next, the server would be sent a Last-Event-ID header with the value "1". The third block fires
an event with data "second event", and also has an "id" field, this time with no value, which
resets the last event ID to the empty string (meaning no Last-Event-ID header will now be sent in the event of a
reconnection being attempted). Finally, the last block just fires an event with the data "thirdevent" (with a single leading space character). Note that the last still has to
end with a blank line, the end of the stream is not enough to trigger the dispatch of the last
event. : test stream data: first event id: 1 data:second event id data:third event The following stream fires two events:

http://developers.whatwg.org/terminology-2.html[4/16/2014 9:30:57 PM]

11 Terminology HTML: The Living Standard - Edition for Web Developers

data data data data: The first block fires events with the data set to the empty string, as would the last block if
it was followed by a blank line. The middle block fires an event with the data set to a single
newline character. The last block is discarded because it is not followed by a blank line. The following stream fires two identical events: data:test data:test This is because the space after the colon is ignored if present.

Authoring notes
Legacy proxy servers are known to, in certain cases, drop HTTP connections after a short
timeout. To protect against such proxy servers, authors can include a comment line (one starting
with a ':' character) every 15 seconds or so. Authors wishing to relate event source connections to each other or to specific documents
previously served might find that relying on IP addresses doesn't work, as individual clients can
have multiple IP addresses (due to having multiple proxy servers) and individual IP addresses can
have multiple clients (due to sharing a proxy server). It is better to include a unique identifier
in the document when it is served and then pass that identifier as part of the URL when the
connection is established. Authors are also cautioned that HTTP chunking can have unexpected negative effects on the
reliability of this protocol. Where possible, chunking should be disabled for serving event
streams unless the rate of messages is high enough for this not to matter. Clients that support HTTP's per-server connection limitation might run into

http://developers.whatwg.org/terminology-2.html[4/16/2014 9:30:57 PM]

11 Terminology HTML: The Living Standard - Edition for Web Developers

trouble when
opening multiple pages from a site if each page has an EventSource to the same
domain. Authors can avoid this using the relatively complex mechanism of using unique domain names
per connection, or by allowing the user to enable or disable the EventSource
functionality on a perpage basis, or by sharing a single EventSource object using a
shared worker.

Connectionless push and other features


User agents running in controlled environments, e.g. browsers on mobile handsets tied to
specific carriers, may offload the management of the connection to a proxy on the network. In such
a situation, the user agent for the purposes of conformance is considered to include both the
handset software and the network proxy. For example, a browser on a mobile device, after having established a connection, might detect
that it is on a supporting network and request that a proxy server on the network take over the
management of the connection. The timeline for such a situation might be as follows: 1. Browser connects to a remote HTTP server and requests the resource specified by the author
in the EventSource constructor. 2. The server sends occasional messages. 3. In between two messages, the browser detects that it is idle except for the network activity
involved in keeping the TCP connection alive, and decides to switch to sleep mode to save
power. 4. The browser disconnects from the server. 5. The browser contacts a service on the network, and requests that that service, a "push
proxy", maintain the connection instead. 6. The "push proxy" service contacts the remote HTTP server and requests the resource specified
by the author in the EventSource constructor (possibly including a Last-Event-ID HTTP header, etc). 7. The browser allows the mobile device to go to sleep. 8. The server sends another message. 9. The "push proxy" service uses a technology such as OMA push to convey the event to the
mobile device, which wakes only enough to process the event and then returns to sleep. This can reduce the total data usage, and can therefore result in considerable power
savings. As well as implementing the existing API and text/event-stream wire
http://developers.whatwg.org/terminology-2.html[4/16/2014 9:30:57 PM]

11 Terminology HTML: The Living Standard - Edition for Web Developers

format as
defined by this specification and in more distributed ways as described above, formats of event
framing defined by other applicable specifications may be supported. This
specification does not define how they are to be parsed or processed.

Garbage collection
While an EventSource object's readyState is CONNECTING , and the object has one or more event
listeners registered for open, message or error events, there must
be a strong reference from the Window or WorkerGlobalScope object that
the EventSource object's constructor was invoked from to the EventSource
object itself. While an EventSource object's readyState is OPEN, and the object has one or more event listeners
registered for message or error events, there must be a strong reference from the
Window or WorkerGlobalScope object that the EventSource
object's constructor was invoked from to the EventSource object itself. While there is a task queued by an EventSource object on the remote event task source, there must be a strong reference from the Window or WorkerGlobalScope object that the EventSource object's constructor was invoked from to that EventSource object. If a user agent is to forcibly close an
EventSource object (this happens when a Document object goes away
permanently), the user agent must abort any instances of the fetch algorithm started
for this EventSource object, and must set the readyState attribute to CLOSED . If an EventSource object is garbage collected while its connection is still open,
the user agent must abort any instance of the fetch algorithm opened by
this EventSource. It's possible for one active network connection to be shared by multiple EventSource objects and their fetch algorithms, which is why the above
is phrased in terms of aborting the fetch algorithm and not the actual underlying
download.

http://developers.whatwg.org/terminology-2.html[4/16/2014 9:30:57 PM]

11 Terminology HTML: The Living Standard - Edition for Web Developers

Implementation advice
User agents are strongly urged to provide detailed diagnostic information about
EventSource objects and their related network connections in their development
consoles, to aid authors in debugging code using this API. For example, a user agent could have a panel displaying all the EventSource objects a page has created, each listing the constructor's arguments, whether there was a network
error, what the CORS status of the connection is and what headers were sent by the client and
received from the server to lead to that status, the messages that were received and how they were
parsed, and so forth. Implementations are especially encouraged to report detailed information to their development
consoles whenever an error event is fired, since little to no
information can be made available in the events themselves.

IANA considerations

text/event-stream
This registration is for community review and will be submitted to the IESG for review,
approval, and registration with IANA. Type name: text Subtype name: event-stream Required parameters: No parameters Optional parameters: charset The charset parameter may be provided. The parameter's value must be
" utf-8 ". This parameter serves no purpose; it is only allowed for
compatibility with legacy servers. Encoding considerations: 8bit (always UTF-8)

http://developers.whatwg.org/terminology-2.html[4/16/2014 9:30:57 PM]

11 Terminology HTML: The Living Standard - Edition for Web Developers

Security considerations: An event stream from an origin distinct from the origin of the content consuming the event
stream can result in information leakage. To avoid this, user agents are required to apply CORS
semantics. Event streams can overwhelm a user agent; a user agent is expected to apply suitable
restrictions to avoid depleting local resources because of an overabundance of information from
an event stream. Servers can be overwhelmed if a situation develops in which the server is causing clients to
reconnect rapidly. Servers should use a 5xx status code to indicate capacity problems, as this
will prevent conforming clients from reconnecting automatically. Interoperability considerations:
Rules for processing both conforming and non-conforming content are defined in this
specification. Published specification:
This document is the relevant specification. Applications that use this media type:
Web browsers and tools using Web services. Additional information: Magic number(s): No sequence of bytes can uniquely identify an event stream. File extension(s): No specific file extensions are recommended for this type. Macintosh file type code(s): No specific Macintosh file type codes are recommended for this type. Person & email address to contact for further information: Ian Hickson <ian@hixie.ch> Intended usage: Common Restrictions on usage: This format is only expected to be used by dynamic open-ended streams served using HTTP or a
similar protocol. Finite resources are not expected to be labeled with this type. Author: Ian Hickson <ian@hixie.ch>

http://developers.whatwg.org/terminology-2.html[4/16/2014 9:30:57 PM]

11 Terminology HTML: The Living Standard - Edition for Web Developers

Change controller: W3C Fragment identifiers have no meaning with


text/event-stream resources.

Last-Event-ID
This section describes a header for registration in the Permanent Message Header Field
Registry. Header field name: Last-Event-ID Applicable protocol: http Status: standard Author/Change controller: W3C Specification document(s):
This document is the relevant specification. Related information: None.

Web sockets

Introduction
To enable Web applications to maintain bidirectional communications with server-side processes,
this specification introduces the WebSocket interface. This interface does not allow for raw access to the underlying network. For example, this interface could not be used to implement an IRC client without proxying messages
through a custom server.

http://developers.whatwg.org/terminology-2.html[4/16/2014 9:30:57 PM]

11 Terminology HTML: The Living Standard - Edition for Web Developers


Up next

12 Conformance requirements

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/terminology-2.html[4/16/2014 9:30:57 PM]

12 Conformance requirements HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
Conformance requirements
Dependencies

12 CONFORMANCE REQUIREMENTS
All diagrams, examples, and notes in this specification are
non-normative, as are all sections explicitly marked non-normative.
Everything else in this specification is normative. The key words "MUST", "MUST NOT", "REQUIRED", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and
"OPTIONAL" in the normative parts of this document are to be
interpreted as described in RFC2119. For readability, these words do
not appear in all uppercase letters in this specification. Requirements phrased in the imperative as part of algorithms
(such as "strip any leading space characters" or "return false and
abort these steps") are to be interpreted with the meaning of the
key word ("must", "should", "may", etc) used in introducing the
algorithm. Some conformance requirements are phrased as requirements on
attributes, methods or objects. Such requirements are to be
interpreted as requirements on user agents. Conformance requirements phrased as algorithms or specific steps
may be implemented in any manner, so long as the end result is
equivalent. (In particular, the algorithms defined in this
specification are intended to be easy to follow, and not intended to
be performant.) The only conformance class defined by this specification is user
agents. User agents may impose implementation-specific limits on
otherwise

http://developers.whatwg.org/conformance-requirements-0.html[4/16/2014 9:31:03 PM]

12 Conformance requirements HTML: The Living Standard - Edition for Web Developers

unconstrained inputs, e.g. to prevent denial of service


attacks, to guard against running out of memory, or to work around
platform-specific limitations. When support for a feature is disabled (e.g. as an emergency
measure to mitigate a security problem, or to aid in development, or
for performance reasons), user agents must act as if they had no
support for the feature whatsoever, and as if the feature was not
mentioned in this specification. For example, if a particular
feature is accessed via an attribute in a Web IDL interface, the
attribute itself would be omitted from the objects that implement
that interface leaving the attribute on the object but
making it return null or throw an exception is insufficient.

Dependencies
This specification relies on several other underlying
specifications. HTML Many fundamental concepts from HTML are used by this
specification. WebIDL The IDL blocks in this specification use the semantics of the
WebIDL specification.

Up next

13 Terminology

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/conformance-requirements-0.html[4/16/2014 9:31:03 PM]

13 Terminology HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
Terminology
The WebSocket interface
Feedback from the protocol
Ping and Pong frames
Parsing WebSocket URLs
Event definitions
Garbage collection
Cross-document messaging
Introduction
Security
Posting messages
Channel messaging
Introduction
Examples
Ports as the basis of an object-capability model on the Web
Ports as the basis of abstracting out service implementations
Message channels
Message ports
Broadcasting to many ports
Ports and garbage collection

13 TERMINOLOGY
The construction "a Foo object", where
Foo is actually an interface, is sometimes
used instead of the more accurate "an object implementing the interface Foo". The term DOM is used to refer to the API set made available to
scripts in Web applications, and does not necessarily imply the
existence of an actual

http://developers.whatwg.org/terminology-3.html[4/16/2014 9:31:09 PM]

13 Terminology HTML: The Living Standard - Edition for Web Developers

Document object or of any other


Node objects as defined in the DOM specifications. An IDL attribute is said to be getting when its value is
being retrieved (e.g. by author script), and is said to be
setting when a new value is assigned to it.

The WebSocket interface


The WebSocket(url, protocols) constructor takes one or two arguments. The first argument,
url, specifies the URL to which to connect. The second, protocols, if present, is either a string or an array of strings. If it is a
string, it is equivalent to an array consisting of just that string; if it is omitted, it is equivalent to the empty array. Each string in the array is a subprotocol name. The connection will
only be established if the server reports that it has selected one of these subprotocols. The
subprotocol names must all be strings that match the requirements for elements that comprise the
value of Sec-WebSocket-Protocol fields as
defined by the WebSocket protocol specification. When the WebSocket() constructor is invoked, the UA must run these steps: 1. Parse a WebSocket URL's components from the url argument, to
obtain host, port, resource name, and
secure. If this fails, throw a SyntaxError exception and abort
these steps. [WSP] 2. If secure is false but the origin of the entry
script has a scheme component that is itself a secure protocol, e.g. HTTPS, then throw a
SecurityError exception and abort these steps. 3. If port is a port to which the user agent is configured to block access,
then throw a SecurityError exception and abort these steps. (User agents typically
block access to well-known ports like SMTP.) Access to ports 80 and 443 should not be blocked, including the unlikely cases when secure is false but port is 443 or secure
is true but port is 80. 4. If protocols is absent, let protocols be an empty
array. Otherwise, if protocols is present and a string, let protocols instead be an array consisting of just that string. 5. If any of the values in protocols occur more than once or otherwise
fail to

http://developers.whatwg.org/terminology-3.html[4/16/2014 9:31:09 PM]

13 Terminology HTML: The Living Standard - Edition for Web Developers

match the requirements for elements that comprise the value of Sec-WebSocket-Protocol fields as defined by the
WebSocket protocol specification, then throw a SyntaxError exception and abort these
steps. [WSP] 6. Let origin be the ASCII
serialization of the origin of the entry script, converted
to ASCII lowercase. 7. Return a new WebSocket object, but continue these steps
asynchronously. 8. Let the new object's client-specified protocols be the values (if any) given in protocols. 9. Establish a WebSocket connection given the set (host, port, resource name, secure), along with
the protocols list, an empty list for the extensions, and origin. The headers to send appropriate cookies must be a Cookie header whose value is the cookie-string computed from
the user's cookie store and the URL url; for these purposes this is
not a "non-HTTP" API. When the user agent validates the server's
response during the "establish a WebSocket connection" algorithm, if the status code
received from the server is not 101 (e.g. it is a redirect), the user agent must fail the
WebSocket connection. Following HTTP procedures here could introduce serious security problems in a
Web browser context. For example, consider a host with a WebSocket server at one path and an
open HTTP redirector at another. Suddenly, any script that can be given a particular WebSocket
URL can be tricked into communicating to (and potentially sharing secrets with) any host on the Internet, even if the script checks that the URL has the right hostname. If the establish a WebSocket connection algorithm fails, it triggers the
fail the WebSocket connection algorithm, which then invokes the close the WebSocket
connection algorithm, which then establishes that the WebSocket connection is closed,
which fires the close event as
described below. The url attribute must return the result of
resolving the URL that was passed to the
constructor. (It doesn't matter what it is resolved relative to, since we already know it is an
absolute URL.) The readyState attribute represents
the state of the connection. It can have the following values:

http://developers.whatwg.org/terminology-3.html[4/16/2014 9:31:09 PM]

13 Terminology HTML: The Living Standard - Edition for Web Developers

CONNECTING (numeric value 0) The connection has not yet been established. OPEN (numeric value 1) The WebSocket connection is established and communication is possible. CLOSING (numeric value 2) The connection is going through the closing handshake, or the close() method has been invoked. CLOSED (numeric value 3) The connection has been closed or could not be opened. When the object is created its readyState must be
set to CONNECTING (0). The extensions attribute must
initially return the empty string. After the WebSocket connection is established, its value
might change, as defined below. The extensions attribute returns the
extensions selected by the server, if any. (Currently this will only ever be the empty
string.) The protocol attribute must initially
return the empty string. After the WebSocket connection is established, its value might
change, as defined below. The protocol attribute returns the
subprotocol selected by the server, if any. It can be used in conjunction with the array form of
the constructor's second argument to perform subprotocol negotiation. The close() method must run the following
steps: 1. If the method's first argument is present but is neither an integer equal to 1000 nor an
integer in the range 3000 to 4999, throw an InvalidAccessError exception and abort
these steps. 2. If the method's second argument is present, then run these substeps: 1. Let raw reason be the method's second argument. 2. Let Unicode reason be the result of converting raw reason to a sequence of Unicode characters. 3. Let reason be the result of encoding Unicode
reason as UTF-8.

http://developers.whatwg.org/terminology-3.html[4/16/2014 9:31:09 PM]

13 Terminology HTML: The Living Standard - Edition for Web Developers

4. If reason is longer than 123 bytes, then throw a


SyntaxError exception and abort these steps. 3. Run the first matching steps from the following list: If the readyState attribute is in the CLOSING (2) or CLOSED (3) state Do nothing. The connection is already closing or is already closed. If it has not already,
a close event will eventually fire as described below. If the WebSocket connection is not yet established [WSP] Fail the WebSocket connection and set the readyState attribute's value to CLOSING (2). [WSP] The fail the WebSocket connection algorithm invokes the close the WebSocket connection algorithm, which then establishes that the WebSocket connection is
closed, which fires the close event as described below. If the WebSocket closing handshake has not yet been started [WSP] Start the WebSocket closing handshake and set the readyState attribute's value to CLOSING (2). [WSP] If the first argument is present, then the status code to use in the
WebSocket Close message must be the integer given by the first argument. [WSP] If the second argument is also present, then reason must be provided in
the Close message after the status code. [RFC3629]
[WSP] The start the WebSocket closing handshake algorithm eventually invokes
the close the WebSocket connection algorithm, which then establishes that the WebSocket connection is closed, which fires the close event as described below. Otherwise Set the readyState attribute's value to CLOSING (2). The WebSocket closing handshake is started, and will eventually invoke
the close the WebSocket connection algorithm, which will establish that the WebSocket connection is closed, and thus the close
event will fire, as described below. The bufferedAmount attribute must
return the number of bytes of application

http://developers.whatwg.org/terminology-3.html[4/16/2014 9:31:09 PM]

13 Terminology HTML: The Living Standard - Edition for Web Developers

data (UTF-8 text and binary data) that have been queued
using send() but that, as of the last time the event
loop started executing a task, had not yet been
transmitted to the network. (This thus includes any text sent during the execution of the current
task, regardless of whether the user agent is able to transmit text asynchronously with script
execution.) This does not include framing overhead incurred by the protocol, or buffering done by
the operating system or network hardware. If the connection is closed, this attribute's value will
only increase with each call to the send() method (the
number does not reset to zero once the connection closes). In this simple example, the bufferedAmount
attribute is used to ensure that updates are sent either at the rate of one update every 50ms, if
the network can handle that rate, or at whatever rate the network can handle, if that is too fast. var socket = new WebSocket('ws://game.example.com:12010/updates'); socket.onopen = function () { setInterval(function() { if (socket.bufferedAmount == 0) socket.send(getUpdateData()); }, 50); }; The bufferedAmount attribute can also be
used to saturate the network without sending the data at a higher rate than the network can
handle, though this requires more careful monitoring of the value of the attribute over time. When a WebSocket object is created, its binaryType IDL attribute must be set to the
string "blob". On getting, it must return the last value it was set to. On
setting, the user agent must set the IDL attribute to the new value. This attribute allows authors to control how binary data is exposed to scripts. By
setting the attribute to "blob", binary data is returned in
Blob form; by setting it to "arraybuffer ", it is returned in
ArrayBuffer form. User agents can use this as a hint for how to handle incoming
binary data: if the attribute is set to "blob", it is safe to spool it to
disk, and if it is set to "arraybuffer", it is likely more efficient to keep
the data in memory. Naturally, user agents are encouraged to use more subtle heuristics to decide
whether to keep incoming data in memory or not, e.g. based on how big the data is or how

http://developers.whatwg.org/terminology-3.html[4/16/2014 9:31:09 PM]

13 Terminology HTML: The Living Standard - Edition for Web Developers

common it
is for a script to change the attribute at the last minute. This latter aspect is important in
particular because it is quite possible for the attribute to be changed after the user agent has
received the data but before the user agent has fired the event for it. The send(data) method
transmits data using the connection. If the readyState attribute is CONNECTING, it must throw an
InvalidStateError exception. Otherwise, the user agent must run the appropriate set
of steps from the following list: If the argument is a string Let data be the result of converting the data argument to a sequence of Unicode
characters. If the WebSocket connection is established and the WebSocket closing handshake has not yet started, then the
user agent must send a WebSocket Message comprised of data using a
text frame opcode; if the data cannot be sent, e.g. because it would need to be buffered but the buffer is full, the user agent must close the WebSocket connection with prejudice. Any invocation of this method with a
string argument that does not throw an exception must increase the bufferedAmount attribute by the number of bytes
needed to express the argument as UTF-8. If the argument is a Blob object If the WebSocket connection is established, and the WebSocket closing handshake has not yet started, then the user
agent must send a WebSocket Message comprised of data using a binary
frame opcode; if the data cannot be sent, e.g. because it would need to be buffered but the
buffer is full, the user agent must close the WebSocket connection with prejudice. The data to be sent is the raw data
represented by the Blob object. Any invocation of this method with a
Blob argument that does not throw an exception must increase the bufferedAmount attribute by the size of the
Blob object's raw data, in bytes. If the argument is an ArrayBuffer object If the WebSocket connection is established, and the WebSocket closing handshake has not yet started, then the user
agent must send a WebSocket Message comprised of data using a binary
frame opcode; if the data cannot be sent, e.g. because it would need to be buffered but the
buffer is full, the user agent must close the WebSocket connection with prejudice. The data to be sent is the data
stored in the buffer described by the ArrayBuffer object.
Any invocation of this method with an ArrayBuffer argument that does not throw an
exception must increase the bufferedAmount
attribute by the
http://developers.whatwg.org/terminology-3.html[4/16/2014 9:31:09 PM]

13 Terminology HTML: The Living Standard - Edition for Web Developers

length of the ArrayBuffer in bytes. If the argument is an ArrayBufferView object If the WebSocket connection is established, and the WebSocket closing handshake has not yet started, then the user
agent must send a WebSocket Message comprised of data using a binary
frame opcode; if the data cannot be sent, e.g. because it would need to be buffered but the
buffer is full, the user agent must close the WebSocket connection with prejudice. The data to be sent is the data
stored in the section of the buffer described by the ArrayBuffer object that the
ArrayBufferView object references. Any invocation of
this method with an ArrayBufferView argument that does not throw an exception must
increase the bufferedAmount attribute by the length of the ArrayBufferView in bytes. [WSP] [TYPEDARRAY] The following are the event handlers (and their corresponding event handler event types) that must be supported, as event handler IDL attributes,
by all objects implementing the WebSocket interface: Event handler Event handler event type onopen onmessage onerror onclose open message error close

Feedback from the protocol


When the WebSocket connection is established, the user agent must queue a task to run these steps: 1. If the WebSocket object's client-specified protocols was not an
empty list, but the subprotocol in use is the null value, then fail the WebSocket
connection, set the readyState attribute's
value to CLOSING (2), and abort these steps. [WSP] 2. Change the readyState attribute's value to
OPEN (1). 3. Change the extensions attribute's value to
the extensions in use, if is not the null value. [WSP]

http://developers.whatwg.org/terminology-3.html[4/16/2014 9:31:09 PM]

13 Terminology HTML: The Living Standard - Edition for Web Developers

4. Change the protocol attribute's value to the


subprotocol in use, if is not the null value. [WSP] 5. Act as if the user agent had received a
set-cookie-string consisting of the cookies set during the server's opening
handshake, for the URL url given to the WebSocket() constructor. [COOKIES] [RFC3629] [WSP] 6. Fire a simple event named open at the
WebSocket object. When a WebSocket message has been received with type type and data
data, the user agent must queue a task to follow these steps: [WSP] 1. If the readyState attribute's value is not
OPEN (1), then abort these steps. 2. Let event be a newly created trusted event that uses the MessageEvent interface, with the event type message, which does not
bubble, is not cancelable, and has no default action. 3. Initialize event's origin
attribute to the Unicode serialization of
the origin of the URL that was passed to the WebSocket
object's constructor. 4. If type indicates that the data is Text, then initialize event's data attribute to data. If type indicates that the data is Binary, and binaryType is set to "blob", then
initialize event's data attribute
to a new Blob object that represents data as its raw data. [FILEAPI] If type indicates that the data is Binary, and binaryType is set to " arraybuffer", then initialize event's data attribute to a new read-only ArrayBuffer
object whose contents are data. [TYPEDARRAY] 5. Dispatch event at the
WebSocket object. User agents are encouraged to check if they can perform the above steps efficiently before they run the task, picking tasks from other task
queues while they prepare the buffers if not. For example, if the binaryType attribute was set to "blob " when the data arrived, and the user agent spooled all the data to disk, but
just before running the above task for this particular message
the script switched binaryType to "arraybuffer", the user agent would want to page the data back to RAM before
running this task so as to avoid stalling the main thread while
it created the ArrayBuffer object.

http://developers.whatwg.org/terminology-3.html[4/16/2014 9:31:09 PM]

13 Terminology HTML: The Living Standard - Edition for Web Developers

Here is an example of how to define a handler for the message event in the case of text frames: mysocket.onmessage = function (event) { if (event.data == 'on') { turnLampOn(); } else if (event.data == 'off') { turnLampOff(); } }; The protocol here is a trivial one, with the server just sending "on" or "off" messages. When the WebSocket closing handshake is started, the user agent must queue a
task to change the readyState attribute's
value to CLOSING (2). (If the close() method was called, the readyState attribute's value will already be set to CLOSING (2) when this task runs.) [WSP] When the WebSocket connection is closed, possibly cleanly, the user agent must queue a task to run the following
substeps: 1. Change the readyState attribute's value to
CLOSED (3). 2. If the user agent was required to fail the WebSocket connection or the WebSocket
connection is closed with prejudice,
fire a simple event named error at the WebSocket
object. [WSP] 3. Create a trusted event that uses the
CloseEvent interface, with the event type close , which does not bubble, is not cancelable, has no default
action, whose wasClean attribute is initialized to
true if the connection closed cleanly and false otherwise, whose code attribute is initialized to the WebSocket connection
close code, and whose reason attribute is
initialized to the result of applying the UTF-8 decoder to the WebSocket
connection close reason, and dispatch the event
at the WebSocket object. [WSP] User agents must not convey any failure information to scripts in a way that would allow a
script to distinguish the following situations:

A server whose host name could not be resolved. A server to which packets could not successfully be routed. A server that refused the connection on the specified port.
A server that failed to correctly perform a TLS handshake (e.g., the server
http://developers.whatwg.org/terminology-3.html[4/16/2014 9:31:09 PM]

13 Terminology HTML: The Living Standard - Edition for Web Developers

certificate
can't be verified).

A server that did not complete the opening handshake (e.g. because it was
not a WebSocket
server).

A WebSocket server that sent a correct opening handshake, but that


specified options that
caused the client to drop the connection (e.g. the server specified a subprotocol that the
client did not offer).

A WebSocket server that abruptly closed the connection after successfully


completing the
opening handshake. In all of these cases, the the WebSocket connection close code would be 1006, as
required by the WebSocket Protocol specification. [WSP] Allowing a script to distinguish these cases would allow a script to probe the user's local
network in preparation for an attack. In particular, this means the code 1015 is not used by the user agent (unless the
server erroneously uses it in its close frame, of course). The task source for all tasks queued in this section is the WebSocket task source.

Ping and Pong frames


The WebSocket protocol specification defines Ping and Pong frames that can be used for
keep-alive, heart-beats, network status probing, latency instrumentation, and so forth. These are
not currently exposed in the API. User agents may send ping and unsolicited pong frames as desired, for example in an attempt to
maintain local network NAT mappings, to detect failed connections, or to display latency metrics
to the user. User agents must not use pings or unsolicited pongs to aid the server; it is assumed
that servers will solicit pongs whenever appropriate for the server's needs.

Parsing WebSocket URLs


The steps to parse a WebSocket URL's components from a string url are as follows. These steps return either a host, a port, a resource name, and a secure flag,
or they fail.

http://developers.whatwg.org/terminology-3.html[4/16/2014 9:31:09 PM]

13 Terminology HTML: The Living Standard - Edition for Web Developers

1. If the url string is not an absolute URL, then fail this


algorithm. 2. Resolve the url string, with the URL
character encoding set to UTF-8. [RFC3629] It doesn't matter what it is resolved relative to, since we already know it is
an absolute URL at this point. 3. If the resulting parsed URL does not have a scheme component whose value is either "ws " or "wss", then fail this algorithm. 4. If the resulting parsed URL has a non-null fragment component, then fail this algorithm. 5. If the scheme component of the resulting
parsed URL is "ws ", set secure to false;
otherwise, the scheme component is "wss", set secure to true. 6. Let host be the value of the resulting parsed URL's host component. 7. If the resulting parsed URL has a port
component that is not the empty string, then let port be that component's
value; otherwise, there is no explicit port. 8. If there is no explicit port, then: if secure is
false, let port be 80, otherwise let port be
443. 9. Let resource name be the value of the resulting parsed
URL's path component (which might be
empty). 10. If resource name is the empty string, set it to a single character
U+002F SOLIDUS (/). 11. If the resulting parsed URL has a non-null query component, then append a single U+003F QUESTION MARK
character (?) to resource name, followed by the value of the query component. 12. Return host, port, resource
name, and secure.

Event definitions
The wasClean attribute must return the
value it was initialized to. When the object is created, this attribute must be initialized to
false. It represents whether the connection closed cleanly or not. The code attribute must return the value it
was initialized to. When the object
http://developers.whatwg.org/terminology-3.html[4/16/2014 9:31:09 PM]

13 Terminology HTML: The Living Standard - Edition for Web Developers

is created, this attribute must be initialized to zero. It


represents the WebSocket connection close code provided by the server. The reason attribute must return the
value it was initialized to. When the object is created, this attribute must be initialized to
empty string. It represents the WebSocket connection close reason provided by the server.

Garbage collection
A WebSocket object whose readyState
attribute's value was set to CONNECTING (0) as of
the last time the event loop started executing a task must not be garbage collected if there are any event listeners
registered for open events, message events, error events, or
close events. A WebSocket object whose readyState
attribute's value was set to OPEN (1) as of the last time
the event loop started executing a task must not be
garbage collected if there are any event listeners registered for message events, error , or close events. A WebSocket object whose readyState
attribute's value was set to CLOSING (2) as of the last
time the event loop started executing a task must
not be garbage collected if there are any event listeners registered for error or close events. A WebSocket object with an
established connection that has data queued to be transmitted to the network must not be
garbage collected. [WSP] If a WebSocket object is garbage collected while its connection is still open, the
user agent must start the WebSocket closing handshake, with no status code
for the Close message. [WSP] If a user agent is to make disappear a WebSocket object (this happens
when a Document object goes away), the user agent must follow the first appropriate set of steps from the following list: If the WebSocket connection is not yet established [WSP] Fail the WebSocket connection. [WSP] If the WebSocket closing handshake has not yet been started [WSP] Start the WebSocket closing handshake, with the status code to use in
the WebSocket Close message being 1001. [WSP]

http://developers.whatwg.org/terminology-3.html[4/16/2014 9:31:09 PM]

13 Terminology HTML: The Living Standard - Edition for Web Developers

Otherwise Do nothing.

Cross-document messaging
Web browsers, for security and privacy reasons, prevent documents in different domains from
affecting each other; that is, cross-site scripting is disallowed. While this is an important security feature, it prevents pages from different domains from
communicating even when those pages are not hostile. This section introduces a messaging system
that allows documents to communicate with each other regardless of their source domain, in a way designed to not enable cross-site scripting attacks.

Introduction
For example, if document A contains an iframe element that contains document B,
and script in document A calls postMessage() on the
Window object of document B, then a message event will be fired on that object, marked as originating from the Window of document A. The script in document A might
look like: var o = document.getElementsByTagName('iframe')[0]; o.contentWindow.postMessage('Hello world', 'http://b.example.org/'); To register an event handler for incoming events, the script would use addEventListener() (or similar mechanisms). For example, the script in document B
might look like: window.addEventListener('message', receiver, false); function receiver(e) { if (e.origin == 'http://example.com') { if (e.data == 'Hello world') { e.source.postMessage('Hello', e.origin); } else { alert(e.data);

http://developers.whatwg.org/terminology-3.html[4/16/2014 9:31:09 PM]

13 Terminology HTML: The Living Standard - Edition for Web Developers

} } } This script first checks the domain is the expected domain, and then looks at the message,
which it either displays to the user, or responds to by sending a message back to the document
which sent the message in the first place.

Security
Use of this API requires extra care to protect users from
hostile entities abusing a site for their own purposes. Authors should check the origin attribute to
ensure that messages are only accepted from domains that they expect to receive messages from.
Otherwise, bugs in the author's message handling code could be exploited by hostile sites. Furthermore, even after checking the origin
attribute, authors should also check that the data in question is of the expected format.
Otherwise, if the source of the event has been attacked using a cross-site scripting flaw, further unchecked processing of information sent using the postMessage() method could result in the attack being
propagated into the receiver. Authors should not use the wildcard keyword (*) in the targetOrigin argument in messages that contain any confidential information, as otherwise there is no way to
guarantee that the message is only delivered to the recipient to which it was intended. Authors who accept messages from any origin are encouraged to consider the risks of a
denial-of-service attack. An attacker could send a high volume of messages; if the receiving page
performs expensive computation or causes network traffic to be sent for each such message, the
attacker's message could be multplied into a denial-of-service attack. Authors are encouraged to employ rate limiting (only accepting a certain number of messages per minute) to make such attacks
impractical.

Posting messages
window . postMessage(message, targetOrigin [, transfer ])
http://developers.whatwg.org/terminology-3.html[4/16/2014 9:31:09 PM]

13 Terminology HTML: The Living Standard - Edition for Web Developers

Posts a message to the given window. Messages can be structured objects, e.g. nested objects
and arrays, can contain JavaScript values (strings, numbers, Dates, etc), and can
contain certain data objects such as File Blob, FileList ,
and ArrayBuffer objects. Objects listed in transfer are transferred, not just cloned, meaning that
they are no longer usable on the sending side. If the origin of the target window doesn't match the given origin, the message is discarded,
to avoid information leakage. To send the message to the target regardless of origin, set the
target origin to "* ". To restrict the message to same-origin targets only,
without needing to explicitly state the origin, set the target origin to "/ ". Throws a DataCloneError exception if transfer array contains
duplicate objects or if message could not be cloned. When posting a message to a Window of a browsing context
that has just been navigated to a new Document is likely to result in the message not
receiving its intended recipient: the scripts in the target browsing context have to
have had time to set up listeners for the messages. Thus, for instance, in situations where a
message is to be sent to the Window of newly created child iframe, authors are advised to have the child Document post a message to their parent
announcing their readiness to receive messages, and for the parent to wait for this message before
beginning posting messages.

Channel messaging

Introduction
To enable independent pieces of code (e.g. running in different browsing contexts) to communicate directly, authors can use channel
messaging. Communication channels in this mechanism are implemented as two-ways pipes, with a port at each
end. Messages sent in one port are delivered at the other port, and vice-versa. Messages are
asynchronous, and delivered as DOM events.

http://developers.whatwg.org/terminology-3.html[4/16/2014 9:31:09 PM]

13 Terminology HTML: The Living Standard - Edition for Web Developers

To create a connection (two "entangled" ports), the MessageChannel() constructor is called: var channel = new MessageChannel(); One of the ports is kept as the local port, and the other port is sent to the remote code, e.g.
using postMessage() : otherWindow.postMessage('hello', 'http://example.com', [channel.port2]); To send messages, the postMessage() method on
the port is used: channel.port1.postMessage('hello'); To receive messages, one listens to message events: channel.port1.onmessage = handleMessage; function handleMessage(event) { // message is in event.data // ... } Data sent on a port can be structured data; for example here an array of strings is passed on a
MessagePort : port1.postMessage(['hello', 'world']);

Examples
In this example, two JavaScript libraries are connected to each other using MessagePorts. This allows the libraries to later be hosted in different frames, or
in Worker objects, without any change to the APIs. <script src="contacts.js"></script> <!-- exposes a contacts object --> <script src="compose-mail.js"></script> <!-- exposes a composer object --> <script> var channel = new MessageChannel(); composer.addContactsProvider(channel.port1);

http://developers.whatwg.org/terminology-3.html[4/16/2014 9:31:09 PM]

13 Terminology HTML: The Living Standard - Edition for Web Developers

contacts.registerConsumer(channel.port2); </script> Here's what the "addContactsProvider()" function's implementation could look like: function addContactsProvider(port) { port.onmessage = function (event) { switch (event.data.messageType) { 'search-result': handleSearchResult(event.data.results); break; 'search-done': handleSearchDone(); break; 'search-error': handleSearchError(event.data.message); break; // ... } }; }; Alternatively, it could be implemented as follows: function addContactsProvider(port) { port.addEventListener('message', function (event) { if (event.data.messageType == 'search-result') handleSearchResult(event.data.results); }); port.addEventListener('message', function (event) { if (event.data.messageType == 'search-done') handleSearchDone(); }); port.addEventListener('message', function (event) { if (event.data.messageType == 'search-error') handleSearchError(event.data.message); }); // ... port.start(); }; The key difference is that when using addEventListener() , the start() method must also be invoked. When using onmessage , the call to start() is implied.

http://developers.whatwg.org/terminology-3.html[4/16/2014 9:31:09 PM]

13 Terminology HTML: The Living Standard - Edition for Web Developers

The start() method, whether called explicitly or


implicitly (by setting onmessage ), starts the
flow of messages: messages posted on message ports are initially paused, so that they don't get
dropped on the floor before the script has had a chance to set up its handlers.

Ports as the basis of an object-capability model on the Web


Ports can be viewed as a way to expose limited capabilities (in the objectcapability model
sense) to other actors in the system. This can either be a weak capability system, where the ports
are merely used as a convenient model within a particular origin, or as a strong capability model,
where they are provided by one origin provider as the only mechanism by which
another origin consumer can effect change in or obtain information from provider. For example, consider a situation in which a social Web site embeds in one iframe
the user's e-mail contacts provider (an address book site, from a second origin), and in a second
iframe a game (from a third origin). The outer social site and the game in the second
iframe cannot access anything inside the first iframe; together they can
only:

Navigate the iframe to a new URL, such as the same


URL but with a different
fragment identifier, causing the Window in the
iframe to receive a hashchange event.

Resize the iframe, causing the Window in the iframe to


receive a resize
event.

Send a message event to the Window in the


iframe using the
window.postMessage()
API. The contacts provider can use these methods, most particularly the third one, to provide an API
that can be accessed by other origins to manipulate the user's address book. For example, it could
respond to a message " add-contact Guillaume Tell
<tell@pomme.example.net>" by adding the given person and e-mail address to the user's
address book. To avoid any site on the Web being able to manipulate the user's contacts, the contacts
provider might only allow certain trusted sites, such as the social site, to do this. Now suppose the game wanted to add a contact to the user's address book, and that the social
site was willing to allow it to do so on its behalf, essentially

http://developers.whatwg.org/terminology-3.html[4/16/2014 9:31:09 PM]

13 Terminology HTML: The Living Standard - Edition for Web Developers

"sharing" the trust that the


contacts provider had with the social site. There are several ways it could do this; most simply,
it could just proxy messages between the game site and the contacts site. However, this solution
has a number of difficulties: it requires the social site to either completely trust the game site
not to abuse the privilege, or it requires that the social site verify each request to make sure
it's not a request that it doesn't want to allow (such as adding multiple contacts, reading the
contacts, or deleting them); it also requires some additional complexity if there's ever the
possibility of multiple games simultaneously trying to interact with the contacts provider. Using message channels and MessagePort objects, however, all of these problems can
go away. When the game tells the social site that it wants to add a contact, the social site can
ask the contacts provider not for it to add a contact, but for the capability to add a
single contact. The contacts provider then creates a pair of MessagePort objects, and
sends one of them back to the social site, who forwards it on to the game. The game and the
contacts provider then have a direct connection, and the contacts provider knows to only honor a
single "add contact" request, nothing else. In other words, the game has been granted the
capability to add a single contact.

Ports as the basis of abstracting out service implementations


Continuing the example from the previous section, consider the contacts provider in particular.
While an initial implementation might have simply used XMLHttpRequest objects in the
service's iframe, an evolution of the service might instead want to use a shared worker with a single WebSocket connection. If the initial design used MessagePort objects to grant capabilities, or even just
to allow multiple simultaneous independent sessions, the service implementation can switch from
the XMLHttpRequest s-in-each-iframe model to the
shared-WebSocket model without changing the API at all: the ports on the service
provider side can all be forwarded to the shared worker without it affecting the users of the API
in the slightest.

Message channels
channel = new MessageChannel ()

http://developers.whatwg.org/terminology-3.html[4/16/2014 9:31:09 PM]

13 Terminology HTML: The Living Standard - Edition for Web Developers

Returns a new MessageChannel object with two new MessagePort objects. channel . port1 Returns the first MessagePort object. channel . port2 Returns the second MessagePort object.

Message ports
Each channel has two message ports. Data sent through one port is received by the other port,
and vice versa. port . postMessage (message [, transfer] ) Posts a message through the channel. Objects listed in transfer are transferred, not just cloned, meaning that they are no longer usable on the sending side. Throws a DataCloneError exception if transfer array contains
duplicate objects or the source or target ports, or if message could not be
cloned. port . start () Begins dispatching messages received on the port. port . close () Disconnects the port, so that it is no longer active.

Broadcasting to many ports


The API described in this section is controversial, as, in an attempt to solve
an architectural memory leak, it instead exposes the details of Garbage Collection. This is a
lose-lose scenario. A better solution is really needed here. Broadcasting to many ports is in principle relatively simple: keep an array of MessagePort objects to send messages to, and iterate through the array to send a
message. However, this has one rather unfortunate effect: it prevents the ports from being garbage
collected, even if the other side has gone away. To avoid this problem, the PortCollection object can be used. It acts as an opaque
array of MessagePort objects, thus allowing the objects to be garbage

http://developers.whatwg.org/terminology-3.html[4/16/2014 9:31:09 PM]

13 Terminology HTML: The Living Standard - Edition for Web Developers

collected when
they stop being relevant, while still allowing scripts to iterate over the
MessagePort objects. portCollection = new PortCollection() Returns a new empty PortCollection object. portCollection . add (port) Adds port to the collection, if it isn't already present. portCollection . remove (port) Removes port from the collection, if it is present. portCollection . clear () Removes all ports from the collection. portCollection . iterate (callback) Calls callback for each port in the collection.

Ports and garbage collection


Authors are strongly encouraged to explicitly close MessagePort
objects to disentangle them, so that their resources can be recollected. Creating many MessagePort objects and discarding them without closing them can lead to high
transient memory usage since garbage collection is not necessarily performed promptly.

Up next

14 Web workers

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/terminology-3.html[4/16/2014 9:31:09 PM]

14 Web workers HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
Web workers
Introduction
Scope
Examples
A background number-crunching worker
Worker used for background I/O
Shared workers introduction
Shared state using a shared worker
Delegation
Tutorials
Creating a dedicated worker
Communicating with a dedicated worker
Shared workers

14 WEB WORKERS

Introduction

Scope
This specification defines an API for running scripts in the background independently of any
user interface scripts. This allows for long-running scripts that are not interrupted by scripts that respond to clicks
or other user interactions, and allows long tasks to be executed without yielding to keep the page
responsive. Workers (as these background scripts are called herein) are relatively heavy-

http://developers.whatwg.org/workers.html[4/16/2014 9:31:15 PM]

14 Web workers HTML: The Living Standard - Edition for Web Developers

weight, and are


not intended to be used in large numbers. For example, it would be inappropriate to launch one
worker for each pixel of a four megapixel image. The examples below show some appropriate uses of workers. Generally, workers are expected to be long-lived, have a high start-up performance cost, and a
high per-instance memory cost.

Examples
There are a variety of uses that workers can be put to. The following subsections show various
examples of this use.

A background number-crunching worker


The simplest use of workers is for performing a computationally
expensive task without interrupting the user interface. In this example, the main document spawns a worker to (navely) compute prime numbers, and
progressively displays the most recently found prime number. The main page is as follows: <!DOCTYPE HTML> <html> <head> <title>Worker example: One-core computation</title> </head> <body> <p>The highest prime number discovered so far is: <output id="result"></output></p> <script> var worker = new Worker('worker.js'); worker.onmessage = function (event) { document.getElementById('result').textContent = event.data; }; </script> </body>
http://developers.whatwg.org/workers.html[4/16/2014 9:31:15 PM]

14 Web workers HTML: The Living Standard - Edition for Web Developers

</html> The Worker() constructor call creates a worker and returns a


Worker object representing that worker, which is used to communicate with the worker. That object's onmessage event handler allows the
code to receive messages from the worker. The worker itself is as follows: var n = 1; search: while (true) { n += 1; for (var i = 2; i <= Math.sqrt(n); i += 1) if (n % i == 0) continue search; // found a prime! postMessage(n); } The bulk of this code is simply an unoptimized search for a prime number. The postMessage() method is used to send a
message back to the page when a prime is found. View this example online.

Worker used for background I/O


In this example, the main document uses two workers, one for fetching stock updates at regular
intervals, and one for performing search queries that the user requests. The main page is as follows: <!DOCTYPE HTML> <html> <head> <title>Worker example: Stock ticker</title> <script> // TICKER var symbol = 'GOOG'; // default symbol to watch var ticker = new Worker('ticker.js');

http://developers.whatwg.org/workers.html[4/16/2014 9:31:15 PM]

14 Web workers HTML: The Living Standard - Edition for Web Developers

// SEARCHER var searcher = new Worker('searcher.js'); function search(query) { searcher.postMessage(query); } // SYMBOL SELECTION UI function select(newSymbol) { symbol = newSymbol; ticker.postMessage(symbol); } </script> </head> <body onload="search('')"> <p><output id="symbol"></output> <output id="value"> </output></p> <script> ticker.onmessage = function (event) { var data = event.data.split(' '); document.getElementById('symbol').textContent = data[0]; document.getElementById('value').textContent = data[1]; }; ticker.postMessage(symbol); </script> <p><label>Search: <input type="text" autofocus oninput="search(this.value)"></label></p> <ul id="results"></ul> <script> searcher.onmessage = function (event) { var data = event.data.split(' '); var results = document.getElementById('results'); while (results.hasChildNodes()) // clear previous results results.removeChild(results.firstChild); for (var i = 0; i < data.length; i += 1) { // add a list item with a button for each result var li = document.createElement('li'); var button = document.createElement('button'); button.value = data[i];

http://developers.whatwg.org/workers.html[4/16/2014 9:31:15 PM]

14 Web workers HTML: The Living Standard - Edition for Web Developers

button.type = 'button'; button.onclick = function () { select(this.value); }; button.textContent = data[i]; li.appendChild(button); results.appendChild(li); } }; </script> <p>(The data in this example is not real. Try searching for "Google" or "Apple".)</p> </body> </html> The two workers use a common library for performing the actual network calls. This library is
as follows: function get(url) { try { var xhr = new XMLHttpRequest(); xhr.open('GET', url, false); xhr.send(); return xhr.responseText; } catch (e) { return ''; // turn all errors into empty results } } The stock updater worker is as follows: importScripts('io.js'); var timer; var symbol; function update() { postMessage(symbol + ' ' + get('stock.cgi?' + symbol)); timer = setTimeout(update, 10000); } onmessage = function (event) { if (timer) clearTimeout(timer); symbol = event.data; update();

http://developers.whatwg.org/workers.html[4/16/2014 9:31:15 PM]

14 Web workers HTML: The Living Standard - Edition for Web Developers

}; The search query worker is as follows: importScripts('io.js'); onmessage = function (event) { postMessage(get('search.cgi?' + event.data)); }; View this example online.

Shared workers introduction


This section introduces shared workers using a Hello World example. Shared workers use slightly
different APIs, since each worker can have multiple connections. This first example shows how you connect to a worker and how a worker can send a message back
to the page when it connects to it. Received messages are displayed in a log. Here is the HTML page: <!DOCTYPE HTML> <title>Shared workers: demo 1</title> <pre id="log">Log:</pre> <script> var worker = new SharedWorker('test.js'); var log = document.getElementById('log'); worker.port.onmessage = function(e) { // note: not worker.onmessage! log.textContent += '\n' + e.data; } </script> Here is the JavaScript worker: onconnect = function(e) { var port = e.ports[0]; port.postMessage('Hello World!'); }

http://developers.whatwg.org/workers.html[4/16/2014 9:31:15 PM]

14 Web workers HTML: The Living Standard - Edition for Web Developers

View this example online. This second example extends the first one by changing two things: first, messages are received
using addEventListener() instead of an event handler IDL attribute, and second, a message is sent to the
worker, causing the worker to send another message in return. Received messages are again displayed in a log. Here is the HTML page: <!DOCTYPE HTML> <title>Shared workers: demo 2</title> <pre id="log">Log:</pre> <script> var worker = new SharedWorker('test.js'); var log = document.getElementById('log'); worker.port.addEventListener('message', function(e) { log.textContent += '\n' + e.data; }, false); worker.port.start(); // note: need this when using addEventListener worker.port.postMessage('ping'); </script> Here is the JavaScript worker: onconnect = function(e) { var port = e.ports[0]; port.postMessage('Hello World!'); port.onmessage = function(e) { port.postMessage('pong'); // not e.ports[0].postMessage! // e.target.postMessage('pong'); would work also } } View this example online. Finally, the example is extended to show how two pages can connect to the same worker; in this
case, the second page is merely in an iframe on the first page, but the same
principle would apply to an entirely separate page in a separate top-level browsing
context.

http://developers.whatwg.org/workers.html[4/16/2014 9:31:15 PM]

14 Web workers HTML: The Living Standard - Edition for Web Developers

Here is the outer HTML page: <!DOCTYPE HTML> <title>Shared workers: demo 3</title> <pre id="log">Log:</pre> <script> var worker = new SharedWorker('test.js'); var log = document.getElementById('log'); worker.port.addEventListener('message', function(e) { log.textContent += '\n' + e.data; }, false); worker.port.start(); worker.port.postMessage('ping'); </script> <iframe src="inner.html"></iframe> Here is the inner HTML page: <!DOCTYPE HTML> <title>Shared workers: demo 3 inner frame</title> <pre id=log>Inner log:</pre> <script> var worker = new SharedWorker('test.js'); var log = document.getElementById('log'); worker.port.onmessage = function(e) { log.textContent += '\n' + e.data; } </script> Here is the JavaScript worker: var count = 0; onconnect = function(e) { count += 1; var port = e.ports[0]; port.postMessage('Hello World! You are connection #' + count); port.onmessage = function(e) { port.postMessage('pong'); } }

http://developers.whatwg.org/workers.html[4/16/2014 9:31:15 PM]

14 Web workers HTML: The Living Standard - Edition for Web Developers

View this example online.

Shared state using a shared worker


In this example, multiple windows (viewers) can be opened that are all viewing the same map.
All the windows share the same map information, with a single worker coordinating all the viewers.
Each viewer can move around independently, but if they set any data on the map, all the viewers
are updated. The main page isn't interesting, it merely provides a way to open the viewers: <!DOCTYPE HTML> <html> <head> <title>Workers example: Multiviewer</title> <script> function openViewer() { window.open('viewer.html'); } </script> </head> <body> <p><button type=button onclick="openViewer()">Open a new viewer</button></p> <p>Each viewer opens in a new window. You can have as many viewers as you like, they all view the same data.</p> </body> </html> The viewer is more involved: <!DOCTYPE HTML> <html> <head> <title>Workers example: Multiviewer viewer</title> <script> var worker = new SharedWorker('worker.js', 'core');

http://developers.whatwg.org/workers.html[4/16/2014 9:31:15 PM]

14 Web workers HTML: The Living Standard - Edition for Web Developers

// CONFIGURATION function configure(event) { if (event.data.substr(0, 4) != 'cfg ') return; var name = event.data.substr(4).split(' ', 1)[0]; // update display to mention our name is name document.getElementsByTagName('h1')[0].textContent += ' ' + name; // no longer need this listener worker.port.removeEventListener('message', configure, false); } worker.port.addEventListener('message', configure, false); // MAP function paintMap(event) { if (event.data.substr(0, 4) != 'map ') return; var data = event.data.substr(4).split(','); // display tiles data[0] .. data[8] var canvas = document.getElementById('map'); var context = canvas.getContext('2d'); for (var y = 0; y < 3; y += 1) { for (var x = 0; x < 3; x += 1) { var tile = data[y * 3 + x]; if (tile == '0') context.fillStyle = 'green'; else context.fillStyle = 'maroon'; context.fillRect(x * 50, y * 50, 50, 50); } } } worker.port.addEventListener('message', paintMap, false); // PUBLIC CHAT function updatePublicChat(event) { if (event.data.substr(0, 4) != 'txt ') return; var name = event.data.substr(4).split(' ', 1)[0]; var message = event.data.substr(4 + name.length + 1); // display "<name> message" in public chat var public = document.getElementById('public');

http://developers.whatwg.org/workers.html[4/16/2014 9:31:15 PM]

14 Web workers HTML: The Living Standard - Edition for Web Developers

var p = document.createElement('p'); var n = document.createElement('button'); n.textContent = '<' + name + '> '; n.onclick = function () { worker.port.postMessage('msg ' + name); }; p.appendChild(n); var m = document.createElement('span'); m.textContent = message; p.appendChild(m); public.appendChild(p); } worker.port.addEventListener('message', updatePublicChat, false); // PRIVATE CHAT function startPrivateChat(event) { if (event.data.substr(0, 4) != 'msg ') return; var name = event.data.substr(4).split(' ', 1)[0]; var port = event.ports[0]; // display a private chat UI var ul = document.getElementById('private'); var li = document.createElement('li'); var h3 = document.createElement('h3'); h3.textContent = 'Private chat with ' + name; li.appendChild(h3); var div = document.createElement('div'); var addMessage = function(name, message) { var p = document.createElement('p'); var n = document.createElement('strong'); n.textContent = '<' + name + '> '; p.appendChild(n); var t = document.createElement('span'); t.textContent = message; p.appendChild(t); div.appendChild(p); }; port.onmessage = function (event) { addMessage(name, event.data); }; li.appendChild(div);

http://developers.whatwg.org/workers.html[4/16/2014 9:31:15 PM]

14 Web workers HTML: The Living Standard - Edition for Web Developers

var form = document.createElement('form'); var p = document.createElement('p'); var input = document.createElement('input'); input.size = 50; p.appendChild(input); p.appendChild(document.createTextNode(' ')); var button = document.createElement('button'); button.textContent = 'Post'; p.appendChild(button); form.onsubmit = function () { port.postMessage(input.value); addMessage('me', input.value); input.value = ''; return false; }; form.appendChild(p); li.appendChild(form); ul.appendChild(li); } worker.port.addEventListener('message', startPrivateChat, false); worker.port.start(); </script> </head> <body> <h1>Viewer</h1> <h2>Map</h2> <p><canvas id="map" height=150 width=150></canvas></p> <p> <button type=button onclick="worker.port.postMessage('mov left')">Left</button> <button type=button onclick="worker.port.postMessage('mov up')">Up</button> <button type=button onclick="worker.port.postMessage('mov down')">Down</button> <button type=button onclick="worker.port.postMessage('mov right')">Right</button> <button type=button onclick="worker.port.postMessage('set 0')">Set 0</button>

http://developers.whatwg.org/workers.html[4/16/2014 9:31:15 PM]

14 Web workers HTML: The Living Standard - Edition for Web Developers

<button type=button onclick="worker.port.postMessage('set 1')">Set 1</button> </p> <h2>Public Chat</h2> <div id="public"></div> <form onsubmit="worker.port.postMessage('txt ' + message.value); message.value = ''; return false;"> <p> <input type="text" name="message" size="50"> <button>Post</button> </p> </form> <h2>Private Chat</h2> <ul id="private"></ul> </body> </html> There are several key things worth noting about the way the viewer is written. Multiple listeners. Instead of a single message processing function, the code
here attaches multiple event listeners, each one performing a quick check to see if it is relevant
for the message. In this example it doesn't make much difference, but if multiple authors wanted
to collaborate using a single port to communicate with a worker, it would allow for independent
code instead of changes having to all be made to a single event handling function. Registering event listeners in this way also allows you to unregister specific listeners when
you are done with them, as is done with the configure() method in this
example. Finally, the worker: var nextName = 0; function getNextName() { // this could use more friendly names // but for now just return a number return nextName++; } var map = [ [0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 1, 0, 1, 1],

http://developers.whatwg.org/workers.html[4/16/2014 9:31:15 PM]

14 Web workers HTML: The Living Standard - Edition for Web Developers

[0, 1, 0, 1, 0, 0, 0], [0, 1, 0, 1, 0, 1, 1], [0, 0, 0, 1, 0, 0, 0], [1, 0, 0, 1, 1, 1, 1], [1, 1, 0, 1, 1, 0, 1], ]; function wrapX(x) { if (x < 0) return wrapX(x + map[0].length); if (x >= map[0].length) return wrapX(x - map[0].length); return x; } function wrapY(y) { if (y < 0) return wrapY(y + map.length); if (y >= map[0].length) return wrapY(y - map.length); return y; } function wrap(val, min, max) { if (val < min) return val + (max-min)+1; if (val > max) return val - (max-min)-1; return val; } function sendMapData(viewer) { var data = ''; for (var y = viewer.y-1; y <= viewer.y+1; y += 1) { for (var x = viewer.x-1; x <= viewer.x+1; x += 1) { if (data != '') data += ','; data += map[wrap(y, 0, map[0].length-1)][wrap(x, 0, map.length-1)]; } } viewer.port.postMessage('map ' + data); }

http://developers.whatwg.org/workers.html[4/16/2014 9:31:15 PM]

14 Web workers HTML: The Living Standard - Edition for Web Developers

var viewers = {}; onconnect = function (event) { var name = getNextName(); event.ports[0]._data = { port: event.ports[0], name: name, x: 0, y: 0, }; viewers[name] = event.ports[0]._data; event.ports[0].postMessage('cfg ' + name); event.ports[0].onmessage = getMessage; sendMapData(event.ports[0]._data); }; function getMessage(event) { switch (event.data.substr(0, 4)) { case 'mov ': var direction = event.data.substr(4); var dx = 0; var dy = 0; switch (direction) { case 'up': dy = -1; break; case 'down': dy = 1; break; case 'left': dx = -1; break; case 'right': dx = 1; break; } event.target._data.x = wrapX(event.target._data.x + dx); event.target._data.y = wrapY(event.target._data.y + dy); sendMapData(event.target._data); break; case 'set ': var value = event.data.substr(4); map[event.target._data.y][event.target._data.x] = value; for (var viewer in viewers) sendMapData(viewers[viewer]._data); break; case 'txt ': var name = event.target._data.name; var message = event.data.substr(4); for (var viewer in viewers)

http://developers.whatwg.org/workers.html[4/16/2014 9:31:15 PM]

14 Web workers HTML: The Living Standard - Edition for Web Developers

viewers[viewer].port.postMessage('txt ' + name + ' ' + message); break; case 'msg ': var party1 = event.target._data; var party2 = viewers[event.data.substr(4).split(' ', 1) [0]]; if (party2) { var channel = new MessageChannel(); party1.port.postMessage('msg ' + party2.name, [channel.port1]); party2.port.postMessage('msg ' + party1.name, [channel.port2]); } break; } } Connecting to multiple pages. The script uses the onconnect event listener to listen for
multiple connections. Direct channels. When the worker receives a "msg" message from one viewer
naming another viewer, it sets up a direct connection between the two, so that the two viewers can
communicate directly without the worker having to proxy all the messages. View this example online.

Delegation
With multicore CPUs becoming prevalent, one way to obtain better performance is to split
computationally expensive tasks amongst multiple workers. In this example, a computationally
expensive task that is to be performed for every number from 1 to 10,000,000 is farmed out to ten subworkers. The main page is as follows, it just reports the result: <!DOCTYPE HTML> <html> <head>

http://developers.whatwg.org/workers.html[4/16/2014 9:31:15 PM]

14 Web workers HTML: The Living Standard - Edition for Web Developers

<title>Worker example: Multicore computation</title> </head> <body> <p>Result: <output id="result"></output></p> <script> var worker = new Worker('worker.js'); worker.onmessage = function (event) { document.getElementById('result').textContent = event.data; }; </script> </body> </html> The worker itself is as follows: // settings var num_workers = 10; var items_per_worker = 1000000; // start the workers var result = 0; var pending_workers = num_workers; for (var i = 0; i < num_workers; i += 1) { var worker = new Worker('core.js'); worker.postMessage(i * items_per_worker); worker.postMessage((i+1) * items_per_worker); worker.onmessage = storeResult; } // handle the results function storeResult(event) { result += 1*event.data; pending_workers -= 1; if (pending_workers <= 0) postMessage(result); // finished! } It consists of a loop to start the subworkers, and then a handler
that waits for all the subworkers to respond.

http://developers.whatwg.org/workers.html[4/16/2014 9:31:15 PM]

14 Web workers HTML: The Living Standard - Edition for Web Developers

The subworkers are implemented as follows: var start; onmessage = getStart; function getStart(event) { start = 1*event.data; onmessage = getEnd; } var end; function getEnd(event) { end = 1*event.data; onmessage = null; work(); } function work() { var result = 0; for (var i = start; i < end; i += 1) { // perform some complex calculation here result += 1; } postMessage(result); close(); } They receive two numbers in two events, perform the computation for the range of numbers thus
specified, and then report the result back to the parent. View this example online.

Tutorials

Creating a dedicated worker


Creating a worker requires a URL to a JavaScript file. The Worker() constructor is invoked with the URL to that file as its only
argument; a worker is then created and returned:

http://developers.whatwg.org/workers.html[4/16/2014 9:31:15 PM]

14 Web workers HTML: The Living Standard - Edition for Web Developers

var worker = new Worker('helper.js');

Communicating with a dedicated worker


Dedicated workers use MessagePort objects behind the scenes, and thus support all
the same features, such as sending structured data, transferring binary data, and transferring
other ports. To receive messages from a dedicated worker, use the onmessage event handler IDL attribute on the Worker object: worker.onmessage = function (event) { ... }; You can also use the addEventListener()
method. The implicit MessagePort used by dedicated workers has its port
message queue implicitly enabled when it is created, so there is no equivalent to the MessagePort interface's start() method on
the Worker interface. To send data to a worker, use the postMessage() method. Structured data can be sent over this
communication channel. To send ArrayBuffer objects efficiently (by transferring them
rather than cloning them), list them in an array in the second argument. worker.postMessage({ operation: 'find-edges', input: buffer, // an ArrayBuffer object threshold: 0.6, }, [buffer]); To receive a message inside the worker, the onmessage event handler IDL attribute is used. onmessage = function (event) { ... }; You can again also use the addEventListener() method. In either case, the data is provided in the event object's data attribute. To send messages back, you again use postMessage(). It supports the structured data in the same manner.
http://developers.whatwg.org/workers.html[4/16/2014 9:31:15 PM]

14 Web workers HTML: The Living Standard - Edition for Web Developers

postMessage(event.data.input, [event.data.input]); // transfer the buffer back

Shared workers
Shared workers are identified by the URL of the script used to create it, optionally with an
explicit name. The name allows multiple instances of a particular shared worker to be started. Shared workers are scoped by origin. Two different sites using the same names will
not collide. However, if a page tries to use the same shared worker name as another page on the
same site, but with a different script URL, it will fail. Creating shared workers is done using the SharedWorker()
constructor. This constructor takes the URL to the script to use for its first argument, and the name of the worker, if any, as the second argument. var worker = new SharedWorker('service.js'); Communicating with shared workers is done with explicit MessagePort objects. The
object returned by the SharedWorker() constructor holds a reference to the port on its port attribute. worker.port.onmessage = function (event) { ... }; worker.port.postMessage('some message'); worker.port.postMessage({ foo: 'structured', bar: ['data', 'also', 'possible']}); Inside the shared worker, new clients of the worker are announced using the connect event. The port for the new client is given by the event
object's source attribute. onconnect = function (event) { var newPort = event.source; // set up a listener newPort.onmessage = function (event) { ... }; // send a message back to the port newPort.postMessage('ready!'); // can also send structured data, of course

http://developers.whatwg.org/workers.html[4/16/2014 9:31:15 PM]

14 Web workers HTML: The Living Standard - Edition for Web Developers

};

Up next

15 Conformance requirements

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/workers.html[4/16/2014 9:31:15 PM]

15 Conformance requirements HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
Conformance requirements
Dependencies

15 CONFORMANCE REQUIREMENTS
All diagrams, examples, and notes in this specification are
non-normative, as are all sections explicitly marked non-normative.
Everything else in this specification is normative. The key words "MUST", "MUST NOT", "REQUIRED", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and
"OPTIONAL" in the normative parts of this document are to be
interpreted as described in RFC2119. For readability, these words do
not appear in all uppercase letters in this specification. Requirements phrased in the imperative as part of algorithms
(such as "strip any leading space characters" or "return false and
abort these steps") are to be interpreted with the meaning of the
key word ("must", "should", "may", etc) used in introducing the
algorithm. Some conformance requirements are phrased as requirements on
attributes, methods or objects. Such requirements are to be
interpreted as requirements on user agents. Conformance requirements phrased as algorithms or specific steps
may be implemented in any manner, so long as the end result is
equivalent. (In particular, the algorithms defined in this
specification are intended to be easy to follow, and not intended to
be performant.) The only conformance class defined by this specification is user
agents. User agents may impose implementation-specific limits on
otherwise

http://developers.whatwg.org/conformance-requirements-1.html[4/16/2014 9:31:20 PM]

15 Conformance requirements HTML: The Living Standard - Edition for Web Developers

unconstrained inputs, e.g. to prevent denial of service


attacks, to guard against running out of memory, or to work around
platform-specific limitations. When support for a feature is disabled (e.g. as an emergency
measure to mitigate a security problem, or to aid in development, or
for performance reasons), user agents must act as if they had no
support for the feature whatsoever, and as if the feature was not
mentioned in this specification. For example, if a particular
feature is accessed via an attribute in a Web IDL interface, the
attribute itself would be omitted from the objects that implement
that interface leaving the attribute on the object but
making it return null or throw an exception is insufficient.

Dependencies
This specification relies on several other underlying
specifications. HTML Many fundamental concepts from HTML are used by this
specification. WebIDL The IDL blocks in this specification use the semantics of the
WebIDL specification.

Up next

16 Terminology

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/conformance-requirements-1.html[4/16/2014 9:31:20 PM]

16 Terminology HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
Terminology
Infrastructure
The global scope
The WorkerGlobalScope common interface
Dedicated workers and the DedicatedWorkerGlobalScope interface
Shared workers and the SharedWorkerGlobalScope interface
The event loop
The worker's lifetime
Processing model
Runtime script errors
Creating workers
The AbstractWorker abstract interface
Script settings for workers
Dedicated workers and the Worker interface
Shared workers and the SharedWorker interface
APIs available to workers
Importing scripts and libraries
The WorkerNavigator object
Interface objects and constructors
Worker locations

16 TERMINOLOGY
The construction "a Foo object", where
Foo is actually an interface, is sometimes
used instead of the more accurate "an object implementing the interface Foo". The term DOM is used to refer to the API set made available to
scripts in Web applications, and does not necessarily imply the
existence of an actual

http://developers.whatwg.org/terminology-4.html[4/16/2014 9:31:25 PM]

16 Terminology HTML: The Living Standard - Edition for Web Developers

Document object or of any other


Node objects as defined in the DOM specifications. An IDL attribute is said to be getting when its value is
being retrieved (e.g. by author script), and is said to be
setting when a new value is assigned to it. The term "JavaScript" is used to refer to ECMA262, rather than
the official term ECMAScript, since the term JavaScript is more
widely known.

Infrastructure
There are two kinds of workers; dedicated workers, and shared workers. Dedicated workers, once
created, and are linked to their creator; but message ports can be used to communicate from a
dedicated worker to multiple other browsing contexts or workers. Shared workers, on the other
hand, are named, and once created any script running in the same origin can obtain a
reference to that worker and communicate with it.

The global scope


The global scope is the "inside" of a worker.

The WorkerGlobalScope common interface


The self attribute must return the
WorkerGlobalScope object itself. The location attribute must
return the WorkerLocation object created for the WorkerGlobalScope
object when the worker was created. It represents the absolute URL of the script that
was used to initialize the worker, after any redirects. When a script invokes the close()
method on a WorkerGlobalScope object, the user agent must run the following steps
(atomically): 1. Discard any tasks that have been added to the
WorkerGlobalScope object's event loop's task
queues. 2. Set the worker's WorkerGlobalScope object's closing flag to true. (This prevents any further
tasks from being queued.)
http://developers.whatwg.org/terminology-4.html[4/16/2014 9:31:25 PM]

16 Terminology HTML: The Living Standard - Edition for Web Developers

The following are the event handlers (and their corresponding event handler event types) that must be supported, as event handler IDL attributes,
by objects implementing the WorkerGlobalScope interface: Event handler Event handler event type onerror onoffline ononline error offline online

Each WorkerGlobalScope object has a worker origin that is set when the object is created. For data: URLs, this is
the origin of the entry script when the constructor was called. For
other URLs, this is the origin of the value of the
absolute URL given in the worker's attribute.

Dedicated workers and the DedicatedWorkerGlobalScope interface


The DedicatedWorkerGlobalScope interface must only be exposed to JavaScript if the JavaScript global environment is a dedicated worker environment. DedicatedWorkerGlobalScope objects act as if they had an implicit MessagePort associated with them. This port is part of a channel that is set up when
the worker is created, but it is not exposed. This object must never be garbage collected before
the DedicatedWorkerGlobalScope object. All messages received by that port must immediately be retargeted at the DedicatedWorkerGlobalScope object. The postMessage()
method on DedicatedWorkerGlobalScope objects must act as if, when invoked, it
immediately invoked the method of the same name on the port, with the same arguments, and returned the same return value. The following are the event handlers (and their corresponding event handler event types) that must be supported, as event
handler IDL attributes, by objects implementing the DedicatedWorkerGlobalScope
interface:

http://developers.whatwg.org/terminology-4.html[4/16/2014 9:31:25 PM]

16 Terminology HTML: The Living Standard - Edition for Web Developers

Event handler Event handler event type onmessage message

For the purposes of the application cache networking model, a dedicated worker is
an extension of the cache host from which it was created.

Shared workers and the SharedWorkerGlobalScope interface


The SharedWorkerGlobalScope interface must only be exposed to
JavaScript if the JavaScript global environment is a shared worker
environment. Shared workers receive message ports through connect events on their SharedWorkerGlobalScope object for each
connection. The name attribute must return
the value it was assigned when the SharedWorkerGlobalScope object was created by the
"run a worker" algorithm. Its value represents the name that can be used to obtain a reference to the worker using the SharedWorker constructor. The following are the event handlers (and their corresponding event handler event types) that must be supported, as event
handler IDL attributes, by objects implementing the SharedWorkerGlobalScope
interface: Event handler Event handler event type onconnect connect

For the purposes of the application cache networking model, a shared worker is its
own cache host. The run a worker algorithm takes care of associating the
worker with an application cache. The applicationCache attribute returns the
ApplicationCache object for the worker.

The event loop


Each WorkerGlobalScope object has a distinct event loop, separate
from those used by units of related
similar-origin browsing contexts. This event loop has no associated
browsing context, and its task queues only have
events, callbacks, and networking activity as tasks. These event loops are created by the run a worker algorithm.
http://developers.whatwg.org/terminology-4.html[4/16/2014 9:31:25 PM]

16 Terminology HTML: The Living Standard - Edition for Web Developers

Each WorkerGlobalScope object also has a closing flag, which must initially be false, but which
can get set to true by the algorithms in the processing model section below. Once the WorkerGlobalScope 's closing flag is set to true, the event
loop's task queues must discard any further tasks that would be added to them (tasks already on the queue are
unaffected except where otherwise specified). Effectively, once the closing flag is true, timers stop firing,
notifications for all pending asynchronous operations are dropped, etc.

The worker's lifetime


Workers communicate with other workers and with browsing
contexts through message channels and their
MessagePort objects. Each WorkerGlobalScope worker global scope has a list of
the worker's ports, which consists of all the MessagePort objects that are
entangled with another port and that have one (but only one) port owned by worker
global scope. This list includes the implicit MessagePort in the case of dedicated workers. Each WorkerGlobalScope also has a list of the worker's workers.
Initially this list is empty; it is populated when the worker creates or obtains further workers. Finally, each WorkerGlobalScope also has a list of the worker's
Documents. Initially this list is empty; it is populated when the worker is
created. Whenever a Document d is added to the worker's Documents, the user agent must, for
each worker q in the list of the worker's workers whose list of
the worker's Documents does not contain d, add d to q's WorkerGlobalScope owner's list of the worker's
Documents. Whenever a Document object is discarded,
it must be removed from the list of the worker's Document s of each
worker whose list contains that Document. Given a settings object o when creating or obtaining a
worker, the list of relevant Document objects to add depends on the type
of global object specified by o's. If o
specifies a global object that is a WorkerGlobalScope object
(i.e. if we are creating a nested worker), then the relevant Documents

http://developers.whatwg.org/terminology-4.html[4/16/2014 9:31:25 PM]

16 Terminology HTML: The Living Standard - Edition for Web Developers

are the
the worker's Documents of the global object specified by
o. Otherwise, o specifies a global object that is a Window object,
and the relevant Document is just the responsible document specified by o. A worker is said to be a permissible worker if its list of the worker's
Document s is not empty. A worker is said to be a protected worker if it is a permissible worker
and either it has outstanding timers, database transactions, or network connections, or its list
of the worker's ports is not empty, or its WorkerGlobalScope is actually
a SharedWorkerGlobalScope object (i.e. the worker is a shared worker). A worker is said to be an active needed worker if any of the Document
objects in the worker's Documents are fully active. A worker is said to be a suspendable worker if it is not an active needed worker but it is a permissible worker.

Processing model
When a user agent is to run a worker for a script with URL url, a script settings object settings object,
and an origin owner origin, it
must run the following steps: 1. Create a separate parallel execution environment (i.e. a separate thread or process or
equivalent construct), and run the rest of these steps asynchronously in that context. For the purposes of timing APIs, this is the official moment of creation of the worker. 2. Let worker global scope be the global object specified
by settings object. 3. If worker global scope is actually a
SharedWorkerGlobalScope object (i.e. the worker is a shared worker), and there are
any relevant application caches that are
identified by a manifest URL with the same origin as url and
that have url as one of their entries, not excluding entries marked
as foreign, then associate the worker
global scope with the most appropriate application cache of those that match. 4. Attempt to fetch the resource identified by url,
from the owner origin, using

http://developers.whatwg.org/terminology-4.html[4/16/2014 9:31:25 PM]

16 Terminology HTML: The Living Standard - Edition for Web Developers

the responsible document specified by settings object as the


referrer source (not the specified API referrer source!), with the synchronous flag set and the force same-origin
flag set. If the attempt fails, then for each Worker or SharedWorker object
associated with worker global scope, queue a task to fire
a simple event named error at that object. Abort these
steps. If the attempt succeeds, then let source be the result of running the
UTF-8 decode algorithm on the script resource. Let language be JavaScript. As with script elements, the MIME type of the script is ignored.
Unlike with script elements, there is no way to override the type. It's always
assumed to be JavaScript. 5. In the newly created execution environment, create a JavaScript global environment whose global object is worker global scope. If worker global scope is a DedicatedWorkerGlobalScope object, then this
is a dedicated worker environment. Otherwise, worker global
scope is a SharedWorkerGlobalScope object, and this is a shared worker
environment. (In either case, by definition, it is a worker
environment.) 6. Let script be a new script. Obtain the appropriate script execution environment for the scripting language
language from settings object. Parse/compile/initialize source using that script execution
environment, as appropriate for language, and thus obtain a
code entry-point. Let script's settings object be settings
object. 7. Closing orphan workers: Start monitoring the worker such that no sooner than
it stops being either a protected worker or a suspendable worker, and
no later than it stops being a permissible worker, worker global
scope's closing flag is set to true. 8. Suspending workers: Start monitoring the worker, such that whenever worker global scope's closing
flag is false and the worker is a suspendable worker, the user agent suspends
execution of script in that worker until such time as either the closing flag switches to true or the worker stops
being a suspendable worker.

http://developers.whatwg.org/terminology-4.html[4/16/2014 9:31:25 PM]

16 Terminology HTML: The Living Standard - Edition for Web Developers

9. Jump to the script's code entry-point, and let that run until
it either returns, fails to catch an exception, or gets prematurely aborted by the "kill a
worker" or "terminate a worker" algorithms defined below. 10. If worker global scope is actually a
DedicatedWorkerGlobalScope object (i.e. the worker is a dedicated worker), then
enable the port message queue of the worker's implicit port. 11. Event loop: Run the responsible
event loop specified by settings object until it is destroyed. The handling of events or the execution of callbacks by tasks run by the event loop might get prematurely
aborted by the "kill a worker" or "terminate a worker" algorithms
defined below. The worker processing model remains on this step until the event loop is destroyed, which happens after the closing
flag is set to true, as described in the event loop processing model. 12. Empty the worker global scope's list of active timers. 13. Disentangle all the ports in the list of the worker's ports. When a user agent is to kill a worker it must run the following steps in parallel
with the worker's main loop (the "run a worker" processing model defined above): 1. Set the worker's WorkerGlobalScope object's closing flag to true. 2. If there are any tasks queued in the
WorkerGlobalScope object's event loop's task
queues, discard them without processing them. 3. Wait a user-agent-defined amount of time. 4. Abort the script currently running in the worker. User agents may invoke the "kill a worker" processing model on a worker at any
time, e.g. in response to user requests, in response to CPU quota management, or when a worker
stops being an active needed worker if the worker continues executing even after its
closing flag was set to true. When a user agent is to terminate a worker it must run the following steps in parallel with the worker's main loop (the "run a worker" processing model defined
above):

http://developers.whatwg.org/terminology-4.html[4/16/2014 9:31:25 PM]

16 Terminology HTML: The Living Standard - Edition for Web Developers

1. Set the worker's WorkerGlobalScope object's closing flag to true. 2. If there are any tasks queued in the
WorkerGlobalScope object's event loop's task
queues, discard them without processing them. 3. Abort the script currently running in the worker. 4. If the worker's WorkerGlobalScope object is actually a DedicatedWorkerGlobalScope object (i.e. the worker is a dedicated worker), then
empty the port message queue of the port that the worker's implicit port is
entangled with. The task source for the tasks mentioned above is the DOM manipulation task source.

Runtime script errors


Whenever an uncaught runtime script error occurs in one of the worker's scripts, if the error
did not occur while handling a previous script error, the user agent must report the
error for that script, with the position (line number
and column number) where the error occurred, using the WorkerGlobalScope object as the target. For shared workers, if the error is still not handled
afterwards, the error may be reported to the user.
[HTML] For dedicated workers, if the error is still not
handled afterwards, the user agent must queue a task to fire a trusted event that uses the ErrorEvent interface, with the name error , that doesn't bubble and is
cancelable, with its message, filename, lineno, colno,
attributes initialized appropriately,
and with the error attribute initialized to null,
at the Worker object associated with the
worker. If the event is not canceled, the user agent must act as if the uncaught runtime script
error had occurred in the global scope that the Worker object is in, thus repeating
the entire runtime script error reporting process one level up. If the implicit port connecting the worker to its Worker object has been disentangled (i.e. if the parent worker has been terminated), then the user agent must act as if
the Worker object had no error event handler and as
if that worker's onerror attribute was
null, but must otherwise act as described above.

http://developers.whatwg.org/terminology-4.html[4/16/2014 9:31:25 PM]

16 Terminology HTML: The Living Standard - Edition for Web Developers

Thus, error reports propagate up to the chain of dedicated workers up to the original Document, even if some of the workers along this chain have been terminated
and garbage collected. The task source for the task mentioned above is the DOM manipulation task source.

Creating workers

The AbstractWorker abstract interface


The following are the event handlers (and their
corresponding event handler event types) that must be supported, as event handler IDL attributes, by objects implementing the AbstractWorker interface: Event handler Event handler event type onerror error

Script settings for workers


When the user agent is required to set up a worker script settings object, given a
worker global scope, it must run the following steps: 1. Let inherited responsible browsing context be the responsible
browsing context specified by the incumbent script's settings
object. 2. Let inherited responsible document be the responsible
document specified by the incumbent script's settings
object. 3. Let worker event loop be a newly created event
loop. 4. Let settings object be a new script settings object whose
algorithms are defined as follows: The script execution environments When the script settings object is created, for each language supported by the user agent, create an appropriate execution environment as defined by the relevant
specification.

http://developers.whatwg.org/terminology-4.html[4/16/2014 9:31:25 PM]

16 Terminology HTML: The Living Standard - Edition for Web Developers

When a script execution environment is needed, return the appropriate one from
those created when the script settings object was created. Currently, workers only support JavaScript, so only a JavaScript execution environment is actually needed here. The global object Return worker global scope. The responsible browsing context Return inherited responsible browsing context. The responsible document Return inherited responsible document. The responsible event loop Return worker event loop. The API referrer source Return the Document with which the Window is currently
associated. The API URL character encoding Return UTF-8. The API base URL Return worker URL. 5. Return settings object.

Dedicated workers and the Worker interface


The terminate() method, when invoked, must
cause the "terminate a worker" algorithm to be run on the worker with which the object
is associated. Worker objects act as if they had an implicit MessagePort associated
with them. This port is part of a channel that is set up when the worker is created, but it is not
exposed. This object must never be garbage collected before the Worker object. All messages received by that port must immediately be retargeted at the Worker
object. The postMessage() method on
Worker objects must act as if, when invoked,
http://developers.whatwg.org/terminology-4.html[4/16/2014 9:31:25 PM]

16 Terminology HTML: The Living Standard - Edition for Web Developers

it immediately invoked the method of the same name on the port, with the same
arguments, and returned the same return value. The postMessage()
method's first argument can be structured data: worker.postMessage({opcode: 'activate', device: 1938, parameters: [23, 102]}); The following are the event handlers (and their corresponding event handler event types) that must be supported, as event handler IDL attributes,
by objects implementing the Worker interface: Event handler Event handler event type onmessage message

When the Worker(scriptURL) constructor is invoked, the


user agent must run the following steps: 1. The user agent may throw a SecurityError exception and abort these steps if
the request violates a policy decision (e.g. if the user agent is configured to not allow the
page to start dedicated workers). 2. Resolve the scriptURL argument
relative to the API base URL specified by the entry script's settings object when
the method was invoked. 3. If this fails, throw a SyntaxError exception and abort these steps. 4. Let worker URL be the resulting absolute URL. 5. If the scheme component of worker URL
is not "data", and the origin of worker URL
is not the same as the
origin of the entry script, then throw a SecurityError exception and
abort these steps. Thus, scripts must either be external files with the same scheme, host, and port
as the original page, or data: URLs.
For example, you can't load a script from a javascript: URL, and an https: page couldn't start workers
using scripts with http: URLs. 6. Create a new DedicatedWorkerGlobalScope object whose worker
origin is the origin of the entry script. Let worker global
scope be this new object. 7. Set up a worker script settings object with worker global
scope, and let settings object be the result.

http://developers.whatwg.org/terminology-4.html[4/16/2014 9:31:25 PM]

16 Terminology HTML: The Living Standard - Edition for Web Developers

8. Create a new Worker object, associated with worker global


scope. Let worker be this new object. 9. Create a new MessagePort object whose owner
is the settings object of the incumbent script. Let
this be the outside port. 10. Associate the outside port with worker. 11. Create a new MessagePort object whose owner is script settings
Let inside port be this new object. 12. Associate inside port with worker global
scope. 13. Entangle outside port and inside
port. 14. Return worker, and run the following steps asynchronously. 15. Enable outside port's port message queue. 16. Let docs be the list of relevant Document objects to
add given the settings object of the
incumbent script. 17. Add to worker global
scope's list of the worker's Documents the
Document objects in docs. 18. If the global object specified by the incumbent
script's settings object is a WorkerGlobalScope object (i.e. we are creating a nested worker),
add worker global scope to the list of the worker's workers of
the WorkerGlobalScope object that is the global object of the incumbent script's settings object. 19. Run a worker for the script with URL worker
URL, the script settings object settings object, and the
origin of the entry script as the owner
origin.

Shared workers and the SharedWorker interface


The port attribute must return the value
it was assigned by the object's constructor. It represents the MessagePort for
communicating with the shared worker. When the SharedWorker(scriptURL, name) constructor is invoked, the user agent must run the following
steps: 1. The user agent may throw a SecurityError exception and abort these steps if
the request violates a policy decision (e.g. if the user agent is configured to not
http://developers.whatwg.org/terminology-4.html[4/16/2014 9:31:25 PM]

16 Terminology HTML: The Living Standard - Edition for Web Developers

allow the
page to start shared workers). 2. Resolve the scriptURL
argument. 3. If this fails, throw a SyntaxError exception and abort these steps. 4. Let scriptURL be the resulting absolute URL and parsed scriptURL be the resulting parsed URL. 5. Let name be the value of the second argument, or the empty string if
the second argument was omitted. 6. If the scheme component of parsed
scriptURL is not "data", and the origin of scriptURL is not the same as the origin of
the entry script, then throw a SecurityError exception and abort these
steps. Thus, scripts must either be external files with the same scheme, host, and port
as the original page, or data: URLs.
For example, you can't load a script from a javascript: URL, and an https: page couldn't start workers
using scripts with http: URLs. 7. Let docs be the list of relevant Document objects to
add given the settings object of the
incumbent script. 8. Execute the following substeps atomically: 1. Create a new SharedWorker object, which will shortly be associated with a SharedWorkerGlobalScope object. Let this SharedWorker object be worker. 2. Create a new MessagePort object whose owner
is the settings object of the incumbent script. Let
this be the outside port. 3. Assign outside port to the port attribute of worker. 4. Let worker global scope be null. 5. If name is not the empty string and there exists a SharedWorkerGlobalScope object whose closing flag is false, whose name attribute is exactly equal to name, and whose worker origin is the same origin as
scriptURL, then let worker global scope be that SharedWorkerGlobalScope object. Otherwise, if name is the empty string and there exists a SharedWorkerGlobalScope object whose closing flag is false, whose name
http://developers.whatwg.org/terminology-4.html[4/16/2014 9:31:25 PM]

16 Terminology HTML: The Living Standard - Edition for Web Developers

attribute is the empty string, and whose location attribute represents an absolute
URL that is exactly equal to scriptURL, then let worker global scope be that SharedWorkerGlobalScope object. 6. If worker global scope is not null, but the user agent has been
configured to disallow communication between the incumbent script and the worker represented by the worker global scope, then set worker
global scope to null. For example, a user agent could have a development mode that isolates a particular top-level browsing context from all other pages, and scripts in that
development mode could be blocked from connecting to shared workers running in the normal
browser mode. 7. If worker global scope is not null, then run these steps: 1. If worker global scope's location attribute represents an absolute
URL that is not exactly equal to scriptURL, then throw a
URLMismatchError exception and abort all these steps. 2. Associate worker with worker global
scope. 3. Let settings object be the script settings object
whose global object is worker global scope. 4. Create a new MessagePort object whose owner
is settings object. Let this be the inside port. 5. Entangle outside port
and inside port. 6. Create a trusted event that uses the
MessageEvent interface, with the name connect, which does not bubble, is not cancelable, has no
default action, has a data attribute whose value
is initialized to the empty string, has a ports
attribute whose value is initialized to a read only array containing only the newly created port, and has a source attribute whose value is initialized to the
newly created port, and queue a task to dispatch the event at worker global
scope. 7. Add to worker global
scope's list of the worker's Documents the Document objects in docs. 8. If the global object specified by the incumbent
script's settings object is a WorkerGlobalScope object, add worker global
scope to the list of the worker's workers of the

http://developers.whatwg.org/terminology-4.html[4/16/2014 9:31:25 PM]

object that is the global

16 Terminology HTML: The Living Standard - Edition for Web Developers

WorkerGlobalScope object specified by the incumbent script's settings object. 9. Return worker and abort all these steps. 8. Create a new SharedWorkerGlobalScope object whose worker
origin is the origin of the entry script. Let worker global
scope be this new object. 9. Set up a worker script settings object with worker global
scope, and let settings object be the result. 10. Associate worker with worker global
scope. 11. Set the name attribute of worker global scope to name. 12. Create a new MessagePort object whose owner is settings object.
Let inside port be this new object. 13. Entangle outside port and inside
port. 9. Return worker and perform the remaining steps asynchronously. 10. Create a trusted event that uses the
MessageEvent interface, with the name connect,
which does not bubble, is not cancelable, has no default action, has a data attribute whose value is initialized to the empty
string, has a ports attribute whose value is
initialized to a read only array containing only the newly created port, and has a source attribute whose
value is initialized to the newly created port, and queue a task to dispatch the event at worker global
scope. 11. Add to worker global
scope's list of the worker's Documents the
Document objects in docs. 12. If the global object specified by the settings object of the incumbent
script is a WorkerGlobalScope object, add worker global scope to the list of the worker's workers of the
WorkerGlobalScope object that is the global
object specified by the incumbent script's settings object. 13. Run a worker for the script with URL scriptURL, the script settings object settings
object, and the origin of the entry script as the owner origin. The task source for the tasks mentioned above is the DOM manipulation task source.

http://developers.whatwg.org/terminology-4.html[4/16/2014 9:31:25 PM]

16 Terminology HTML: The Living Standard - Edition for Web Developers

APIs available to workers


The WindowTimers and WindowBase64
interfaces are defined in the HTML specification. [HTML] The DOM APIs specifically, all the interfaces defined in the DOM specification other
than exceptions must not be exposed to JavaScript if the JavaScript
global environment is a worker environment. [DOM]

Importing scripts and libraries


When a script invokes the importScripts(urls) method on a WorkerGlobalScope object, the user
agent must run the following steps: 1. If there are no arguments, return without doing anything. Abort these steps. 2. Let settings object be the script settings object of the
incumbent script. 3. Resolve each argument. 4. If any fail, throw a SyntaxError exception and abort these steps. 5. Attempt to fetch each resource identified by the resulting absolute URLs, from the entry script's
origin, using the API referrer source specified by settings object, and with the synchronous flag set. 6. For each argument in turn, in the order given, starting with the first one, run these
substeps: 1. Wait for the fetching attempt for the corresponding resource to complete. If the fetching attempt failed, throw a NetworkError exception and abort all
these steps. If the attempt succeeds, then let source be the result of running the
UTF-8 decode algorithm on the script resource. Let language be JavaScript. As with the worker's script, the script here is always assumed to be JavaScript, regardless of the MIME type. 2. Create a script using source as the script source, the
URL from which

http://developers.whatwg.org/terminology-4.html[4/16/2014 9:31:25 PM]

16 Terminology HTML: The Living Standard - Edition for Web Developers

source was obtained, language as the scripting language, and settings object as
the script settings object. If the script came from a resource whose URL does not have the same origin as the worker origin, then pass the muted
errors flag to the create a script algorithm as well. Let the newly created script run until it either
returns, fails to parse, fails to catch an exception, or gets prematurely aborted by the
"kill a worker" or "terminate a worker" algorithms defined
above. If it failed to parse, then throw an ECMAScript SyntaxError exception and abort all these steps. [ECMA262] If an exception was thrown or if the script was prematurely aborted, then abort all these
steps, letting the exception or aborting continue to be processed by the incumbent
script. If the "kill a worker" or "terminate a worker" algorithms abort
the script then abort all these steps.

The WorkerNavigator object


The navigator attribute
of the WorkerGlobalScope interface must return an instance of
the WorkerNavigator interface, which represents the
identity and state of the user agent (the client): The WorkerNavigator interface must only be exposed
to JavaScript if the JavaScript global
environment is a worker environment.

Interface objects and constructors


Nothing must be exposed to JavaScript when the JavaScript global environment is a worker environment except for the following:

Any interfaces and exceptions defined by a specification that explicitly


specifies that
they are exposed to JavaScript when the JavaScript global environment
is a worker environment.

The interfaces of any objects made accessible through, and the exceptions
thrown by any,
interfaces or objects of interfaces that are themselves
exposed

http://developers.whatwg.org/terminology-4.html[4/16/2014 9:31:25 PM]

16 Terminology HTML: The Living Standard - Edition for Web Developers

to JavaScript (i.e. this requirement is transitive). These requirements do not override the requirements defined by the Web IDL
specification, in particular concerning the visibility of interfaces annotated with the [NoInterfaceObject] extended attribute.

Worker locations
A WorkerLocation object represents an absolute URL set at its
creation. The WorkerLocation interface supports the URLUtilsReadOnly
interface. When the object is created, the user agent must invoke the element's URLUtilsReadOnly interface's set the
input algorithm with the absolute URL that the WorkerLocation
object represents as the given value. The element's URLUtilsReadOnly interface's get the base algorithm must return null. The WorkerLocation interface must only be exposed to JavaScript if
the JavaScript global environment is a worker environment.

Up next

17 The HTML syntax

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/terminology-4.html[4/16/2014 9:31:25 PM]

17 The HTML syntax HTML: The Living Standard - Edition for Web Developers

W H A TW G

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
The HTML syntax
Writing HTML documents
The DOCTYPE
Elements
Start tags
End tags
Attributes
Optional tags
Restrictions on content models
Restrictions on the contents of raw text and escapable raw text elements
Text
Newlines
Character references
CDATA sections
Comments

17THE HTML SYNTAX

This section only describes the rules for resources labeled with an HTML MIME type. Rules for XML resources are discussed in the section below entitled "The
XHTML syntax".

Writing HTML documents


Documents must consist of the following parts, in the given
order: 1. Optionally, a single U+FEFF BYTE ORDER MARK (BOM) character. 2. Any number of comments and space characters.

http://developers.whatwg.org/syntax.html[4/16/2014 9:31:32 PM]

17 The HTML syntax HTML: The Living Standard - Edition for Web Developers

3. A DOCTYPE. 4. Any number of comments and space characters. 5. The root element, in the form of an html element. 6. Any number of comments and space characters. The various types of content mentioned above are described in the next few sections. In addition, there are some restrictions on how character encoding declarations are to be serialized, as discussed in the
section on that topic. Space characters before the root html element, and space characters at the start
of the html element and before the head element, will be dropped when
the document is parsed; space characters after the root html element will
be parsed as if they were at the end of the body element. Thus, space characters around the root element do not round-trip. It is suggested that newlines be inserted after the DOCTYPE, after any comments that are
before the root element, after the html element's start tag (if it is not omitted), and after any comments that are inside the
html element but before the head element. Many strings in the HTML syntax (e.g. the names of elements and their attributes) are
case-insensitive, but only for uppercase ASCII letters and lowercase ASCII
letters. For convenience, in this section this is just referred to as
"case-insensitive".

The DOCTYPE
A DOCTYPE is a required preamble. DOCTYPEs are required for legacy reasons. When omitted, browsers tend to use a
different rendering mode that is incompatible with some specifications. Including the DOCTYPE in a
document ensures that the browser makes a best-effort attempt at following the relevant
specifications. A DOCTYPE must consist of the following components, in this order: 1. A string that is an ASCII case-insensitive match for the string "<!DOCTYPE". 2. One or more space characters. 3. A string that is an ASCII case-insensitive match for the string "html". 4. Optionally, a DOCTYPE legacy string or an obsolete permitted DOCTYPE

http://developers.whatwg.org/syntax.html[4/16/2014 9:31:32 PM]

17 The HTML syntax HTML: The Living Standard - Edition for Web Developers

string (defined below). 5. Zero or more space characters. 6. A U+003E GREATER-THAN SIGN character (>). In other words, <!DOCTYPE html> , case-insensitively. For the purposes of HTML generators that cannot output HTML markup with the short DOCTYPE
"<!DOCTYPE html>", a DOCTYPE legacy string may be inserted
into the DOCTYPE (in the position defined above). This string must consist of: 1. One or more space characters. 2. A string that is an ASCII case-insensitive match for the string "SYSTEM". 3. One or more space characters. 4. A U+0022 QUOTATION MARK or U+0027 APOSTROPHE character (the quote mark). 5. The literal string "about:legacy-compat". 6. A matching U+0022 QUOTATION MARK or U+0027 APOSTROPHE character (i.e. the same character as in the earlier step labeled quote mark). In other words, <!DOCTYPE html SYSTEM "about:legacy-compat"> or <!DOCTYPE html SYSTEM 'about:legacy-compat'>, case-insensitively except for the
part in single or double quotes. The DOCTYPE legacy string should not be used unless the document is generated from
a system that cannot output the shorter string. To help authors transition from HTML4 and XHTML1, an obsolete permitted DOCTYPE
string can be inserted into the DOCTYPE (in the position defined above). This string must
consist of: 1. One or more space characters. 2. A string that is an ASCII case-insensitive match for the string "PUBLIC". 3. One or more space characters. 4. A U+0022 QUOTATION MARK or U+0027 APOSTROPHE character (the first quote mark). 5. The string from one of the cells in the first column of the table below. The row to which this cell belongs is the selected row. 6. A matching U+0022 QUOTATION MARK or U+0027 APOSTROPHE character (i.e. the same character as in the earlier step labeled first quote mark). 7. If the cell in the second column of the selected row is not blank, one or more space characters.

http://developers.whatwg.org/syntax.html[4/16/2014 9:31:32 PM]

17 The HTML syntax HTML: The Living Standard - Edition for Web Developers

8. If the cell in the second column of the selected row is not blank, a U+0022 QUOTATION MARK or U+0027 APOSTROPHE character (the third quote mark). 9. If the cell in the second column of the selected row is not blank, the string from the cell in the second column of the selected row. 10. If the cell in the second column of the selected row is not blank, a matching U+0022 QUOTATION MARK or U+0027 APOSTROPHE character (i.e. the same character as in the earlier step labeled third quote mark).
Allowed values for public and system identifiers in an obsolete permitted DOCTYPE string. Public identifier -//W3C//DTDHTML4.0//EN -//W3C//DTDHTML4.0//EN -//W3C//DTDHTML4.01//EN -//W3C//DTDHTML4.01//EN //W3C//DTDXHTML1.0Strict//EN -//W3C//DTDXHTML1.1//EN http://www.w3.org/TR/html4/strict.dtd http://www.w3.org/TR/xhtml1/DTD/xhtml1strict.dtd http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd http://www.w3.org/TR/REC-html40/strict.dtd System identifier

A DOCTYPE containing an obsolete permitted DOCTYPE


string is an obsolete permitted DOCTYPE. Authors should not use obsolete permitted DOCTYPEs, as they are unnecessarily
long.

Elements
There are five different kinds of elements: void
elements, raw text elements, escapable raw text elements,
foreign elements, and normal elements. Void elements area, base, br , col, embed,
hr , img, input, keygen , link,
menuitem, meta, param , source,
track , wbr Raw text elements script , style escapable raw text elements textarea, title Foreign elements Elements from the MathML namespace and the SVG namespace.

http://developers.whatwg.org/syntax.html[4/16/2014 9:31:32 PM]

17 The HTML syntax HTML: The Living Standard - Edition for Web Developers

Normal elements All other allowed HTML elements are normal elements. Tags are used to delimit the start and end of elements in the
markup. Raw text, escapable raw text, and normal elements have
a start tag to indicate where they begin, and an end tag to indicate where they end. The start and end tags of
certain normal elements can be omitted, as
described below in the section on optional tags. Those
that cannot be omitted must not be omitted. Void elements only have a start tag; end
tags must not be specified for void elements. Foreign elements must
either have a start tag and an end tag, or a start tag that is marked as self-closing, in which
case they must not have an end tag. The contents of the element must be placed between
just after the start tag (which might be implied, in certain
cases) and just before the end tag (which again, might be
implied in certain cases). The exact allowed contents of each individual element depend on
the content model of that element, as described earlier in
this specification. Elements must not contain content that their content model disallows. In
addition to the restrictions placed on the contents by those content models, however, the five
types of elements have additional syntactic requirements. Void elements can't have any contents (since there's no end tag, no content can be
put between the start tag and the end tag). Raw text elements can have text, though it has restrictions described below. Escapable raw text elements can have text and
character references, but the text must not contain an ambiguous ampersand. There are also further restrictions described below. Foreign elements whose start tag is marked as self-closing can't have any contents
(since, again, as there's no end tag, no content can be put between the start tag and the end
tag). Foreign elements whose start tag is not marked as self-closing can
have text, character
references, CDATA sections, other elements, and comments, but
the text must not contain the character U+003C LESS-THAN SIGN (<) or an ambiguous ampersand. The HTML syntax does not support namespace declarations, even in foreign elements. For instance, consider the following HTML fragment:

http://developers.whatwg.org/syntax.html[4/16/2014 9:31:32 PM]

17 The HTML syntax HTML: The Living Standard - Edition for Web Developers

<p> <svg> <metadata> <!-- this is invalid --> <cdr:license xmlns:cdr="http://www.example.com/cdr/metadata" name="MIT"/> </metadata> </svg> </p> The innermost element, cdr:license, is actually in the SVG namespace, as the "xmlns:cdr" attribute has no effect (unlike in XML). In fact, as the comment in the fragment above says, the fragment is actually nonconforming. This is because the
SVG specification does not define any elements called "cdr:license" in the
SVG namespace. Normal elements can have text, character references, other elements, and comments, but
the text must not contain the character U+003C LESS-THAN SIGN (<) or an ambiguous ampersand. Some normal elements
also have yet more restrictions on what content they are
allowed to hold, beyond the restrictions imposed by the content model and those described in this paragraph. Those restrictions are described below. Tags contain a tag name, giving the element's name. HTML
elements all have names that only use alphanumeric ASCII characters. In the HTML
syntax, tag names, even those for foreign elements, may be written with any mix of lower- and uppercase letters that, when converted to all-lowercase, matches the element's tag
name; tag names are case-insensitive.

Start tags
Start tags must have the following format: 1. The first character of a start tag must be a U+003C LESS-THAN SIGN character (<). 2. The next few characters of a start tag must be the element's tag name. 3. If there are to be any attributes in the next step, there must first be one or more space characters. 4. Then, the start tag may have a number of attributes, the syntax for which is described below. Attributes must be
separated from each other by one or more space
characters.

http://developers.whatwg.org/syntax.html[4/16/2014 9:31:32 PM]

17 The HTML syntax HTML: The Living Standard - Edition for Web Developers

5. After the attributes, or after the tag name if there are


no attributes, there may be one or more space characters.
(Some attributes are required to be followed by a space. See the attributes section below.) 6. Then, if the element is one of the void elements, or if the element is a foreign element, then there may be a single U+002F SOLIDUS
character (/). This character has no effect on void elements, but on foreign
elements it marks the start tag as self-closing. 7. Finally, start tags must be closed by a U+003E GREATER-THAN SIGN character (>).

End tags
End tags must have the following format: 1. The first character of an end tag must be a U+003C LESS-THAN SIGN character (<). 2. The second character of an end tag must be a U+002F SOLIDUS character (/). 3. The next few characters of an end tag must be the element's tag
name. 4. After the tag name, there may be one or more space
characters. 5. Finally, end tags must be closed by a U+003E GREATER-THAN SIGN character (>).

Attributes
Attributes for an element are expressed inside the
element's start tag. Attributes have a name and a value. Attribute names
must consist of one or more characters other than the space
characters, U+0000 NULL, U+0022 QUOTATION MARK ("), U+0027 APOSTROPHE ('), U+003E
GREATERTHAN SIGN (>), U+002F SOLIDUS (/), and U+003D EQUALS SIGN (=) characters, the control
characters, and any characters that are not defined by Unicode. In the HTML syntax, attribute
names, even those for foreign elements, may be written with any mix of lower- and
uppercase letters that are an ASCII case-insensitive match for the attribute's
name. Attribute values are a mixture of text and character references,
except with the additional restriction that the text cannot contain an ambiguous ampersand. Attributes can be specified in four different ways:

http://developers.whatwg.org/syntax.html[4/16/2014 9:31:32 PM]

17 The HTML syntax HTML: The Living Standard - Edition for Web Developers

Empty attribute syntax Just the attribute name. The value is implicitly
the empty string. In the following example, the disabled attribute is
given with the empty attribute syntax: <input disabled> If an attribute using the empty attribute syntax is to be followed by another attribute, then
there must be a space character separating the two. Unquoted attribute value syntax The attribute name, followed by zero or more space characters, followed by a single U+003D EQUALS SIGN
character, followed by zero or more space characters,
followed by the attribute value, which, in addition
to the requirements given above for attribute values, must not contain any literal space characters, any U+0022 QUOTATION MARK characters ("),
U+0027 APOSTROPHE characters ('), U+003D EQUALS SIGN characters (=), U+003C LESS-THAN SIGN
characters (<), U+003E GREATER-THAN SIGN characters (>), or U+0060 GRAVE ACCENT characters
(`), and must not be the empty string. In the following example, the value attribute is given
with the unquoted attribute value syntax: <input value=yes> If an attribute using the unquoted attribute syntax is to be followed by another attribute or
by the optional U+002F SOLIDUS character (/) allowed in step 6 of the start tag syntax above, then there must be a space
character separating the two. Single-quoted attribute value syntax The attribute name, followed by zero or more space characters, followed by a single U+003D EQUALS SIGN
character, followed by zero or more space characters,
followed by a single U+0027 APOSTROPHE character ('), followed by the attribute value, which, in addition to the requirements
given above for attribute values, must not contain any literal U+0027 APOSTROPHE characters ('),
and finally followed by a second single U+0027 APOSTROPHE character ('). In the following example, the type attribute is given
with the single-quoted attribute value syntax:

http://developers.whatwg.org/syntax.html[4/16/2014 9:31:32 PM]

17 The HTML syntax HTML: The Living Standard - Edition for Web Developers

<input type='checkbox'> If an attribute using the single-quoted attribute syntax is to be followed by another
attribute, then there must be a space character separating the two. Double-quoted attribute value syntax The attribute name, followed by zero or more space characters, followed by a single U+003D EQUALS SIGN
character, followed by zero or more space characters,
followed by a single U+0022 QUOTATION MARK character ("), followed by the attribute value, which, in addition to the requirements
given above for attribute values, must not contain any literal U+0022 QUOTATION MARK characters
("), and finally followed by a second single U+0022 QUOTATION MARK character ("). In the following example, the name attribute is given with
the double-quoted attribute value syntax: <input name="be evil"> If an attribute using the double-quoted attribute syntax is to be followed by another
attribute, then there must be a space character separating the two. There must never be two or more attributes on the same start tag whose names are an ASCII
case-insensitive match for each other. When a foreign element has one of the namespaced
attributes given by the local name and namespace of the first and second cells of a row from the following table, it must be written using the name given by the third cell from the same row. Local name actuate arcrole href role show title type XLink namespace XLink namespace XLink namespace XLink namespace XLink namespace XLink namespace XLink namespace Namespace Attribute name xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type

http://developers.whatwg.org/syntax.html[4/16/2014 9:31:32 PM]

17 The HTML syntax HTML: The Living Standard - Edition for Web Developers

base lang space xmlns xlink

XML namespace XML namespace XML namespace XMLNS namespace XMLNS namespace

xml:base xml:lang xml:space xmlns xmlns:xlink

No other namespaced attribute can be expressed in the HTML syntax. Whether the attributes in the table above are conforming or not is defined by other specifications (e.g. the SVG and MathML specifications); this section only describes the
syntax rules if the attributes are serialized using the HTML syntax.

Optional tags
Certain tags can be omitted. Omitting an element's start tag in the
situations described below does not mean the element is not present; it is implied, but it is
still there. For example, an HTML document always has a root html element, even if
the string <html> doesn't appear anywhere in the markup. An html element's start tag may be omitted
if the first thing inside the html element is not a comment. An html element's end tag may be omitted if
the html element is not immediately followed by a comment. A head element's start tag may be omitted if
the element is empty, or if the first thing inside the head element is an
element. A head element's end tag may be omitted if the
head element is not immediately followed by a space character or a comment. A body element's start tag may be omitted if
the element is empty, or if the first thing inside the body element is not a
space character or a comment, except if the
first thing inside the body element is a meta, link, script, style , or template
element. A body element's end tag may be omitted if the
body element is not immediately followed by a comment.

http://developers.whatwg.org/syntax.html[4/16/2014 9:31:32 PM]

17 The HTML syntax HTML: The Living Standard - Edition for Web Developers

An li element's end tag may be omitted if the


li element is immediately followed by another li element or if there is
no more content in the parent element. A dt element's end tag may be omitted if the
dt element is immediately followed by another dt element or a
dd element. A dd element's end tag may be omitted if the
dd element is immediately followed by another dd element or a
dt element, or if there is no more content in the parent element. A p element's end tag may be omitted if the
p element is immediately followed by an address, article,
aside , blockquote , div, dl ,
fieldset, footer, form, h1, h2 ,
h3 , h4, h5 , h6 , header,
hgroup , hr, main, menu, nav,
ol, p , pre, section, table, or
ul , element, or if there is no more content in the parent element and the parent
element is not an a element. An rt element's end tag may be omitted if the
rt element is immediately followed by an rt or rp element,
or if there is no more content in the parent element. An rp element's end tag may be omitted if the
rp element is immediately followed by an rt or rp element,
or if there is no more content in the parent element. An optgroup element's end tag may be omitted
if the optgroup element is immediately followed by another optgroup element, or if there is no more content in
the parent element. An option element's end tag may be omitted if
the option element is immediately followed by another option element, or
if it is immediately followed by an optgroup element, or if there is no more content
in the parent element. A colgroup element's start tag may be
omitted if the first thing inside the colgroup element is a col element,
and if the element is not immediately preceded by another colgroup element whose
end tag has been omitted. (It can't be omitted if the element
is empty.) A colgroup element's end tag may be omitted if
the colgroup element is not immediately followed by a space character or
a comment. A thead element's end tag may be omitted if
the thead element is

http://developers.whatwg.org/syntax.html[4/16/2014 9:31:32 PM]

17 The HTML syntax HTML: The Living Standard - Edition for Web Developers

immediately followed by a tbody or


tfoot element. A tbody element's start tag may be omitted
if the first thing inside the tbody element is a tr element, and if the
element is not immediately preceded by a tbody , thead, or
tfoot element whose end tag has been omitted. (It
can't be omitted if the element is empty.) A tbody element's end tag may be omitted if
the tbody element is immediately followed by a tbody or
tfoot element, or if there is no more content in the parent element. A tfoot element's end tag may be omitted if
the tfoot element is immediately followed by a tbody element, or if
there is no more content in the parent element. A tr element's end tag may be omitted if the
tr element is immediately followed by another tr element, or if there is
no more content in the parent element. A td element's end tag may be omitted if the
td element is immediately followed by a td or th element,
or if there is no more content in the parent element. A th element's end tag may be omitted if the
th element is immediately followed by a td or th element,
or if there is no more content in the parent element. However, a start tag must never be
omitted if it has any attributes.

Restrictions on content models


For historical reasons, certain elements have extra restrictions beyond even the restrictions
given by their content model. A table element must not contain tr elements, even though these
elements are technically allowed inside table elements according to the content models described in this specification. (If a tr element is put inside a
table in the markup, it will in fact imply a tbody start tag before
it.) A single newline may be placed immediately after the start tag of pre and textarea elements.
This does not affect the processing of the element. The otherwise optional newline must be included if the element's contents

http://developers.whatwg.org/syntax.html[4/16/2014 9:31:32 PM]

17 The HTML syntax HTML: The Living Standard - Edition for Web Developers

themselves start with a newline (because otherwise the


leading newline in the contents would be treated like the optional newline, and ignored). The following two pre blocks are equivalent: <pre>Hello</pre> <pre> Hello</pre>

Restrictions on the contents of raw text and escapable raw text elements
The text in raw text and escapable raw text
elements must not contain any occurrences of the string "</ "
(U+003C LESS-THAN SIGN, U+002F SOLIDUS) followed by characters that case-insensitively match the
tag name of the element followed by one of U+0009 CHARACTER TABULATION (tab), U+000A LINE FEED
(LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), U+0020 SPACE, U+003E GREATER-THAN SIGN
(>), or U+002F SOLIDUS (/).

Text
Text is allowed inside elements, attribute values, and comments.
Extra constraints are placed on what is and what is not allowed in text based on where the text is
to be put, as described in the other sections.

Newlines
Newlines in HTML may be represented either as U+000D
CARRIAGE RETURN (CR) characters, U+000A LINE FEED (LF) characters, or pairs of U+000D CARRIAGE
RETURN (CR), U+000A LINE FEED (LF) characters in that order. Where character references are allowed, a character
reference of a U+000A LINE FEED (LF) character (but not a U+000D CARRIAGE RETURN (CR) character)
also represents a newline.

http://developers.whatwg.org/syntax.html[4/16/2014 9:31:32 PM]

17 The HTML syntax HTML: The Living Standard - Edition for Web Developers

Character references
In certain cases described in other sections, text may be
mixed with character references. These can be used to escape
characters that couldn't otherwise legally be included in text. Character references must start with a U+0026 AMPERSAND character (&). Following this,
there are three possible kinds of character references: Named character references The ampersand must be followed by one of the names given in the named character
references section, using the same case. Decimal numeric character reference The ampersand must be followed by a U+0023 NUMBER SIGN character (#), followed by one or more
ASCII digits, representing a base-ten integer that corresponds to a Unicode code
point that is allowed according to the definition below. The digits must then be followed by a
U+003B SEMICOLON character (;). Hexadecimal numeric character reference The ampersand must be followed by a U+0023 NUMBER SIGN character (#), which must be followed
by either a U+0078 LATIN SMALL LETTER X character (x) or a U+0058 LATIN CAPITAL LETTER X
character (X), which must then be followed by one or more ASCII hex digits,
representing a basesixteen integer that corresponds to a Unicode code point that is allowed according to the definition below. The digits must then be followed by a U+003B SEMICOLON
character (;). The numeric character reference forms described above are allowed to reference any Unicode code
point other than U+0000, U+000D, permanently undefined Unicode characters (noncharacters),
surrogates (U+D800 U+DFFF), and control characters other than space characters. An ambiguous ampersand is a U+0026 AMPERSAND
character (&) that is followed by one or more alphanumeric ASCII characters,
followed by a U+003B SEMICOLON character (;), where these characters do not match any of the names
given in the named character references section.

CDATA sections

http://developers.whatwg.org/syntax.html[4/16/2014 9:31:32 PM]

17 The HTML syntax HTML: The Living Standard - Edition for Web Developers

CDATA sections must consist of the following components, in


this order: 1. The string "<![CDATA[ ". 2. Optionally, text, with the additional restriction that the
text must not contain the string "]]>". 3. The string "]]> ". CDATA sections can only be used in foreign content (MathML or SVG). In this example, a CDATA
section is used to escape the contents of an ms element: <p>You can add a string to a number, but this stringifies the number:</p> <math> <ms><![CDATA[x<y]]></ms> <mo>+</mo> <mn>3</mn> <mo>=</mo> <ms><![CDATA[x<y3]]></ms> </math>

Comments
Comments must start with the four character sequence U+003C
LESS-THAN SIGN, U+0021 EXCLAMATION MARK, U+002D HYPHEN-MINUS, U+002D HYPHEN-MINUS (<!--). Following this sequence, the comment may have text, with the additional restriction that the text must not start with a single U+003E GREATER-THAN SIGN character (>), nor start with a U+002D HYPHEN-MINUS character
(-) followed by a U+003E GREATERTHAN SIGN (>) character, nor contain two consecutive U+002D
HYPHENMINUS characters ( --), nor end with a U+002D HYPHEN-MINUS character (-). Finally, the comment must be ended by the three character sequence U+002D HYPHEN-MINUS,
U+002D HYPHEN-MINUS, U+003E GREATER-THAN SIGN (-->).

Up next

17.2 Named character references

http://developers.whatwg.org/syntax.html[4/16/2014 9:31:32 PM]

17 The HTML syntax HTML: The Living Standard - Edition for Web Developers

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/syntax.html[4/16/2014 9:31:32 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

Named character references


This table lists the character reference names that are supported by HTML, and the code points
to which they refer. It is referenced by the previous sections. Name Aacute; aacute; Abreve; abreve; ac; acd; acE; Acirc; acirc; acute; Acy; acy; AElig; aelig; af; Afr; Character(s) Glyph U+000C1 U+000E1 U+00102 U+00103 U+0223E U+0223F U+0223E U+00333 U+000C2 U+000E2 U+000B4 U+00410 U+00430 U+000C6 U+000E6 U+02061 U+1D504 &Acy; &acy; &af; &Afr; &Abreve; &abreve; &ac; &acd; &ac;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

afr; Agrave; agrave; alefsym; aleph; Alpha; alpha; Amacr; amacr; amalg; AMP; amp; And; and; andand; andd; andslope; andv; ang; ange; angle; angmsd; angmsdaa; angmsdab; angmsdac; angmsdad; angmsdae; angmsdaf;

U+1D51E U+000C0 U+000E0 U+02135 U+02135 U+00391 U+003B1 U+00100 U+00101 U+02A3F U+00026 U+00026 U+02A53 U+02227 U+02A55 U+02A5C U+02A58 U+02A5A U+02220 U+029A4 U+02220 U+02221 U+029A8 U+029A9 U+029AA U+029AB U+029AC U+029AD

&afr; &aleph; &aleph; &Amacr; &amacr; &amalg; & & &And; &wedge; &andand; &andd; &andslope; &andv; &angle; &ange; &angle; &angmsd; &angmsdaa; &angmsdab; &angmsdac; &angmsdad; &angmsdae; &angmsdaf;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

angmsdag; angmsdah; angrt; angrtvb; angrtvbd; angsph; angst; angzarr; Aogon; aogon; Aopf; aopf; ap; apacir; apE; ape; apid; apos; ApplyFunction; approx; approxeq; Aring; aring; Ascr; ascr; Assign; ast; asymp; asympeq;
http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

U+029AE U+029AF U+0221F U+022BE U+0299D U+02222 U+000C5 U+0237C U+00104 U+00105 U+1D538 U+1D552 U+02248 U+02A6F U+02A70 U+0224A U+0224B U+00027 U+02061 U+02248 U+0224A U+000C5 U+000E5 U+1D49C U+1D4B6 U+02254 U+0002A U+02248 U+0224D

&angmsdag; &angmsdah; &angrt; &angrtvb; &angrtvbd; &angsph; &angst; &angzarr; &Aogon; &aogon; &Aopf; &aopf; &thkap; &apacir; &apE; &approxeq; &apid; ' &af; &thkap; &approxeq; &angst; &Ascr; &ascr; &coloneq; * &thkap; &asympeq;

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

Atilde; atilde; Auml; auml; awconint; awint; backcong; backepsilon; backprime; backsim; backsimeq; Backslash; Barv; barvee; Barwed; barwed; barwedge; bbrk; bbrktbrk; bcong; Bcy; bcy; bdquo; becaus; Because; because; bemptyv; bepsi;

U+000C3 U+000E3 U+000C4 U+000E4 U+02233 U+02A11 U+0224C U+003F6 U+02035 U+0223D U+022CD U+02216 U+02AE7 U+022BD U+02306 U+02305 U+02305 U+023B5 U+023B6 U+0224C U+00411 U+00431 U+0201E U+02235 U+02235 U+02235 U+029B0 U+003F6

&awconint; &awint; &bcong; &backepsilon; &bprime; &backsim; &backsimeq; &smallsetminus; &Barv; &barvee; &doublebarwedge; &barwedge; &barwedge; &bbrk; &bbrktbrk; &bcong; &Bcy; &bcy; &ldquor; &becaus; &becaus; &becaus; &bemptyv; &backepsilon;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

bernou; Bernoullis; Beta; beta; beth; between; Bfr; bfr; bigcap; bigcirc; bigcup; bigodot; bigoplus; bigotimes; bigsqcup; bigstar; bigtriangledown; bigtriangleup; biguplus; bigvee; bigwedge; bkarow; blacklozenge; blacksquare; blacktriangle; blacktriangledown; blacktriangleleft; blacktriangleright; blank;
http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

U+0212C U+0212C U+00392 U+003B2 U+02136 U+0226C U+1D505 U+1D51F U+022C2 U+025EF U+022C3 U+02A00 U+02A01 U+02A02 U+02A06 U+02605 U+025BD U+025B3 U+02A04 U+022C1 U+022C0 U+0290D U+029EB U+025AA U+025B4 U+025BE U+025C2 U+025B8 U+02423

&bernou; &bernou; &beth; &between; &Bfr; &bfr; &bigcap; &xcirc; &xcup; &bigodot; &bigoplus; &xotime; &bigsqcup; &bigstar; &xdtri; &bigtriangleup; &xuplus; &bigvee; &xwedge; &rbarr; &lozf; &blacksquare; &utrif; &blacktriangledown; &blacktriangleleft; &blacktriangleright; &blank;

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

blk12; blk14; blk34; block; bne; bnequiv; bNot; bnot; Bopf; bopf; bot; bottom; bowtie; boxbox; boxDL; boxDl; boxdL; boxdl; boxDR; boxDr; boxdR; boxdr; boxH; boxh; boxHD; boxHd; boxhD;

U+02592 U+02591 U+02593 U+02588 U+0003D U+020E5 U+02261 U+020E5 U+02AED U+02310 U+1D539 U+1D553 U+022A5 U+022A5 U+022C8 U+029C9 U+02557 U+02556 U+02555 U+02510 U+02554 U+02553 U+02552 U+0250C U+02550 U+02500 U+02566 U+02564 U+02565

&blk12; &blk14; &blk34; &block; =

&bNot; &bnot; &Bopf; &bopf; &bottom; &bottom; &bowtie; &boxbox; &boxDL; &boxDl; &boxdL; &boxdl; &boxDR; &boxDr; &boxdR; &boxdr; &boxH; &boxh; &boxHD; &boxHd; &boxhD;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

boxhd; boxHU; boxHu; boxhU; boxhu; boxminus; boxplus; boxtimes; boxUL; boxUl; boxuL; boxul; boxUR; boxUr; boxuR; boxur; boxV; boxv; boxVH; boxVh; boxvH; boxvh; boxVL; boxVl; boxvL; boxvl; boxVR; boxVr;

U+0252C U+02569 U+02567 U+02568 U+02534 U+0229F U+0229E U+022A0 U+0255D U+0255C U+0255B U+02518 U+0255A U+02559 U+02558 U+02514 U+02551 U+02502 U+0256C U+0256B U+0256A U+0253C U+02563 U+02562 U+02561 U+02524 U+02560 U+0255F U+0255E

&boxhd; &boxHU; &boxHu; &boxhU; &boxhu; &minusb; &boxplus; &timesb; &boxUL; &boxUl; &boxuL; &boxul; &boxUR; &boxUr; &boxuR; &boxur; &boxV; &boxv; &boxVH; &boxVh; &boxvH; &boxvh; &boxVL; &boxVl; &boxvL; &boxvl; &boxVR; &boxVr; &boxvR;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

boxvR; boxvr; bprime; Breve; breve; brvbar; Bscr; bscr; bsemi; bsim; bsime; bsol; bsolb; bsolhsub; bull; bullet; bump; bumpE; bumpe; Bumpeq; bumpeq; Cacute; cacute; Cap; cap; capand; capbrcup; capcap; capcup;
http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

U+0251C U+02035 U+002D8 U+002D8 U+000A6 U+0212C U+1D4B7 U+0204F U+0223D U+022CD U+0005C U+029C5 U+027C8 U+02022 U+02022 U+0224E U+02AAE U+0224F U+0224E U+0224F U+00106 U+00107 U+022D2 U+02229 U+02A44 U+02A49 U+02A4B U+02A47

&boxvr; &bprime; &breve; &breve; &bernou; &bscr; &bsemi; &backsim; &backsimeq; \ &bsolb; &bsolhsub; &bullet; &bullet; &bump; &bumpE; &bumpeq; &bump; &bumpeq; &Cacute; &cacute; &Cap; &capand; &capbrcup; &capcap; &capcup;

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

capdot; CapitalDifferentialD; caps; caret; caron; Cayleys; ccaps; Ccaron; ccaron; Ccedil; ccedil; Ccirc; ccirc; Cconint; ccups; ccupssm; Cdot; cdot; cedil; Cedilla; cemptyv; cent; CenterDot; centerdot; Cfr; cfr; CHcy; chcy;
http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

U+02A40 U+02145 U+02229 U+0FE00 U+02041 U+002C7 U+0212D U+02A4D U+0010C U+0010D U+000C7 U+000E7 U+00108 U+00109 U+02230 U+02A4C U+02A50 U+0010A U+0010B U+000B8 U+000B8 U+029B2 U+000A2 U+000B7 U+000B7 U+0212D U+1D520 U+00427 U+00447

&capdot; &DD;

&caret; &caron; &Cayleys; &ccaps; &Ccaron; &ccaron; &Ccirc; &ccirc; &Cconint; &ccups; &ccupssm; &Cdot; &cdot; &cemptyv; &Cayleys; &cfr; &CHcy; &chcy;

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

check; checkmark; Chi; chi; cir; circ; circeq; circlearrowleft; circlearrowright; circledast; circledcirc; circleddash; CircleDot; circledR; circledS; CircleMinus; CirclePlus; CircleTimes; cirE; cire; cirfnint; cirmid; cirscir; ClockwiseContourIntegral; CloseCurlyDoubleQuote; CloseCurlyQuote; clubs; clubsuit;

U+02713 U+02713 U+003A7 U+003C7 U+025CB U+002C6 U+02257 U+021BA U+021BB U+0229B U+0229A U+0229D U+02299 U+000AE U+024C8 U+02296 U+02295 U+02297 U+029C3 U+02257 U+02A10 U+02AEF U+029C2 U+02232 U+0201D U+02019 U+02663 U+02663

&check; &check; &cir; &cire; &olarr; &orarr; &oast; &ocir; &circleddash; &odot; &oS; &ominus;

&cirE; &cire; &cirfnint; &cirmid; &cirscir; &cwconint; &rsquor;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

Colon; colon; Colone; colone; coloneq; comma; commat; comp; compfn; complement; complexes; cong; congdot; Congruent; Conint; conint; ContourIntegral; Copf; copf; coprod; Coproduct; COPY; copy; copysr; CounterClockwiseContourIntegral; crarr; Cross; cross; Cscr;
http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

U+02237 U+0003A U+02A74 U+02254 U+02254 U+0002C U+00040 U+02201 U+02218 U+02201 U+02102 U+02245 U+02A6D U+02261 U+0222F U+0222E U+0222E U+02102 U+1D554 U+02210 U+02210 U+000A9 U+000A9 U+02117 U+02233 U+021B5 U+02A2F U+02717 U+1D49E

&Colon; : &Colone; &coloneq; &coloneq; , @ &complement; &compfn; &complement; &complexes;

&congdot; &Conint; &conint; &conint; &complexes; &copf; &coprod; &coprod; &copysr; &awconint;

&Cross; &cross; &Cscr;

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

cscr; csub; csube; csup; csupe; ctdot; cudarrl; cudarrr; cuepr; cuesc; cularr; cularrp; Cup; cup; cupbrcap; CupCap; cupcap; cupcup; cupdot; cupor; cups; curarr; curarrm; curlyeqprec; curlyeqsucc; curlyvee; curlywedge; curren;
http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

U+1D4B8 U+02ACF U+02AD1 U+02AD0 U+02AD2 U+022EF U+02938 U+02935 U+022DE U+022DF U+021B6 U+0293D U+022D3 U+0222A U+02A48 U+0224D U+02A46 U+02A4A U+0228D U+02A45 U+0222A U+0FE00 U+021B7 U+0293C U+022DE U+022DF U+022CE U+022CF U+000A4

&cscr; &csub; &csube; &csup; &csupe; &ctdot; &cudarrl; &cudarrr; &cuepr; &curlyeqsucc; &curvearrowleft; &cularrp; &Cup;

&cupbrcap; &asympeq; &cupcap; &cupcup; &cupdot; &cupor;

&curarr; &curarrm; &cuepr; &curlyeqsucc; &cuvee; &curlywedge;

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

curvearrowleft; curvearrowright; cuvee; cuwed; cwconint; cwint; cylcty; Dagger; dagger; daleth; Darr; dArr; darr; dash; Dashv; dashv; dbkarow; dblac; Dcaron; dcaron; Dcy; dcy; DD; dd; ddagger; ddarr; DDotrahd; ddotseq;

U+021B6 U+021B7 U+022CE U+022CF U+02232 U+02231 U+0232D U+02021 U+02020 U+02138 U+021A1 U+021D3 U+02193 U+02010 U+02AE4 U+022A3 U+0290F U+002DD U+0010E U+0010F U+00414 U+00434 U+02145 U+02146 U+02021 U+021CA U+02911 U+02A77

&curvearrowleft; &curarr; &cuvee; &curlywedge; &cwconint; &cwint; &cylcty; &ddagger; &daleth; &Darr; &DoubleDownArrow; &downarrow; &dash; &DoubleLeftTee; &dashv; &dbkarow; &dblac; &Dcaron; &dcaron; &Dcy; &dcy; &DD; &dd; &ddagger; &ddarr; &DDotrahd; &ddotseq;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

deg; Del; Delta; delta; demptyv; dfisht; Dfr; dfr; dHar; dharl; dharr; DiacriticalAcute; DiacriticalDot; DiacriticalDoubleAcute; DiacriticalGrave; DiacriticalTilde; diam; Diamond; diamond; diamondsuit; diams; die; DifferentialD; digamma; disin; div; divide; divideontimes; divonx;
http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

U+000B0 U+02207 U+00394 U+003B4 U+029B1 U+0297F U+1D507 U+1D521 U+02965 U+021C3 U+021C2 U+000B4 U+002D9 U+002DD U+00060 U+002DC U+022C4 U+022C4 U+022C4 U+02666 U+02666 U+000A8 U+02146 U+003DD U+022F2 U+000F7 U+000F7 U+022C7 U+022C7

&demptyv; &dfisht; &Dfr; &dfr; &dHar; &downharpoonleft; &dharr; &dot; &dblac; ` &diamond; &diamond; &diamond; &die; &dd; &gammad; &disin; &divonx; &divonx;

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

DJcy; djcy; dlcorn; dlcrop; dollar; Dopf; dopf; Dot; dot; DotDot; doteq; doteqdot; DotEqual; dotminus; dotplus; dotsquare; doublebarwedge; DoubleContourIntegral; DoubleDot; DoubleDownArrow; DoubleLeftArrow; DoubleLeftRightArrow; DoubleLeftTee; DoubleLongLeftArrow; DoubleLongLeftRightArrow; DoubleLongRightArrow; DoubleRightArrow; DoubleRightTee;

U+00402 U+00452 U+0231E U+0230D U+00024 U+1D53B U+1D555 U+000A8 U+002D9 U+020DC U+02250 U+02251 U+02250 U+02238 U+02214 U+022A1 U+02306 U+0222F U+000A8 U+021D3 U+021D0 U+021D4 U+02AE4 U+027F8 U+027FA U+027F9 U+021D2 U+022A8

&DJcy; &djcy; &dlcorn; &dlcrop; $ &Dopf; &dopf; &die; &dot; &DotDot; &esdot; &doteqdot; &esdot; &dotminus; &dotplus; &dotsquare; &doublebarwedge; &Conint; &die; &DoubleDownArrow;

&iff; &DoubleLeftTee; &Longleftarrow; &DoubleLongLeftRightArrow; &xrArr; &Implies; &vDash;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

DoubleUpArrow; DoubleUpDownArrow; DoubleVerticalBar; DownArrow; Downarrow; downarrow; DownArrowBar; DownArrowUpArrow; DownBreve; downdownarrows; downharpoonleft; downharpoonright; DownLeftRightVector; DownLeftTeeVector; DownLeftVector; DownLeftVectorBar; DownRightTeeVector; DownRightVector; DownRightVectorBar; DownTee; DownTeeArrow; drbkarow; drcorn; drcrop; Dscr; dscr; DScy; dscy; dsol;
http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

U+021D1 U+021D5 U+02225 U+02193 U+021D3 U+02193 U+02913 U+021F5 U+00311 U+021CA U+021C3 U+021C2 U+02950 U+0295E U+021BD U+02956 U+0295F U+021C1 U+02957 U+022A4 U+021A7 U+02910 U+0231F U+0230C U+1D49F U+1D4B9 U+00405 U+00455 U+029F6

&Uparrow; &DoubleUpDownArrow; &spar; &downarrow; &DoubleDownArrow; &downarrow; &DownArrowBar; &duarr; &DownBreve; &ddarr; &downharpoonleft; &dharr; &DownLeftRightVector; &DownLeftTeeVector; &leftharpoondown; &DownLeftVectorBar; &DownRightTeeVector; &rhard; &DownRightVectorBar; &top; &mapstodown; &drbkarow; &drcorn; &drcrop; &Dscr; &dscr; &DScy; &dscy; &dsol;

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

Dstrok; dstrok; dtdot; dtri; dtrif; duarr; duhar; dwangle; DZcy; dzcy; dzigrarr; Eacute; eacute; easter; Ecaron; ecaron; ecir; Ecirc; ecirc; ecolon; Ecy; ecy; eDDot; Edot; eDot; edot; ee; efDot;

U+00110 U+00111 U+022F1 U+025BF U+025BE U+021F5 U+0296F U+029A6 U+0040F U+0045F U+027FF U+000C9 U+000E9 U+02A6E U+0011A U+0011B U+02256 U+000CA U+000EA U+02255 U+0042D U+0044D U+02A77 U+00116 U+02251 U+00117 U+02147 U+02252

&Dstrok; &dstrok; &dtdot; &triangledown; &blacktriangledown; &duarr; &duhar; &dwangle; &DZcy; &dzcy; &dzigrarr; &easter; &Ecaron; &ecaron; &eqcirc; &eqcolon; &Ecy; &ecy; &ddotseq; &Edot; &doteqdot; &edot; &exponentiale; &fallingdotseq;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

Efr; efr; eg; Egrave; egrave; egs; egsdot; el; Element; elinters; ell; els; elsdot; Emacr; emacr; empty; emptyset; EmptySmallSquare; emptyv; EmptyVerySmallSquare; emsp; emsp13; emsp14; ENG; eng; ensp; Eogon; eogon; Eopf;
http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

U+1D508 U+1D522 U+02A9A U+000C8 U+000E8 U+02A96 U+02A98 U+02A99 U+02208 U+023E7 U+02113 U+02A95 U+02A97 U+00112 U+00113 U+02205 U+02205 U+025FB U+02205 U+025AB U+02003 U+02004 U+02005 U+0014A U+0014B U+02002 U+00118 U+00119 U+1D53C

&Efr; &efr; &eg; &egs; &egsdot; &el; &in; &elinters; &ell; &eqslantless; &elsdot; &Emacr; &emacr; &emptyv; &emptyv; &EmptySmallSquare; &emptyv; &EmptyVerySmallSquare; &emsp13; &emsp14; &ENG; &eng; &Eogon; &eogon; &Eopf;

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

eopf; epar; eparsl; eplus; epsi; Epsilon; epsilon; epsiv; eqcirc; eqcolon; eqsim; eqslantgtr; eqslantless; Equal; equals; EqualTilde; equest; Equilibrium; equiv; equivDD; eqvparsl; erarr; erDot; Escr; escr; esdot; Esim; esim;

U+1D556 U+022D5 U+029E3 U+02A71 U+003B5 U+00395 U+003B5 U+003F5 U+02256 U+02255 U+02242 U+02A96 U+02A95 U+02A75 U+0003D U+02242 U+0225F U+021CC U+02261 U+02A78 U+029E5 U+02971 U+02253 U+02130 U+0212F U+02250 U+02A73 U+02242

&eopf; &epar; &eparsl; &eplus; &epsi; &epsi; &straightepsilon; &eqcirc; &eqcolon; &esim; &egs; &eqslantless; &Equal; = &esim; &questeq; &rlhar; &equivDD; &eqvparsl; &erarr; &risingdotseq; &expectation; &escr; &esdot; &Esim; &esim;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

Eta; eta; ETH; eth; Euml; euml; euro; excl; exist; Exists; expectation; ExponentialE; exponentiale; fallingdotseq; Fcy; fcy; female; ffilig; fflig; ffllig; Ffr; ffr; filig; FilledSmallSquare; FilledVerySmallSquare; fjlig; flat; fllig;

U+00397 U+003B7 U+000D0 U+000F0 U+000CB U+000EB U+020AC U+00021 U+02203 U+02203 U+02130 U+02147 U+02147 U+02252 U+00424 U+00444 U+02640 U+0FB03 U+0FB00 U+0FB04 U+1D509 U+1D523 U+0FB01 U+025FC U+025AA U+00066 U+0006A U+0266D U+0FB02

&expectation; &exponentiale; &exponentiale; &fallingdotseq; &Fcy; &fcy; &female; &ffilig; &fflig; &ffllig; &Ffr; &ffr; &filig; &FilledSmallSquare; &blacksquare; fj

&flat; &fllig;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

fltns; fnof; Fopf; fopf; ForAll; forall; fork; forkv; Fouriertrf; fpartint; frac12; frac13; frac14; frac15; frac16; frac18; frac23; frac25; frac34; frac35; frac38; frac45; frac56; frac58; frac78; frasl; frown; Fscr; fscr;
http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

U+025B1 U+00192 U+1D53D U+1D557 U+02200 U+02200 U+022D4 U+02AD9 U+02131 U+02A0D U+000BD U+02153 U+000BC U+02155 U+02159 U+0215B U+02154 U+02156 U+000BE U+02157 U+0215C U+02158 U+0215A U+0215D U+0215E U+02044 U+02322 U+02131 U+1D4BB

&fltns; &Fopf; &fopf;

&fork; &forkv; &Fscr; &fpartint; &half; &frac13; &frac15; &frac16; &frac18; &frac23; &frac25; &frac35; &frac38; &frac45; &frac56; &frac58; &frac78; &frown; &Fscr; &fscr;

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

gacute; Gamma; gamma; Gammad; gammad; gap; Gbreve; gbreve; Gcedil; Gcirc; gcirc; Gcy; gcy; Gdot; gdot; gE; ge; gEl; gel; geq; geqq; geqslant; ges; gescc; gesdot; gesdoto; gesdotol; gesl;

U+001F5 U+00393 U+003B3 U+003DC U+003DD U+02A86 U+0011E U+0011F U+00122 U+0011C U+0011D U+00413 U+00433 U+00120 U+00121 U+02267 U+02265 U+02A8C U+022DB U+02265 U+02267 U+02A7E U+02A7E U+02AA9 U+02A80 U+02A82 U+02A84 U+022DB

&gacute; &Gammad; &gammad; &gap; &Gbreve; &gbreve; &Gcedil; &Gcirc; &gcirc; &Gcy; &gcy; &Gdot; &gdot; &geqq; &gtreqqless; &gel; &geqq; &ges; &ges; &gescc; &gesdot; &gesdoto; &gesdotol; &gel;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

U+0FE00 gesles; Gfr; gfr; Gg; gg; ggg; gimel; GJcy; gjcy; gl; gla; glE; glj; gnap; gnapprox; gnE; gne; gneq; gneqq; gnsim; Gopf; gopf; grave; GreaterEqual; GreaterEqualLess; GreaterFullEqual; GreaterGreater; GreaterLess;
http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

U+02A94 U+1D50A U+1D524 U+022D9 U+0226B U+022D9 U+02137 U+00403 U+00453 U+02277 U+02AA5 U+02A92 U+02AA4 U+02A8A U+02A8A U+02269 U+02A88 U+02A88 U+02269 U+022E7 U+1D53E U+1D558 U+00060 U+02265 U+022DB U+02267 U+02AA2 U+02277

&gesles; &Gfr; &gfr; &ggg; &gg; &ggg; &gimel; &GJcy; &gjcy; &gtrless; &gla; &glE; &glj; &gnap; &gnap; &gneqq; &gne; &gne; &gneqq; &gnsim; &Gopf; &gopf; ` &gel; &geqq; &GreaterGreater; &gtrless;

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

GreaterSlantEqual; GreaterTilde; Gscr; gscr; gsim; gsime; gsiml; GT; Gt; gt; gtcc; gtcir; gtdot; gtlPar; gtquest; gtrapprox; gtrarr; gtrdot; gtreqless; gtreqqless; gtrless; gtrsim; gvertneqq; gvnE; Hacek; hairsp; half;

U+02A7E U+02273 U+1D4A2 U+0210A U+02273 U+02A8E U+02A90 U+0003E U+0226B U+0003E U+02AA7 U+02A7A U+022D7 U+02995 U+02A7C U+02A86 U+02978 U+022D7 U+022DB U+02A8C U+02277 U+02273 U+02269 U+0FE00 U+02269 U+0FE00 U+002C7 U+0200A U+000BD

&ges; &gtrsim; &Gscr; &gscr; &gtrsim; &gsime; &gsiml; > &gg; > &gtcc; &gtcir; &gtdot; &gtlPar; &gtquest; &gap; &gtrarr; &gtdot; &gel; &gtreqqless; &gtrless; &gtrsim; &gneqq;

&gneqq;

&caron; &hairsp; &half;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

hamilt; HARDcy; hardcy; hArr; harr; harrcir; harrw; Hat; hbar; Hcirc; hcirc; hearts; heartsuit; hellip; hercon; Hfr; hfr; HilbertSpace; hksearow; hkswarow; hoarr; homtht; hookleftarrow; hookrightarrow; Hopf; hopf; horbar; HorizontalLine; Hscr;
http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

U+0210B U+0042A U+0044A U+021D4 U+02194 U+02948 U+021AD U+0005E U+0210F U+00124 U+00125 U+02665 U+02665 U+02026 U+022B9 U+0210C U+1D525 U+0210B U+02925 U+02926 U+021FF U+0223B U+021A9 U+021AA U+0210D U+1D559 U+02015 U+02500 U+0210B

&hamilt; &HARDcy; &hardcy; &iff; &leftrightarrow; &harrcir; &leftrightsquigarrow; ^ &hslash; &Hcirc; &hcirc; &mldr; &hercon; &Hfr; &hfr; &hamilt; &hksearow; &hkswarow; &hoarr; &homtht; &hookleftarrow; &hookrightarrow; &quaternions; &hopf; &horbar; &boxh; &hamilt;

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

hscr; hslash; Hstrok; hstrok; HumpDownHump; HumpEqual; hybull; hyphen; Iacute; iacute; ic; Icirc; icirc; Icy; icy; Idot; IEcy; iecy; iexcl; iff; Ifr; ifr; Igrave; igrave; ii; iiiint; iiint; iinfin;

U+1D4BD U+0210F U+00126 U+00127 U+0224E U+0224F U+02043 U+02010 U+000CD U+000ED U+02063 U+000CE U+000EE U+00418 U+00438 U+00130 U+00415 U+00435 U+000A1 U+021D4 U+02111 U+1D526 U+000CC U+000EC U+02148 U+02A0C U+0222D U+029DC

&hscr; &hslash; &Hstrok; &hstrok; &bump; &bumpeq; &hybull; &dash; &ic; &Icy; &icy; &Idot; &IEcy; &iecy; &iff;

&ifr; &ii; &iiiint; &iiint; &iinfin;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

iiota; IJlig; ijlig; Im; Imacr; imacr; image; ImaginaryI; imagline; imagpart; imath; imof; imped; Implies; in; incare; infin; infintie; inodot; Int; int; intcal; integers; Integral; intercal; Intersection; intlarhk; intprod; InvisibleComma;
http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

U+02129 U+00132 U+00133 U+02111 U+0012A U+0012B U+02111 U+02148 U+02110 U+02111 U+00131 U+022B7 U+001B5 U+021D2 U+02208 U+02105 U+0221E U+029DD U+00131 U+0222C U+0222B U+022BA U+02124 U+0222B U+022BA U+022C2 U+02A17 U+02A3C U+02063

&iiota; &IJlig; &ijlig;

&Imacr; &imacr;

&ii; &imagline;

&inodot; &imof; &imped; &Implies; &in; &incare; &infintie; &inodot; &Int; &intcal; &integers; &intcal; &bigcap; &intlarhk; &iprod; &ic;

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

InvisibleTimes; IOcy; iocy; Iogon; iogon; Iopf; iopf; Iota; iota; iprod; iquest; Iscr; iscr; isin; isindot; isinE; isins; isinsv; isinv; it; Itilde; itilde; Iukcy; iukcy; Iuml; iuml; Jcirc; jcirc;

U+02062 U+00401 U+00451 U+0012E U+0012F U+1D540 U+1D55A U+00399 U+003B9 U+02A3C U+000BF U+02110 U+1D4BE U+02208 U+022F5 U+022F9 U+022F4 U+022F3 U+02208 U+02062 U+00128 U+00129 U+00406 U+00456 U+000CF U+000EF U+00134 U+00135

&it; &IOcy; &iocy; &Iogon; &iogon; &Iopf; &iopf; &iprod; &imagline; &iscr; &in; &isindot; &isinE; &isins; &isinsv; &in; &it; &Itilde; &itilde; &Iukcy; &iukcy; &Jcirc; &jcirc;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

Jcy; jcy; Jfr; jfr; jmath; Jopf; jopf; Jscr; jscr; Jsercy; jsercy; Jukcy; jukcy; Kappa; kappa; kappav; Kcedil; kcedil; Kcy; kcy; Kfr; kfr; kgreen; KHcy; khcy; KJcy; kjcy; Kopf; kopf;
http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

U+00419 U+00439 U+1D50D U+1D527 U+00237 U+1D541 U+1D55B U+1D4A5 U+1D4BF U+00408 U+00458 U+00404 U+00454 U+0039A U+003BA U+003F0 U+00136 U+00137 U+0041A U+0043A U+1D50E U+1D528 U+00138 U+00425 U+00445 U+0040C U+0045C U+1D542 U+1D55C

&Jcy; &jcy; &Jfr; &jfr; &jmath; &Jopf; &jopf; &Jscr; &jscr; &Jsercy; &jsercy; &Jukcy; &jukcy; &kappav; &Kcedil; &kcedil; &Kcy; &kcy; &Kfr; &kfr; &kgreen; &KHcy; &khcy; &KJcy; &kjcy; &Kopf; &kopf;

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

Kscr; kscr; lAarr; Lacute; lacute; laemptyv; lagran; Lambda; lambda; Lang; lang; langd; langle; lap; Laplacetrf; laquo; Larr; lArr; larr; larrb; larrbfs; larrfs; larrhk; larrlp; larrpl; larrsim; larrtl; lat;

U+1D4A6 U+1D4C0 U+021DA U+00139 U+0013A U+029B4 U+02112 U+0039B U+003BB U+027EA U+027E8 U+02991 U+027E8 U+02A85 U+02112 U+000AB U+0219E U+021D0 U+02190 U+021E4 U+0291F U+0291D U+021A9 U+021AB U+02939 U+02973 U+021A2 U+02AAB

&Kscr; &kscr; &Lleftarrow; &Lacute; &lacute; &laemptyv; &lagran; &Lang;

&langd;

&lap; &lagran; &twoheadleftarrow;

&slarr; &larrb; &larrbfs; &larrfs; &hookleftarrow; &looparrowleft; &larrpl; &larrsim; &leftarrowtail; &lat;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

lAtail; latail; late; lates; lBarr; lbarr; lbbrk; lbrace; lbrack; lbrke; lbrksld; lbrkslu; Lcaron; lcaron; Lcedil; lcedil; lceil; lcub; Lcy; lcy; ldca; ldquo; ldquor; ldrdhar; ldrushar; ldsh; lE; le;

U+0291B U+02919 U+02AAD U+02AAD U+0FE00 U+0290E U+0290C U+02772 U+0007B U+0005B U+0298B U+0298F U+0298D U+0013D U+0013E U+0013B U+0013C U+02308 U+0007B U+0041B U+0043B U+02936 U+0201C U+0201E U+02967 U+0294B U+021B2 U+02266 U+02264

&lAtail; &latail; &late; &late;

&lBarr; &lbarr; &lbbrk; { [ &lbrke; &lbrksld; &lbrkslu; &Lcaron; &lcaron; &Lcedil; &lcedil;

{ &Lcy; &lcy; &ldca; &ldquor; &ldrdhar; &ldrushar; &ldsh; &leqq;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

LeftAngleBracket; LeftArrow; Leftarrow; leftarrow; LeftArrowBar; LeftArrowRightArrow; leftarrowtail; LeftCeiling; LeftDoubleBracket; LeftDownTeeVector; LeftDownVector; LeftDownVectorBar; LeftFloor; leftharpoondown; leftharpoonup; leftleftarrows; LeftRightArrow; Leftrightarrow; leftrightarrow; leftrightarrows; leftrightharpoons; leftrightsquigarrow; LeftRightVector; LeftTee; LeftTeeArrow; LeftTeeVector; leftthreetimes; LeftTriangle; LeftTriangleBar;
http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

U+027E8 U+02190 U+021D0 U+02190 U+021E4 U+021C6 U+021A2 U+02308 U+027E6 U+02961 U+021C3 U+02959 U+0230A U+021BD U+021BC U+021C7 U+02194 U+021D4 U+02194 U+021C6 U+021CB U+021AD U+0294E U+022A3 U+021A4 U+0295A U+022CB U+022B2 U+029CF &leftharpoondown; &lharu; &llarr; &leftrightarrow; &iff; &leftrightarrow; &leftrightarrows; &leftrightharpoons; &leftrightsquigarrow; &LeftRightVector; &dashv; &mapstoleft; &LeftTeeVector; &lthree; &vartriangleleft; &LeftTriangleBar; &lobrk; &LeftDownTeeVector; &downharpoonleft; &LeftDownVectorBar; &slarr; &larrb; &leftrightarrows; &leftarrowtail; &slarr;

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

LeftTriangleEqual; LeftUpDownVector; LeftUpTeeVector; LeftUpVector; LeftUpVectorBar; LeftVector; LeftVectorBar; lEg; leg; leq; leqq; leqslant; les; lescc; lesdot; lesdoto; lesdotor; lesg; lesges; lessapprox; lessdot; lesseqgtr; lesseqqgtr; LessEqualGreater; LessFullEqual; LessGreater; lessgtr;

U+022B4 U+02951 U+02960 U+021BF U+02958 U+021BC U+02952 U+02A8B U+022DA U+02264 U+02266 U+02A7D U+02A7D U+02AA8 U+02A7F U+02A81 U+02A83 U+022DA U+0FE00 U+02A93 U+02A85 U+022D6 U+022DA U+02A8B U+022DA U+02266 U+02276 U+02276 U+02AA1

&ltrie; &LeftUpDownVector; &LeftUpTeeVector; &upharpoonleft; &LeftUpVectorBar; &lharu; &LeftVectorBar; &lesseqqgtr; &lesseqgtr; &leqq; &les; &les; &lescc; &lesdot; &lesdoto; &lesdotor; &lesseqgtr;

&lesges; &lap; &lessdot; &lesseqgtr; &lesseqqgtr; &lesseqgtr; &leqq; &lessgtr; &lessgtr; &LessLess;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

LessLess; lesssim; LessSlantEqual; LessTilde; lfisht; lfloor; Lfr; lfr; lg; lgE; lHar; lhard; lharu; lharul; lhblk; LJcy; ljcy; Ll; ll; llarr; llcorner; Lleftarrow; llhard; lltri; Lmidot; lmidot; lmoust; lmoustache; lnap;
http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

U+02272 U+02A7D U+02272 U+0297C U+0230A U+1D50F U+1D529 U+02276 U+02A91 U+02962 U+021BD U+021BC U+0296A U+02584 U+00409 U+00459 U+022D8 U+0226A U+021C7 U+0231E U+021DA U+0296B U+025FA U+0013F U+00140 U+023B0 U+023B0 U+02A89

&lesssim; &les; &lesssim; &lfisht;

&Lfr; &lfr; &lessgtr; &lgE; &lHar; &leftharpoondown; &lharu; &lharul; &lhblk; &LJcy; &ljcy; &Ll; &ll; &llarr; &dlcorn; &Lleftarrow; &llhard; &lltri; &Lmidot; &lmidot; &lmoust; &lmoust; &lnapprox;

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

lnapprox; lnE; lne; lneq; lneqq; lnsim; loang; loarr; lobrk; LongLeftArrow; Longleftarrow; longleftarrow; LongLeftRightArrow; Longleftrightarrow; longleftrightarrow; longmapsto; LongRightArrow; Longrightarrow; longrightarrow; looparrowleft; looparrowright; lopar; Lopf; lopf; loplus; lotimes; lowast; lowbar;

U+02A89 U+02268 U+02A87 U+02A87 U+02268 U+022E6 U+027EC U+021FD U+027E6 U+027F5 U+027F8 U+027F5 U+027F7 U+027FA U+027F7 U+027FC U+027F6 U+027F9 U+027F6 U+021AB U+021AC U+02985 U+1D543 U+1D55D U+02A2D U+02A34 U+02217 U+0005F

&lnapprox; &lneqq; &lne; &lne; &lneqq; &lnsim; &loang; &loarr; &lobrk; &xlarr; &Longleftarrow; &xlarr; &xharr; &DoubleLongLeftRightArrow; &xharr; &xmap; &xrarr; &xrArr; &xrarr; &looparrowleft; &rarrlp; &lopar; &Lopf; &lopf; &loplus; &lotimes;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

LowerLeftArrow; LowerRightArrow; loz; lozenge; lozf; lpar; lparlt; lrarr; lrcorner; lrhar; lrhard; lrm; lrtri; lsaquo; Lscr; lscr; Lsh; lsh; lsim; lsime; lsimg; lsqb; lsquo; lsquor; Lstrok; lstrok; LT; Lt; lt;
http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

U+02199 U+02198 U+025CA U+025CA U+029EB U+00028 U+02993 U+021C6 U+0231F U+021CB U+0296D U+0200E U+022BF U+02039 U+02112 U+1D4C1 U+021B0 U+021B0 U+02272 U+02A8D U+02A8F U+0005B U+02018 U+0201A U+00141 U+00142 U+0003C U+0226A U+0003C

&swarrow; &searrow; &lozenge; &lozenge; &lozf; ( &lparlt; &leftrightarrows; &drcorn; &leftrightharpoons; &lrhard;

&lrtri; &lagran; &lscr; &lsh; &lsh; &lesssim; &lsime; &lsimg; [ &Lstrok; &lstrok; < &ll; <

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

ltcc; ltcir; ltdot; lthree; ltimes; ltlarr; ltquest; ltri; ltrie; ltrif; ltrPar; lurdshar; luruhar; lvertneqq; lvnE; macr; male; malt; maltese; Map; map; mapsto; mapstodown; mapstoleft; mapstoup; marker; mcomma;

U+02AA6 U+02A79 U+022D6 U+022CB U+022C9 U+02976 U+02A7B U+025C3 U+022B4 U+025C2 U+02996 U+0294A U+02966 U+02268 U+0FE00 U+02268 U+0FE00 U+000AF U+02642 U+02720 U+02720 U+02905 U+021A6 U+021A6 U+021A7 U+021A4 U+021A5 U+025AE U+02A29

&ltcc; &ltcir; &lessdot; &lthree; &ltimes; &ltlarr; &ltquest; &triangleleft; &ltrie; &blacktriangleleft; &ltrPar; &lurdshar; &luruhar; &lneqq;

&lneqq;

&strns; &male; &malt; &malt; &Map; &mapsto; &mapsto; &mapstodown; &mapstoleft; &mapstoup; &marker; &mcomma;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

Mcy; mcy; mdash; mDDot; measuredangle; MediumSpace; Mellintrf; Mfr; mfr; mho; micro; mid; midast; midcir; middot; minus; minusb; minusd; minusdu; MinusPlus; mlcp; mldr; mnplus; models; Mopf; mopf; mp; Mscr;

U+0041C U+0043C U+02014 U+0223A U+02221 U+0205F U+02133 U+1D510 U+1D52A U+02127 U+000B5 U+02223 U+0002A U+02AF0 U+000B7 U+02212 U+0229F U+02238 U+02A2A U+02213 U+02ADB U+02026 U+02213 U+022A7 U+1D544 U+1D55E U+02213 U+02133 U+1D4C2

&Mcy; &mcy; &mDDot; &angmsd; &MediumSpace; &phmmat; &Mfr; &mfr; &mho; &mid; * &midcir; &minusb; &dotminus; &minusdu; &mp; &mlcp; &mldr; &mp; &models; &Mopf; &mopf; &mp; &phmmat; &mscr;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

mscr; mstpos; Mu; mu; multimap; mumap; nabla; Nacute; nacute; nang; nap; napE; napid; napos; napprox; natur; natural; naturals; nbsp; nbump; nbumpe; ncap; Ncaron; ncaron; Ncedil; U+0223E U+0039C U+003BC U+022B8 U+022B8 U+02207 U+00143 U+00144 U+02220 U+020D2 U+02249 U+02A70 U+00338 U+0224B U+00338 U+00149 U+02249 U+0266E U+0266E U+02115 U+000A0 U+0224E U+00338 U+0224F U+00338 U+02A43 U+00147 U+00148 U+00145 &ncap; &Ncaron; &ncaron; &Ncedil; &bumpeq; &napos; &nap; &natural; &natural; &naturals; &bump; &apid; &nap; &apE; &Nacute; &nacute; &angle; &ac; &multimap; &multimap;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

ncedil; ncong; ncongdot; ncup; Ncy; ncy; ndash; ne; nearhk; neArr; nearr; nearrow; nedot; NegativeMediumSpace; NegativeThickSpace; NegativeThinSpace; NegativeVeryThinSpace; nequiv; nesear; nesim; NestedGreaterGreater; NestedLessLess; NewLine; nexist; nexists; Nfr; nfr;
http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

U+00146 U+02247 U+02A6D U+00338 U+02A42 U+0041D U+0043D U+02013 U+02260 U+02924 U+021D7 U+02197 U+02197 U+02250 U+00338 U+0200B U+0200B U+0200B U+0200B U+02262 U+02928 U+02242 U+00338 U+0226B U+0226A U+0000A U+02204 U+02204 U+1D511 U+1D52B

&ncedil; &ncong; &congdot;

&ncup; &Ncy; &ncy; &nearhk; &neArr; &nearrow; &nearrow; &esdot;

&NegativeThickSpace; &NegativeThickSpace; &NegativeThickSpace; &NegativeThickSpace; &nequiv; &toea; &esim;

&gg; &ll;

&nexists; &nexists; &Nfr; &nfr;

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

ngE; nge; ngeq; ngeqq; ngeqslant; nges; nGg; ngsim; nGt; ngt; ngtr; nGtv; nhArr; nharr; nhpar; ni; nis; nisd; niv; NJcy; njcy; nlArr; nlarr;

U+02267 U+00338 U+02271 U+02271 U+02267 U+00338 U+02A7E U+00338 U+02A7E U+00338 U+022D9 U+00338 U+02275 U+0226B U+020D2 U+0226F U+0226F U+0226B U+00338 U+021CE U+021AE U+02AF2 U+0220B U+022FC U+022FA U+0220B U+0040A U+0045A U+021CD U+0219A

&geqq;

&ngeq; &ngeq; &geqq;

&ges;

&ges;

&ggg;

&ngsim; &gg;

&ngt; &ngt; &gg;

&nhArr; &nharr; &nhpar; &niv; &nis; &nisd; &niv; &NJcy; &njcy; &nlArr; &nlarr;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

nldr; nlE; nle; nLeftarrow; nleftarrow; nLeftrightarrow; nleftrightarrow; nleq; nleqq; nleqslant; nles; nless; nLl; nlsim; nLt; nlt; nltri; nltrie; nLtv; nmid; NoBreak; NonBreakingSpace; Nopf; nopf;

U+02025 U+02266 U+00338 U+02270 U+021CD U+0219A U+021CE U+021AE U+02270 U+02266 U+00338 U+02A7D U+00338 U+02A7D U+00338 U+0226E U+022D8 U+00338 U+02274 U+0226A U+020D2 U+0226E U+022EA U+022EC U+0226A U+00338 U+02224 U+02060 U+000A0 U+02115 U+1D55F

&nldr; &leqq;

&nle; &nlArr; &nlarr; &nhArr; &nharr; &nle; &leqq;

&les;

&les;

&nless; &Ll;

&nlsim; &ll;

&nless; &nltri; &nltrie; &ll;

&nmid; &NoBreak; &naturals; &nopf;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

Not; not; NotCongruent; NotCupCap; NotDoubleVerticalBar; NotElement; NotEqual; NotEqualTilde; NotExists; NotGreater; NotGreaterEqual; NotGreaterFullEqual; NotGreaterGreater; NotGreaterLess; NotGreaterSlantEqual; NotGreaterTilde; NotHumpDownHump; NotHumpEqual; notin; notindot; notinE; notinva; notinvb;

U+02AEC U+000AC U+02262 U+0226D U+02226 U+02209 U+02260 U+02242 U+00338 U+02204 U+0226F U+02271 U+02267 U+00338 U+0226B U+00338 U+02279 U+02A7E U+00338 U+02275 U+0224E U+00338 U+0224F U+00338 U+02209 U+022F5 U+00338 U+022F9 U+00338 U+02209 U+022F7

&Not; &nequiv; &NotCupCap; &nspar; &notinva; &esim;

&nexists; &ngt; &ngeq; &geqq;

&gg;

&ntgl; &ges;

&ngsim; &bump;

&bumpeq;

&notinva; &isindot;

&isinE;

&notinva; &notinvb;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

notinvc; NotLeftTriangle; NotLeftTriangleBar; NotLeftTriangleEqual; NotLess; NotLessEqual; NotLessGreater; NotLessLess; NotLessSlantEqual; NotLessTilde; NotNestedGreaterGreater; NotNestedLessLess; notni; notniva; notnivb; notnivc; NotPrecedes; NotPrecedesEqual; NotPrecedesSlantEqual; NotReverseElement; NotRightTriangle; NotRightTriangleBar; NotRightTriangleEqual; NotSquareSubset;

U+022F6 U+022EA U+029CF U+00338 U+022EC U+0226E U+02270 U+02278 U+0226A U+00338 U+02A7D U+00338 U+02274 U+02AA2 U+00338 U+02AA1 U+00338 U+0220C U+0220C U+022FE U+022FD U+02280 U+02AAF U+00338 U+022E0 U+0220C U+022EB U+029D0 U+00338 U+022ED U+0228F

&notinvc; &nltri; &LeftTriangleBar;

&nltrie; &nless; &nle; &ntlg; &ll;

&les;

&nlsim; &GreaterGreater;

&LessLess;

&notni; &notni; &notnivb; &notnivc; &nprec; &pre;

&nprcue; &notni; &ntriangleright; &RightTriangleBar;

&nrtrie; &sqsub;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

U+00338 NotSquareSubsetEqual; NotSquareSuperset; NotSquareSupersetEqual; NotSubset; NotSubsetEqual; NotSucceeds; NotSucceedsEqual; NotSucceedsSlantEqual; NotSucceedsTilde; NotSuperset; NotSupersetEqual; NotTilde; NotTildeEqual; NotTildeFullEqual; NotTildeTilde; NotVerticalBar; npar; nparallel; nparsl; npart; npolint; npr; nprcue; U+022E2 U+02290 U+00338 U+022E3 U+02282 U+020D2 U+02288 U+02281 U+02AB0 U+00338 U+022E1 U+0227F U+00338 U+02283 U+020D2 U+02289 U+02241 U+02244 U+02247 U+02249 U+02224 U+02226 U+02226 U+02AFD U+020E5 U+02202 U+00338 U+02A14 U+02280 U+022E0 &npolint; &nprec; &nprcue; &nsupseteq; &nsim; &nsimeq; &ncong; &nap; &nmid; &nspar; &nspar; &parsl; &nsccue; &scsim; &nsube; &nsc; &succeq; &nsqsupe; &nsqsube; &sqsupset;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

npre; nprec; npreceq; nrArr; nrarr; nrarrc; nrarrw; nRightarrow; nrightarrow; nrtri; nrtrie; nsc; nsccue; nsce; Nscr; nscr; nshortmid; nshortparallel; nsim; nsime; nsimeq; nsmid; nspar; nsqsube; nsqsupe;

U+02AAF U+00338 U+02280 U+02AAF U+00338 U+021CF U+0219B U+02933 U+00338 U+0219D U+00338 U+021CF U+0219B U+022EB U+022ED U+02281 U+022E1 U+02AB0 U+00338 U+1D4A9 U+1D4C3 U+02224 U+02226 U+02241 U+02244 U+02244 U+02224 U+02226 U+022E2 U+022E3

&pre;

&nprec; &pre;

&nrArr; &nrarr; &rarrc;

&rightsquigarrow;

&nrArr; &nrarr; &ntriangleright; &nrtrie; &nsc; &nsccue; &succeq;

&Nscr; &nscr; &nmid; &nspar; &nsim; &nsimeq; &nsimeq; &nmid; &nspar; &nsqsube; &nsqsupe;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

nsub; nsubE; nsube; nsubset; nsubseteq; nsubseteqq; nsucc; nsucceq; nsup; nsupE; nsupe; nsupset; nsupseteq; nsupseteqq; ntgl; Ntilde; ntilde; ntlg; ntriangleleft; ntrianglelefteq; ntriangleright; ntrianglerighteq; Nu; nu;

U+02284 U+02AC5 U+00338 U+02288 U+02282 U+020D2 U+02288 U+02AC5 U+00338 U+02281 U+02AB0 U+00338 U+02285 U+02AC6 U+00338 U+02289 U+02283 U+020D2 U+02289 U+02AC6 U+00338 U+02279 U+000D1 U+000F1 U+02278 U+022EA U+022EC U+022EB U+022ED U+0039D U+003BD &ntgl; &ntlg; &nltri; &nltrie; &ntriangleright; &nrtrie; &nsupseteq; &supseteqq; &nsupseteq; &nsup; &supseteqq; &nsc; &succeq; &nsube; &subseteqq; &nsube; &subseteqq;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

num; numero; numsp; nvap; nVDash; nVdash; nvDash; nvdash; nvge; nvgt; nvHarr; nvinfin; nvlArr; nvle; nvlt; nvltrie; nvrArr; nvrtrie; nvsim; nwarhk; nwArr; nwarr; nwarrow;

U+00023 U+02116 U+02007 U+0224D U+020D2 U+022AF U+022AE U+022AD U+022AC U+02265 U+020D2 U+0003E U+020D2 U+02904 U+029DE U+02902 U+02264 U+020D2 U+0003C U+020D2 U+022B4 U+020D2 U+02903 U+022B5 U+020D2 U+0223C U+020D2 U+02923 U+021D6 U+02196 U+02196

# &numero; &numsp; &asympeq;

&nVDash; &nVdash; &nvDash; &nvdash;

>

&nvHarr; &nvinfin; &nvlArr;

<

&ltrie;

&nvrArr; &rtrie;

&thksim;

&nwarhk; &nwArr; &nwarrow; &nwarrow;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

nwnear; Oacute; oacute; oast; ocir; Ocirc; ocirc; Ocy; ocy; odash; Odblac; odblac; odiv; odot; odsold; OElig; oelig; ofcir; Ofr; ofr; ogon; Ograve; ograve; ogt; ohbar; ohm; oint; olarr; olcir;
http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

U+02927 U+000D3 U+000F3 U+0229B U+0229A U+000D4 U+000F4 U+0041E U+0043E U+0229D U+00150 U+00151 U+02A38 U+02299 U+029BC U+00152 U+00153 U+029BF U+1D512 U+1D52C U+002DB U+000D2 U+000F2 U+029C1 U+029B5 U+003A9 U+0222E U+021BA U+029BE

&nwnear; &oast; &ocir; &Ocy; &ocy; &circleddash; &Odblac; &odblac; &odiv; &odot; &odsold; &ofcir; &Ofr; &ofr; &ogon; &ogt; &ohbar; &ohm; &conint; &olarr; &olcir;

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

olcross; oline; olt; Omacr; omacr; Omega; omega; Omicron; omicron; omid; ominus; Oopf; oopf; opar; OpenCurlyDoubleQuote; OpenCurlyQuote; operp; oplus; Or; or; orarr; ord; order; orderof; ordf; ordm; origof; oror;

U+029BB U+0203E U+029C0 U+0014C U+0014D U+003A9 U+003C9 U+0039F U+003BF U+029B6 U+02296 U+1D546 U+1D560 U+029B7 U+0201C U+02018 U+029B9 U+02295 U+02A54 U+02228 U+021BB U+02A5D U+02134 U+02134 U+000AA U+000BA U+022B6 U+02A56

&olcross; &olt; &Omacr; &omacr; &ohm; &omid; &ominus; &Oopf; &oopf; &opar; &operp;

&Or; &vee; &orarr; &ord; &oscr; &oscr; &origof; &oror;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

orslope; orv; oS; Oscr; oscr; Oslash; oslash; osol; Otilde; otilde; Otimes; otimes; otimesas; Ouml; ouml; ovbar; OverBar; OverBrace; OverBracket; OverParenthesis; par; para; parallel; parsim; parsl; part; PartialD; Pcy; pcy;
http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

U+02A57 U+02A5B U+024C8 U+1D4AA U+02134 U+000D8 U+000F8 U+02298 U+000D5 U+000F5 U+02A37 U+02297 U+02A36 U+000D6 U+000F6 U+0233D U+0203E U+023DE U+023B4 U+023DC U+02225 U+000B6 U+02225 U+02AF3 U+02AFD U+02202 U+02202 U+0041F U+0043F

&orslope; &orv; &oS; &Oscr; &oscr; &osol; &Otimes;

&otimesas; &ovbar; &OverBrace; &tbrk; &OverParenthesis; &spar; &spar; &parsim; &parsl; &Pcy; &pcy;

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

percnt; period; permil; perp; pertenk; Pfr; pfr; Phi; phi; phiv; phmmat; phone; Pi; pi; pitchfork; piv; planck; planckh; plankv; plus; plusacir; plusb; pluscir; plusdo; plusdu; pluse; PlusMinus; plusmn;

U+00025 U+0002E U+02030 U+022A5 U+02031 U+1D513 U+1D52D U+003A6 U+003C6 U+003D5 U+02133 U+0260E U+003A0 U+003C0 U+022D4 U+003D6 U+0210F U+0210E U+0210F U+0002B U+02A23 U+0229E U+02A22 U+02214 U+02A25 U+02A72 U+000B1 U+000B1

% . &bottom; &pertenk; &Pfr; &pfr; &phiv; &phmmat; &phone; &fork; &varpi; &hslash; &planckh; &hslash; + &plusacir; &boxplus; &pluscir; &dotplus; &plusdu; &pluse;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

plussim; plustwo; pm; Poincareplane; pointint; Popf; popf; pound; Pr; pr; prap; prcue; prE; pre; prec; precapprox; preccurlyeq; Precedes; PrecedesEqual; PrecedesSlantEqual; PrecedesTilde; preceq; precnapprox; precneqq; precnsim; precsim; Prime; prime; primes;
http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

U+02A26 U+02A27 U+000B1 U+0210C U+02A15 U+02119 U+1D561 U+000A3 U+02ABB U+0227A U+02AB7 U+0227C U+02AB3 U+02AAF U+0227A U+02AB7 U+0227C U+0227A U+02AAF U+0227C U+0227E U+02AAF U+02AB9 U+02AB5 U+022E8 U+0227E U+02033 U+02032 U+02119

&plussim; &plustwo; &Hfr; &pointint; &primes; &popf; &Pr; &pr; &prap; &preccurlyeq; &prE; &pre; &pr; &prap; &preccurlyeq; &pr; &pre; &preccurlyeq; &prsim; &pre; &prnap; &precneqq; &prnsim; &prsim; &primes;

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

prnap; prnE; prnsim; prod; Product; profalar; profline; profsurf; prop; Proportion; Proportional; propto; prsim; prurel; Pscr; pscr; Psi; psi; puncsp; Qfr; qfr; qint; Qopf; qopf; qprime; Qscr; qscr; quaternions;

U+02AB9 U+02AB5 U+022E8 U+0220F U+0220F U+0232E U+02312 U+02313 U+0221D U+02237 U+0221D U+0221D U+0227E U+022B0 U+1D4AB U+1D4C5 U+003A8 U+003C8 U+02008 U+1D514 U+1D52E U+02A0C U+0211A U+1D562 U+02057 U+1D4AC U+1D4C6 U+0210D

&prnap; &precneqq; &prnsim; &profalar; &profline; &profsurf; &propto; &Colon; &propto; &propto; &prsim; &prurel; &Pscr; &pscr; &puncsp; &Qfr; &qfr; &iiiint; &rationals; &qopf; &qprime; &Qscr; &qscr; &quaternions;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

quatint; quest; questeq; QUOT; quot; rAarr; race; Racute; racute; radic; raemptyv; Rang; rang; rangd; range; rangle; raquo; Rarr; rArr; rarr; rarrap; rarrb; rarrbfs; rarrc; rarrfs; rarrhk; rarrlp; rarrpl;

U+02A16 U+0003F U+0225F U+00022 U+00022 U+021DB U+0223D U+00331 U+00154 U+00155 U+0221A U+029B3 U+027EB U+027E9 U+02992 U+029A5 U+027E9 U+000BB U+021A0 U+021D2 U+02192 U+02975 U+021E5 U+02920 U+02933 U+0291E U+021AA U+021AC U+02945

&quatint; ? &questeq; " " &rAarr; &backsim;

&Racute; &racute; &raemptyv; &Rang;

&rangd; &range;

&twoheadrightarrow; &Implies; &srarr; &rarrap; &rarrb; &rarrbfs; &rarrc; &rarrfs; &hookrightarrow; &rarrlp; &rarrpl;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

rarrsim; Rarrtl; rarrtl; rarrw; rAtail; ratail; ratio; rationals; RBarr; rBarr; rbarr; rbbrk; rbrace; rbrack; rbrke; rbrksld; rbrkslu; Rcaron; rcaron; Rcedil; rcedil; rceil; rcub; Rcy; rcy; rdca; rdldhar; rdquo; rdquor;
http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

U+02974 U+02916 U+021A3 U+0219D U+0291C U+0291A U+02236 U+0211A U+02910 U+0290F U+0290D U+02773 U+0007D U+0005D U+0298C U+0298E U+02990 U+00158 U+00159 U+00156 U+00157 U+02309 U+0007D U+00420 U+00440 U+02937 U+02969 U+0201D U+0201D

&rarrsim; &Rarrtl; &rightarrowtail; &rightsquigarrow; &rAtail; &ratail; &ratio; &rationals; &drbkarow; &dbkarow; &rbarr; &rbbrk; } ] &rbrke; &rbrksld; &rbrkslu; &Rcaron; &rcaron; &Rcedil; &rcedil;

} &Rcy; &rcy; &rdca; &rdldhar;

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

rdsh; Re; real; realine; realpart; reals; rect; REG; reg; ReverseElement; ReverseEquilibrium; ReverseUpEquilibrium; rfisht; rfloor; Rfr; rfr; rHar; rhard; rharu; rharul; Rho; rho; rhov; RightAngleBracket; RightArrow; Rightarrow; rightarrow; RightArrowBar;

U+021B3 U+0211C U+0211C U+0211B U+0211C U+0211D U+025AD U+000AE U+000AE U+0220B U+021CB U+0296F U+0297D U+0230B U+0211C U+1D52F U+02964 U+021C1 U+021C0 U+0296C U+003A1 U+003C1 U+003F1 U+027E9 U+02192 U+021D2 U+02192 U+021E5

&rdsh; &realpart; &realpart; &realine; &realpart; &reals; &rect; &niv; &leftrightharpoons; &duhar; &rfisht;

&realpart; &rfr; &rHar; &rhard; &rharu; &rharul; &rhov;

&srarr; &Implies; &srarr; &rarrb;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

RightArrowLeftArrow; rightarrowtail; RightCeiling; RightDoubleBracket; RightDownTeeVector; RightDownVector; RightDownVectorBar; RightFloor; rightharpoondown; rightharpoonup; rightleftarrows; rightleftharpoons; rightrightarrows; rightsquigarrow; RightTee; RightTeeArrow; RightTeeVector; rightthreetimes; RightTriangle; RightTriangleBar; RightTriangleEqual; RightUpDownVector; RightUpTeeVector; RightUpVector; RightUpVectorBar; RightVector; RightVectorBar; ring; risingdotseq;
http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

U+021C4 U+021A3 U+02309 U+027E7 U+0295D U+021C2 U+02955 U+0230B U+021C1 U+021C0 U+021C4 U+021CC U+021C9 U+0219D U+022A2 U+021A6 U+0295B U+022CC U+022B3 U+029D0 U+022B5 U+0294F U+0295C U+021BE U+02954 U+021C0 U+02953 U+002DA U+02253

&rlarr; &rightarrowtail;

&robrk; &RightDownTeeVector; &dharr; &RightDownVectorBar;

&rhard; &rharu; &rlarr; &rlhar; &rightrightarrows; &rightsquigarrow; &vdash; &mapsto; &RightTeeVector; &rightthreetimes; &vartriangleright; &RightTriangleBar; &rtrie; &RightUpDownVector; &RightUpTeeVector; &upharpoonright; &RightUpVectorBar; &rharu; &RightVectorBar; &ring; &risingdotseq;

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

rlarr; rlhar; rlm; rmoust; rmoustache; rnmid; roang; roarr; robrk; ropar; Ropf; ropf; roplus; rotimes; RoundImplies; rpar; rpargt; rppolint; rrarr; Rrightarrow; rsaquo; Rscr; rscr; Rsh; rsh; rsqb; rsquo; rsquor;

U+021C4 U+021CC U+0200F U+023B1 U+023B1 U+02AEE U+027ED U+021FE U+027E7 U+02986 U+0211D U+1D563 U+02A2E U+02A35 U+02970 U+00029 U+02994 U+02A12 U+021C9 U+021DB U+0203A U+0211B U+1D4C7 U+021B1 U+021B1 U+0005D U+02019 U+02019

&rlarr; &rlhar;

&rmoustache; &rmoustache; &rnmid; &roang; &roarr; &robrk; &ropar; &reals; &ropf; &roplus; &rotimes; &RoundImplies; ) &rpargt; &rppolint; &rightrightarrows; &rAarr; &realine; &rscr; &rsh; &rsh; ] &rsquor; &rsquor;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

rthree; rtimes; rtri; rtrie; rtrif; rtriltri; RuleDelayed; ruluhar; rx; Sacute; sacute; sbquo; Sc; sc; scap; Scaron; scaron; sccue; scE; sce; Scedil; scedil; Scirc; scirc; scnap; scnE; scnsim; scpolint; scsim;
http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

U+022CC U+022CA U+025B9 U+022B5 U+025B8 U+029CE U+029F4 U+02968 U+0211E U+0015A U+0015B U+0201A U+02ABC U+0227B U+02AB8 U+00160 U+00161 U+0227D U+02AB4 U+02AB0 U+0015E U+0015F U+0015C U+0015D U+02ABA U+02AB6 U+022E9 U+02A13 U+0227F

&rightthreetimes; &rtimes; &triangleright; &rtrie; &blacktriangleright; &rtriltri; &RuleDelayed; &ruluhar; &rx; &Sacute; &sacute; &Sc; &succ; &succapprox; &sccue; &scE; &succeq; &Scedil; &scedil; &Scirc; &scirc; &scnap; &succneqq; &succnsim; &scpolint; &scsim;

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

Scy; scy; sdot; sdotb; sdote; searhk; seArr; searr; searrow; sect; semi; seswar; setminus; setmn; sext; Sfr; sfr; sfrown; sharp; SHCHcy; shchcy; SHcy; shcy; ShortDownArrow; ShortLeftArrow; shortmid; shortparallel; ShortRightArrow;

U+00421 U+00441 U+022C5 U+022A1 U+02A66 U+02925 U+021D8 U+02198 U+02198 U+000A7 U+0003B U+02929 U+02216 U+02216 U+02736 U+1D516 U+1D530 U+02322 U+0266F U+00429 U+00449 U+00428 U+00448 U+02193 U+02190 U+02223 U+02225 U+02192

&Scy; &scy;

&dotsquare; &sdote; &hksearow; &seArr; &searrow; &searrow; ; &tosa; &smallsetminus; &smallsetminus; &sext; &Sfr; &sfr; &frown; &sharp; &SHCHcy; &shchcy; &SHcy; &shcy; &downarrow; &slarr; &mid; &spar; &srarr;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

ShortUpArrow; shy; Sigma; sigma; sigmaf; sigmav; sim; simdot; sime; simeq; simg; simgE; siml; simlE; simne; simplus; simrarr; slarr; SmallCircle; smallsetminus; smashp; smeparsl; smid; smile; smt; smte; smtes; SOFTcy;

U+02191 U+000AD U+003A3 U+003C3 U+003C2 U+003C2 U+0223C U+02A6A U+02243 U+02243 U+02A9E U+02AA0 U+02A9D U+02A9F U+02246 U+02A24 U+02972 U+02190 U+02218 U+02216 U+02A33 U+029E4 U+02223 U+02323 U+02AAA U+02AAC U+02AAC U+0FE00 U+0042C

&uparrow; &sigmav; &sigmav; &thksim; &simdot; &simeq; &simeq; &simg; &simgE; &siml; &simlE; &simne; &simplus; &simrarr; &slarr; &compfn; &smallsetminus; &smashp; &smeparsl; &mid; &smile; &smt; &smte; &smte;

&SOFTcy;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

softcy; sol; solb; solbar; Sopf; sopf; spades; spadesuit; spar; sqcap; sqcaps; sqcup; sqcups; Sqrt; sqsub; sqsube; sqsubset; sqsubseteq; sqsup; sqsupe; sqsupset; sqsupseteq; squ; Square; square; SquareIntersection; SquareSubset;

U+0044C U+0002F U+029C4 U+0233F U+1D54A U+1D564 U+02660 U+02660 U+02225 U+02293 U+02293 U+0FE00 U+02294 U+02294 U+0FE00 U+0221A U+0228F U+02291 U+0228F U+02291 U+02290 U+02292 U+02290 U+02292 U+025A1 U+025A1 U+025A1 U+02293 U+0228F

&softcy; / &solb; &solbar; &Sopf; &sopf; &spadesuit; &spadesuit; &spar; &sqcap; &sqcap;

&sqcup; &sqcup;

&sqsub; &sqsubseteq; &sqsub; &sqsubseteq; &sqsupset; &sqsupe; &sqsupset; &sqsupe; &squ; &squ; &squ; &sqcap; &sqsub;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

SquareSubsetEqual; SquareSuperset; SquareSupersetEqual; SquareUnion; squarf; squf; srarr; Sscr; sscr; ssetmn; ssmile; sstarf; Star; star; starf; straightepsilon; straightphi; strns; Sub; sub; subdot; subE; sube; subedot; submult; subnE; subne; subplus; subrarr;
http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

U+02291 U+02290 U+02292 U+02294 U+025AA U+025AA U+02192 U+1D4AE U+1D4C8 U+02216 U+02323 U+022C6 U+022C6 U+02606 U+02605 U+003F5 U+003D5 U+000AF U+022D0 U+02282 U+02ABD U+02AC5 U+02286 U+02AC3 U+02AC1 U+02ACB U+0228A U+02ABF U+02979

&sqsubseteq; &sqsupset; &sqsupe; &sqcup; &blacksquare; &blacksquare; &srarr; &Sscr; &sscr; &smallsetminus; &smile; &sstarf; &sstarf; &star; &bigstar; &straightepsilon; &phiv; &strns; &Sub;

&subdot; &subseteqq; &subseteq; &subedot; &submult; &subsetneqq; &subsetneq; &subplus; &subrarr;

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

Subset; subset; subseteq; subseteqq; SubsetEqual; subsetneq; subsetneqq; subsim; subsub; subsup; succ; succapprox; succcurlyeq; Succeeds; SucceedsEqual; SucceedsSlantEqual; SucceedsTilde; succeq; succnapprox; succneqq; succnsim; succsim; SuchThat; Sum; sum; sung; Sup; sup;

U+022D0 U+02282 U+02286 U+02AC5 U+02286 U+0228A U+02ACB U+02AC7 U+02AD5 U+02AD3 U+0227B U+02AB8 U+0227D U+0227B U+02AB0 U+0227D U+0227F U+02AB0 U+02ABA U+02AB6 U+022E9 U+0227F U+0220B U+02211 U+02211 U+0266A U+022D1 U+02283

&Sub;

&subseteq; &subseteqq; &subseteq; &subsetneq; &subsetneqq; &subsim; &subsub; &subsup; &succ; &succapprox; &sccue; &succ; &succeq; &sccue; &scsim; &succeq; &scnap; &succneqq; &succnsim; &scsim; &niv; &sung; &Supset;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

sup1; sup2; sup3; supdot; supdsub; supE; supe; supedot; Superset; SupersetEqual; suphsol; suphsub; suplarr; supmult; supnE; supne; supplus; Supset; supset; supseteq; supseteqq; supsetneq; supsetneqq; supsim; supsub; supsup; swarhk; swArr; swarr;
http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

U+000B9 U+000B2 U+000B3 U+02ABE U+02AD8 U+02AC6 U+02287 U+02AC4 U+02283 U+02287 U+027C9 U+02AD7 U+0297B U+02AC2 U+02ACC U+0228B U+02AC0 U+022D1 U+02283 U+02287 U+02AC6 U+0228B U+02ACC U+02AC8 U+02AD4 U+02AD6 U+02926 U+021D9 U+02199

&supdot; &supdsub; &supseteqq; &supseteq; &supedot;

&supseteq; &suphsol; &suphsub; &suplarr; &supmult; &supsetneqq; &supsetneq; &supplus; &Supset;

&supseteq; &supseteqq; &supsetneq; &supsetneqq; &supsim; &supsub; &supsup; &hkswarow; &swArr; &swarrow;

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

swarrow; swnwar; szlig; Tab; target; Tau; tau; tbrk; Tcaron; tcaron; Tcedil; tcedil; Tcy; tcy; tdot; telrec; Tfr; tfr; there4; Therefore; therefore; Theta; theta; thetasym; thetav; thickapprox; thicksim; ThickSpace;

U+02199 U+0292A U+000DF U+00009 U+02316 U+003A4 U+003C4 U+023B4 U+00164 U+00165 U+00162 U+00163 U+00422 U+00442 U+020DB U+02315 U+1D517 U+1D531 U+02234 U+02234 U+02234 U+00398 U+003B8 U+003D1 U+003D1 U+02248 U+0223C U+0205F U+0200A

&swarrow; &swnwar;

&target; &tbrk; &Tcaron; &tcaron; &Tcedil; &tcedil; &Tcy; &tcy; &tdot; &telrec; &Tfr; &tfr; &therefore; &therefore; &therefore; &thetav; &thetav; &thkap; &thksim; &MediumSpace;&hairsp;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

thinsp; ThinSpace; thkap; thksim; THORN; thorn; Tilde; tilde; TildeEqual; TildeFullEqual; TildeTilde; times; timesb; timesbar; timesd; tint; toea; top; topbot; topcir; Topf; topf; topfork; tosa; tprime; TRADE; trade; triangle;

U+02009 U+02009 U+02248 U+0223C U+000DE U+000FE U+0223C U+002DC U+02243 U+02245 U+02248 U+000D7 U+022A0 U+02A31 U+02A30 U+0222D U+02928 U+022A4 U+02336 U+02AF1 U+1D54B U+1D565 U+02ADA U+02929 U+02034 U+02122 U+02122 U+025B5

&thkap; &thksim; &thksim; &simeq;

&thkap; &timesb; &timesbar; &timesd; &iiint; &toea; &top; &topbot; &topcir; &Topf; &topf; &topfork; &tosa; &tprime; &triangle;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

triangledown; triangleleft; trianglelefteq; triangleq; triangleright; trianglerighteq; tridot; trie; triminus; TripleDot; triplus; trisb; tritime; trpezium; Tscr; tscr; TScy; tscy; TSHcy; tshcy; Tstrok; tstrok; twixt; twoheadleftarrow; twoheadrightarrow; Uacute; uacute; Uarr; uArr;
http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

U+025BF U+025C3 U+022B4 U+0225C U+025B9 U+022B5 U+025EC U+0225C U+02A3A U+020DB U+02A39 U+029CD U+02A3B U+023E2 U+1D4AF U+1D4C9 U+00426 U+00446 U+0040B U+0045B U+00166 U+00167 U+0226C U+0219E U+021A0 U+000DA U+000FA U+0219F U+021D1

&triangledown; &triangleleft; &ltrie; &triangleq; &triangleright; &rtrie; &tridot; &triangleq; &triminus; &tdot; &triplus; &trisb; &tritime; &trpezium; &Tscr; &tscr; &TScy; &tscy; &TSHcy; &tshcy; &Tstrok; &tstrok; &between; &twoheadleftarrow; &twoheadrightarrow; &Uarr; &Uparrow;

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

uarr; Uarrocir; Ubrcy; ubrcy; Ubreve; ubreve; Ucirc; ucirc; Ucy; ucy; udarr; Udblac; udblac; udhar; ufisht; Ufr; ufr; Ugrave; ugrave; uHar; uharl; uharr; uhblk; ulcorn; ulcorner; ulcrop; ultri; Umacr;

U+02191 U+02949 U+0040E U+0045E U+0016C U+0016D U+000DB U+000FB U+00423 U+00443 U+021C5 U+00170 U+00171 U+0296E U+0297E U+1D518 U+1D532 U+000D9 U+000F9 U+02963 U+021BF U+021BE U+02580 U+0231C U+0231C U+0230F U+025F8 U+0016A

&uparrow; &Uarrocir; &Ubrcy; &ubrcy; &Ubreve; &ubreve; &Ucy; &ucy; &udarr; &Udblac; &udblac; &udhar; &ufisht; &Ufr; &ufr; &uHar; &upharpoonleft; &upharpoonright; &uhblk; &ulcorn; &ulcorn; &ulcrop; &ultri; &Umacr;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

umacr; uml; UnderBar; UnderBrace; UnderBracket; UnderParenthesis; Union; UnionPlus; Uogon; uogon; Uopf; uopf; UpArrow; Uparrow; uparrow; UpArrowBar; UpArrowDownArrow; UpDownArrow; Updownarrow; updownarrow; UpEquilibrium; upharpoonleft; upharpoonright; uplus; UpperLeftArrow; UpperRightArrow; Upsi; upsi; upsih;
http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

U+0016B U+000A8 U+0005F U+023DF U+023B5 U+023DD U+022C3 U+0228E U+00172 U+00173 U+1D54C U+1D566 U+02191 U+021D1 U+02191 U+02912 U+021C5 U+02195 U+021D5 U+02195 U+0296E U+021BF U+021BE U+0228E U+02196 U+02197 U+003D2 U+003C5 U+003D2

&umacr; &die; _ &UnderBrace; &bbrk; &UnderParenthesis; &xcup; &uplus; &Uogon; &uogon; &Uopf; &uopf; &uparrow; &Uparrow; &uparrow; &UpArrowBar; &udarr; &varr; &DoubleUpDownArrow; &varr; &udhar; &upharpoonleft; &upharpoonright; &uplus; &nwarrow; &nearrow;

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

Upsilon; upsilon; UpTee; UpTeeArrow; upuparrows; urcorn; urcorner; urcrop; Uring; uring; urtri; Uscr; uscr; utdot; Utilde; utilde; utri; utrif; uuarr; Uuml; uuml; uwangle; vangrt; varepsilon; varkappa; varnothing; varphi; varpi;

U+003A5 U+003C5 U+022A5 U+021A5 U+021C8 U+0231D U+0231D U+0230E U+0016E U+0016F U+025F9 U+1D4B0 U+1D4CA U+022F0 U+00168 U+00169 U+025B5 U+025B4 U+021C8 U+000DC U+000FC U+029A7 U+0299C U+003F5 U+003F0 U+02205 U+003D5 U+003D6

&bottom; &mapstoup; &uuarr; &urcorn; &urcorn; &urcrop; &Uring; &uring; &urtri; &Uscr; &uscr; &utdot; &Utilde; &utilde; &triangle; &utrif; &uuarr; &uwangle; &vangrt; &straightepsilon; &kappav; &emptyv; &phiv; &varpi;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

varpropto; vArr; varr; varrho; varsigma; varsubsetneq; varsubsetneqq; varsupsetneq; varsupsetneqq; vartheta; vartriangleleft; vartriangleright; Vbar; vBar; vBarv; Vcy; vcy; VDash; Vdash; vDash; vdash; Vdashl; Vee; vee; veebar; veeeq;

U+0221D U+021D5 U+02195 U+003F1 U+003C2 U+0228A U+0FE00 U+02ACB U+0FE00 U+0228B U+0FE00 U+02ACC U+0FE00 U+003D1 U+022B2 U+022B3 U+02AEB U+02AE8 U+02AE9 U+00412 U+00432 U+022AB U+022A9 U+022A8 U+022A2 U+02AE6 U+022C1 U+02228 U+022BB U+0225A

&propto; &DoubleUpDownArrow; &varr; &rhov; &sigmav; &subsetneq;

&subsetneqq;

&supsetneq;

&supsetneqq;

&thetav; &vartriangleleft; &vartriangleright; &Vbar; &vBar; &vBarv; &Vcy; &vcy; &VDash; &Vdash; &vDash; &vdash; &Vdashl; &bigvee; &vee; &veebar; &veeeq;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

vellip; Verbar; verbar; Vert; vert; VerticalBar; VerticalLine; VerticalSeparator; VerticalTilde; VeryThinSpace; Vfr; vfr; vltri; vnsub; vnsup; Vopf; vopf; vprop; vrtri; Vscr; vscr; vsubnE; vsubne; vsupnE; vsupne;

U+022EE U+02016 U+0007C U+02016 U+0007C U+02223 U+0007C U+02758 U+02240 U+0200A U+1D519 U+1D533 U+022B2 U+02282 U+020D2 U+02283 U+020D2 U+1D54D U+1D567 U+0221D U+022B3 U+1D4B1 U+1D4CB U+02ACB U+0FE00 U+0228A U+0FE00 U+02ACC U+0FE00 U+0228B

&vellip; &Vert; | &Vert; | &mid; | &VerticalSeparator; &wreath; &hairsp; &Vfr; &vfr; &vartriangleleft;

&Vopf; &vopf; &propto; &vartriangleright; &Vscr; &vscr; &subsetneqq;

&subsetneq;

&supsetneqq;

&supsetneq;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

U+0FE00 Vvdash; vzigzag; Wcirc; wcirc; wedbar; Wedge; wedge; wedgeq; weierp; Wfr; wfr; Wopf; wopf; wp; wr; wreath; Wscr; wscr; xcap; xcirc; xcup; xdtri; Xfr; xfr; xhArr; xharr; Xi; xi;
http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

U+022AA U+0299A U+00174 U+00175 U+02A5F U+022C0 U+02227 U+02259 U+02118 U+1D51A U+1D534 U+1D54E U+1D568 U+02118 U+02240 U+02240 U+1D4B2 U+1D4CC U+022C2 U+025EF U+022C3 U+025BD U+1D51B U+1D535 U+027FA U+027F7 U+0039E U+003BE

&Vvdash; &vzigzag; &Wcirc; &wcirc; &wedbar; &xwedge; &wedge; &wedgeq; &wp; &Wfr; &wfr; &Wopf; &wopf; &wp; &wreath; &wreath; &Wscr; &wscr; &bigcap; &xcirc; &xcup; &xdtri; &Xfr; &xfr; &DoubleLongLeftRightArrow; &xharr;

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

xlArr; xlarr; xmap; xnis; xodot; Xopf; xopf; xoplus; xotime; xrArr; xrarr; Xscr; xscr; xsqcup; xuplus; xutri; xvee; xwedge; Yacute; yacute; YAcy; yacy; Ycirc; ycirc; Ycy; ycy; yen; Yfr;

U+027F8 U+027F5 U+027FC U+022FB U+02A00 U+1D54F U+1D569 U+02A01 U+02A02 U+027F9 U+027F6 U+1D4B3 U+1D4CD U+02A06 U+02A04 U+025B3 U+022C1 U+022C0 U+000DD U+000FD U+0042F U+0044F U+00176 U+00177 U+0042B U+0044B U+000A5 U+1D51C

&Longleftarrow; &xlarr; &xmap; &xnis; &bigodot; &Xopf; &xopf; &bigoplus; &xotime; &xrArr; &xrarr; &Xscr; &xscr; &bigsqcup; &xuplus; &bigtriangleup; &bigvee; &xwedge; &YAcy; &yacy; &Ycirc; &ycirc; &Ycy; &ycy; &Yfr;

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

yfr; YIcy; yicy; Yopf; yopf; Yscr; yscr; YUcy; yucy; Yuml; yuml; Zacute; zacute; Zcaron; zcaron; Zcy; zcy; Zdot; zdot; zeetrf; ZeroWidthSpace; Zeta; zeta; Zfr; zfr; ZHcy; zhcy; zigrarr; Zopf;
http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

U+1D536 U+00407 U+00457 U+1D550 U+1D56A U+1D4B4 U+1D4CE U+0042E U+0044E U+00178 U+000FF U+00179 U+0017A U+0017D U+0017E U+00417 U+00437 U+0017B U+0017C U+02128 U+0200B U+00396 U+003B6 U+02128 U+1D537 U+00416 U+00436 U+021DD U+02124

&yfr; &YIcy; &yicy; &Yopf; &yopf; &Yscr; &yscr; &YUcy; &yucy; &Zacute; &zacute; &Zcaron; &zcaron; &Zcy; &zcy; &Zdot; &zdot; &zeetrf; &NegativeThickSpace; &zeetrf; &zfr; &ZHcy; &zhcy; &zigrarr; &integers;

17.2 Named character references HTML: The Living Standard - Edition for Web Developers

zopf; Zscr; zscr; zwj; zwnj; This data is also available as a JSON file.

U+1D56B U+1D4B5 U+1D4CF U+0200D U+0200C

&zopf; &Zscr; &zscr;

The glyphs displayed above are non-normative. Refer to the Unicode specifications for formal
definitions of the characters listed above.

Up next

18 The XHTML syntax

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/named-character-references.html[4/16/2014 9:31:40 PM]

18 The XHTML syntax HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

18THE XHTML SYNTAX

This section only describes the rules for XML resources. Rules for
text/html resources are discussed in the section above entitled "The HTML
syntax". The syntax for using HTML with XML, whether in XHTML documents or embedded in other XML
documents, is defined in the XML and Namespaces in XML specifications. This specification does not define any syntax-level requirements beyond those defined for XML
proper. XML documents may contain a DOCTYPE if desired, but this is not required to conform to this specification. This specification does not define a public or system identifier,
nor provide a formal DTD. According to the XML specification, XML processors are not guaranteed to process
the external DTD subset referenced in the DOCTYPE. This means, for example, that using entity references for characters in XHTML documents
is unsafe if they are defined in an external file (except for &lt;, &gt;, &amp;, &quot;
and &apos;).

Up next

19 Obsolete features

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/the-xhtml-syntax.html[4/16/2014 9:31:52 PM]

19 Obsolete features HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
Obsolete features
Obsolete but conforming features
Non-conforming features

19 OBSOLETE FEATURES

Obsolete but conforming features


Features listed in this section will trigger warnings in conformance checkers. Authors should not specify a border attribute on an
img element. If the attribute is present, its value must be the string "0 ". CSS should be used instead. Authors should not specify a language attribute on a
script element. If the attribute is present, its value must be an ASCII
case-insensitive match for the string "JavaScript " and either the
type attribute must be omitted or its value must be an
ASCII case-insensitive match for the string " text/javascript".
The attribute should be entirely omitted instead (with the value "JavaScript", it has no effect), or replaced with use of the type attribute. Authors should not specify the name attribute on
a elements. If the attribute is present, its value must not be the empty string and
must neither be equal to the value of any of the IDs in the
element's home subtree other than the element's own ID, if any, nor be equal to the value of any of the other name attributes on a elements in the element's home
subtree. If this attribute is present and the element has an ID, then the attribute's value must be equal to the element's ID. In earlier versions of the language, this attribute was intended as
a way to specify possible targets for fragment identifiers in URLs.
http://developers.whatwg.org/obsolete.html[4/16/2014 9:31:57 PM]

19 Obsolete features HTML: The Living Standard - Edition for Web Developers

The
id attribute should be used instead. Authors should not, but may despite requirements to the contrary elsewhere in this
specification, specify the maxlength and size attributes on input elements whose type attributes are in the Number state. One valid reason for using these attributes
regardless is to help legacy user agents that do not support input elements with
type="number" to still render the text field with a useful width. In the HTML syntax, specifying a DOCTYPE that is an obsolete permitted DOCTYPE will also
trigger a warning.

Non-conforming features
Elements in the following list are entirely obsolete, and must not be used by authors: applet Use embed or object instead. acronym Use abbr instead. bgsound Use audio instead. dir Use ul instead. frame frameset noframes Either use iframe and CSS instead, or use server-side includes to generate complete pages with the various invariant parts merged in. isindex Use an explicit form and text field combination instead. listing Use pre and code instead.

http://developers.whatwg.org/obsolete.html[4/16/2014 9:31:57 PM]

19 Obsolete features HTML: The Living Standard - Edition for Web Developers

nextid Use GUIDs instead. noembed Use object instead of embed when fallback is necessary. plaintext Use the "text/plain" MIME type instead. rb Providing the ruby base directly inside the ruby element is sufficient; the rb element is unnecessary. Omit it altogether. strike Use del instead if the element is marking an edit, otherwise use s instead. xmp Use pre and code instead, and escape "< " and "&" characters as "&lt; " and " &amp; " respectively. basefont big blink center font marquee multicol nobr spacer tt Use appropriate elements or CSS instead. Where the tt element would have been used for marking up keyboard input, consider the kbd element; for variables, consider the var element; for computer code, consider the code element; and for computer output, consider the
samp element. Similarly, if the big element is being used to denote a heading, consider using the h1 element; if it is being used for marking up important passages, consider the
strong element; and if it is being used for highlighting text for reference
purposes, consider the mark element.

http://developers.whatwg.org/obsolete.html[4/16/2014 9:31:57 PM]

19 Obsolete features HTML: The Living Standard - Edition for Web Developers

See also the text-level semantics usage summary for more


suggestions with examples. The following attributes are obsolete (though the elements are still part of the language), and
must not be used by authors: charset on a elements charset on link elements Use an HTTP Content-Type header on the linked resource instead. coords on a elements shape on a elements Use area instead of a for image maps. methods on a elements methods on link elements Use the HTTP OPTIONS feature instead. name on a elements (except as noted in the previous section) name on embed elements name on img elements name on option elements Use the id attribute instead. rev on a elements rev on link elements Use the rel
attribute instead, with an opposite term. (For example, instead of rev="made" , use rel="author".) urn on a elements urn on link elements Specify the preferred persistent identifier using the href attribute instead. accept on form elements Use the accept attribute directly on the input elements instead. nohref on area elements Omitting the href
attribute is sufficient; the nohref attribute is
unnecessary. Omit it altogether. profile on head elements When used for declaring which meta terms are
used in the document,

http://developers.whatwg.org/obsolete.html[4/16/2014 9:31:57 PM]

19 Obsolete features HTML: The Living Standard - Edition for Web Developers

unnecessary; omit it altogether, and register the names. When used for triggering specific user agent behaviors: use
a link element instead. version on html elements Unnecessary. Omit it altogether. ismap on input elements Unnecessary. Omit it altogether. All input elements with a type attribute in the Image
Button state are processed as server-side image maps. usemap on input elements Use img instead of input for image maps. longdesc on iframe elements longdesc on img elements Use a regular a element to link to the
description, or (in the case of images) use an image
map to provide a link from the image to the image's
description. lowsrc on img elements Use a progressive JPEG image (given in the src attribute),
instead of using two separate images. target on link elements Unnecessary. Omit it altogether. scheme on meta elements Use only one scheme per field, or make the scheme declaration part of the value. archive on object elements classid on object elements code on object elements codebase on object elements codetype on object elements Use the data and type attributes to invoke plugins. To set parameters with these names
in particular, the param element can be used. declare on object elements Repeat the object element completely each time the resource is to be reused. standby on object elements Optimize the linked resource so that it loads quickly or, at least, incrementally.
http://developers.whatwg.org/obsolete.html[4/16/2014 9:31:57 PM]

19 Obsolete features HTML: The Living Standard - Edition for Web Developers

type on param elements valuetype on param elements Use the name and value attributes without declaring
value types. language on script elements (except as noted in the previous section) Use the type attribute
instead. event on script elements for on script elements Use DOM Events mechanisms to register event listeners. datapagesize on table elements Unnecessary. Omit it altogether. summary on table elements Use one of the techniques for describing
tables given in the table section instead. abbr on td elements Use text that begins in an unambiguous and terse manner, and include any more elaborate text after that. The title attribute can also be useful in including more detailed text, so that the cell's contents can be made terse. If it's a heading, use th (which has an abbr attribute). axis on td and th elements Use the scope attribute on the relevant th. scope on td elements Use th elements for heading cells. datasrc on a, applet , button , div, frame , iframe , img, input, label , legend , marquee, object , option , select, span, table , and textarea elements datafld on a, applet , button , div, fieldset, frame , iframe, img, input , label , legend, marquee , object , param , select , span, and textarea elements dataformatas on button, div , input , label, legend , marquee, object, option , select, span , and table elements Use script and a mechanism such as XMLHttpRequest to populate the page dynamically.

http://developers.whatwg.org/obsolete.html[4/16/2014 9:31:57 PM]

19 Obsolete features HTML: The Living Standard - Edition for Web Developers

alink on body elements bgcolor on body elements link on body elements marginbottom on body elements marginheight on body elements marginleft on body elements marginright on body elements margintop on body elements marginwidth on body elements text on body elements vlink on body elements clear on br elements align on caption elements align on col elements char on col elements charoff on col elements valign on col elements width on col elements align on div elements compact on dl elements align on embed elements hspace on embed elements vspace on embed elements align on hr elements color on hr elements noshade on hr elements size on hr elements width on hr elements align on h1h6 elements align on iframe elements allowtransparency on iframe elements frameborder on iframe elements hspace on iframe elements marginheight on iframe elements marginwidth on iframe elements scrolling on iframe elements vspace on iframe elements align on input elements hspace on input elements

http://developers.whatwg.org/obsolete.html[4/16/2014 9:31:57 PM]

19 Obsolete features HTML: The Living Standard - Edition for Web Developers

vspace on input elements align on img elements border on img elements (except as noted in the previous section) hspace on img elements vspace on img elements align on legend elements type on li elements compact on menu elements align on object elements border on object elements hspace on object elements vspace on object elements compact on ol elements align on p elements width on pre elements align on table elements bgcolor on table elements border on table elements bordercolor on table elements cellpadding on table elements cellspacing on table elements frame on table elements rules on table elements width on table elements align on tbody, thead , and tfoot elements char on tbody, thead , and tfoot elements charoff on tbody, thead , and tfoot elements valign on tbody, thead , and tfoot elements align on td and th elements bgcolor on td and th elements char on td and th elements charoff on td and th elements height on td and th elements nowrap on td and th elements valign on td and th elements width on td and th elements align on tr elements bgcolor on tr elements char on tr elements
http://developers.whatwg.org/obsolete.html[4/16/2014 9:31:57 PM]

19 Obsolete features HTML: The Living Standard - Edition for Web Developers

charoff on tr elements valign on tr elements compact on ul elements type on ul elements background on body, table , thead , tbody, tfoot , tr , td, and th elements Use CSS instead.

Up next

20 IANA considerations

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/obsolete.html[4/16/2014 9:31:57 PM]

20 IANA considerations HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
IANA considerations
text/html
multipart/x-mixed-replace
application/xhtml+xml
application/x-www-form-urlencoded
text/cache-manifest
text/ping
application/microdata+json
Ping-From
Ping-To
web+ scheme prefix

20 IANA CONSIDERATIONS

text/html
This registration is for community review and will be submitted to the IESG for review,
approval, and registration with IANA. Type name: text Subtype name: html Required parameters: No required parameters Optional parameters: charset The charset parameter may be provided to definitively specify the

http://developers.whatwg.org/iana.html[4/16/2014 9:32:03 PM]

20 IANA considerations HTML: The Living Standard - Edition for Web Developers

document's character encoding, overriding any character encoding declarations in the document. The parameter's value
must be one of the labels of the character encoding used to serialize the file. Encoding considerations:
8bit (see the section on character encoding
declarations) Security considerations: Entire novels have been written about the security considerations that apply to HTML
documents. Many are listed in this document, to which the reader is referred for more details.
Some general concerns bear mentioning here, however: HTML is scripted language, and has a large number of APIs (some of which are described in
this document). Script can expose the user to potential risks of information leakage, credential
leakage, cross-site scripting attacks, crosssite request forgeries, and a host of other
problems. While the designs in this specification are intended to be safe if implemented
correctly, a full implementation is a massive undertaking and, as with any software, user agents
are likely to have security bugs. Even without scripting, there are specific features in HTML which, for historical reasons,
are required for broad compatibility with legacy content but that expose the user to unfortunate
security problems. In particular, the img element can be used in conjunction with
some other features as a way to effect a port scan from the user's location on the Internet.
This can expose local network topologies that the attacker would otherwise not be able to determine. HTML relies on a compartmentalization scheme sometimes known as the same-origin
policy. An origin in most cases consists of all the pages served from the same
host, on the same port, using the same protocol. It is critical, therefore, to ensure that any untrusted content that forms part of a site be
hosted on a different origin than any sensitive content on that site. Untrusted
content can easily spoof any other page on the same origin, read data from that origin, cause
scripts in that origin to execute, submit forms to and from that origin even if they are
protected from cross-site request forgery attacks by unique tokens, and make use of any
third-party resources exposed to or rights granted to that origin. Interoperability considerations:
Rules for processing both conforming and non-conforming content
are

http://developers.whatwg.org/iana.html[4/16/2014 9:32:03 PM]

20 IANA considerations HTML: The Living Standard - Edition for Web Developers

defined in this specification. Published specification:


This document is the relevant specification. Labeling a resource
with the text/html type asserts that the resource is
an HTML document using
the HTML syntax. Applications that use this media type:
Web browsers, tools for processing Web content, HTML authoring
tools, search engines, validators. Additional information: Magic number(s): No sequence of bytes can uniquely identify an HTML
document. More information on detecting HTML documents is
available in the MIME Sniffing specification. File extension(s): "html" and "htm"
are commonly, but certainly not exclusively, used as the extension for HTML documents. Macintosh file type code(s): TEXT Person & email address to contact for further information: Ian Hickson <ian@hixie.ch> Intended usage: Common Restrictions on usage: No restrictions apply. Author: Ian Hickson <ian@hixie.ch> Change controller: W3C Fragment identifiers used with text/html resources either refer to the indicated part of the document or provide state information for in-page scripts.

multipart/x-mixed-replace

http://developers.whatwg.org/iana.html[4/16/2014 9:32:03 PM]

20 IANA considerations HTML: The Living Standard - Edition for Web Developers

This registration is for community review and will be submitted to the IESG for review,
approval, and registration with IANA. Type name: multipart Subtype name: x-mixed-replace Required parameters:

boundary (defined in RFC2046)


Optional parameters: No optional parameters. Encoding considerations: binary Security considerations:
Subresources of a multipart/x-mixed-replace
resource can be of any type, including types with non-trivial
security implications such as text/html . Interoperability considerations:
None. Published specification:
This specification describes processing rules for Web browsers.
Conformance requirements for generating resources with this type are the same as for multipart/mixed. [RFC2046] Applications that use this media type:
This type is intended to be used in resources generated by Web servers, for consumption by Web browsers. Additional information: Magic number(s): No sequence of bytes can uniquely identify a multipart/x-mixed-replace resource. File extension(s): No specific file extensions are recommended for this type. Macintosh file type code(s): No specific Macintosh file type codes are recommended for this type. Person & email address to contact for further information: Ian Hickson <ian@hixie.ch>

http://developers.whatwg.org/iana.html[4/16/2014 9:32:03 PM]

20 IANA considerations HTML: The Living Standard - Edition for Web Developers

Intended usage: Common Restrictions on usage: No restrictions apply. Author: Ian Hickson <ian@hixie.ch> Change controller: W3C Fragment identifiers used with multipart/x-mixed-replace resources apply to each
body part as defined by the type used by that body part.

application/xhtml+xml
This registration is for community review and will be submitted to the IESG for review,
approval, and registration with IANA. Type name: application Subtype name: xhtml+xml Required parameters: Same as for application/xml Optional parameters: Same as for application/xml [RFC3023] Encoding considerations: Same as for application/xml [RFC3023] Security considerations: Same as for application/xml [RFC3023] Interoperability considerations: Same as for application/xml [RFC3023] Published specification:
Labeling a resource with the application/xhtml+xml
type asserts that the resource is an XML document that likely has
a root element from the HTML namespace. Thus, the
relevant specifications are the XML specification, the

http://developers.whatwg.org/iana.html[4/16/2014 9:32:03 PM]

20 IANA considerations HTML: The Living Standard - Edition for Web Developers

Namespaces
in XML specification, and this specification. Applications that use this media type: Same as for application/xml [RFC3023] Additional information: Magic number(s): Same as for application/xml [RFC3023] File extension(s): "xhtml " and "xht"
are sometimes used as extensions for XML resources that have a
root element from the HTML namespace. Macintosh file type code(s): TEXT Person & email address to contact for further information: Ian Hickson <ian@hixie.ch> Intended usage: Common Restrictions on usage: No restrictions apply. Author: Ian Hickson <ian@hixie.ch> Change controller: W3C Fragment identifiers used with application/xhtml+xml resources have the same
semantics as with any XML MIME type. [RFC3023]

application/x-www-form-urlencoded
This registration is for community review and will be submitted to the IESG for review,
approval, and registration with IANA. Type name: application Subtype name: x-www-form-urlencoded Required parameters:
http://developers.whatwg.org/iana.html[4/16/2014 9:32:03 PM]

20 IANA considerations HTML: The Living Standard - Edition for Web Developers

No parameters Optional parameters: No parameters Encoding considerations: 7bit (US-ASCII encoding of octets that themselves can be encoding text using any ASCII-compatible character encoding) Security considerations: In isolation, an application/x-www-form-urlencoded
payload poses no security risks. However, as this type is usually
used as part of a form submission, all the risks that apply to
HTML forms need to be considered in the context of this type. Interoperability considerations:
Rules for generating and processing
application/x-www-form-urlencoded payloads are
defined in this specification. Published specification:
This document is the relevant specification.
Algorithms for encoding
and decoding are defined. Applications that use this media type:
Web browsers and servers. Additional information: Magic number(s): There is no reliable mechanism for recognising application/x-www-form-urlencoded payloads. File extension(s): Not applicable. Macintosh file type code(s): Not applicable. Person & email address to contact for further information: Ian Hickson <ian@hixie.ch> Intended usage: Common Restrictions on usage: This type is only intended to be used to describe HTML form
submission payloads. Author:

http://developers.whatwg.org/iana.html[4/16/2014 9:32:03 PM]

20 IANA considerations HTML: The Living Standard - Edition for Web Developers

Ian Hickson <ian@hixie.ch> Change controller: W3C Fragment identifiers have no meaning with the application/x-www-form-urlencoded
type.

text/cache-manifest
This registration is for community review and will be submitted
to the IESG for review, approval, and registration with IANA. Type name: text Subtype name: cache-manifest Required parameters: No parameters Optional parameters: charset The charset parameter may be provided. The parameter's value must be
" utf-8 ". This parameter serves no purpose; it is only allowed for
compatibility with legacy servers. Encoding considerations: 8bit (always UTF-8) Security considerations: Cache manifests themselves pose no immediate risk unless
sensitive information is included within the
manifest. Implementations, however, are required to follow
specific rules when populating a cache based on a cache manifest,
to ensure that certain origin-based restrictions are
honored. Failure to correctly implement these rules can result in
information leakage, crosssite scripting attacks, and the
like. Interoperability considerations:
Rules for processing both conforming and non-conforming content
are defined in this specification.

http://developers.whatwg.org/iana.html[4/16/2014 9:32:03 PM]

20 IANA considerations HTML: The Living Standard - Edition for Web Developers

Published specification:
This document is the relevant specification. Applications that use this media type:
Web browsers. Additional information: Magic number(s): Cache manifests begin with the string "CACHE
MANIFEST", followed by either a U+0020 SPACE character, a
U+0009 CHARACTER TABULATION (tab) character, a U+000A LINE FEED
(LF) character, or a U+000D CARRIAGE RETURN (CR) character. File extension(s): "appcache" Macintosh file type code(s): No specific Macintosh file type codes are recommended for this type. Person & email address to contact for further information: Ian Hickson <ian@hixie.ch> Intended usage: Common Restrictions on usage: No restrictions apply. Author: Ian Hickson <ian@hixie.ch> Change controller: W3C Fragment identifiers have no meaning with text/cache-manifest resources.

text/ping
This registration is for community review and will be submitted to the IESG for review,
approval, and registration with IANA. Type name: text Subtype name:

http://developers.whatwg.org/iana.html[4/16/2014 9:32:03 PM]

20 IANA considerations HTML: The Living Standard - Edition for Web Developers

ping Required parameters: No parameters Optional parameters: charset The charset parameter may be provided. The parameter's value must be
" utf-8 ". This parameter serves no purpose; it is only allowed for
compatibility with legacy servers. Encoding considerations: Not applicable. Security considerations: If used exclusively in the fashion described in the context of
hyperlink auditing, this type introduces no new
security concerns. Interoperability considerations:
Rules applicable to this type are defined in this specification. Published specification:
This document is the relevant specification. Applications that use this media type:
Web browsers. Additional information: Magic number(s): text/ping resources always consist of the four
bytes 0x50 0x49 0x4E 0x47 (ASCII 'PING'). File extension(s): No specific file extension is recommended for this type. Macintosh file type code(s): No specific Macintosh file type codes are recommended for this type. Person & email address to contact for further information: Ian Hickson <ian@hixie.ch> Intended usage: Common Restrictions on usage: Only intended for use with HTTP POST requests generated as part
of a Web browser's processing of the ping attribute. Author:

http://developers.whatwg.org/iana.html[4/16/2014 9:32:03 PM]

20 IANA considerations HTML: The Living Standard - Edition for Web Developers

Ian Hickson <ian@hixie.ch> Change controller: W3C Fragment identifiers have no meaning with text/ping resources.

application/microdata+json
This registration is for community review and will be submitted to the IESG for review,
approval, and registration with IANA. Type name: application Subtype name: microdata+json Required parameters: Same as for application/json Optional parameters: Same as for application/json [JSON] Encoding considerations: 8bit (always UTF-8) Security considerations: Same as for application/json [JSON] Interoperability considerations: Same as for application/json [JSON] Published specification:
Labeling a resource with the application/microdata+json type asserts that the
resource is a JSON text that consists of an object with a single entry called "items " consisting of an array of entries, each of which consists of an object
with an entry called "id " whose value is a string, an entry called "type" whose value is another string, and an entry called "properties" whose value is an object whose entries each have a value consisting
of an array of either objects or strings, the objects being of the same form as the objects in
the aforementioned "items " entry. Thus, the relevant specifications are
the JSON specification and this specification. [JSON]

http://developers.whatwg.org/iana.html[4/16/2014 9:32:03 PM]

20 IANA considerations HTML: The Living Standard - Edition for Web Developers

Applications that use this media type: Applications that transfer data intended for use with HTML's microdata feature, especially in
the context of drag-and-drop, are the primary application class for this type. Additional information: Magic number(s): Same as for application/json [JSON] File extension(s): Same as for application/json [JSON] Macintosh file type code(s): Same as for application/json [JSON] Person & email address to contact for further information: Ian Hickson <ian@hixie.ch> Intended usage: Common Restrictions on usage: No restrictions apply. Author: Ian Hickson <ian@hixie.ch> Change controller: W3C Fragment identifiers used with application/microdata+json resources have the same
semantics as when used with application/json (namely, at the time of writing, no
semantics at all). [JSON]

Ping-From
This section describes a header for registration in the Permanent Message Header Field
Registry. Header field name: Ping-From Applicable protocol: http

http://developers.whatwg.org/iana.html[4/16/2014 9:32:03 PM]

20 IANA considerations HTML: The Living Standard - Edition for Web Developers

Status: standard Author/Change controller: W3C Specification document(s):


This document is the relevant specification. Related information: None.

Ping-To
This section describes a header for registration in the Permanent Message Header Field
Registry. [RFC3864] Header field name: Ping-To Applicable protocol: http Status: standard Author/Change controller: W3C Specification document(s):
This document is the relevant specification. Related information: None.

web+ scheme prefix


This section describes a convention for use with the IANA URI scheme registry. It does not
itself register a specific scheme. URI scheme name:
Schemes starting with the four characters "web+" followed by one or more

http://developers.whatwg.org/iana.html[4/16/2014 9:32:03 PM]

20 IANA considerations HTML: The Living Standard - Edition for Web Developers

letters in the range


a -z . Status: permanent URI scheme syntax: Scheme-specific. URI scheme semantics: Scheme-specific. Encoding considerations: All "web+" schemes should use UTF-8 encodings where relevant. Applications/protocols that use this URI scheme name: Scheme-specific. Interoperability considerations: The scheme is expected to be used in the context of Web applications. Security considerations:
Any Web page is able to register a handler for all " web+" schemes. As
such, these schemes must not be used for features intended to be core platform features (e.g.
network transfer protocols like HTTP or FTP). Similarly, such schemes must not store
confidential information in their URLs, such as usernames, passwords, personal information, or
confidential project names. Contact: Ian Hickson <ian@hixie.ch> Author/Change controller: Ian Hickson <ian@hixie.ch> References: Custom scheme and content handlers, HTML Living Standard: http://www.whatwg.org/specs/web-apps/current-work/#custom-handlers

Up next

Index

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/iana.html[4/16/2014 9:32:03 PM]

Index HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
In this section In this section

Search. Press '/'

INDEX

Elements
List of elements Element a Description Hyperlink Categories flow; phrasing*; interactive Parents phrasing Children transparent* Attributes globals;
href; target ; download;
ping; rel;
hreflang; type globals globals Interface HTMLAnchorElement

abbr address

Abbreviation Contact information for a page or article element Hyperlink or dead area on an image map

flow;
phrasing flow

phrasing flow

phrasing flow*

HTMLElement HTMLElement

area

flow;
phrasing

phrasing*

empty

globals;
alt; coords ;
shape ; href;
target ; download;
ping; rel;
hreflang; type globals

HTMLAreaElement

article

Selfcontained syndicatable or reusable composition Sidebar for tangentially related content Audio player

flow;
sectioning

flow

flow

HTMLElement

aside

flow;
sectioning

flow

flow

globals

HTMLElement

audio

flow;
phrasing; embedded; interactive

phrasing

source *; transparent*

globals;
src; crossorigin; preload; autoplay; mediagroup ; loop;
muted ; controls globals globals;
href; target

HTMLAudioElement

b base

Keywords Base URL and default target browsing context for hyperlinks and forms Text directionality isolation Text directionality formatting

flow;
phrasing metadata

phrasing head; template

phrasing empty

HTMLElement HTMLBaseElement

bdi

flow;
phrasing

phrasing

phrasing

globals

HTMLElement

bdo

flow;
phrasing

phrasing

phrasing

globals

HTMLElement

blockquote A section quoted from another source

flow;
sectioning root

flow

flow

globals;
cite

HTMLQuoteElement

http://developers.whatwg.org/section-index.html[4/16/2014 9:32:10 PM]

Index HTML: The Living Standard - Edition for Web Developers

body

Document body

sectioning root

html

flow

globals; onafterprint; onbeforeprint ; onbeforeunload ;


onhashchange; onmessage ; onoffline ; ononline; onpagehide ; onpageshow ; onpopstate ; onresize; onstorage ; onunload globals

HTMLBodyElement

br

Line break, e.g. in poem or postal address Button control

flow;
phrasing

phrasing

empty

HTMLBRElement

button

flow;
phrasing; interactive; listed; labelable; submittable; reassociateable;
formassociated

phrasing

phrasing*

globals; autofocus ; disabled;


form; formaction ; formenctype; formmethod ; formnovalidate ;
formtarget; menu;
name;
type; value globals;
width ; height globals globals globals globals;
span globals;
span

HTMLButtonElement

canvas

Scriptable bitmap canvas Table caption Title of a work Computer code Table column Group of columns in a table Machinereadable equivalent Container for options for combo box control Content for corresponding dt element(s) A removal from the document Disclosure control for hiding details Defining instance Dialog box or window Generic flow container Association list consisting of zero or more name-

flow;
phrasing; embedded none flow;
phrasing flow;
phrasing none none

phrasing

transparent

HTMLCanvasElement

caption cite code col colgroup

table ; template phrasing phrasing colgroup; template table ; template phrasing

flow* phrasing phrasing empty col*;


scriptsupporting elements* phrasing

HTMLTableCaptionElement HTMLElement HTMLElement HTMLTableColElement HTMLTableColElement

data

flow;
phrasing

globals;
value

HTMLDataElement

datalist

flow;
phrasing

phrasing

phrasing; option

globals

HTMLDataListElement

dd

none

dl ; template phrasing

flow

globals

HTMLElement

del

flow;
phrasing*

transparent

globals;
cite; datetime globals;
open

HTMLModElement

details

flow;
sectioning root; interactive flow;
phrasing flow;
sectioning root flow flow

flow

summary*;
flow

HTMLDetailsElement

dfn dialog div dl

phrasing flow flow flow

phrasing* flow flow dt *;


dd *;
scriptsupporting elements

globals globals;
open globals globals

HTMLElement HTMLDialogElement HTMLDivElement HTMLDListElement

http://developers.whatwg.org/section-index.html[4/16/2014 9:32:10 PM]

Index HTML: The Living Standard - Edition for Web Developers

value groups dt Legend for corresponding dd element(s) Stress emphasis Plugin none dl ; template phrasing phrasing flow* globals HTMLElement

em embed

flow;
phrasing flow;
phrasing; embedded; interactive flow;
sectioning root;
listed; reassociateable;
formassociated none flow;
sectioning root flow

phrasing empty

globals globals;
src;
type ;
width ;
height; any* globals;
disabled ;
form;
name

HTMLElement HTMLEmbedElement

fieldset

Group of form controls

flow

legend *;
flow

HTMLFieldSetElement

figcaption Caption for figure figure Figure with optional caption Footer for a page or section Usersubmittable form

figure ; template flow

flow figcaption *; flow flow*

globals globals

HTMLElement HTMLElement

footer

flow

globals

HTMLElement

form

flow

flow

flow*

globals; accept-charset ;
action; autocomplete; enctype;
method ;
name; novalidate ; target globals globals

HTMLFormElement

h1 , h2, h3 , h4 , h5, h6 head

Section heading Container for document metadata Introductory or navigational aids for a page or section heading group

flow;
heading none

hgroup ; flow html

phrasing metadata content* flow*

HTMLHeadingElement HTMLHeadElement

header

flow

flow

globals

HTMLElement

hgroup

flow;
heading

flow

One or more h1 , h2, h3 , h4 , h5, h6 , and scriptsupporting elements empty head*;


body* phrasing text*

globals

HTMLElement

hr html i iframe

Thematic break Root element Alternate voice Nested browsing context

flow none flow;


phrasing flow;
phrasing; embedded; interactive

flow none* phrasing phrasing

globals globals;
manifest globals globals;
src; srcdoc ;
name; sandbox; seamless; allowfullscreen ;
width ;
height globals;
alt;
src ; srcset ; crossorigin; usemap ;
ismap ; width ;
height globals;
accept ; alt; autocomplete; autofocus ;

HTMLHRElement HTMLHtmlElement HTMLElement HTMLIFrameElement

img

Image

flow;
phrasing; embedded; interactive*; formassociated flow;
phrasing; interactive*; listed; labelable;

phrasing

empty

HTMLImageElement

input

Form control

phrasing

empty

HTMLInputElement

http://developers.whatwg.org/section-index.html[4/16/2014 9:32:10 PM]

Index HTML: The Living Standard - Edition for Web Developers

submittable; resettable; reassociateable;


formassociated

checked; dirname; disabled;


form; formaction ; formenctype; formmethod ; formnovalidate ;
formtarget; height ;
list; max;
maxlength ; min;
minlength ; multiple;
name; pattern; placeholder; readonly; required;
size; src;
step;
type; value ;
width phrasing phrasing phrasing transparent phrasing empty globals;
cite; datetime globals globals; autofocus ; challenge ; disabled;
form; keytype;
name HTMLModElement HTMLElement HTMLKeygenElement

ins kbd keygen

An addition to the document User input Cryptographic key-pair generator form control

flow;
phrasing* flow;
phrasing flow;
phrasing; interactive; listed; labelable; submittable; resettable; reassociateable;
formassociated flow;
phrasing; interactive; reassociateable;
formassociated none none

label

Caption for a form control

phrasing

phrasing*

globals;
form;
for

HTMLLabelElement

legend li

Caption for fieldset List item

fieldset; template ol ;
ul ; menu*; template head; template; noscript*;
phrasing* flow

phrasing flow

globals globals;
value *

HTMLLegendElement HTMLLIElement

link

Link metadata

metadata; flow*; phrasing*

empty

globals;
href; crossorigin; rel;
media ; hreflang;
type; sizes globals

HTMLLinkElement

main

Container for the dominant contents of another element Image map Highlight Menu of commands

flow

flow

HTMLElement

map mark menu

flow;
phrasing* flow;
phrasing flow

phrasing phrasing flow;


menu*

transparent; area* phrasing li *;


flow*; menuitem*;
hr *;
menu*;
scriptsupporting elements* empty

globals;
name globals globals;
type; label

HTMLMapElement HTMLElement HTMLMenuElement

menuitem

Menu command

none

menu; template

globals;
type; label ;
icon; disabled; checked; radiogroup ; default; command globals;
name; http-equiv ; ;

HTMLMenuItemElement

meta

Text metadata

metadata; flow*; phrasing*

head; template; *;

empty

HTMLMetaElement

http://developers.whatwg.org/section-index.html[4/16/2014 9:32:10 PM]

Index HTML: The Living Standard - Edition for Web Developers

noscript
phrasing* meter Gauge flow;
phrasing; labelable flow;
sectioning phrasing phrasing*

content charset globals;


value ; min;
max ;
low; high;
optimum globals HTMLMeterElement

nav

Section with navigational links Fallback content for script Image, nested browsing context, or plugin

flow

flow

HTMLElement

noscript

metadata;
flow;
phrasing flow;
phrasing; embedded; interactive*; listed; submittable; reassociateable;
formassociated flow

head*; template*;
phrasing* phrasing

varies*

globals

HTMLElement

object

param *; transparent

globals;
data; type; typemustmatch ; name;
usemap ; form;
width ; height

HTMLObjectElement

ol

Ordered list

flow

li ;
scriptsupporting elements option ;
scriptsupporting elements text*

globals;
reversed ;
start ;
type globals;
disabled ;
label globals;
disabled ;
label ; selected;
value globals;
for;
form ;
name

HTMLOListElement

optgroup

Group of options in a list box Option in a list box or combo box control Calculated output value

none

select ; template select ; datalist; optgroup; template phrasing

HTMLOptGroupElement

option

none

HTMLOptionElement

output

flow;
phrasing; listed; labelable; resettable; reassociateable;
formassociated flow none flow

phrasing

HTMLOutputElement

p param pre

Paragraph Parameter for object Block of preformatted text Progress bar Quotation Parenthesis for ruby annotation text Ruby annotation text Ruby annotation(s) Inaccurate text Computer output Embedded script

flow object ; template flow

phrasing empty phrasing

globals globals;
name; value globals

HTMLParagraphElement HTMLParamElement HTMLPreElement

progress q rp

flow;
phrasing; labelable flow;
phrasing none

phrasing phrasing ruby; template

phrasing* phrasing phrasing

globals;
value ; max globals;
cite globals

HTMLProgressElement HTMLQuoteElement HTMLElement

rt

none

ruby; template phrasing phrasing phrasing head; phrasing; scriptsupporting flow

phrasing

globals

HTMLElement

ruby s samp script

flow;
phrasing flow;
phrasing flow;
phrasing metadata;
flow;
phrasing; scriptsupporting flow;
sectioning

phrasing;
rt; rp * phrasing phrasing script, data, or script documentation* flow

globals globals globals globals;


src;
type ;
charset ;
async;
defer; crossorigin globals

HTMLElement HTMLElement HTMLElement HTMLScriptElement

section

Generic document or application section

HTMLElement

http://developers.whatwg.org/section-index.html[4/16/2014 9:32:10 PM]

Index HTML: The Living Standard - Edition for Web Developers

select

List box control

flow;
phrasing; interactive; listed; labelable; submittable; resettable; reassociateable;
formassociated flow;
phrasing none

phrasing

option , optgroup

globals; autofocus ; disabled;


form; multiple;
name; required;
size

HTMLSelectElement

small source

Side comment Media source for video or audio Generic phrasing container Importance Embedded styling information Subscript Caption for details Superscript Table

phrasing video ; audio ; template phrasing

phrasing empty

globals globals;
src;
type ;
media globals

HTMLElement HTMLSourceElement

span

flow;
phrasing

phrasing

HTMLSpanElement

strong style

flow;
phrasing metadata;
flow

phrasing head; noscript*;


flow* phrasing details phrasing flow

phrasing varies*

globals globals;
media ; type;
scoped globals globals globals globals

HTMLElement HTMLStyleElement

sub summary sup table

flow;
phrasing none flow;
phrasing flow

phrasing phrasing phrasing caption*; colgroup*; thead *;


tbody *;
tfoot *;
tr*; scriptsupporting elements tr ;
scriptsupporting elements flow

HTMLElement HTMLElement HTMLElement HTMLTableElement

tbody

Group of rows in a table Table cell

none

table ; template tr ; template metadata; phrasing; scriptsupporting;


colgroup* phrasing

globals

HTMLTableSectionElement

td

sectioning root

globals;
colspan; rowspan; headers globals

HTMLTableDataCellElement

template

Template

metadata;
flow;
phrasing; scriptsupporting flow;
phrasing; interactive; listed; labelable; submittable; resettable; reassociateable;
formassociated

it's complicated*

HTMLTemplateElement

textarea

Multiline text field

text

globals; autofocus ;
cols;
dirname; disabled;
form; maxlength ; minlength ;
name;
placeholder; readonly; required;
rows; wrap globals

HTMLTextAreaElement

tfoot

Group of footer rows in a table Table header cell

none

table ; template tr ; template

tr ;
scriptsupporting elements flow*

HTMLTableSectionElement

th

none

globals;
colspan; rowspan; headers;
scope ; sorted ;
abbr globals

HTMLTableHeaderCellElement

thead

Group of heading rows in a table Machinereadable equivalent of date- or time-

none

table ; template phrasing

tr ;
scriptsupporting elements phrasing

HTMLTableSectionElement

time

flow;
phrasing

globals;
datetime

HTMLTimeElement

http://developers.whatwg.org/section-index.html[4/16/2014 9:32:10 PM]

Index HTML: The Living Standard - Edition for Web Developers

related data title tr Document title Table row metadata none head; template table ; thead ; tbody ; tfoot ; template audio ; video ; template phrasing flow text* th *;
td ;
scriptsupporting elements globals globals HTMLTitleElement HTMLTableRowElement

track

Timed text track Keywords List

none

empty

globals;
default; kind;
label ;
src;
srclang globals globals

HTMLTrackElement

u ul

flow;
phrasing flow

phrasing li ;
scriptsupporting elements phrasing source *; transparent*

HTMLElement HTMLUListElement

var video

Variable Video player

flow;
phrasing flow;
phrasing; embedded; interactive

phrasing phrasing

globals globals;
src; crossorigin; poster ;
preload ;
autoplay; mediagroup ; loop;
muted ; controls;
width ;
height globals

HTMLElement HTMLVideoElement

wbr

Line breaking opportunity

flow;
phrasing

phrasing

empty

HTMLElement

An asterisk (*) in a cell indicates that the actual rules are more
complicated than indicated in the table above.

Categories in the "Parents" column refer to parents that list the given categories in
their content model, not to elements that themselves are in those categories. For example, the
a element's "Parents" column says "phrasing", so any element whose content model
contains the "phrasing" category could be a parent of an a element. Since the "flow"
category includes all the "phrasing" elements, that means the th element could be a
parent to an a element.

Element content categories


List of element content categories Category Metadata content Flow content Elements base;
link;
meta;
noscript;
script ;
style; template;
title a ;
abbr;
address;
article;
aside ;
audio;
b ; bdi;
bdo ;
blockquote;
br;
button ;
canvas; cite;
code;
data;
datalist;
del ;
details;
dfn ;
dialog ;
div;
dl;
em ;
embed;
fieldset;
figure ;
footer ;
form;
h1;
h2 ;
h3;
h4;
h5 ;
h6 ;
header; hgroup ;
hr ;
i;
iframe;
img ;
input;
ins;
kbd; keygen ;
label ;
main;
map;
mark;
math;
menu; meter ;
nav ;
noscript;
object;
ol ;
output;
p ; pre;
progress;
q;
ruby;
s ;
samp;
script; section;
select ;
small;
span;
strong ;
sub; sup;
svg ;
table;
template;
textarea;
time;
u ; ul ;
var ;
video;
wbr;
Text article;
aside ;
nav;
section h1 ;
h2 ;
h3;
h4;
h5 ;
h6;
hgroup a ;
abbr;
audio;
b ;
bdi ;
bdo;
br;
button ;
canvas ;
cite;
code;
data;
datalist;
del;
dfn;
em ; embed ;
i ;
iframe;
img;
input ;
ins;
kbd;
keygen ;
label ;
map;
mark;
math;
meter;
noscript; object ;
output ;
progress;
q ;
ruby;
s;
samp; script ;
select ;
small;
span;
strong ;
sub;
sup Elements with exceptions
area (if it is a descendant of a map element);
link (if the itemprop attribute is present);
meta (if the itemprop attribute is present); style (if the scoped attribute is present)

Sectioning content Heading content Phrasing content


area (if it is a descendant of a map element);
link (if the itemprop attribute is present);
meta (if the itemprop attribute is present)

http://developers.whatwg.org/section-index.html[4/16/2014 9:32:10 PM]

Index HTML: The Living Standard - Edition for Web Developers

;
svg ;
template;
textarea;
time;
u;
var;
video ;
wbr ;
Text Embedded content Interactive content audio
canvas
embed
iframe
img
math
object svg
video a ;
button ;
details;
embed ;
iframe ;
keygen; label ;
select ;
textarea;
audio (if the controls attribute is present);
img (if the usemap attribute is present);
input (if the type attribute is not in the Hidden state);
object (if the usemap attribute is present); video (if the controls attribute is present)

Sectioning roots Formassociated elements Listed elements Submittable elements Resettable elements Labelable elements Reassociateable elements Palpable content

blockquote ;
body;
details;
dialog;
fieldset ;
figure ;
td button ;
fieldset;
input;
keygen;
label ; object ;
output ;
select;
textarea;
img button ;
fieldset;
input;
keygen;
object ; output ;
select ;
textarea button ;
input ;
keygen;
object;
select ; textarea input ;
keygen ;
output;
select;
textarea button ;
input ;
keygen;
meter ;
output ; progress;
select ;
textarea button ;
fieldset;
input;
keygen;
label ; object ;
output ;
select;
textarea a ;
abbr;
address;
article;
aside ;
b;
bdi;
bdo; blockquote ;
button ;
canvas;
cite;
code;
data ;
details ;
dfn;
div;
em ;
embed;
fieldset; figure ;
footer ;
form;
h1;
h2 ;
h3;
h4;
h5 ;
h6 ; header ;
hgroup ;
i;
iframe;
img ;
ins;
kbd; keygen ;
label ;
main;
map;
mark;
math;
meter ; nav;
object ;
output;
p ;
pre ;
progress;
q ;
ruby ;
s ;
samp;
section;
select ;
small;
span; strong ;
sub ;
sup;
svg;
table ;
textarea;
time; u ;
var ;
video





audio (if the controls attribute is present);
dl (if the element's children include at least one name-value group);
input (if the type attribute is not in the Hidden state);
menu (if the type attribute is in the toolbar state); ol (if the element's children include at least one li element); ul (if the element's children include at least one li element); Text that is not inter-element whitespace

Scriptsupporting elements

script ;
template

Attributes
List of attributes (excluding event handler content attributes) Attribute abbr Element(s) th Description Alternative label to use for the header cell when referencing the cell in other contexts Hint for expected file type in file upload controls Character encodings to use for form submission Keyboard shortcut to activate or focus element URL to use for form submission Value Text*

accept

input

Set of comma-separated tokens* consisting of valid MIME types with no parameters or audio/* , video/*, or image/* Ordered set of unique space-separated tokens, ASCII case-insensitive, consisting of labels of ASCII-compatible character encodings* Ordered set of unique space-separated tokens, case-sensitive, consisting of one Unicode code point in length Valid non-empty URL potentially surrounded by spaces

accept-charset form

accesskey

HTML elements form

action

http://developers.whatwg.org/section-index.html[4/16/2014 9:32:10 PM]

Index HTML: The Living Standard - Edition for Web Developers

allowfullscreen iframe

Whether to allow the iframe 's contents to use requestFullscreen() Replacement text for use when images are not available Execute script asynchronously Default setting for autofill feature for controls in the form Hint for form autofill feature Automatically focus the form control when the page is loaded

Boolean attribute

alt

area;
img ; input script form

Text*

async autocomplete

Boolean attribute "on"; "off "

autocomplete

input ; select ; textarea button ; input ; keygen ; select ; textarea audio ;


video

Autofill field name and related tokens*

autofocus

Boolean attribute

autoplay

Hint that the media resource can be started automatically when the page is loaded String to package with the generated and signed public key Character encoding declaration Character encoding of the external script resource Whether the command or control is checked Link to the source of the quotation or more information about the edit Classes to which the element belongs Maximum number of characters per line Number of columns that the cell is to span Command definition Value of the element Whether the element is editable The element's context menu Show user agent controls Coordinates for the shape to be created in an image map How the element handles crossorigin requests Address of the resource Date and (optionally) time of the change Machine-readable value

Boolean attribute

challenge

keygen

Text

charset charset

meta script

Encoding label* Encoding label*

checked cite

menuitem; input blockquote ; del;


ins ;
q

Boolean attribute Valid URL potentially surrounded by spaces

class cols colspan command content

HTML elements textarea td ;


th menuitem meta

Set of space-separated tokens Valid non-negative integer greater than zero Valid non-negative integer greater than zero ID* Text* "true"; "false " ID* Boolean attribute Valid list of integers*

contenteditable HTML elements contextmenu controls coords HTML elements audio ;


video area

crossorigin

audio ;
img ; link;
script ;
video object del;
ins time

"anonymous "; "use-credentials "

data datetime datetime

Valid non-empty URL potentially surrounded by spaces Valid date string with optional time Valid month string,
valid date string, valid yearless date string,
valid time

http://developers.whatwg.org/section-index.html[4/16/2014 9:32:10 PM]

Index HTML: The Living Standard - Edition for Web Developers

string,
valid local date and time string, valid time-zone offset string,
valid global date and time string,
valid week string, valid non-negative integer, or
valid duration string default menuitem Mark the command as being a default command Enable the track if no other text track is more suitable Defer script execution The text directionality of the element Name of form field to use for sending the element's directionality in form submission Whether the form control is disabled Boolean attribute

default

track

Boolean attribute

defer dir dirname

script HTML elements input ; textarea

Boolean attribute "ltr"; "rtl "; "auto" Text*

disabled

button ; menuitem; fieldset; input ; keygen ; optgroup; option ; select ; textarea a ;


area

Boolean attribute

download

Whether to download the resource instead of navigating to it, and its file name if so Whether the element is draggable Accepted item types for drag-and-drop

Text

draggable dropzone

HTML elements HTML elements

"true"; "false " Unordered set of unique space-separated tokens, ASCII case-insensitive, consisting of accepted types and drag feedback* " application/x-www-form-urlencoded "; "multipart/form-data"; " text/plain " ID* Unordered set of unique space-separated tokens, case-sensitive, consisting of IDs* ID*

enctype

form

Form data set encoding type to use for form submission Associate the label with form control Specifies controls from which the output was calculated Associates the control with a form element

for for

label output

form

button ; fieldset; input ; keygen ; label ; object ; output ; select ; textarea button ; input button ; input

formaction formenctype

URL to use for form submission Form data set encoding type to use for form submission HTTP method to use for form submission Bypass form control validation for form submission

Valid non-empty URL potentially surrounded by spaces " application/x-www-form-urlencoded "; "multipart/form-data"; " text/plain " "GET"; "POST" Boolean attribute

formmethod

button ; input

formnovalidate button ; input

http://developers.whatwg.org/section-index.html[4/16/2014 9:32:10 PM]

Index HTML: The Living Standard - Edition for Web Developers

formtarget headers height

button ; input td ;
th canvas ; embed ; iframe ;
img ; input ; object ; video HTML elements meter a ;
area link base a ;
area;
link meta menuitem HTML elements HTML elements input ; textarea img HTML elements HTML elements

Browsing context for form submission The header cells for this cell Vertical dimension

Valid browsing context name or keyword Unordered set of unique space-separated tokens, case-sensitive, consisting of IDs* Valid non-negative integer

hidden high href href href hreflang http-equiv icon id inert inputmode

Whether the element is relevant Low limit of high range Address of the hyperlink Address of the hyperlink Document base URL Language of the linked resource Pragma directive Icon for the command The element's ID Whether the element is inert Hint for selecting an input modality Whether the image is a server-side image map Global identifier for a microdata item Property names of a microdata item

Boolean attribute Valid floating-point number* Valid URL potentially surrounded by spaces Valid non-empty URL potentially surrounded by spaces Valid URL potentially surrounded by spaces Valid BCP 47 language tag Text* Valid non-empty URL potentially surrounded by spaces Text* Boolean attribute verbatim; latin ; latin-name; latin-prose; full-width-latin; kana ; katakana; numeric; tel; email ; url Boolean attribute Valid URL potentially surrounded by spaces Unordered set of unique space-separated tokens, case-sensitive, consisting of valid absolute URLs, defined property names, or text* Unordered set of unique space-separated tokens, case-sensitive, consisting of IDs* Boolean attribute Unordered set of unique space-separated tokens, case-sensitive, consisting of valid absolute URL* Text*

ismap itemid itemprop

itemref itemscope itemtype

HTML elements HTML elements HTML elements keygen

Referenced elements Introduces a microdata item Item types of a microdata item The type of cryptographic key to generate The type of text track

keytype

kind

track

"subtitles ";
"captions";
" descriptions";
"chapters";
"metadata " Text

label

menuitem; menu; optgroup; option ; track HTML elements input audio ;


video

User-visible label

lang list loop

Language of the element List of autocomplete options Whether to loop the media resource

Valid BCP 47 language tag or the empty string ID* Boolean attribute

http://developers.whatwg.org/section-index.html[4/16/2014 9:32:10 PM]

Index HTML: The Living Standard - Edition for Web Developers

low manifest max max maxlength media mediagroup

meter html input meter ; progress input ; textarea link;


source ;
style audio ;
video

High limit of low range Application cache manifest Maximum value Upper bound of range Maximum length of value Applicable media Groups media elements together with an implicit MediaController Specifies the element's designated pop-up menu HTTP method to use for form submission Minimum value Lower bound of range Minimum length of value Whether to allow multiple values Whether to mute the media resource by default Name of form control to use for form submission and in the form.elements API

Valid floating-point number* Valid non-empty URL potentially surrounded by spaces Varies* Valid floating-point number* Valid non-negative integer Valid media query Text

menu

button

ID*

method min min minlength multiple muted

form input meter input ; textarea input ; select audio ;


video

"GET";
"POST ";
"dialog " Varies* Valid floating-point number* Valid non-negative integer Boolean attribute Boolean attribute

name

button ; fieldset; input ; keygen ; output ; select ; textarea form

Text*

name

Name of form to use in the document.forms API Name of nested browsing context Name of image map to reference from the usemap attribute Metadata name Name of parameter Bypass form control validation for form submission Whether the details are visible Whether the dialog box is showing Optimum value in gauge Pattern to be matched by the form control's value URLs to ping User-visible label to be placed within the form control

Text*

name name

iframe ; object map

Valid browsing context name or keyword Text*

name name novalidate

meta param form

Text* Text Boolean attribute

open open optimum pattern

details dialog meter input

Boolean attribute Boolean attribute Valid floating-point number* Regular expression matching the JavaScript Pattern production Set of space-separated tokens consisting of valid non-empty URLs Text*

ping placeholder

a ;
area input ; textarea

http://developers.whatwg.org/section-index.html[4/16/2014 9:32:10 PM]

Index HTML: The Living Standard - Edition for Web Developers

poster preload

video audio ;
video

Poster frame to show prior to video playback Hints how much buffering the media resource will likely need Name of group of commands to treat as a radio button group Whether to allow the value to be edited by the user Relationship between the document containing the hyperlink and the destination resource Whether the control is required for form submission Number the list backwards Number of lines to show Number of rows that the cell is to span Security rules for nested content

Valid non-empty URL potentially surrounded by spaces "none";


"metadata";
"auto"

radiogroup

menuitem

Text

readonly

input ; textarea a ;
area;
link

Boolean attribute

rel

Set of space-separated tokens*

required

input ; select ; textarea ol textarea td ;


th iframe

Boolean attribute

reversed rows rowspan sandbox

Boolean attribute Valid non-negative integer greater than zero Valid non-negative integer Unordered set of unique space-separated tokens, ASCII case-insensitive, consisting of
"allow-forms",
" allow-pointer-lock ",
"allow-popups ",
"allow-same-origin ",
" allow-scripts and
" allow-top-navigation" "true"; "false "

spellcheck

HTML elements th

Whether the element is to have its spelling and grammar checked Specifies which cells the header cell applies to Whether the styles apply to the entire document or just the parent subtree Whether to apply the document's styles to the nested content Whether the option is selected by default The kind of shape to be created in an image map Size of the control Sizes of the icons (for rel="icon") Column sort direction and ordinality

scope

"row";
"col ";
"rowgroup";
"colgroup"

scoped

style

Boolean attribute

seamless

iframe

Boolean attribute

selected shape

option area

Boolean attribute "circle";


"default ";
"poly";
"rect"

size sizes

input ; select link

Valid non-negative integer greater than zero Unordered set of unique space-separated tokens, ASCII case-insensitive, consisting of sizes* Set of space-separated tokens, ASCII case-insensitive, consisting of neither, one, or both of "reversed" and a valid non-negative integer greater than zero Valid non-negative integer greater than zero Valid non-empty URL potentially surrounded by spaces

sorted

th

span

col; colgroup audio ;


embed ;
iframe ;
img ;
input ;

Number of columns spanned by the element Address of the resource

src

http://developers.whatwg.org/section-index.html[4/16/2014 9:32:10 PM]

Index HTML: The Living Standard - Edition for Web Developers

script ; source ; track ;


video srcdoc srclang srcset iframe track img A document to render in the iframe Language of the text track Images to use in different situations (e.g. high-resolution displays, small monitors, etc) Ordinal value of the first item Granularity to be matched by the form control's value Presentational and formatting instructions Whether the element is focusable, and the relative order of the element for the purposes of sequential focus navigation Browsing context for hyperlink navigation Default browsing context for hyperlink navigation and form submission Browsing context for form submission Advisory information for the element Full term or expansion of abbreviation Hint describing the command Title of the link Alternative style sheet set name Whether the element is to be translated when the page is localized Hint for the type of the referenced resource Type of button Type of embedded resource The source of an iframe srcdoc document* Valid BCP 47 language tag Comma-separated list of image candidate strings

start step

ol input

Valid integer Valid floating-point number greater than zero, or "any " CSS declarations*

style

HTML elements HTML elements

tabindex

Valid integer

target target

a ;
area base

Valid browsing context name or keyword Valid browsing context name or keyword

target title title title title title translate

form HTML elements abbr;


dfn menuitem link link;
style HTML elements

Valid browsing context name or keyword Text Text Text Text Text "yes"; "no "

type type type

a ;
area;
link button embed ; object ; script ; source ; style input menu menuitem ol object

Valid MIME type "submit";


"reset ";
"button ";
"menu" Valid MIME type

type type type type typemustmatch

Type of form control Type of menu Type of command Kind of list marker Whether the type attribute and the Content-Type value need to match for the resource to be used

input type keyword "popup "; "toolbar " "command";


"checkbox";
"radio " "1 ";
"a ";
"A ";
"i ";
"I " Boolean attribute

http://developers.whatwg.org/section-index.html[4/16/2014 9:32:10 PM]

Index HTML: The Living Standard - Edition for Web Developers

usemap value value value value value value width

img;
object button ; option data input li meter ; progress param canvas ; embed ; iframe ;
img ; input ; object ; video textarea

Name of image map to use Value to be used for form submission Machine-readable value Value of the form control Ordinal value of the list item Current value of the element Value of parameter Horizontal dimension

Valid hash-name reference* Text Text* Varies* Valid integer Valid floating-point number Text Valid non-negative integer

wrap

How the value of the form control is to be wrapped for form submission

"soft";
"hard "

An asterisk (*) in a cell indicates that the actual rules are more
complicated than indicated in the table above.

List of event handler content attributes Attribute onabort onafterprint onbeforeprint onbeforeunload onblur oncancel oncanplay Element(s) HTML elements body body body HTML elements HTML elements HTML elements Description abort event handler afterprint event handler for Window object beforeprint event handler for Window object beforeunload event handler for Window object blur event handler cancel event handler canplay event handler canplaythrough event handler change event handler click event handler close event handler contextmenu event handler cuechange event handler dblclick event handler drag event handler dragend event handler dragenter event handler Value Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute

oncanplaythrough HTML elements onchange onclick onclose oncontextmenu oncuechange ondblclick ondrag ondragend ondragenter HTML elements HTML elements HTML elements HTML elements HTML elements HTML elements HTML elements HTML elements HTML elements

http://developers.whatwg.org/section-index.html[4/16/2014 9:32:10 PM]

Index HTML: The Living Standard - Edition for Web Developers

ondragexit ondragleave ondragover ondragstart ondrop

HTML elements HTML elements HTML elements HTML elements HTML elements

dragexit event handler dragleave event handler dragover event handler dragstart event handler drop event handler durationchange event handler emptied event handler ended event handler error event handler focus event handler hashchange event handler for Window object input event handler invalid event handler keydown event handler keypress event handler keyup event handler load event handler loadeddata event handler loadedmetadata event handler loadstart event handler message event handler for Window object mousedown event handler mouseenter event handler mouseleave event handler mousemove event handler mouseout event handler mouseover event handler mouseup event handler mousewheel event handler offline event handler for Window object online event handler for Window object

Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute

ondurationchange HTML elements onemptied onended onerror onfocus onhashchange oninput oninvalid onkeydown onkeypress onkeyup onload onloadeddata HTML elements HTML elements HTML elements HTML elements body HTML elements HTML elements HTML elements HTML elements HTML elements HTML elements HTML elements

onloadedmetadata HTML elements onloadstart onmessage onmousedown onmouseenter onmouseleave onmousemove onmouseout onmouseover onmouseup onmousewheel onoffline ononline HTML elements body HTML elements HTML elements HTML elements HTML elements HTML elements HTML elements HTML elements HTML elements body body

http://developers.whatwg.org/section-index.html[4/16/2014 9:32:10 PM]

Index HTML: The Living Standard - Edition for Web Developers

onpagehide onpageshow onpause onplay onplaying onpopstate onprogress onratechange onreset onresize onscroll onseeked onseeking onselect onshow onsort onstalled onstorage onsubmit onsuspend ontimeupdate ontoggle onunload onvolumechange onwaiting

body body HTML elements HTML elements HTML elements body HTML elements HTML elements HTML elements body HTML elements HTML elements HTML elements HTML elements HTML elements HTML elements HTML elements body HTML elements HTML elements HTML elements HTML elements body HTML elements HTML elements

pagehide event handler for Window object pageshow event handler for Window object pause event handler play event handler playing event handler popstate event handler for Window object progress event handler ratechange event handler reset event handler resize event handler for Window object scroll event handler seeked event handler seeking event handler select event handler show event handler sort event handler stalled event handler storage event handler for Window object submit event handler suspend event handler timeupdate event handler toggle event handler unload event handler for Window object volumechange event handler waiting event handler

Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute Event handler content attribute

Element Interfaces
List of interfaces for elements Element(s) a abbr address area article Interface(s) HTMLAnchorElement : HTMLElement HTMLElement HTMLElement HTMLAreaElement : HTMLElement HTMLElement

http://developers.whatwg.org/section-index.html[4/16/2014 9:32:10 PM]

Index HTML: The Living Standard - Edition for Web Developers

aside audio b base bdi bdo blockquote body br button canvas caption cite code col colgroup menuitem data datalist dd del details dfn dialog div dl dt em embed fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 head header hgroup hr html i iframe img input ins kbd

HTMLElement HTMLAudioElement : HTMLMediaElement : HTMLElement HTMLElement HTMLBaseElement : HTMLElement HTMLElement HTMLElement HTMLQuoteElement : HTMLElement HTMLBodyElement : HTMLElement HTMLBRElement : HTMLElement HTMLButtonElement : HTMLElement HTMLCanvasElement : HTMLElement HTMLTableCaptionElement : HTMLElement HTMLElement HTMLElement HTMLTableColElement : HTMLElement HTMLTableColElement : HTMLElement HTMLMenuItemElement : HTMLElement HTMLDataElement : HTMLElement HTMLDataListElement : HTMLElement HTMLElement HTMLModElement : HTMLElement HTMLDetailsElement : HTMLElement HTMLElement HTMLDialogElement : HTMLElement HTMLDivElement : HTMLElement HTMLDListElement : HTMLElement HTMLElement HTMLElement HTMLEmbedElement : HTMLElement HTMLFieldSetElement : HTMLElement HTMLElement HTMLElement HTMLElement HTMLFormElement : HTMLElement HTMLHeadingElement : HTMLElement HTMLHeadingElement : HTMLElement HTMLHeadingElement : HTMLElement HTMLHeadingElement : HTMLElement HTMLHeadingElement : HTMLElement HTMLHeadingElement : HTMLElement HTMLHeadElement : HTMLElement HTMLElement HTMLElement HTMLHRElement : HTMLElement HTMLHtmlElement : HTMLElement HTMLElement HTMLIFrameElement : HTMLElement HTMLImageElement : HTMLElement HTMLInputElement : HTMLElement HTMLModElement : HTMLElement HTMLElement

http://developers.whatwg.org/section-index.html[4/16/2014 9:32:10 PM]

Index HTML: The Living Standard - Edition for Web Developers

keygen label legend li link main map mark menu meta meter nav noscript object ol optgroup option output p param pre progress q rp rt ruby s samp script section select small source span strong style sub summary sup table tbody td template textarea tfoot th thead time title tr track

HTMLKeygenElement : HTMLElement HTMLLabelElement : HTMLElement HTMLLegendElement : HTMLElement HTMLLIElement : HTMLElement HTMLLinkElement : HTMLElement HTMLElement HTMLMapElement : HTMLElement HTMLElement HTMLMenuElement : HTMLElement HTMLMetaElement : HTMLElement HTMLMeterElement : HTMLElement HTMLElement HTMLElement HTMLObjectElement : HTMLElement HTMLOListElement : HTMLElement HTMLOptGroupElement : HTMLElement HTMLOptionElement : HTMLElement HTMLOutputElement : HTMLElement HTMLParagraphElement : HTMLElement HTMLParamElement : HTMLElement HTMLPreElement : HTMLElement HTMLProgressElement : HTMLElement HTMLQuoteElement : HTMLElement HTMLElement HTMLElement HTMLElement HTMLElement HTMLElement HTMLScriptElement : HTMLElement HTMLElement HTMLSelectElement : HTMLElement HTMLElement HTMLSourceElement : HTMLElement HTMLSpanElement : HTMLElement HTMLElement HTMLStyleElement : HTMLElement HTMLElement HTMLElement HTMLElement HTMLTableElement : HTMLElement HTMLTableSectionElement : HTMLElement HTMLTableDataCellElement : HTMLTableCellElement : HTMLElement HTMLTemplateElement : HTMLElement HTMLTextAreaElement : HTMLElement HTMLTableSectionElement : HTMLElement HTMLTableHeaderCellElement : HTMLTableCellElement : HTMLElement HTMLTableSectionElement : HTMLElement HTMLTimeElement : HTMLElement HTMLTitleElement : HTMLElement HTMLTableRowElement : HTMLElement HTMLTrackElement : HTMLElement

http://developers.whatwg.org/section-index.html[4/16/2014 9:32:10 PM]

Index HTML: The Living Standard - Edition for Web Developers

u ul var video wbr

HTMLElement HTMLUListElement : HTMLElement HTMLElement HTMLVideoElement : HTMLMediaElement : HTMLElement HTMLElement

All Interfaces Events


List of events Event abort afterprint beforeprint beforeunload Interface Event Event Event BeforeUnloadEvent Description Fired at the Window when the download was aborted by the user Fired at the Window after printing Fired at the Window before printing Fired at the Window when the page is about to be unloaded, in case the page would like to show a warning prompt Fired at nodes losing focus Fired at controls when the user commits a value change Fired at an element before its activation behavior is run Fired at elements when the user requests their context menu Fired at the Document once the parser has finished Fired at elements when network and script errors occur Fired at nodes gaining focus Fired at the Window when the fragment identifier part of the document's address changes Fired at controls when the user changes the value Fired at controls during form validation if they do not satisfy their constraints Fired at the Window when the document has finished loading; fired at an element containing a resource (e.g. img, embed) when its resource has finished loading Fired at an object when the object receives a message Fired at the Window when the network connections fails Fired at the Window when the network connections returns Fired at the Window when the page's entry in the session history stops being the current entry Fired at the Window when the page's entry in the session history becomes the current entry Fired at the Window when the user navigates the session history Fired at the Document when it finishes parsing and again when all its subresources have finished loading Fired at a form element when it is reset Fired at a menu element when it is shown as a context menu Fired at a form element when it is submitted Fired at the Window object when the page is going away

blur change click contextmenu DOMContentLoaded error focus hashchange input invalid load

Event Event Event Event Event Event Event HashChangeEvent Event Event Event

message offline online pagehide pageshow popstate readystatechange reset show submit unload events.

MessageEvent Event Event PageTransitionEvent PageTransitionEvent PopStateEvent Event Event Event Event Event

See also media element


events, application cache events,
and drag-and-drop

http://developers.whatwg.org/section-index.html[4/16/2014 9:32:10 PM]

Index HTML: The Living Standard - Edition for Web Developers

Up next

References

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/section-index.html[4/16/2014 9:32:10 PM]

References HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

REFERENCES
All references are normative unless marked "Non-normative". [ABNF] Augmented BNF for Syntax Specifications: ABNF, D. Crocker, P. Overell. IETF. [ABOUT] The 'about' URI scheme, S. Moonesamy. IETF. [AGIF] (Non-normative) GIF Application Extension: NETSCAPE2.0. R. Frazier. [APNG] (Non-normative) APNG Specification. S. Parmenter, V. Vukicevic, A. Smith. Mozilla. [ARIA] Accessible Rich Internet Applications (WAI-ARIA), J. Craig, M. Cooper, L. Pappas, R. Schwerdtfeger, L. Seeman. W3C. [ARIAIMPL] WAI-ARIA 1.0 User Agent Implementation Guide, A. Snow-Weaver, M. Cooper. W3C. [ATAG] (Non-normative) Authoring Tool Accessibility Guidelines (ATAG) 2.0, J. Richards, J. Spellman, J. Treviranus. W3C. [ATOM] (Non-normative) The Atom Syndication Format, M. Nottingham, R. Sayre. IETF. [BCP47] Tags for Identifying Languages; Matching of Language Tags, A. Phillips, M.

http://developers.whatwg.org/references.html[4/16/2014 9:33:16 PM]

References HTML: The Living Standard - Edition for Web Developers

Davis. IETF. [BECSS] Behavioral Extensions to CSS, I. Hickson. W3C. [BEZIER] Courbes poles, P. de Casteljau. INPI, 1959. [BIDI] UAX #9: Unicode Bidirectional Algorithm, M. Davis. Unicode Consortium. [BOCU1] (Non-normative) UTN #6: BOCU-1: MIME-Compatible Unicode Compression, M. Scherer, M. Davis. Unicode Consortium. [CESU8] (Non-normative) UTR #26: Compatibility Encoding Scheme For UTF-16: 8BIT (CESU-8), T. Phipps. Unicode Consortium. [CHARMOD] (Non-normative) Character Model for the World Wide Web 1.0: Fundamentals, M. Drst, F. Yergeau, R. Ishida, M. Wolf, T. Texin. W3C. [CLDR] Unicode Common Locale Data Repository. Unicode. [COMPOSITE] Compositing and Blending. R. Cabanier, N. Andronikos. W3C. [COOKIES] HTTP State Management Mechanism, A. Barth. IETF. [CORS] Cross-Origin Resource Sharing, A. van Kesteren. WHATWG. [CP50220] (Non-normative) CP50220, Y. Naruse. IANA. [CSP] (Non-normative) Content Security Policy, B. Sterne, A. Barth. W3C. [CSS] Cascading Style Sheets Level 2 Revision 1, B. Bos, T. elik, I. Hickson, H. Lie. W3C. [CSSANIMATIONS] (Non-normative) CSS Animations, D. Jackson, D. Hyatt, C. Marrin, S. Galineau, L. Baron. W3C. [CSSATTR] CSS Styling Attribute Syntax, T. elik, E. Etemad. W3C.

http://developers.whatwg.org/references.html[4/16/2014 9:33:16 PM]

References HTML: The Living Standard - Edition for Web Developers

[CSSCOLOR] CSS Color Module Level 3, T. elik, C. Lilley, L. Baron. W3C. [CSSFONTLOAD] CSS Font Load Events, J. Daggett. W3C. [CSSFONTS] CSS Fonts, J. Daggett. W3C. [CSSIMAGES] CSS Image Values and Replaced Content Module, E. Etemad, T. Atkins. W3C. [CSSOM] Cascading Style Sheets Object Model (CSSOM), S. Pieters, G. Adams. W3C. [CSSOMVIEW] CSSOM View Module, S. Pieters, G. Adams. W3C. [CSSRUBY] CSS3 Ruby Module, R. Ishida. W3C. [CSSTRANSITIONS] (Non-normative) CSS Transitions, D. Jackson, D. Hyatt, C. Marrin, L. Baron. W3C. [CSSUI] CSS3 Basic User Interface Module, T. elik. W3C. [CSSSCOPED] CSS Scoped Style Sheets, T. Atkins. Your Imagination. [CSSVALUES] CSS3 Values and Units, H. Lie, T. Atkins, E. Etemad. W3C. [DASH] Dynamic adaptive streaming over HTTP (DASH). ISO. [DOM] DOM, A. van Kesteren, A. Gregor, Ms2ger. WHATWG. [DOMEVENTS] Document Object Model (DOM) Level 3 Events Specification, T. Leithead, J. Rossi, D. Schepers, B. Hhrmann, P. Le Hgaret, T. Pixley. W3C. [DOMPARSING] DOM Parsing and Serialization, Ms2ger. WHATWG. [DOT] (Non-normative) The DOT Language. Graphviz. [E163] Recommendation E.163 Numbering Plan for The International Telephone
http://developers.whatwg.org/references.html[4/16/2014 9:33:16 PM]

References HTML: The Living Standard - Edition for Web Developers

Service, CCITT Blue Book, Fascicle II.2, pp. 128-134, November 1988. [ECMA262] ECMAScript Language Specification. ECMA. [ECMA357] (Non-normative) ECMAScript for XML (E4X) Specification. ECMA. [EDITING] HTML Editing APIs, A. Gregor. W3C Editing APIs CG. [ENCODING] Encoding, A. van Kesteren, J. Bell. WHATWG. [FILEAPI] File API, A. Ranganathan. W3C. [FULLSCREEN] Fullscreen, A. van Kesteren, T. elik. WHATWG. [GIF] (Non-normative) Graphics Interchange Format. CompuServe. [GRAPHICS] (Non-normative) Computer Graphics: Principles and Practice in C, Second Edition, J. Foley, A. van Dam, S. Feiner, J. Hughes. Addison-Wesley. ISBN 0201-84840-6. [GREGORIAN] (Non-normative) Inter Gravissimas, A. Lilius, C. Clavius. Gregory XIII Papal Bull, February 1582. [HTML] HTML, I. Hickson. WHATWG. [HTTP] Hypertext Transfer Protocol HTTP/1.1, R. Fielding, J. Gettys, J. Mogul, H. Frystyk, L. Masinter, P. Leach, T. Berners-Lee. IETF. [HTTPS] (Non-normative) HTTP Over TLS, E. Rescorla. IETF. [IANAPERMHEADERS] Permanent Message Header Field Names. IANA. [ISO3166] ISO 3166: Codes for the representation of names of countries and their subdivisions. ISO. [ISO8601] (Non-normative) ISO8601: Data elements and interchange formats
http://developers.whatwg.org/references.html[4/16/2014 9:33:16 PM]

References HTML: The Living Standard - Edition for Web Developers

Information interchange Representation of dates and times. ISO. [JLREQ] Requirements for Japanese Text Layout. W3C. [JPEG] JPEG File Interchange Format, E. Hamilton. [JSON] The application/json Media Type for JavaScript Object Notation (JSON), D. Crockford. IETF. [JSURL] The 'javascript' resource identifier scheme, B. Hhrmann. IETF. [MAILTO] (Non-normative) The 'mailto' URI scheme, M. Duerst, L. Masinter, J. Zawinski. IETF. [MATHML] Mathematical Markup Language (MathML), D. Carlisle, P. Ion, R. Miner, N. Poppelier. W3C. [MEDIAFRAG] Media Fragments URI, R. Troncy, E. Mannens, S. Pfeiffer, D. Van Deursen. W3C. [MFREL] Microformats Wiki: existing rel values. Microformats. [MIMESNIFF] MIME Sniffing, G. Hemsley. WHATWG. [MNG] MNG (Multiple-image Network Graphics) Format. G. Randers-Pehrson. [MPEG2] ISO/IEC 13818-1: Information technology Generic coding of moving pictures and associated audio information: Systems. ISO/IEC. [MPEG4] ISO/IEC 14496-12: ISO base media file format. ISO/IEC. [MQ] Media Queries, H. Lie, T. elik, D. Glazman, A. van Kesteren. W3C. [NPAPI] (Non-normative) Gecko Plugin API Reference. Mozilla. [OGGSKELETONHEADERS] SkeletonHeaders. Xiph.Org.

http://developers.whatwg.org/references.html[4/16/2014 9:33:16 PM]

References HTML: The Living Standard - Edition for Web Developers

[OPENSEARCH] Autodiscovery in HTML/XHTML. In OpenSearch 1.1 Draft 4, Section 4.6.2. OpenSearch.org. [ORIGIN] The Web Origin Concept, A. Barth. IETF. [PAGEVIS] (Non-normative) Page Visibility, J. Mann, A. Jain. W3C. [PDF] (Non-normative) Document management Portable document format Part 1: PDF. ISO. [PINGBACK] Pingback 1.0, S. Langridge, I. Hickson. [PNG] Portable Network Graphics (PNG) Specification, D. Duce. W3C. [POINTERLOCK] Pointer Lock, V. Scheib. W3C. [PPUTF8] (Non-normative) The Properties and Promises of UTF-8, M. Drst. University of Zrich. In Proceedings of the 11th International Unicode Conference. [PSL] Public Suffix List.
Mozilla Foundation. [RFC1034] Domain Names - Concepts and Facilities, P. Mockapetris. IETF, November 1987. [RFC1123] Requirements for Internet Hosts -- Application and Support, R. Braden. IETF, October 1989. [RFC1345] (Non-normative) Character Mnemonics and Character Sets, K. Simonsen. IETF. [RFC1468] (Non-normative) Japanese Character Encoding for Internet Messages, J. Murai, M. Crispin, E. van der Poel. IETF. [RFC1554] (Non-normative) ISO-2022-JP-2: Multilingual Extension of ISO-2022-JP, M. Ohta, K. Handa. IETF.

http://developers.whatwg.org/references.html[4/16/2014 9:33:16 PM]

References HTML: The Living Standard - Edition for Web Developers

[RFC1557] (Non-normative) Korean Character Encoding for Internet Messages, U. Choi, K. Chon, H. Park. IETF. [RFC1842] (Non-normative) ASCII Printable Characters-Based Chinese Character Encoding for Internet Messages, Y. Wei, Y. Zhang, J. Li, J. Ding, Y. Jiang. IETF. [RFC1922] (Non-normative) Chinese Character Encoding for Internet Messages, HF. Zhu, DY. Hu, ZG. Wang, TC. Kao, WCH. Chang, M. Crispin. IETF. [RFC2046] Multipurpose Internet Mail Extensions (MIME) Part Two: Media Types, N. Freed, N. Borenstein. IETF. [RFC2119] Key words for use in RFCs to Indicate Requirement Levels, S. Bradner. IETF. [RFC2237] (Non-normative) Japanese Character Encoding for Internet Messages, K. Tamaru. IETF. [RFC2313] PKCS #1: RSA Encryption, B. Kaliski. IETF. [RFC2318] The text/css Media Type, H. Lie, B. Bos, C. Lilley. IETF. [RFC2388] Returning Values from Forms: multipart/form-data, L. Masinter. IETF. [RFC2397] The "data" URL scheme, L. Masinter. IETF. [RFC2445] Internet Calendaring and Scheduling Core Object Specification (iCalendar), F. Dawson, D. Stenerson. IETF. [RFC2483] URI Resolution Services Necessary for URN Resolution, M. Mealling, R. Daniel. IETF. [RFC3676] The Text/Plain Format and DelSp Parameters, R. Gellens. IETF. [RFC3023] XML Media Types, M. Murata, S. St. Laurent, D. Kohn. IETF.

http://developers.whatwg.org/references.html[4/16/2014 9:33:16 PM]

References HTML: The Living Standard - Edition for Web Developers

[RFC3279] Algorithms and Identifiers for the Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile, W. Polk, R. Housley, L. Bassham. IETF. [RFC3490] Internationalizing Domain Names in Applications (IDNA), P. Faltstrom, P. Hoffman, A. Costello. IETF. [RFC3629] UTF-8, a transformation format of ISO 10646, F. Yergeau. IETF. [RFC3864] Registration Procedures for Message Header Fields, G. Klyne, M. Nottingham, J. Mogul. IETF. [RFC4281] The Codecs Parameter for "Bucket" Media Types, R. Gellens, D. Singer, P. Frojdh. IETF. [RFC4395] Guidelines and Registration Procedures for New URI Schemes, T. Hansen, T. Hardie, L. Masinter. IETF. [RFC4648] The Base16, Base32, and Base64 Data Encodings, S. Josefsson. IETF. [RFC5280] Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile, D. Cooper, S. Santesson, S. Farrell, S. Boeyen, R. Housley, W. Polk. IETF. [RFC5322] Internet Message Format, P. Resnick. IETF. [RFC5724] URI Scheme for Global System for Mobile Communications (GSM) Short Message Service (SMS), E. Wilde, A. Vaha-Sipila. IETF. [RFC6266] Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP), J. Reschke. IETF. [RFC6350] vCard Format Specification, S. Perreault. IETF. [SCSU] (Non-normative) UTR #6: A Standard Compression Scheme For Unicode, M. Wolf, K. Whistler, C. Wicksteed, M. Davis, A. Freytag, M. Scherer. Unicode

http://developers.whatwg.org/references.html[4/16/2014 9:33:16 PM]

References HTML: The Living Standard - Edition for Web Developers

Consortium. [SELECTORS] Selectors, E. Etemad, T. elik, D. Glazman, I. Hickson, P. Linss, J. Williams. W3C. [SRGB] IEC 61966-2-1: Multimedia systems and equipment Colour measurement and management Part 2-1: Colour management Default RGB colour space sRGB. IEC. [SVG] Scalable Vector Graphics (SVG) Tiny 1.2 Specification, O. Andersson, R. Berjon, E. Dahlstrm, A. Emmons, J. Ferraiolo, A. Grasso, V. Hardy, S. Hayman, D. Jackson, C. Lilley, C. McCormack, A. Neumann, C. Northway, A. Quint, N. Ramani, D. Schepers, A. Shellshear. W3C. [TOR] (Non-normative) Tor. [TYPEDARRAY] Typed Array Specification, D. Herman, K. Russell. Khronos. [TZDATABASE] (Non-normative) Time Zone Database. IANA. [UAAG] (Non-normative) User Agent Accessibility Guidelines (UAAG) 2.0, J. Allan, K. Ford, J. Richards, J. Spellman. W3C. [UCA] UTR #10: Unicode Collation Algorithm, M. Davis, K. Whistler. Unicode Consortium. [UNDO] UndoManager and DOM Transaction, R. Niwa. [UNICODE] The Unicode Standard. Unicode Consortium. [UNIVCHARDET] (Non-normative) A composite approach to language/encoding detection, S. Li, K. Momoi. Netscape. In Proceedings of the 19th International Unicode Conference. [URL] URL, A. van Kesteren. WHATWG. [UTF7] (Non-normative) UTF-7: A Mail-Safe Transformation Format of Unicode, D.
http://developers.whatwg.org/references.html[4/16/2014 9:33:16 PM]

References HTML: The Living Standard - Edition for Web Developers

Goldsmith, M. Davis. IETF. [UTF8DET] (Non-normative) Multilingual form encoding, M. Drst. W3C. [UTR36] (Non-normative) UTR #36: Unicode Security Considerations, M. Davis, M. Suignard. Unicode Consortium. [WCAG] (Non-normative) Web Content Accessibility Guidelines (WCAG) 2.0, B. Caldwell, M. Cooper, L. Reid, G. Vanderheiden. W3C. [WEBGL] WebGL Specification, D. Jackson. Khronos Group. [WEBIDL] Web IDL, C. McCormack. W3C. [WEBLINK] Web Linking, M. Nottingham. IETF. [WEBMCG] WebM Container Guidelines. The WebM Project. [WEBSTORAGE] Web Storage, I. Hickson. W3C. [WEBVTT] WebVTT, I. Hickson. W3C. [WEBWORKERS] Web Workers, I. Hickson. W3C. [WHATWGWIKI] The WHATWG Wiki. WHATWG. [WSP] The WebSocket protocol, I. Fette, A. Melnikov. IETF. [X121] Recommendation X.121 International Numbering Plan for Public Data Networks, CCITT Blue Book, Fascicle VIII.3, pp. 317-332. [X690] Recommendation X.690 Information Technology ASN.1 Encoding Rules Specification of Basic Encoding Rules (BER), Canonical Encoding Rules (CER), and Distinguished Encoding Rules (DER). International Telecommunication Union. [XFN]

http://developers.whatwg.org/references.html[4/16/2014 9:33:16 PM]

References HTML: The Living Standard - Edition for Web Developers

XFN 1.1 profile, T. elik, M. Mullenweg, E. Meyer. GMPG. [XHR] XMLHttpRequest , A. van Kesteren. WHATWG. [XML] Extensible Markup Language, T. Bray, J. Paoli, C. Sperberg-McQueen, E. Maler, F. Yergeau. W3C. [XMLBASE] XML Base, J. Marsh, R. Tobin. W3C. [XMLNS] Namespaces in XML, T. Bray, D. Hollander, A. Layman, R. Tobin. W3C. [XPATH10] XML Path Language (XPath) Version 1.0, J. Clark, S. DeRose. W3C. [XSLT10] (Non-normative) XSL Transformations (XSLT) Version 1.0, J. Clark. W3C.

Up next

Acknowledgments

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/references.html[4/16/2014 9:33:16 PM]

Acknowledgments HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ACKNOWLEDGMENTS
Thanks to Tim Berners-Lee for inventing HTML, without which none
of this would exist. Thanks to
Aankhen,
Aaron Boodman,
Aaron Leventhal,
Adam Barth,
Adam de Boor,
Adam Hepton,
Adam Klein,
Adam Roben,
Addison Phillips,
Adele Peterson,
Adrian Bateman,
Adrian Sutton,
Agustn Fernndez,
Aharon (Vladimir) Lanin,
Ajai Tirumali,
Akatsuki Kitamura,
Alan Plum,
Alastair Campbell,
Alejandro G. Castro,
Alex Bishop,
Alex Nicolaou,
Alex Rousskov, Alexander Farkas,
Alexander J. Vincent,
Alexandre Morgaut,
Alexey Feldgendler,
&Acy;&lcy;&iecy;&kcy;&scy;&iecy;&jcy; &Pcy;&rcy;&ocy;&scy;&kcy;&ucy;&rcy;&yacy;&kcy;&ocy;&vcy; (Alexey Proskuryakov),
Alexis Deveria,
Allan Clements,
Amos Jeffries,
Anders Carlsson,
Andreas,
Andreas Kling,
Andrei Popescu,
Andr E. Veltstra,
Andrew Barfield,
Andrew Clover,
Andrew Gove,
Andrew Grieve,
Andrew Oakley, Andrew Sidwell,
Andrew Simons,
Andrew Smith,
Andrew W. Hagen,
Andrey V. Lukyanov,
Andry Rendy,
Andy Earnshaw,
Andy Heydon,
Andy Palay,
Anne van Kesteren,
Anthony Boyd,
Anthony Bryan,
Anthony Hickson,
Anthony Ricaud,
Antti Koivisto,
Arne Thomassen,
Aron Spohr,
Arphen Lin,
Arthur Stolyar,
Arun Patole,
Aryeh Gregor,
Asbjrn Ulsberg,
Ashley Gullen,
Ashley Sheridan,
Atsushi Takayama,
Aurelien Levy,
Ave Wrigley,
Axel Dahmen,
Ben Boyle,
Ben Godfrey,
Ben Lerner,
Ben Leslie,
Ben Meadowcroft,
Ben Millard, Benjamin Carl Wiley Sittler,
Benjamin Hawkes-Lewis,
Benoit Ren,
Bert Bos, Bijan Parsia,
Bil Corry,
Bill Mason,
Bill McCoy,
Billy Wong,
Bjartur Thorlacius,
Bjrn Hhrmann,
Blake Frantz,
Bob Lund,
Bob Owen,
Boris Zbarsky,
Brad Fults,
Brad Neuberg,
Brad Spencer,
Brady Eidson,
Brendan Eich,
Brenton Simpson,
Brett Wilson,
Brett Zamir,
Brian Campbell,
Brian Korver,
Brian Kuhn,
Brian M. Dube,
Brian Ryner,
Brian Smith,
Brian Wilson, Bryan Sullivan,
Bruce Bailey,
Bruce D'Arcus,
Bruce Lawson,
Bruce Miller,
C. Williams,
Cameron McCormack,
Cameron Zemek,
Cao Yipeng,
Carlos

http://developers.whatwg.org/acknowledgments.html[4/16/2014 9:34:17 PM]

Acknowledgments HTML: The Living Standard - Edition for Web Developers

Amengual,
Carlos Gabriel Cardona,
Carlos Perell Marn,
Chao Cai,
(Channy Yun),
Charl van Niekerk,
Charles Iliya Krempeaux,
Charles McCathieNevile,
Chris Apers,
Chris Cressman,
Chris Evans,
Chris Morris, Chris Pearce,
Chris Peterson,
Chris Weber,
Christian Biesinger,
Christian Johansen,
Christian Schmidt,
Christoph Pper,
Christophe Dumez, Christopher Aillon,
Christopher Ferris,
Chriswa,
Clark Buehler,
Cole Robison,
Colin Fine,
Collin Jackson,
Corprew Reed,
Craig Cockburn,
Csaba Gabor, Csaba Marton,
Cynthia Shelly,
Dan Yoder,
Daniel Barclay,
Daniel Bratell, Daniel Brooks,
Daniel Brumbaugh Keeney,
Daniel Cheng,
Daniel Davis, Daniel Glazman,
Daniel Peng,
Daniel Schattenkirchner,
Daniel Spng,
Daniel Steinberg,
Daniel Trebbien,
Danny Sullivan,
Darin Adler,
Darin Fisher, Darxus,
Dave Camp,
Dave Hodder,
Dave Lampton,
Dave Singer,
Dave Townsend,
David Baron,
David Bloom,
David Bruant,
David Carlisle,
David E. Cleary,
David Egan Evans,
David Flanagan,
David Gerard,
David Hsther, David Hyatt,
David I. Lehn,
David John Burrowes,
David Kendal,
David Matja,
David Remahl,
David Smith,
David Woolley,
DeWitt Clinton,
Dean Edridge,
Dean Edwards,
Debi Orton,
Derek Featherstone,
Devarshi Pant, Devdatta,
Dimitri Glazkov,
Dimitry Golubovsky,
Dirk Pranke,
Dirk Schulze, Dirkjan Ochtman,
Divya Manian,
Dmitry Titov,
dolphinling,
Domenic Denicola,
Dominique Hazal-Massieux,
Don Brutzman,
Doron Rosenberg, Doug Kramer,
Doug Simpkinson,
Drew Wilson,
Edmund Lai,
Eduard Pascual,
Eduardo Vela,
Edward O'Connor,
Edward Welbourne,
Edward Z. Yang,
Ehsan Akhgari,
Eira Monstad,
Eitan Adler,
Eliot Graff,
Elisabeth Robson,
Elizabeth Castro,
Elliott Sprehn,
Elliotte Harold,
Eric Carlson,
Eric Lawrence,
Eric Rescorla,
Eric Semling,
Erik Arvidsson,
Erik Rose,
Evan Martin,
Evan Prodromou,
Evert,
fantasai,
Felix Sasaki,
Francesco Schwarz,
Francis Brosnan Blazquez,
Franck 'Shift' Qulain,
Frank Barchard,
(Fumitoshi Ukai), Futomi Hatano,
Gavin Carothers,
Gavin Kistner,
Gareth Rees,
Garrett Smith, Geoff Richards,
Geoffrey Garen,
Geoffrey Sneddon,
George Lund,
Gianmarco Armellin,
Giovanni Campagna,
Giuseppe Pascale,
Glenn Adams,
Glenn Maynard,
Graham Klyne,
Greg Botten,
Greg Houston,
Greg Wilkins,
Gregg Tavares,
Gregory J. Rosmaita,
Grey,
Guilherme Johansson Tramontina,
Gytis Jakutonis,
Hkon Wium Lie,
Hallvord Reiar Michaelsen Steen,
Hans S. Tmmerhalt,
Hans Stimer,
Harald Alvestrand,
Henri Sivonen,
Henrik Lied, Henry Mason,
Hugh Guiney,
Hugh Winkler,
Ian Bicking,
Ian Clelland,
Ian Davis,
Ian Fette,
Ido Green,
Ignacio Javier,
Ivan Enderlin,
Ivo Emanuel Gonalves,
J. King,
Jacob Davies,
Jacques Distler,
Jake Verbaten,
Jakub &Lstrok;opusza&nacute;ski,
James Craig,
James Graham,
James Greene, James Justin Harrell,
James Kozianski,
James M Snell,
James Perrett,
James Robinson,
Jamie Lokier,
Janusz Majnert,
Jan-Klaas Kollhof,
Jared Jacobs,

http://developers.whatwg.org/acknowledgments.html[4/16/2014 9:34:17 PM]

Acknowledgments HTML: The Living Standard - Edition for Web Developers

Jason Duell,
Jason Kersey,
Jason Lustig,
Jason White,
Jasper Bryant-Greene, Jasper St. Pierre,
Jatinder Mann,
Jed Hartman,
Jeff Balogh,
Jeff Cutsinger, Jeff Schiller,
Jeff Walden,
Jeffrey Zeldman,
(Jennifer Braithwaite), Jens Bannmann,
Jens Fendler,
Jens Lindstrm,
Jens Meiert,
Jeremey Hustman,
Jeremy Keith,
Jeremy Orlow,
Jeroen van der Meer,
Jian Li,
Jim Jewett,
Jim Ley,
Jim Meehan,
Jim Michaels,
Jirka Kosek,
Jjgod Jiang,
Joo Eiras,
Joe Clark,
Joe Gregorio,
Joel Spolsky,
Joel Verhagen,
Johan Herland, John Boyer,
John Bussjaeger,
John Carpenter,
John Daggett,
John Fallows, John Foliot,
John Harding,
John Keiser,
John Snyders,
John Stockton,
JohnMark Bell,
Johnny Stenback,
Jon Ferraiolo,
Jon Gibbins,
Jon Perlow,
Jonas Sicking,
Jonathan Cook,
Jonathan Rees,
Jonathan Watt,
Jonathan Worent, Jonny Axelsson,
Jordan Tucker,
Jorgen Horstink,
Jorunn Danielsen Newth, Joseph Kesselman,
Joseph Mansfield,
Joseph Pecoraro,
Josh Aas,
Josh Hart, Josh Levenberg,
Joshua Bell,
Joshua Randall,
Jukka K. Korpela,
Jules Novosad,
Justin Schuh,
Justin Sinclair,
Ka-Sing Chou,
Kai Hendry,
(KangHao Lu),
Kartikaya Gupta,
Kathy Walton,
Kelly Ford,
Kelly Norton, Kevin Benson,
Kevin Gadd,
Kevin Cole,
Kornl Pl,
Kornel Lesinski,
Kris Northfield,
Kristof Zelechovski,
Krzysztof Maczy&nacute;ski,
(Kurosawa Takeshi),
Kyle Barnhart,
Kyle Hofmann,
Kyle Huey,
Lonard Bouchet,
Lonie Watson,
Lachlan Hunt,
Larry Masinter,
Larry Page,
Lars Gunther,
Lars Solberg,
Laura Carlson,
Laura Granka,
Laura L. Carlson,
Laura Wisewell,
Laurens Holst,
Lawrence Forooghian,
Lee Kowalkowski,
Leif Halvard Silli,
Lenny Domnitser,
Leonard Rosenthol,
Leons Petrazickis, Lobotom Dysmon,
Logan,
Loune,
Luke Kenneth Casson Leighton,
Maciej Stachowiak,
Magnus Kristiansen,
Maik Merten,
Malcolm Rowe,
Manish Tripathi,
Marcus Bointon,
Mark Birbeck,
Mark Davis,
Mark Miller,
Mark Nottingham,
Mark Pilgrim,
Mark Rowe,
Mark Schenk,
Mark Vickers,
Mark Wilton-Jones,
Martijn Wargers,
Martin Atkins,
Martin Drst,
Martin Honnen,
Martin Janecke,
Martin Kutschker,
Martin Nilsson,
Martin Thomson,
Masataka Yakura,
Mathias Bynens,
Mathieu Henri,
Matias Larsson,
Matt Falkenhagen,
Matt Schmidt,
Matt Wright,
Matthew Gregan, Matthew Mastracci,
Matthew Raymond,
Matthew Thomas,
Mattias Waldau, Max Romantschuk,
Menno van Slooten,
Micah Dubinko,
Michael 'Ratt' Iannarelli,
Michael A. Nachbaur,
Michael A. Puls II,
Michael Carter,
Michael Daskalov,
Michael Day,
Michael Dyck,
Michael Enright,
Michael Gratton, Michael Nordman,
Michael Powers,
Michael Rakowski,
Michael(tm) Smith, Michal Zalewski,
Michel Fortin,
Michelangelo De Simone,
Michiel van der Blonk,
Mihai &Scedil;ucan,
Mihai Parparita,
Mike Brown,
Mike Dierken, Mike Dixon,
Mike Hearn,
Mike Schinkel,
Mike Shaver,
Mikko Rantalainen, Clment-Ripoche,
Julian Reschke,
Jrgen Jeka,
Justin Lebar,
Justin

http://developers.whatwg.org/acknowledgments.html[4/16/2014 9:34:17 PM]

Acknowledgments HTML: The Living Standard - Edition for Web Developers

Mohamed Zergaoui,
Mohammad Al Houssami,
Mounir Lamouri,
Ms2ger, Nadia Heninger,
NARUSE Yui,
Neil Deakin,
Neil Rashbrook,
Neil Soiffer, Nicholas Shanks,
Nicholas Stimpson,
Nicholas Zakas,
Nickolay Ponomarev, Nicolas Gallagher,
Noah Mendelsohn,
Noah Slater,
Noel Gordon,
Nolan Waite,
NoozNooz42,
Norbert Lindenberg,
Ojan Vafai,
Olaf Hoffmann,
Olav Junker Kjr,
Old&rcaron;ich Vetenk,
Oli Studholme,
Oliver Hunt,
Oliver Rigby,
Olivier Gendrin,
Olli Pettay,
oSand, Pablo Flouret,
Patrick Garies, Patrick H. Lauke,
Patrik Persson,
Paul Adenot,
Paul Norman,
Per-Erik Brodin,
Perry Smith,
Peter Beverloo,
Peter Karlsson,
Peter Kasting,
Peter Moulder,
Peter Occil,
Peter Stark,
Peter Van der Beken,
Peter-Paul Koch,
Phil
Prateek Rungta,
Pravir Gupta,
(Pujun Li),
Rachid Finge,
Rafael Pickering,
Philip Jgenstedt,
Philip Taylor,
Philip TAYLOR,
Philippe De Ryck, Weinstein,
Rafa&lstrok; Mi&lstrok;ecki,
Raj Doshi,
Rajas Moonka,
Ralf Stoltze,
Ralph Giles,
Raphael Champeimont,
Remci Mizkur,
Remco,
Remy Sharp,
Rene Saarsoo,
Rene Stach,
Ric Hardacre,
Rich Clark,
Rich Doughty, Richard Ishida,
Rigo Wenning,
Rikkert Koppes,
Rimantas Liubertas,
Riona Macnamara,
Rob Ennals,
Rob Jellinghaus,
Rob S,
Robert Blaut,
Robert Collins,
Robert Kieffer,
Robert Millan,
Robert O'Callahan,
Robert Sayre, Robin Berjon,
Rodger Combs,
Roland Steiner,
Roma Matusevich,
Roman Ivanov,
Roy Fielding,
Ruud Steltenpool,
Ryan King,
Ryosuke Niwa,
S. Mike Dierken,
Salvatore Loreto,
Sam Dutton,
Sam Kuper,
Sam Ruby,
Sam Weinig, Samuel Bronson,
Samy Kamkar,
Sander van Lambalgen,
Sarven Capadisli, Scott Gonzlez,
Scott Hess,
Sean Fraser,
Sean Hayes,
Sean Hogan,
Sean Knapp,
Sebastian Markbge,
Sebastian Schnitzenbaumer,
Seth Call,
Seth Dillingham,
Shanti Rao,
Shaun Inman,
Shiki Okasaka,
Sierk Bornemann, Sigbjrn Vik,
Silver Ghost, Silvia Pfeiffer,
ime Vidas,
Simon Montagu,
Simon Pieters,
Simon Spiegel,
skeww, Smylers,
Stanton McCandlish,
Stefan Hkansson,
Stefan Haustein,
Stefan Santesson,
Stefan Weiss,
Steffen Meschkat,
Stephen Ma,
Stephen White,
Steve Comstock,
Steve Faulkner, Steve Runyon,
Steven Bennett,
Steven Garrity,
Steven Tate,
Stewart Brodie, Stuart Ballard,
Stuart Langridge,
Stuart Parmenter,
Subramanian Peruvemba,
Sunava Dutta,
Susan Borgrink,
Susan Lesch,
Sylvain Pasche,
T. J. Crowder, Tab Atkins,
Takeshi Yoshino,
Tantek elik,
(TAMURA Kent),
Ted Mielczarek,
Terrence Wood,
Thijs van der Vossen,
Thomas Broyer,
Thomas Koetter,
Thomas O'Connor,
Tim Altman,
Tim Johansson,
TJ VanToll,
Toby Inkster,
Todd Moody,
Tom Baker,
Tom Pike,
Tommy Thorsen,
Tony Ross, Travis Leithead,
Tyler Close,
Victor Carbune,
Vitya Muhachev,
Vladimir Katardjiev,
Vladimir Vuki&cacute;evi&cacute;,
voracity,
Wakaba,
Wayne Carr,
Wayne Pollock,
Wellington Fernando de Macedo,
Weston Ruter, Wilhelm Joys Andersen,
Will Levine,
William Swanson,
Wladimir Palant,

http://developers.whatwg.org/acknowledgments.html[4/16/2014 9:34:17 PM]

Acknowledgments HTML: The Living Standard - Edition for Web Developers

Wojciech Mach,
Wolfram Kriesing,
Xan Gregg,
Yang Chen,
Ye-Kui Wang, Yehuda Katz,
Yi-An Huang,
Yngve Nysaeter Pettersen,
Yonathan Randolph, Yuzo Fujishima,
Zhenbin Xu,
Zoltan Herczeg,
and
istein E. Andersen,
for their useful comments, both large and small, that have led to changes to this specification
over the years. Thanks also to everyone who has ever posted about HTML to their blogs, public mailing lists, or
forums, including all the contributors to the various W3C HTML WG lists and the various WHATWG
lists. Special thanks to Richard Williamson for creating the first implementation of canvas in Safari, from which the canvas feature was designed. Special thanks also to the Microsoft employees who first implemented the event-based
drag-and-drop mechanism, contenteditable, and other features first widely deployed by the Windows Internet Explorer browser. Thanks to the participants of the microdata usability study for allowing us to use their
mistakes as a guide for designing the microdata feature. Thanks to the many sources that provided inspiration for the examples used in the
specification. The image of two cute kittens in a basket used in the context menu example is based on
a photo
by Alex G.
(CC BY 2.0) The Blue Robot Player sprite used in the canvas demo is based on
a work by JohnColburn.
(CC BY-SA 3.0) Thanks also to the Microsoft blogging community for some ideas, to the attendees of the W3C
Workshop on Web Applications and Compound Documents for inspiration, to the #mrt crew, the #mrt.no
crew, and the #whatwg crew, and to Pillar and Hedral for their ideas and support.

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/acknowledgments.html[4/16/2014 9:34:17 PM]

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
In this section In this section

Search. Press '/'

Content models
Each element defined in this specification has a content model: a description of the element's
expected contents. An HTML
element must have contents that match the requirements described in the element's content
model. The contents of an element are its children in the
DOM, except for template elements, where the children are those in the template
contents (a separate DocumentFragment assigned to the element when the element
is created). The space characters are always allowed between elements.
User agents represent these characters between elements in the source markup as Text nodes in the DOM. Empty
Text nodes and Text nodes consisting of just sequences of those
characters are considered inter-element whitespace. Inter-element whitespace, comment nodes, and processing instruction nodes must be
ignored when establishing whether an element's contents match the element's content model or not,
and must be ignored when following algorithms that define document and element semantics. Thus, an element A is said to be preceded or followed
by a second element B if A and B have
the same parent node and there are no other element nodes or Text nodes (other than
inter-element whitespace) between them. Similarly, a node is the only child of
an element if that element contains no other nodes other than inter-element
whitespace, comment nodes, and processing instruction nodes. Authors must not use HTML elements anywhere except where they are explicitly
allowed, as defined for each element, or as explicitly required by other specifications. For XML
compound documents, these contexts could be inside elements from other namespaces, if those
elements are defined as providing the relevant contexts. For example, the Atom specification defines a content element. When its type attribute has the value xhtml, the Atom
specification requires that it contain a single HTML div element. Thus, a
div element is allowed in that context, even though this is not explicitly
normatively stated by this
http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]
(Non-normative) The Atom Syndication Format, M. Nottingham, R. Sayre. IETF.

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

specification. In addition, HTML elements may be orphan nodes (i.e. without a parent node). For example, creating a td element and storing it in a global variable in a script is conforming, even though td elements are otherwise only supposed to be used
inside tr elements. var data = { name: "Banana", cell: document.createElement('td'), };

Kinds of content
Each element in HTML falls into zero or more categories
that group elements with similar characteristics together. The following broad categories are used in this specification:

Metadata content Flow content Sectioning content Heading content Phrasing content Embedded content Interactive content
Some elements also fall into other categories, which are defined in other parts of
this specification. These categories are related as follows:

http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

Sectioning content, heading content, phrasing content, embedded content, and interactive
content are all types of flow content. Metadata is sometimes flow content. Metadata and
interactive content are sometimes phrasing content. Embedded content is also a type of phrasing
content, and sometimes is interactive content. Other categories are also used for specific purposes, e.g. form controls are specified using a
number of categories to define common requirements. Some elements have unique requirements and do
not fit into any particular category.

Metadata content Metadata content is content that sets up the presentation or behavior of the rest of
the content, or that sets up the relationship of the document with other documents, or that
conveys other "out of band" information.

base link meta noscript script style template title


Elements from other namespaces whose semantics are primarily metadatarelated (e.g. RDF) are
also metadata content. Thus, in the XML serialization, one can use RDF, like this: <html xmlns="http://www.w3.org/1999/xhtml" xmlns:r="http://www.w3.org/1999/02/22-rdf-syntax-ns#"> <head> <title>Hedral's Home Page</title> <r:RDF> <Person xmlns="http://www.w3.org/2000/10/swap/pim/contact#" r:about="http://hedral.example.com/#"> <fullName>Cat Hedral</fullName> <mailbox r:resource="mailto:hedral@damowmow.com"/> <personalTitle>Sir</personalTitle> </Person> </r:RDF> </head> <body> <h1>My home page</h1> <p>I like playing with string, I guess. Sister says squirrels are fun
http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

too so sometimes I follow her to play with them.</p> </body> </html> This isn't possible in the HTML serialization, however.

Flow content Most elements that are used in the body of documents and applications are categorized as
flow content.

a abbr address area (if it is a descendant of a map element) article aside audio b bdi bdo blockquote br button canvas cite code data datalist del details dfn dialog div dl em embed fieldset figure footer form h1 h2 h3 h4 h5 h6
http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

header hgroup hr i iframe img input ins kbd keygen label link (if the itemprop attribute is present) main map mark math menu meta (if the itemprop attribute is present) meter nav noscript object ol output p pre progress q ruby s samp script section select small span strong style (if the scoped attribute is present) sub sup svg table template textarea time u ul
http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

var video wbr Text

Sectioning content Sectioning content is content that defines the scope of headings and footers.

article aside nav section


Each sectioning content element potentially has a heading and an
outline. See the section on headings and sections for further
details. There are also certain elements that are sectioning
roots. These are distinct from sectioning content, but they can also have an
outline.

Heading content Heading content defines the header of a section (whether explicitly marked up using
sectioning content elements, or implied by the heading content itself).

h1 h2 h3 h4 h5 h6 hgroup

Phrasing content Phrasing content is the text of the document, as well as elements that mark up that
text at the intra-paragraph level. Runs of phrasing content form paragraphs.

a abbr area (if it is a descendant of a map element) audio b bdi bdo


http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

br button canvas cite code data datalist del dfn em embed i iframe img input ins kbd keygen label link (if the itemprop attribute is present) map mark math meta (if the itemprop attribute is present) meter noscript object output progress q ruby s samp script select small span strong sub sup svg template textarea time u var video
http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

wbr Text
Most elements that are categorized as phrasing content can only contain elements
that are themselves categorized as phrasing content, not any flow content. Text, in the context of content models, means either nothing,
or Text nodes. Text is sometimes used as a content
model on its own, but is also phrasing content, and can be inter-element
whitespace (if the Text nodes are empty or contain just space characters). Text nodes and attribute values must consist of Unicode characters, must not contain U+0000 characters, must not contain
permanently undefined Unicode characters (noncharacters), and must not contain control characters other than space characters.
This specification includes extra constraints on the exact value of Text nodes and
attribute values depending on their precise context.

Embedded content Embedded content is content that imports another


resource into the document, or content from another vocabulary that
is inserted into the document.

audio canvas embed iframe img math object svg video


Elements that are from namespaces other than the HTML namespace and that convey
content but not metadata, are embedded content for the purposes of the content models
defined in this specification. (For example, MathML, or SVG.) Some embedded content elements can have fallback content: content that is to be used
when the external resource cannot be used (e.g. because it is of an unsupported format). The
element definitions state what the fallback is, if any.

http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

Interactive content Interactive content is content that is specifically


intended for user interaction.

a audio (if the controls attribute is present) button details embed iframe img (if the usemap attribute is present) input (if the type attribute is not in the Hidden state) keygen label object (if the usemap attribute is present) select textarea video (if the controls attribute is present)
Certain elements in HTML have an activation behavior, which means that the user
can activate them. This triggers a sequence of events dependent on the activation mechanism, and
normally culminating in a click event.

Palpable content As a general rule, elements whose content model allows any flow content or phrasing content should have at least one node in its contents that is palpable
content and that does not have the hidden attribute
specified. This requirement is not a hard requirement, however, as there are many cases where an element
can be empty legitimately, for example when it is used as a placeholder which will later be filled
in by a script, or when the element is part of a template and would on most pages be filled in but
on some pages is not relevant. Conformance checkers are encouraged to provide a mechanism for authors to find elements that
fail to fulfill this requirement, as an authoring aid. The following elements are palpable content:

a abbr address article aside audio (if the controls attribute is present) b
http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

bdi bdo blockquote button canvas cite code data details dfn div dl (if the element's children include at least one name-value group) em embed fieldset figure footer form h1 h2 h3 h4 h5 h6 header hgroup i iframe img input (if the type attribute is not in the Hidden state) ins kbd keygen label main map mark math menu (if the type attribute is in the toolbar state) meter nav object ol (if the element's children include at least one li element) output p pre progress
http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

q ruby s samp section select small span strong sub sup svg table textarea time u ul (if the element's children include at least one li element) var video Text that is not inter-element whitespace

Script-supporting elements Script-supporting elements are those that do not represent anything themselves (i.e. they are not rendered), but are used
to support scripts, e.g. to provide functionality for the user. The following elements are script-supporting elements:

script template

Transparent content models


Some elements are described as transparent; they have "transparent" in the description of their content model. The content model of a transparent element is
derived from the content model of its parent element: the elements required in the part of the
content model that is "transparent" are the same elements as required in the part of the content
model of the parent of the transparent element in which the transparent element finds itself. For instance, an ins element inside a ruby element cannot contain an
rt element, because the part of the ruby element's content model that
allows ins elements is the part that allows phrasing content, and the
rt element is not phrasing content.
http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

In some cases, where transparent elements are nested in each other, the process
has to be applied iteratively. Consider the following markup fragment: <p><object><param><ins><map><a href="/">Apples</a></map></ins></object></p> To check whether "Apples" is allowed inside the a element, the content models are
examined. The a element's content model is transparent, as is the map element's, as is the ins element's, as is the part of the object
element's in which the ins element is found. The object element is
found in the p element, whose content model is phrasing content. Thus,
"Apples" is allowed, as text is phrasing content. When a transparent element has no parent, then the part of its content model that is
"transparent" must instead be treated as accepting any flow content.

Paragraphs
The term paragraph as defined in this section is used for more than
just the definition of the p element. The paragraph concept defined here
is used to describe how to interpret documents. The p element is merely one of
several ways of marking up a paragraph. A paragraph is typically a run of phrasing content that forms a block
of text with one or more sentences that discuss a particular topic, as in typography, but can also
be used for more general thematic grouping. For instance, an address is also a paragraph, as is a
part of a form, a byline, or a stanza in a poem. In the following example, there are two paragraphs in a section. There is also a heading,
which contains phrasing content that is not a paragraph. Note how the comments and
inter-element whitespace do not form paragraphs. <section> <h1>Example of paragraphs</h1> This is the <em>first</em> paragraph in this example. <p>This is the second.</p> <!-- This is not a paragraph. --> </section> Paragraphs in flow content are defined relative to what the document looks like
without the a , ins, del, and map elements
complicating matters, since
http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

those elements, with their hybrid content models, can straddle


paragraph boundaries, as shown in the first two examples below. Generally, having elements straddle paragraph boundaries is best avoided. Maintaining such markup can be difficult. The following example takes the markup from the earlier example and puts ins and
del elements around some of the markup to show that the text was changed (though in
this case, the changes admittedly don't make much sense). Notice how this example has exactly the
same paragraphs as the previous one, despite the ins and del elements
the ins element straddles the heading and the first paragraph, and the
del element straddles the boundary between the two paragraphs. <section> <ins><h1>Example of paragraphs</h1> This is the <em>first</em> paragraph in</ins> this example<del>. <p>This is the second.</p></del> <!-- This is not a paragraph. --> </section> A paragraph is also formed explicitly by p elements. The p element can be used to wrap individual paragraphs when there
would otherwise not be any content other than phrasing content to separate the paragraphs from
each other. In the following example, the link spans half of the first paragraph, all of the heading
separating the two paragraphs, and half of the second paragraph. It straddles the paragraphs and
the heading. <header> Welcome! <a href="about.html"> This is home of... <h1>The Falcons!</h1> The Lockheed Martin multirole jet fighter aircraft! </a> This page discusses the F-16 Fighting Falcon's innermost secrets. </header> Here is another way of marking this up, this time showing the paragraphs explicitly, and
splitting the one link element into three: <header> <p>Welcome! <a href="about.html">This is home of...</a></p> <h1><a href="about.html">The Falcons!</a></h1>
http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

<p><a href="about.html">The Lockheed Martin multirole jet fighter aircraft!</a> This page discusses the F-16 Fighting Falcon's innermost secrets.</p> </header> It is possible for paragraphs to overlap when using certain elements that define fallback
content. For example, in the following section: <section> <h1>My Cats</h1> You can play with my cat simulator. <object data="cats.sim"> To see the cat simulator, use one of the following links: <ul> <li><a href="cats.sim">Download simulator file</a> <li><a href="http://sims.example.com/watch?v=LYds5xY4INU">Use online simulator</a> </ul> Alternatively, upgrade to the Mellblom Browser. </object> I'm quite proud of it. </section> There are five paragraphs:
1. The paragraph that says "You can play with my cat simulator. object I'm
quite proud of it.", where object is 2. 3. 4. 5.

the object element. The paragraph that says "To see the cat simulator, use one of the following links:". The paragraph that says "Download simulator file". The paragraph that says "Use online simulator". The paragraph that says "Alternatively, upgrade to the Mellblom Browser.". The first paragraph is overlapped by the other four. A user agent that supports the "cats.sim"
resource will only show the first one, but a user agent that shows the fallback will confusingly
show the first sentence of the first paragraph as if it was in the same paragraph as the second
one, and will show the last paragraph as if it was at the start of the second sentence of the
first paragraph. To avoid this confusion, explicit p elements can be used. For example:

<section> <h1>My Cats</h1> <p>You can play with my cat simulator.</p> <object data="cats.sim"> <p>To see the cat simulator, use one of the following links:</p> <ul> <li><a href="cats.sim">Download simulator file</a> <li><a href="http://sims.example.com/watch?v=LYds5xY4INU">Use online simulator</a> </ul>
http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

<p>Alternatively, upgrade to the Mellblom Browser.</p> </object> <p>I'm quite proud of it.</p> </section>

Global attributes
The following attributes are common to and may be specified on all HTML elements:

accesskey class contenteditable contextmenu dir draggable dropzone hidden id inert itemid itemprop itemref itemscope itemtype lang spellcheck style tabindex title translate
To enable assistive technology products to expose a more fine-grained interface than is
otherwise possible with HTML elements and attributes, a set of annotations
for assistive technology products can be specified (the ARIA role and aria-* attributes). The following event handler content attributes may be specified on any HTML element:
Accessible Rich Internet Applications (WAI-ARIA), J. Craig, M. Cooper, L. Pappas, R. Schwerdtfeger, L. Seeman. W3C.

onabort onblur* oncancel oncanplay oncanplaythrough onchange


http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

onclick onclose oncontextmenu oncuechange ondblclick ondrag ondragend ondragenter ondragexit ondragleave ondragover ondragstart ondrop ondurationchange onemptied onended onerror* onfocus* oninput oninvalid onkeydown onkeypress onkeyup onload* onloadeddata onloadedmetadata onloadstart onmousedown onmouseenter onmouseleave onmousemove onmouseout onmouseover onmouseup onmousewheel onpause onplay onplaying onprogress onratechange onreset onscroll* onseeked onseeking onselect onshow onsort
http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

onstalled onsubmit onsuspend ontimeupdate ontoggle onvolumechange onwaiting


The attributes marked with an asterisk have a different meaning when specified on
body elements as those elements expose event handlers of the Window object with the same names. While these attributes apply to all elements, they are not useful on all elements.
For example, only media elements will ever receive a volumechange event fired by the user agent. Custom data attributes (e.g. data-foldername or data-msgid ) can be specified on any HTML element, to store custom data specific to the page. In HTML documents, elements in the HTML namespace may have an xmlns attribute specified, if, and only if, it has the exact value
" http://www.w3.org/1999/xhtml". This does not apply to XML
documents. In HTML, the xmlns attribute has absolutely no effect. It is
basically a talisman. It is allowed merely to make migration to and from XHTML mildly easier. When
parsed by an HTML parser, the attribute ends up in no namespace, not the
" http://www.w3.org/2000/xmlns/" namespace like namespace declaration attributes in
XML do. In XML, an xmlns attribute is part of the namespace
declaration mechanism, and an element cannot actually have an xmlns
attribute in no namespace specified. The XML specification also allows the use of the xml:space
attribute in the XML namespace on any element in an XML
document. This attribute has no effect on HTML elements, as the default
behavior in HTML is to preserve whitespace. There is no way to serialize the xml:space
attribute on HTML elements in the text/html syntax.
Extensible Markup Language, T. Bray, J. Paoli, C. SperbergMcQueen, E. Maler, F. Yergeau. W3C.

The id attribute
The id attribute specifies its element's unique identifier (ID).
http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]
DOM, A. van Kesteren, A.

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers
Gregor, Ms2ger. WHATWG.

The value must be unique amongst all the IDs in the element's
home subtree and must contain at least one character. The value must not contain any
space characters. There are no other restrictions on what form an ID can take; in particular, IDs can consist of just digits, start with a digit, start with an underscore, consist of just
punctuation, etc. An element's unique identifier can be used for a
variety of purposes, most notably as a way to link to specific parts of a document using fragment identifiers, as a way to target an element when scripting, and as a way to style a specific
element from CSS.

The title attribute


The title attribute represents advisory
information for the element, such as would be appropriate for a tooltip. On a link, this could be
the title or a description of the target resource; on an image, it could be the image credit or a
description of the image; on a paragraph, it could be a footnote or commentary on the text; on a
citation, it could be further information about the source; on interactive content,
it could be a label for, or instructions for, use of the element; and so forth. The value is
text. Relying on the title attribute is currently
discouraged as many user agents do not expose the attribute in an accessible manner as required by
this specification (e.g. requiring a pointing device such as a mouse to cause a tooltip to appear,
which excludes keyboard-only users and touch-only users, such as anyone with a modern phone or
tablet). If this attribute is omitted from an element, then it implies that the title attribute of the nearest ancestor HTML
element with a title attribute set is also relevant to this
element. Setting the attribute overrides this, explicitly stating that the advisory information of
any ancestors is not relevant to this element. Setting the attribute to the empty string indicates
that the element has no advisory information. If the title attribute's value contains U+000A LINE FEED (LF)
characters, the content is split into multiple lines. Each U+000A LINE FEED (LF) character
represents a line break. Caution is advised with respect to the use of newlines in title attributes. For instance, the following snippet actually defines an abbreviation's
http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

expansion with a
line break in it: <p>My logs show that there was some interest in <abbr title="Hypertext Transport Protocol">HTTP</abbr> today.</p> Some elements, such as link, abbr, and input , define
additional semantics for the title attribute beyond the semantics
described above.

The lang and xml:lang attributes


The lang attribute (in no namespace) specifies the
primary language for the element's contents and for any of the element's attributes that contain
text. Its value must be a valid BCP 47 language tag, or the empty string. Setting the attribute to
the empty string indicates that the primary language is unknown. The lang attribute in the XML
namespace is defined in XML. [XML] If these attributes are omitted from an element, then the language of this element is the same
as the language of its parent element, if any. The lang attribute in no namespace may be used on any HTML element. The lang attribute in the XML
namespace may be used on HTML elements in XML documents,
as well as elements in other namespaces if the relevant specifications allow it (in particular,
MathML and SVG allow lang attributes in the
XML namespace to be specified on their elements). If both the lang attribute in no namespace and the lang attribute in the XML namespace are specified on the same
element, they must have exactly the same value when compared in an ASCII
case-insensitive manner. Authors must not use the lang attribute in
the XML namespace on HTML elements in HTML
documents. To ease migration to and from XHTML, authors may specify an attribute in no
namespace with no prefix and with the literal localname "xml:lang" on
HTML elements in HTML documents, but such attributes must only be
specified if a lang attribute in no namespace is also specified,
and both attributes must have the same value when compared in an ASCII
case-insensitive manner. The attribute in no namespace with no prefix and with the literal localname " xml:lang" has no effect on language processing.
Tags for Identifying Languages; Matching of Language Tags, A. Phillips, M. Davis. IETF.

The translate attribute


The translate attribute is an enumerated
attribute that is used to specify
http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

whether an element's attribute values and the values of


its Text node children are to be translated when the page is localized, or whether to
leave them unchanged. The attribute's keywords are the empty string, yes, and no . The empty string and the yes keyword map to the
yes state. The no keyword maps to the no state. In addition,
there is a third state, the inherit state, which is the missing value default (and
the invalid value default). Each element (even non-HTML elements) has a translation mode, which is in either the
translate-enabled state or the no-translate state. If an HTML element's translate
attribute is in the yes state, then the element's translation mode is in the
translate-enabled state; otherwise, if the element's translate attribute is in the no state, then the element's
translation mode is in the no-translate state. Otherwise, either the
element's translate attribute is in the inherit state,
or the element is not an HTML element and thus does not have a
translate attribute; in either case, the element's
translation mode is in the same state as its parent element's, if any, or in the
translate-enabled state, if the element is a root element. When an element is in the translate-enabled state, the element's translatable attributes and the values of its Text node children are to be translated when the page is localized. When an element is in the no-translate state, the element's attribute values and the
values of its Text node children are to be left as-is when the page is localized,
e.g. because the element contains a person's name or a the name of a computer program. The following attributes are translatable attributes:

abbr on th elements alt on area,


img, and
input elements content on meta elements, if the name attribute specifies a metadata name whose value is known to be
translatable

download on a and
area elements label on menuitem,
menu,
optgroup,
option , and
track elements lang on HTML elements; must be "translated" to match the language used in the translation placeholder on input and
textarea elements srcdoc on iframe elements; must be parsed and recursively processed style on HTML elements elements; must be parsed and recursively processed (e.g. for the values of
'content' properties)

title on all HTML elements elements


In this example, everything in the document is to be translated when the page is localized,
except the sample keyboard input and sample program output:
http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

<!DOCTYPE HTML> <html> <!-- default on the root element is translate=yes --> <head> <title>The Bee Game</title> <!-- implied translate=yes inherited from ancestors --> </head> <body> <p>The Bee Game is a text adventure game in English.</p> <p>When the game launches, the first thing you should do is type <kbd translate=no>eat honey</kbd>. The game will respond with:</p> <pre><samp translate=no>Yum yum! That was some good honey!</samp></pre> </body> </html>

The xml:base attribute (XML only)


The xml:base attribute is defined in XML Base. The xml:base attribute may be used on HTML
elements of XML documents. Authors must not use the xml:base attribute on HTML elements in HTML documents.
XML Base, J. Marsh, R. Tobin. W3C.

The dir attribute


The dir attribute specifies the element's text directionality.
The attribute is an enumerated attribute with the following keywords and states: The ltr keyword, which maps to the ltr state Indicates that the contents of the element are explicitly
directionally embedded left-to-right text. The rtl keyword, which maps to the rtl state Indicates that the contents of the element are explicitly
directionally embedded right-to-left text. The auto keyword, which maps to the auto state Indicates that the contents of the element are explicitly embedded text, but that the
direction is to be determined programmatically using the contents of the element (as described
below). The heuristic used by this state is very crude (it just looks at the first
character with a strong directionality, in a manner analogous to the Paragraph Level determination in the bidirectional algorithm). Authors are urged to only use this value as a
last resort when the direction of the text is truly unknown and
http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]
UAX #9: Unicode Bidirectional Algorithm, M. Davis. Unicode Consortium.

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

no better server-side heuristic


can be applied. For textarea and pre elements, the heuristic is
applied on a per-paragraph level. The attribute has no invalid value default and no missing value default. The directionality of an element (any element, not just an HTML element) is either 'ltr' or 'rtl', and is determined as per the first appropriate set of steps from
the following list: If the element's dir attribute is in the ltr state If the element is a root element and the dir
attribute is not in a defined state (i.e. it is not present or has an invalid value) If the element is an input element whose type attribute is in the Telephone state, and the dir attribute is not in a defined state (i.e. it is not present or has an invalid value) The directionality of the element is 'ltr'. If the element's dir attribute is in the rtl state The directionality of the element is 'rtl'. If the element is an input element whose type attribute is in the Text, Search,
Telephone, URL,
or E-mail state, and the dir attribute is in the auto
state If the element is a textarea element and the dir
attribute is in the auto state If the element's value contains a character of
bidirectional character type AL or R, and there is no character of bidirectional character type
L anywhere before it in the element's value, then
the directionality of the element is 'rtl'. [BIDI] Otherwise, if the element's value is not the empty
string, or if the element is a root element, the directionality of the
element is 'ltr'. Otherwise, the directionality of the element is the same as the element's parent
element's directionality. If the element's dir attribute is in the auto state If the element is a bdi element and the dir
attribute is not in a defined state (i.e. it is not present or has an invalid value) Find the first character in tree order that matches the following criteria:

The character is from a Text node that is a descendant of the element whose
directionality is being determined.

The character is of bidirectional character type L, AL, or R. [BIDI] The character is not in a Text node that has an ancestor element that is a
descendant of the element whose directionality is
being determined and that
http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

is either:

A bdi element. A script element. A style element. A textarea element. An element with a dir attribute in a defined state.
If such a character is found and it is of bidirectional character type AL or R, the
directionality of the element is 'rtl'. If such a character is found and it is of bidirectional character type L, the directionality of the element is 'ltr'. Otherwise, if the element is empty and is not a root element, the
directionality of the element is the same as the element's parent element's directionality. Otherwise, the directionality of the element is 'ltr'. If the element has a parent element and the dir attribute is
not in a defined state (i.e. it is not present or has an invalid value) The directionality of the element is the same as the element's parent
element's directionality. Since the dir attribute is only defined for
HTML elements, it cannot be present on elements from other namespaces. Thus, elements
from other namespaces always just inherit their directionality from their parent element, or, if they don't have one,
default to 'ltr'. The directionality of an attribute of an
HTML element, which is used when the text of that attribute is
to be included in the rendering in some manner, is determined as per the first appropriate set of
steps from the following list: If the attribute is a directionality-capable attribute and the element's dir attribute is in the auto state Find the first character (in logical order) of the attribute's value that is of bidirectional
character type L, AL, or R. [BIDI] If such a character is found and it is of bidirectional character type AL or R, the
directionality of the attribute is 'rtl'. Otherwise, the directionality of the attribute is 'ltr'. Otherwise The directionality of the attribute is the same as the element's directionality. The following attributes are directionality-capable attributes:
http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

abbr on th elements alt on area,


img, and
input elements content on meta elements, if the name attribute specifies a metadata name whose value is primarily
intended to be human-readable rather than machine-readable

label on menuitem,
menu,
optgroup,
option , and
track elements placeholder on input and
textarea elements title on all HTML elements elements
The effect of this attribute is primarily on the presentation layer. For example, the rendering
section in this specification defines a mapping from this attribute to the CSS 'direction' and
'unicode-bidi' properties, and CSS defines rendering in terms of those properties. document . dir [ = value ] Returns the html element's dir attribute's value, if any. Can be set, to either "ltr", "rtl", or "auto" to replace the html element's dir attribute's value. If there is no html element, returns the empty string and ignores new values. Authors are strongly encouraged to use the dir
attribute to indicate text direction rather than using CSS, since that way their documents will
continue to render correctly even in the absence of CSS (e.g. as interpreted by search engines). This markup fragment is of an IM conversation. <p dir=auto Arabic?</p> <p dir=auto <p dir=auto <p dir=auto <p dir=auto <p dir=auto class="u1"><b><bdi>Student</bdi>:</b> How do you write "What's your name?" in class="u2"><b><bdi>Teacher</bdi>:</b> class="u1"><b><bdi>Student</bdi>:</b> class="u2"><b><bdi>Teacher</bdi>:</b> class="u2"><b><bdi>Teacher</bdi>:</b> class="u1"><b><bdi>Student</bdi>:</b> < /p> Thanks.</p> That's written " ".</p> Do you know how to write "Please"?</p> "" , right?</p>

Given a suitable style sheet and the default alignment styles for the p element,
namely to align the text to the start edge of the paragraph, the resulting rendering could
be as follows:

http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

As noted earlier, the auto value is not a panacea. The


final paragraph in this example is misinterpreted as being right-to-left text, since it begins
with an Arabic character, which causes the "right?" to be to the left of the Arabic text.

The class attribute


Every HTML element may have a class attribute specified. The attribute, if specified, must have a value that is a set of space-separated tokens representing the various classes that the element belongs to. Assigning classes to an element affects class matching in selectors in CSS, the getElementsByClassName() method in the
DOM, and other such features. There are no additional restrictions on the tokens authors can use in the class attribute, but authors are encouraged to use values that describe
the nature of the content, rather than values that describe the desired presentation of the
content.

The style attribute


All HTML elements may have the style content
attribute set. This is a CSS styling attribute as defined by the CSS Styling
Attribute Syntax specification. Documents that use style attributes on any of their elements
must still be comprehensible and usable if those attributes were removed. In particular, using the style attribute to hide
and show content, or to convey meaning that is otherwise not included in the document, is
non-conforming. (To hide and show content, use the hidden
attribute.) element . style Returns a CSSStyleDeclaration object for the element's style attribute.
CSS Styling Attribute Syntax, T. elik, E. Etemad. W3C.

http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

In the following example, the words that refer to colors are marked up using the
span element and the style attribute to make those
words show up in the relevant colors in visual media. <p>My sweat suit is <span style="color: green; background: transparent">green</span> and my eyes are <span style="color: blue; background: transparent">blue</span>.</p>

Embedding custom non-visible data with the data-* attributes


A custom data attribute is an attribute in no namespace whose name starts with the
string "data- ", has at least one character after the
hyphen, is XMLcompatible, and contains no uppercase ASCII letters. All attribute names on HTML elements in HTML documents
get ASCIIlowercased automatically, so the restriction on ASCII uppercase letters doesn't affect
such documents. Custom data attributes are intended to store custom
data private to the page or application, for which there are no more appropriate attributes or elements. These attributes are not intended for use by software that is independent of the site that uses
the attributes. For instance, a site about music could annotate list items representing tracks in an album
with custom data attributes containing the length of each track. This information could then be
used by the site itself to allow the user to sort the list by track length, or to filter the list
for tracks of certain lengths. <ol> <li data-length="2m11s">Beyond The Sea</li> ... </ol> It would be inappropriate, however, for the user to use generic software not associated with
that music site to search for tracks of a certain length by looking at this data. This is because these attributes are intended for use by the site's own scripts, and are not a
generic extension mechanism for publicly-usable metadata. Every HTML element may have any number of custom data attributes specified, with any value. element . dataset
http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

Returns a DOMStringMap object for the element's data-* attributes. Hyphenated names become camel-cased. For example, data-foo-bar="" becomes element.dataset.fooBar. If a Web page wanted an element to represent a space ship, e.g. as part of a game, it would
have to use the class attribute along with data-* attributes: <div class="spaceship" data-ship-id="92432" data-weapons="laser 2" data-shields="50%" data-x="30" data-y="10" data-z="90"> <button class="fire" onclick="spaceships[this.parentNode.dataset.shipId].fire()"> Fire </button> </div> Notice how the hyphenated attribute name becomes camel-cased in the API. Authors should carefully design such extensions so that when the attributes are ignored and any
associated CSS dropped, the page is still usable. JavaScript libraries may use the custom data
attributes, as they are considered to be part of the page on which they are used. Authors
of libraries that are reused by many authors are encouraged to include their name in the attribute names, to reduce the risk of clashes. Where it makes sense, library authors are also encouraged to
make the exact name used in the attribute names customizable, so that libraries whose authors
unknowingly picked the same name can be used on the same page, and so that multiple versions of a particular library can be used on the same page even when those versions are not mutually
compatible. For example, a library called "DoQuery" could use attribute names like data-doquery-range , and a library called "jJo" could use attributes names like
data-jjo-range . The jJo library could also provide an API to set which prefix to use (e.g. J.setDataPrefix('j2') , making the attributes have names
like data-j2-range ).

Requirements relating to bidirectional-algorithm formatting characters


Text content in HTML elements with Text nodes in their
contents, and text in attributes of HTML
elements that allow free-form text, may contain characters in the ranges U+202A to U+202E
and U+2066 to U+2069 (the bidirectional-algorithm formatting characters). However, the use of
these
http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

characters is restricted so that any embedding or overrides generated by these characters do


not start and end with different parent elements, and so that all such embeddings and overrides
are explicitly terminated by a U+202C POP DIRECTIONAL FORMATTING character. This helps reduce
incidences of text being reused in a manner that has unforeseen effects on the bidirectional algorithm. [BIDI] The aforementioned restrictions are defined by specifying that certain parts of documents form
bidirectional-algorithm formatting character ranges, and then imposing a requirement
on such ranges. The strings resulting from applying the following algorithm to an HTML element element are bidirectional-algorithm
formatting character ranges:
1. Let output be an empty list of strings. 2. Let string be an empty string. 3. Let node be the first child node of element, if
any, or null otherwise. 4. Loop: If node is null, jump to the step labeled
end. 5. Process node according to the first matching step from the following
list:

If node is a Text node Append the text data of node to string. If node is a br element If node is an HTML element that is
flow content but that is not also phrasing content If string is not the empty string, push string
onto output, and let string be empty string. Otherwise Do nothing.
6. Let node be node's next sibling, if any, or null
otherwise. 7. Jump to the step labeled loop. 8. End: If string is not the empty string, push string onto output. 9. Return output as the bidirectional-algorithm formatting
character ranges.

The value of a namespace-less attribute of an HTML element


is a bidirectional-algorithm
formatting character range. Any strings that, as described above, are bidirectional-algorithm formatting character
ranges must match the string production in the following ABNF, the
character set for which is Unicode.
Augmented BNF for Syntax Specifications: ABNF, D. Crocker, P. Overell. IETF.

http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

string embedding override isolation lre rle lro rlo pdf lri rli fsi pdi plaintext

= = = = = = = = = = = = = =

*( plaintext ( embedding / override / isolation ) ) plaintext ( lre / rle ) string pdf ( lro / rlo ) string pdf ( lri / rli / fsi ) string pdi %x202A ; U+202A LEFT-TO-RIGHT EMBEDDING %x202B ; U+202B RIGHT-TO-LEFT EMBEDDING %x202D ; U+202D LEFT-TO-RIGHT OVERRIDE %x202E ; U+202E RIGHT-TO-LEFT OVERRIDE %x202C ; U+202C POP DIRECTIONAL FORMATTING %x2066 ; U+2066 LEFT-TO-RIGHT ISOLATE %x2067 ; U+2067 RIGHT-TO-LEFT ISOLATE %x2068 ; U+2068 FIRST STRONG ISOLATE %x2069 ; U+2069 POP DIRECTIONAL ISOLATE *( %x0000-2029 / %x202F-2065 / %x206A-10FFFF ) ; any string with no bidirectional-algorithm formatting characters

While the U+2069 POP DIRECTIONAL ISOLATE character implicitly also ends open
embeddings and overrides, text that relies on this implicit scope closure is not conforming to
this specification. All strings of embeddings, overrides, and isolations need to be explicitly
terminated to conform to this section's requirements. Authors are encouraged to use the dir attribute, the
bdo element, and the bdi element, rather than maintaining the
bidirectional-algorithm formatting characters manually. The bidirectional-algorithm formatting
characters interact poorly with CSS.

WAI-ARIA
Authors may use the ARIA role and aria-* attributes on HTML elements, in accordance with the
requirements described in the ARIA specifications, except where these conflict with the
strong native semantics or are equal to the default implicit ARIA
semantics described below. These exceptions are intended to prevent authors from making
assistive technology products report nonsensical states that do not represent the actual state of
the document. [ARIA] Authors must not set the ARIA role and aria-* attributes in a manner that conflicts with the semantics
described in the following table, except that the presentation role may always be used. Authors must not
set the ARIA role and aria-*
attributes to values that match the default implicit ARIA semantics defined in the
following two tables. The following table defines the strong native semantics and corresponding
http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

default implicit ARIA semantics that apply to HTML elements. Each


language feature (element or attribute) in a cell in the first column implies the ARIA semantics
(any role, states, and properties) given in the cell in the second column of the same row. Language feature area element that creates a hyperlink base element datalist element details element dialog element without an open attribute head element hgroup element hr element html element img element whose alt attribute's value is empty input element with a type attribute in
the Checkbox state input element with a type attribute in
the Color state input element with a type attribute in
the Date state input element with a type attribute in
the Date and Time state input element with a type attribute in
the Local Date and Time state input element with a type attribute in
the Email state with no
http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]

Strong native semantics and default implicit ARIA semantics link role No role listbox role, with the aria-multiselectable property set to "false" aria-expanded state set to "true" if the element's
open attribute is present, and set to "false" otherwise The aria-hidden state set to "true"

No role, with the aria-hidden state set to "true" heading role, with the aria-level property set to the element's outline
depth separator role No role presentation role

aria-checked state set to "mixed" if the element's


indeterminate IDL attribute is true, or "true" if
the element's checkedness is true, or "false" otherwise No role

No role, with the aria-readonly property set to "true" if the element has a readonly attribute No role, with the aria-readonly property set to "true" if the element has a readonly attribute No role, with the aria-readonly property set to "true" if the element has a readonly attribute

textbox role, with the aria-readonly property set to "true" if the element has a
readonly attribute

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

suggestions source element input element with a type attribute in


the File Upload state input element with a type attribute in
the Hidden state input element with a type attribute in
the Month state input element with a type attribute in
the Number state No role

No role

No role, with the aria-readonly property set to "true" if the element has a readonly attribute spinbutton role, with the aria-readonly property set to "true" if the element has a
readonly attribute, the aria-valuemax property set to the element's maximum, the aria-valuemin property set to the element's minimum, and, if the result of applying the rules for
parsing floating-point number values to the element's value is a number, with the aria-valuenow property set to that number textbox role, with the aria-readonly property set to "true" if the element has a
readonly attribute aria-checked state set to "true" if the element's
checkedness is true, or "false" otherwise slider role, with the aria-valuemax property set to the element's maximum, the aria-valuemin property set to the element's minimum, and the aria-valuenow property set to the result of applying the
rules for parsing floating-point number values to the element's value, if that results in a number, or the default value otherwise button role

input element with a type attribute in


the Password state input element with a type attribute in
the Radio Button state input element with a type attribute in
the Range state

input element with a type attribute in


the Reset Button state input element with a type attribute in
the Search state with no suggestions source element input element with a type attribute in
the Submit Button state input element with a type attribute in
the Telephone state with no suggestions source
http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]

textbox role, with the aria-readonly property set to "true" if the element has a
readonly attribute

button role

textbox role, with the aria-readonly property set to "true" if the element has a
readonly attribute

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

element input element with a type attribute in


the Text state with no suggestions source element input element with a type attribute in
the Text, Search, Telephone, URL, or
Email states with a suggestions source element input element with a type attribute in
the Time state input element with a type attribute in
the URL state with no suggestions source element input element with a type attribute in
the Week state input element that is required keygen element label element link element that creates a hyperlink menu element with a type attribute in the popup menu state meta element meter element nav element noscript element optgroup element option element that is in a list of
options or that represents a
http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]

textbox role, with the aria-readonly property set to "true" if the element has a
readonly attribute

combobox role, with the aria-owns property set to the same value as the list attribute, and the aria-readonly property set to "true" if the element has a readonly attribute

No role, with the aria-readonly property set to "true" if the element has a readonly attribute textbox role, with the aria-readonly property set to "true" if the element has a
readonly attribute

No role, with the aria-readonly property set to "true" if the element has a readonly attribute The aria-required state set to "true" No role No role link role No role

No role No role navigation role No role, with the aria-hidden state set to "true" No role option role, with the aria-selected state set to "true" if the element's selectedness is true, or "false" otherwise.

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

suggestion in a datalist element param element progress element No role progressbar role, with, if the progress bar
is determinate, the aria-valuemax property set to the
maximum value of the progress bar, the aria-valuemin
property set to zero, and the aria-valuenow property set to the current value of the progress bar No role, with the aria-hidden state set to "true" listbox role, with the aria-multiselectable property set to "true" listbox role, with the aria-multiselectable property set to "false" The aria-required state set to "true" No role No role, with the aria-hidden state set to "true" No role No role, with the aria-hidden state set to "true" textbox role, with the aria-multiline property set to "true", and the aria-readonly property set to "true" if the element has a
readonly attribute The aria-required state set to "true" No role The aria-disabled state set to "true" The aria-hidden state set to "true" The aria-hidden state set to "true" The aria-invalid state set to "true"

script element select element with a multiple attribute select element with no multiple attribute select element with a required attribute source element style element summary element template element textarea element textarea element with a required attribute title element Element that is disabled Element that is inert Element with a hidden attribute Element that is a candidate for constraint validation but that does not satisfy its constraints

Some HTML elements have native semantics that can be overridden. The following
table lists these elements and their default implicit ARIA semantics, along with the
restrictions that apply to those elements. Each language feature (element or attribute) in a cell
in the first column implies, unless otherwise overridden, the ARIA semantic (role, state, or
property) given in the cell in the second column of the same row, but this semantic may be overridden under the conditions listed in the cell in the third column of that
http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

row. In addition,
any element may be given the presentation role, regardless of the restrictions below. Language feature a element that creates a hyperlink address element article element aside element audio element button element details element dialog element Default implicit ARIA semantic link role No role article role complementary role No role button role group role dialog role Restrictions Role must be either link, menuitem, tab,
or treeitem If specified, role must be contentinfo Role must be either article, document, application, or main Role must be either complementary , note, or search If specified, role must be application Role must be either button, menuitem Role must be a role that supports aria-expanded Role must be either
alert ,
alertdialog , application,
contentinfo,
dialog ,
document, log,
main,
marquee ,
region ,
search, or
status If specified, role must be either application, document, or img If specified, role must be contentinfo Role must be either heading or tab

embed element footer element h1 element that does not have an hgroup ancestor h2 element that does not have an hgroup ancestor h3 element that does not have an hgroup ancestor h4 element that does not have an hgroup ancestor h5 element that does not have an hgroup ancestor

No role No role heading role, with the aria-level property set to the element's outline depth heading role, with the aria-level property set to the element's outline depth heading role, with the aria-level property set to the element's outline depth heading role, with the aria-level property set to the element's outline depth heading role, with the aria-level property set to the element's outline depth

Role must be either heading or tab

Role must be either heading or tab

Role must be either heading or tab

Role must be either heading or tab

http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

h6 element that does not have an hgroup ancestor header element iframe element img element whose alt attribute's value is absent img element whose alt attribute's value is
present and not empty input element with a type attribute in
the Button state input element with a type attribute in
the Checkbox state input element with a type attribute in
the Image Button state input element with a type attribute in
the Radio Button state li element whose parent is an ol or ul element main element menu element with a type attribute in the toolbar state object element ol element output element section element

heading role, with the aria-level property set to the element's outline depth No role No role img role

Role must be either heading or tab

If specified, role must be banner If specified, role must be either application, document, or img No restrictions

img role

No restrictions

button role

Role must be either button, menuitem

checkbox role

Role must be either checkbox or menuitemcheckbox Role must be either button, menuitem

button role

radio role

Role must be either radio or menuitemradio

listitem role

Role must be either listitem, menuitemcheckbox, menuitemradio, option , tab, or


treeitem Role must be either document, application , or main Role must be either directory , list, listbox, menu, menubar, tablist , toolbar, or tree If specified, role must be either application, document, or img Role must be either directory , list, listbox, menu, menubar, tablist , toolbar, or tree No restrictions Role must be either
alert ,
alertdialog , application,
contentinfo,
dialog ,
document,

main role toolbar role

No role list role status role region role

http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

log,
main,
marquee ,
region ,
search, or
status ul element video element The body element list role No role document role Role must be either directory , list, listbox, menu, menubar, tablist , toolbar, tree If specified, role must be application Role must be either document or application

The entry "no role", when used as a strong native semantic, means that no role other than presentation can be used. When used as a default implicit ARIA semantic, it means the user
agent has no default mapping to ARIA roles. (However, it probably will have its own mappings to
the accessibility layer.) These features can be used to make accessibility tools render content to their users in more
useful ways. For example, ASCII art, which is really an image, appears to be text, and in the
absence of appropriate annotations would end up being rendered by screen readers as a very
painful reading of lots of punctuation. Using the features described in this section, one can
instead make the ATs skip the ASCII art and just read the caption: <figure role="img" aria-labelledby="fish-caption"> <pre> o .'`/ ' / ( O .-'` ` `'-._ .') _/ (o) '. .' / ) ))) >< < `\ |_\ _.' '. \ '-._ _ .-' '.) jgs `\__\ </pre> <figcaption id="fish-caption"> Joan G. Stark, "<cite>fish</cite>". October 1997. ASCII on electrons. 288. </figcaption> </figure>

Up next

4 The elements of HTML

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]

3.2.4 Content models HTML: The Living Standard - Edition for Web Developers

http://developers.whatwg.org/content-models.html[4/16/2014 9:34:25 PM]

4.7.2 The iframe element HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
The iframe element
The embed element
The object element
The param element

The iframe element


Categories: Flow content. Phrasing content. Embedded content. Interactive content. Palpable content. Contexts in which this element can be used: Where embedded content is expected. Content model: Text that conforms to the requirements given in the prose. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes src Address of the resource srcdoc A document to render in the iframe name Name of nested browsing context sandbox Security rules for nested content seamless Whether to apply the document's styles to the nested content
http://developers.whatwg.org/the-iframe-element.html[4/16/2014 9:34:34 PM]

4.7.2 The iframe element HTML: The Living Standard - Edition for Web Developers

allowfullscreen Whether to allow the iframe 's contents to use requestFullscreen() width Horizontal dimension height Vertical dimension DOM interface: The iframe element represents a nested browsing
context. The src attribute gives the address of a page
that the nested browsing context is to contain. The attribute, if present, must be a
valid non-empty URL potentially surrounded by spaces. If the itemprop is specified on an iframe element, then the
src attribute must also be specified. The srcdoc attribute gives the content of
the page that the nested browsing context is to contain. The value of the attribute
is the source of an iframe srcdoc
document. For iframe elements in HTML documents, the srcdoc attribute, if present, must have a value using the
HTML syntax that consists of the following syntactic components, in the given order: 1. Any number of comments and space characters. 2. Optionally, a DOCTYPE. 3. Any number of comments and space characters. 4. The root element, in the form of an html element. 5. Any number of comments and space characters. For iframe elements in XML documents, the srcdoc attribute, if present, must have a value that matches the
production labeled document in the XML specification. Here a blog uses the srcdoc attribute in conjunction
with the sandbox and seamless attributes described below to provide users of user
agents that support this feature with an extra layer of protection from script injection in the
blog post comments: <article> <h1>I got my own magazine!</h1> <p>After much effort, I've finally found a publisher, and so now I

http://developers.whatwg.org/the-iframe-element.html[4/16/2014 9:34:34 PM]

4.7.2 The iframe element HTML: The Living Standard - Edition for Web Developers

have my own magazine! Isn't that awesome?! The first issue will come out in September, and we have articles about getting food, and about getting in boxes, it's going to be great!</p> <footer> <p>Written by <a href="/users/cap">cap</a>, 1 hour ago. </footer> <article> <footer> Thirteen minutes ago, <a href="/users/ch">ch</a> wrote: </footer> <iframe seamless sandbox srcdoc="<p>did you get a cover picture yet?"></iframe> </article> <article> <footer> Nine minutes ago, <a href="/users/cap">cap</a> wrote: </footer> <iframe seamless sandbox srcdoc="<p>Yeah, you can see it <a href=&quot;/gallery?mode=cover&amp;amp;page=1&quot;>in my gallery</a>."></iframe> </article> <article> <footer> Five minutes ago, <a href="/users/ch">ch</a> wrote: </footer> <iframe seamless sandbox srcdoc="<p>hey that's earl's table. <p>you should get earl&amp;amp;me on the next cover."> </iframe> </article> Notice the way that quotes have to be escaped (otherwise the srcdoc attribute would end prematurely), and the way raw
ampersands (e.g. in URLs or in prose) mentioned in the sandboxed content have to be
doubly escaped once so that the ampersand is preserved when originally parsing the srcdoc attribute, and once more to prevent the
ampersand from being misinterpreted when parsing the sandboxed content. Furthermore, notice that since the DOCTYPE is optional in
iframe srcdoc documents, and the html,
head, and body elements have optional
start and end tags, and the title element is also optional in iframe srcdoc documents, the markup in a srcdoc attribute can be
relatively succint
http://developers.whatwg.org/the-iframe-element.html[4/16/2014 9:34:34 PM]

4.7.2 The iframe element HTML: The Living Standard - Edition for Web Developers

despite representing an entire document, since only the contents of the


body element need appear literally in the syntax. The other elements are still present, but only by implication. In the HTML syntax, authors need only remember to use U+0022 QUOTATION MARK characters (") to wrap the attribute contents and then to escape all U+0022
QUOTATION MARK (") and U+0026 AMPERSAND (&) characters, and to specify the sandbox attribute, to ensure safe embedding of content. Due to restrictions of the XHTML syntax, in XML the U+003C LESS-THAN SIGN character (<) needs to be escaped as well. In order to prevent attributevalue normalization, some of XML's
whitespace characters specifically U+0009 CHARACTER TABULATION (tab), U+000A LINE FEED
(LF), and U+000D CARRIAGE RETURN (CR) also need to be escaped. [XML] If the src attribute and the srcdoc attribute are both specified together, the srcdoc attribute takes priority. This allows authors to provide
a fallback URL for legacy user agents that do not support the srcdoc attribute. If, when the element is created, the srcdoc attribute is not set, and the src attribute is either also not set or set but its value cannot be
resolved, the browsing context will remain at the initial
about:blank page. If the user navigates away from this page, the
iframe 's corresponding WindowProxy object will proxy new
Window objects for new Document objects, but the src attribute will not change. The name attribute, if present, must be a
valid browsing context name. The given value is used to name the nested
browsing context. The sandbox attribute, when specified,
enables a set of extra restrictions on any content hosted by the iframe . Its value
must be an unordered set of unique space-separated tokens that are ASCII
case-insensitive. The allowed values are allow-forms , allow-pointer-lock , allow-popups, allow-same-origin , allow-scripts, and allow-top-navigation. When the attribute is set, the content is treated as being from a unique origin, forms, scripts, and various potentially annoying APIs are disabled, links are prevented from
targeting other browsing contexts, and plugins are secured. The allow-same-origin keyword causes
the content to be treated as being

http://developers.whatwg.org/the-iframe-element.html[4/16/2014 9:34:34 PM]

4.7.2 The iframe element HTML: The Living Standard - Edition for Web Developers

from its real origin instead of forcing it into a unique


origin; the allow-top-navigation
keyword allows the content to navigate its top-level browsing context;
and the allow-forms, allow-pointer-lock, allow-popups and allow-scripts keywords re-enable forms, the
pointer lock API, popups, and scripts respectively. Setting both the allow-scripts and allow-same-origin keywords together when the
embedded page has the same origin as the page containing the iframe
allows the embedded page to simply remove the sandbox
attribute and then reload itself, effectively breaking out of the sandbox altogether. These flags only take effect when the nested browsing context of
the iframe is navigated. Removing them, or removing the
entire sandbox attribute, has no effect on an
already-loaded page. Potentially hostile files should not be served from the same server as the file
containing the iframe element. Sandboxing hostile content is of minimal help if an
attacker can convince the user to just visit the hostile content directly, rather than in the
iframe. To limit the damage that can be caused by hostile HTML content, it should be
served from a separate dedicated domain. Using a different domain ensures that scripts in the
files are unable to attack the site, even if the user is tricked into visiting those pages directly, without the protection of the sandbox
attribute. In this example, some completely-unknown, potentially hostile, userprovided HTML content is
embedded in a page. Because it is served from a separate domain, it is affected by all the normal
cross-site restrictions. In addition, the embedded page has scripting disabled, plugins disabled,
forms disabled, and it cannot navigate any frames or windows other than itself (or any frames or
windows it itself embeds). <p>We're not scared of you! Here is your content, unedited: </p> <iframe sandbox src="http://usercontent.example.net/getusercontent.cgi? id=12193"></iframe> It is important to use a separate domain so that if the attacker convinces

http://developers.whatwg.org/the-iframe-element.html[4/16/2014 9:34:34 PM]

4.7.2 The iframe element HTML: The Living Standard - Edition for Web Developers

the
user to visit that page directly, the page doesn't run in the context of the site's origin, which
would make the user vulnerable to any attack found in the page. In this example, a gadget from another site is embedded. The gadget has scripting and forms
enabled, and the origin sandbox restrictions are lifted, allowing the gadget to communicate with
its originating server. The sandbox is still useful, however, as it disables plugins and popups,
thus reducing the risk of the user being exposed to malware and other annoyances. <iframe sandbox="allow-same-origin allow-forms allow-scripts" src="http://maps.example.com/embedded.html"></iframe> Suppose a file A contained the following fragment: <iframe sandbox="allow-same-origin allow-forms" src=B> </iframe> Suppose that file B contained an iframe also: <iframe sandbox="allow-scripts" src=C></iframe> Further, suppose that file C contained a link: <a href=D>Link</a> For this example, suppose all the files were served as text/html . Page C in this scenario has all the sandboxing flags set. Scripts are disabled, because the
iframe in A has scripts disabled, and this overrides the allow-scripts keyword set on the
iframe in B. Forms are also disabled, because the inner iframe (in B)
does not have the allow-forms keyword
set. Suppose now that a script in A removes all the sandbox attributes in A and B.
This would change nothing immediately. If the user clicked the link in C, loading page D into the
iframe in B, page D would now act as if the iframe in B had the allow-same-origin and allow-forms keywords set, because that was the
state of the nested browsing context in the iframe in A when page B was
loaded. Generally speaking, dynamically removing or changing the sandbox attribute is ill-advised, because it can make it quite
hard to reason about

http://developers.whatwg.org/the-iframe-element.html[4/16/2014 9:34:34 PM]

4.7.2 The iframe element HTML: The Living Standard - Edition for Web Developers

what will be allowed and what will not. The seamless attribute is a boolean
attribute. When specified, it indicates that the iframe element's
browsing context is to be rendered in a manner that makes it appear to be part of the
containing document (seamlessly included in the parent document). An HTML inclusion is effected using this attribute as in the following example.
In this case, the inclusion is of a site-wide navigation bar. <!DOCTYPE HTML> <title>Mirror Mirror MovieInfo</title> <header> <h1>Mirror Mirror</h1> <p>Part of the MovieInfo Database</p> <nav> <iframe seamless src="nav.inc"></iframe> </nav> </header> ... The attribute can be set or removed dynamically, with the rendering updating in
tandem. In this example, the site's navigation is embedded using a client-side include using an
iframe . Any links in the iframe will, in new user agents, be automatically opened in the iframe's parent browsing context; for legacy user
agents, the site could also include a base element with a target attribute with the value _parent .
Similarly, in new user agents the styles of the parent page will be automatically applied to the
contents of the frame, but to support legacy user agents authors might wish to include the styles explicitly. <nav><iframe seamless src="nav.include.html"></iframe></nav> The contenteditable attribute does not
propagate into seamless iframes. The allowfullscreen attribute is a
boolean attribute. When specified, it indicates that Document objects in
the iframe element's browsing context are to be allowed to use requestFullscreen() (if it's not blocked for other reasons, e.g. there is another ancestor iframe without this attribute set).

http://developers.whatwg.org/the-iframe-element.html[4/16/2014 9:34:34 PM]

4.7.2 The iframe element HTML: The Living Standard - Edition for Web Developers

The iframe element supports dimension attributes for cases where the embedded content has specific dimensions (e.g. ad units have well-defined dimensions). An iframe element never has fallback content, as it will always
create a nested browsing context, regardless of whether the specified initial
contents are successfully used. Descendants of iframe elements represent nothing. (In legacy user agents that do
not support iframe elements, the contents would be parsed as markup that could act as
fallback content.) When used in HTML documents, the allowed content model
of iframe elements is text, except that invoking the HTML fragment parsing
algorithm with the iframe element as the context element and the text contents as the input must result in a list of nodes that are all phrasing content,
with no parse errors having occurred, with no script
elements being anywhere in the list or as descendants of elements in the list, and with all the
elements in the list (including their descendants) being themselves conforming. The iframe element must be empty in XML documents. The HTML parser treats markup inside iframe elements as
text. Here is an example of a page using an iframe to include advertising from an
advertising broker: <iframe src="http://ads.example.com/? customerid=923513721&amp;format=banner" width="468" height="60"></iframe>

The embed element


Categories: Flow content. Phrasing content. Embedded content. Interactive content. Palpable content.

http://developers.whatwg.org/the-iframe-element.html[4/16/2014 9:34:34 PM]

4.7.2 The iframe element HTML: The Living Standard - Edition for Web Developers

Contexts in which this element can be used: Where embedded content is expected. Content model: Empty. Tag omission in text/html: No end tag. Content attributes: Global attributes src Address of the resource type Type of embedded resource width Horizontal dimension height Vertical dimension Any other attribute that has no namespace (see prose). DOM interface: The embed element provides an integration point for an external (typically non-HTML) application or interactive content. The src attribute gives the address of the
resource being embedded. The attribute, if present, must contain a valid non-empty URL
potentially surrounded by spaces. If the itemprop attribute is specified on an
embed element, then the src attribute must also
be specified. The type attribute, if present, gives the
MIME type by which the plugin to instantiate is selected. The value must be a
valid MIME type. If both the type attribute and
the src attribute are present, then the type attribute must specify the same type as the explicit Content-Type metadata of the resource given by the src attribute. Any namespace-less attribute other than name, align , hspace , and vspace may be
specified on the embed element, so long as its name is XMLcompatible
and contains no uppercase ASCII letters. These attributes are then passed as
parameters to the plugin. All attributes in HTML documents get lowercased automatically, so the restriction on uppercase letters doesn't affect such documents.

http://developers.whatwg.org/the-iframe-element.html[4/16/2014 9:34:34 PM]

4.7.2 The iframe element HTML: The Living Standard - Edition for Web Developers

The four exceptions are to exclude legacy attributes that have side-effects beyond
just sending parameters to the plugin. The embed element supports dimension attributes. Here's a way to embed a resource that requires a proprietary plugin, like Flash: <embed src="catgame.swf"> If the user does not have the plugin (for example if the plugin vendor doesn't support the
user's platform), then the user will be unable to use the resource. To pass the plugin a parameter "quality" with the value "high", an attribute can be
specified: <embed src="catgame.swf" quality="high"> This would be equivalent to the following, when using an object element instead: <object data="catgame.swf"> <param name="quality" value="high"> </object>

The object element


Categories: Flow content. Phrasing content. Embedded content. If the element has a usemap attribute: Interactive content. Listed, submittable, and reassociateable form-associated element. Palpable content. Contexts in which this element can be used: Where embedded content is expected. Content model: Zero or more param elements, then, transparent.

http://developers.whatwg.org/the-iframe-element.html[4/16/2014 9:34:34 PM]

4.7.2 The iframe element HTML: The Living Standard - Edition for Web Developers

Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes data Address of the resource type Type of embedded resource typemustmatch Whether the type attribute and the Content-Type value need to match for the resource to be used name Name of nested browsing context usemap Name of image map to use form Associates the control with a form element width Horizontal dimension height Vertical dimension DOM interface: The object element can represent an external resource, which, depending on the
type of the resource, will either be treated as an image, as a nested browsing
context, or as an external resource to be processed by a plugin. The data attribute, if present, specifies the
address of the resource. If present, the attribute must be a valid non-empty URL potentially
surrounded by spaces. Authors who reference resources from other origins
that they do not trust are urged to use the typemustmatch attribute defined below. Without that attribute, it is possible in certain cases for an attacker on the remote host to use the plugin
mechanism to run arbitrary scripts, even if the author has used features such as the Flash
"allowScriptAccess" parameter. The type attribute, if present, specifies the
type of the resource. If present, the attribute must be a valid MIME type. At least one of either the data attribute or the type attribute must be present. If the itemprop attribute is specified on an object
element, then the data attribute must also be specified. The typemustmatch attribute is a
boolean attribute whose presence indicates

http://developers.whatwg.org/the-iframe-element.html[4/16/2014 9:34:34 PM]

4.7.2 The iframe element HTML: The Living Standard - Edition for Web Developers

that the resource specified by the data attribute is only to be used if the value of the type attribute and the Content-Type of the
aforementioned resource match. The typemustmatch attribute must not be
specified unless both the data attribute and the type attribute are present. The name attribute, if present, must be a
valid browsing context name. The given value is used to name the nested
browsing context, if applicable. The usemap attribute, if present while the
object element represents an image, can indicate that the object has an associated
image map. The form attribute is used to explicitly associate the
object element with its form owner. The object element supports dimension attributes. In the following example, a Java applet is embedded in a page using the object
element. (Generally speaking, it is better to avoid using applets like these and instead use
native JavaScript and HTML to provide the functionality, since that way the application will work
on all Web browsers without requiring a third-party plugin. Many devices, especially embedded devices, do not support third-party technologies like Java.) <figure> <object type="application/x-java-applet"> <param name="code" value="MyJavaClass"> <p>You do not have Java available, or it is disabled.</p> </object> <figcaption>My Java Clock</figcaption> </figure> In this example, an HTML page is embedded in another using the object element. <figure> <object data="clock.html"></object> <figcaption>My HTML Clock</figcaption> </figure> The following example shows how a plugin can be used in HTML (in this case the Flash plugin,
to show a video file). Fallback is provided for users who do

http://developers.whatwg.org/the-iframe-element.html[4/16/2014 9:34:34 PM]

4.7.2 The iframe element HTML: The Living Standard - Edition for Web Developers

not have Flash enabled, in this case


using the video element to show the video for those using user agents that support
video , and finally providing a link to the video for those who have neither Flash
nor a video -capable browser. <p>Look at my video: <object type="application/x-shockwave-flash"> <param name=movie value="http://video.example.com/library/watch.swf"> <param name=allowfullscreen value=true> <param name=flashvars value="http://video.example.com/vids/315981"> <video controls src="http://video.example.com/vids/315981"> <a href="http://video.example.com/vids/315981">View video</a>. </video> </object> </p>

The param element


Categories: None. Contexts in which this element can be used: As a child of an object element, before any flow content. Content model: Empty. Tag omission in text/html: No end tag. Content attributes: Global attributes name Name of parameter value Value of parameter DOM interface: The param element defines parameters for plugins invoked by object

http://developers.whatwg.org/the-iframe-element.html[4/16/2014 9:34:34 PM]

4.7.2 The iframe element HTML: The Living Standard - Edition for Web Developers

elements. It does not represent anything on its own. The name attribute gives the name of the
parameter. The value attribute gives the value of the
parameter. Both attributes must be present. They may have any value. The following example shows how the param element can be used to pass a parameter
to a plugin, in this case the O3D plugin. <!DOCTYPE HTML> <html lang="en"> <head> <title>O3D Utah Teapot</title> </head> <body> <p> <object type="application/vnd.o3d.auto"> <param name="o3d_features" value="FloatingPointTextures"> <img src="o3d-teapot.png" title="3D Utah Teapot illustration rendered using O3D." alt="When O3D renders the Utah Teapot, it appears as a squat teapot with a shiny metallic finish on which the surroundings are reflected, with a faint shadow caused by the lighting."> <p>To see the teapot actually rendered by O3D on your computer, please download and install the <a href="http://code.google.com/apis/o3d/docs/gettingstarted.htm l#install">O3D plugin</a>.</p> </object> <script src="o3d-teapot.js"></script> </p> </body> </html>

http://developers.whatwg.org/the-iframe-element.html[4/16/2014 9:34:34 PM]

4.7.2 The iframe element HTML: The Living Standard - Edition for Web Developers
Up next

4.7.6 The video element

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/the-iframe-element.html[4/16/2014 9:34:34 PM]

4.10.6 The button element HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
The button element
The select element
The datalist element
The optgroup element
The option element
The textarea element
The keygen element
The output element
The progress element
The meter element
The fieldset element
The legend element
Form control infrastructure
A form control's value
Mutability

The button element


Categories: Flow content. Phrasing content. Interactive content. Listed, labelable, submittable, and reassociateable form-associated element. Palpable content. Contexts in which this element can be used: Where phrasing content is expected. Content model: Phrasing content, but there must be no interactive content descendant.

http://developers.whatwg.org/the-button-element.html[4/16/2014 9:34:40 PM]

4.10.6 The button element HTML: The Living Standard - Edition for Web Developers

Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes autofocus Automatically focus the form control when the page is loaded disabled Whether the form control is disabled form Associates the control with a form element formaction URL to use for form submission formenctype Form data set encoding type to use for form submission formmethod HTTP method to use for form submission formnovalidate Bypass form control validation for form submission formtarget Browsing context for form submission menu Specifies the element's designated pop-up menu name Name of form control to use for form submission and in the form.elements API type Type of button value Value to be used for form submission DOM interface: The button element represents a button labeled by its contents. The element is a button. The type attribute controls the behavior of
the button when it is activated. It is an enumerated attribute. The following table
lists the keywords and states for the attribute the keywords in the left column map to the
states in the cell in the second column on the same row as the keyword. Keyword State Brief description submit reset button menu Submit Button Reset Button Button Menu Submits the form. Resets the form. Does nothing. Shows a menu.

http://developers.whatwg.org/the-button-element.html[4/16/2014 9:34:40 PM]

4.10.6 The button element HTML: The Living Standard - Edition for Web Developers

The missing value default is the Submit


Button state. If the type attribute is in the Submit Button state, the element is specifically a submit button. The form attribute is used to explicitly associate the
button element with its form owner. The name attribute represents the element's name. The disabled attribute is used to make the control non-interactive and
to prevent its value from being submitted. The autofocus
attribute controls focus. The formaction , formenctype, formmethod , formnovalidate , and formtarget attributes are attributes for form
submission. The formnovalidate attribute can be
used to make submit buttons that do not trigger the constraint validation. The formaction, formenctype, formmethod , formnovalidate, and formtarget must not be specified if the element's type attribute is not in the Submit Button state. The value attribute gives the element's value
for the purposes of form submission. The element's value is
the value of the element's value attribute, if there is
one, or the empty string otherwise. A button (and its value) is only included in the form submission if the button itself was used to initiate the form submission. If the element's type attribute is in the Menu state, the menu attribute must be specified to give the element's
menu. The value must be the ID of a menu element in
the same home subtree whose type attribute is in
the popup menu state. The attribute must not be specified if
the element's type attribute is not in the Menu state. The following button is labeled "Show hint" and pops up a dialog box when activated: <button type=button onclick="alert('This 15-20 minute piece was composed by George Gershwin.')"> Show hint </button>

http://developers.whatwg.org/the-button-element.html[4/16/2014 9:34:40 PM]

4.10.6 The button element HTML: The Living Standard - Edition for Web Developers

The select element


Categories: Flow content. Phrasing content. Interactive content. Listed, labelable, submittable, resettable, and reassociateable form-associated element. Palpable content. Contexts in which this element can be used: Where phrasing content is expected. Content model: Zero or more option , optgroup, and script-supporting elements. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes autofocus Automatically focus the form control when the page is loaded disabled Whether the form control is disabled form Associates the control with a form element multiple Whether to allow multiple values name Name of form control to use for form submission and in the form.elements API required Whether the control is required for form submission size Size of the control DOM interface: The select element represents a control for selecting amongst a set of options. The multiple attribute is a boolean
attribute. If the attribute is present, then the select element
represents a control for selecting zero or more options from the list of options. If the attribute is absent, then the
select element represents a control for selecting a single option from
the list of options.

http://developers.whatwg.org/the-button-element.html[4/16/2014 9:34:40 PM]

4.10.6 The button element HTML: The Living Standard - Edition for Web Developers

The size attribute gives the number of options


to show to the user. The size attribute, if specified, must
have a value that is a valid non-negative integer greater than zero. The list of options for a select
element consists of all the option element children of the select
element, and all the option element children of all the optgroup element
children of the select element, in tree order. The required attribute is a boolean
attribute. When specified, the user will be required to select a value before submitting
the form. If a select element has a required
attribute specified, does not have a multiple attribute
specified, and has a display size of 1; and if the value of the first option element in the
select element's list of options (if
any) is the empty string, and that option element's parent node is the
select element (and not an optgroup element), then that
option is the select element's placeholder label option. If a select element has a required
attribute specified, does not have a multiple attribute
specified, and has a display size of 1, then the
select element must have a placeholder label option. The form attribute is used to explicitly associate the
select element with its form owner. The name attribute represents the element's name. The disabled attribute is used to make the control non-interactive and
to prevent its value from being submitted. The autofocus
attribute controls focus. A select element that is not disabled is
mutable. select . type Returns "select-multiple" if the element has a multiple attribute, and " select-one "
otherwise. select . options Returns an HTMLOptionsCollection of the list of options. select . length [ = value ] Returns the number of elements in the list of
options. When set to a smaller number, truncates the number of option elements in the
select . When set to a greater number, adds new blank option elements to the
select

http://developers.whatwg.org/the-button-element.html[4/16/2014 9:34:40 PM]

4.10.6 The button element HTML: The Living Standard - Edition for Web Developers

. element = select . item(index) select[index] Returns the item with index index from the list of options. The items are sorted in tree
order. element = select . namedItem (name) Returns the first item with ID or name name from the list of options. Returns null if no element with that ID could be found. select . add(element [, before ]) Inserts element before the node given by before. The before argument can be a number, in which case element is inserted before the item with that number, or an element from the
list of options, in which case element is inserted before that element. If before is omitted, null, or a number out of range, then element will be added at the end of the list. This method will throw a HierarchyRequestError exception if element is an ancestor of the element into which it is to be inserted. select . selectedOptions Returns an HTMLCollection of the list
of options that are selected. select . selectedIndex [ = value ] Returns the index of the first selected item, if any, or 1 if there is no selected item. Can be set, to change the selection. select . value [ = value ] Returns the value of the first selected item, if any,
or the empty string if there is no selected item. Can be set, to change the selection. The following example shows how a select element can be used to offer the user
with a set of options from which the user can select a single option. The default option is
preselected.

http://developers.whatwg.org/the-button-element.html[4/16/2014 9:34:40 PM]

4.10.6 The button element HTML: The Living Standard - Edition for Web Developers

<p> <label for="unittype">Select unit type:</label> <select id="unittype" name="unittype"> <option value="1"> Miner </option> <option value="2"> Puffer </option> <option value="3" selected> Snipey </option> <option value="4"> Max </option> <option value="5"> Firebot </option> </select> </p> When there is no default option, a placeholder can be used instead: <select name="unittype" required> <option value=""> Select unit type </option> <option value="1"> Miner </option> <option value="2"> Puffer </option> <option value="3"> Snipey </option> <option value="4"> Max </option> <option value="5"> Firebot </option> </select> Here, the user is offered a set of options from which he can select any number. By default,
all five options are selected. <p> <label for="allowedunits">Select unit types to enable on this map:</label> <select id="allowedunits" name="allowedunits" multiple> <option value="1" selected> Miner </option> <option value="2" selected> Puffer </option> <option value="3" selected> Snipey </option> <option value="4" selected> Max </option> <option value="5" selected> Firebot </option> </select> </p> Sometimes, a user has to select one or more items. This example shows such an interface. <p>Select the songs from that you would like on your Act II Mix Tape:</p>
http://developers.whatwg.org/the-button-element.html[4/16/2014 9:34:40 PM]

4.10.6 The button element HTML: The Living Standard - Edition for Web Developers

<select multiple required name="act2"> <option value="s1">It Sucks to Be Me (Reprise) <option value="s2">There is Life Outside Your Apartment <option value="s3">The More You Ruv Someone <option value="s4">Schadenfreude <option value="s5">I Wish I Could Go Back to College <option value="s6">The Money Song <option value="s7">School for Monsters <option value="s8">The Money Song (Reprise) <option value="s9">There's a Fine, Fine Line (Reprise) <option value="s10">What Do You Do With a B.A. in English? (Reprise) <option value="s11">For Now </select>

The datalist element


Categories: Flow content. Phrasing content. Contexts in which this element can be used: Where phrasing content is expected. Content model: Either: phrasing content. Or: Zero or more option elements. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes DOM interface: The datalist element represents a set of option elements that
represent predefined options for other controls. In the rendering, the datalist
element represents nothing. The datalist element can be used in two ways. In the simplest case, the

http://developers.whatwg.org/the-button-element.html[4/16/2014 9:34:40 PM]

4.10.6 The button element HTML: The Living Standard - Edition for Web Developers

datalist element has just option element children. <label> Sex: <input name=sex list=sexes> <datalist id=sexes> <option value="Female"> <option value="Male"> </datalist> </label> In the more elaborate case, the datalist element can be given contents that are to
be displayed for down-level clients that don't support datalist. In this case, the
option elements are provided inside a select element inside the datalist element. <label> Sex: <input name=sex list=sexes> </label> <datalist id=sexes> <label> or select from the list: <select name=sex> <option value=""> <option>Female <option>Male </select> </label> </datalist> The datalist element is hooked up to an input element using the list attribute on the input element. Each option element that is a descendant of the datalist element,
that is not disabled, and whose value is a string that isn't the empty string, represents a
suggestion. Each suggestion has a value and a label. datalist . options Returns an HTMLCollection of the options elements of the
datalist element.

http://developers.whatwg.org/the-button-element.html[4/16/2014 9:34:40 PM]

4.10.6 The button element HTML: The Living Standard - Edition for Web Developers

The optgroup element


Categories: None. Contexts in which this element can be used: As a child of a select element. Content model: Zero or more option and script-supporting elements. Tag omission in text/html: An optgroup element's end tag can be omitted
if the optgroup element is immediately followed by another optgroup element, or if there is no more content in
the parent element. Content attributes: Global attributes disabled Whether the form control is disabled label User-visible label DOM interface: The optgroup element represents a group of option
elements with a common label. The element's group of option elements consists of the option
elements that are children of the optgroup element. The disabled attribute is a
boolean attribute and can be used to disable a group of option elements
together. The label attribute must be specified. Its
value gives the name of the group, for the purposes of the user interface. The following snippet shows how a set of lessons from three courses could be offered in a
select drop-down widget: <form action="courseselector.dll" method="get"> <p>Which course would you like to watch today? <p><label>Course: <select name="c">

http://developers.whatwg.org/the-button-element.html[4/16/2014 9:34:40 PM]

4.10.6 The button element HTML: The Living Standard - Edition for Web Developers

<optgroup label="8.01 Physics I: Classical Mechanics"> <option value="8.01.1">Lecture 01: Powers of Ten <option value="8.01.2">Lecture 02: 1D Kinematics <option value="8.01.3">Lecture 03: Vectors <optgroup label="8.02 Electricity and Magnestism"> <option value="8.02.1">Lecture 01: What holds our world together? <option value="8.02.2">Lecture 02: Electric Field <option value="8.02.3">Lecture 03: Electric Flux <optgroup label="8.03 Physics III: Vibrations and Waves"> <option value="8.03.1">Lecture 01: Periodic Phenomenon <option value="8.03.2">Lecture 02: Beats <option value="8.03.3">Lecture 03: Forced Oscillations with Damping </select> </label> <p><input type=submit value=" </form> Play">

The option element


Categories: None. Contexts in which this element can be used: As a child of a select element. As a child of a datalist element. As a child of an optgroup element. Content model: If the element has a label attribute and a value attribute: Empty. If the element has a label attribute but no value attribute: Text. If the element has no label attribute: Text that is not inter-element whitespace. Tag omission in text/html: An option element's end tag can be omitted if
the option element is immediately followed by another option element, or
if it is immediately followed by an optgroup element, or if there is no more content
in the parent

http://developers.whatwg.org/the-button-element.html[4/16/2014 9:34:40 PM]

4.10.6 The button element HTML: The Living Standard - Edition for Web Developers

element. Content attributes: Global attributes disabled Whether the form control is disabled label User-visible label selected Whether the option is selected by default value Value to be used for form submission DOM interface: The option element represents an option in a select
element or as part of a list of suggestions in a datalist element. In certain circumstances described in the definition of the select element, an
option element can be a select element's placeholder label
option. A placeholder label option does not represent an actual option, but
instead represents a label for the select control. The disabled attribute is a boolean
attribute. An option element is disabled if its disabled attribute is present or if it is a child of an
optgroup element whose disabled attribute
is present. The label attribute provides a label for
element. The label of an option element is
the value of the label content attribute, if there is one,
or, if there is not, the value of the element's text IDL
attribute. The label content attribute, if specified, must not be
empty. The value attribute provides a value for
element. The value of an option element is
the value of the value content attribute, if there is one,
or, if there is not, the value of the element's text IDL
attribute. The selected attribute is a boolean
attribute. It represents the default selectedness of the element. A select element whose multiple
attribute is not specified must not have more than one descendant option element with
its selected attribute set. option . selected Returns true if the element is selected, and false otherwise.

http://developers.whatwg.org/the-button-element.html[4/16/2014 9:34:40 PM]

4.10.6 The button element HTML: The Living Standard - Edition for Web Developers

Can be set, to override the current state of the element. option . index Returns the index of the element in its select element's options list. option . form Returns the element's form element, if any, or null otherwise. option . text Same as textContent, except that spaces are collapsed and script elements are skipped. option = new Option ( [ text [, value [, defaultSelected [, selected ] ] ]]) Returns a new option element. The text argument sets the contents of the element. The value argument sets the value
attribute. The defaultSelected argument sets the selected attribute. The selected argument sets whether or not the element is selected. If it
is omitted, even if the defaultSelected argument is true, the element is not selected.

The textarea element


Categories: Flow content. Phrasing content. Interactive content. Listed, labelable, submittable, resettable, and reassociateable form-associated element. Palpable content. Contexts in which this element can be used: Where phrasing content is expected. Content model: Text.

http://developers.whatwg.org/the-button-element.html[4/16/2014 9:34:40 PM]

4.10.6 The button element HTML: The Living Standard - Edition for Web Developers

Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes autocomplete Hint for form autofill feature autofocus Automatically focus the form control when the page is loaded cols Maximum number of characters per line dirname Name of form field to use for sending the element's directionality in form submission disabled Whether the form control is disabled form Associates the control with a form element inputmode Hint for selecting an input modality maxlength Maximum length of value minlength Minimum length of value name Name of form control to use for form submission and in the form.elements API placeholder User-visible label to be placed within the form control readonly Whether to allow the value to be edited by the user required Whether the control is required for form submission rows Number of lines to show wrap How the value of the form control is to be wrapped for form submission DOM interface: The textarea element represents a multiline plain text edit
control. The contents of the control represent the control's default value. The readonly attribute is a
boolean attribute used to control whether the text can be edited by the user or
not. In this example, a text field is marked read-only because it represents a readonly file: Filename: <code>/etc/bash.bashrc</code> <textarea name="buffer" readonly>

http://developers.whatwg.org/the-button-element.html[4/16/2014 9:34:40 PM]

4.10.6 The button element HTML: The Living Standard - Edition for Web Developers

# System-wide .bashrc file for interactive bash(1) shells. # To enable the settings / commands in this file for login shells as well, # this file has to be sourced in /etc/profile. # If not running interactively, don't do anything [ -z "$PS1" ] &amp;&amp; return ...</textarea> The cols attribute specifies the expected
maximum number of characters per line. If the cols
attribute is specified, its value must be a valid non-negative integer greater than
zero. The rows attribute specifies the number of
lines to show. If the rows attribute is specified, its
value must be a valid non-negative integer greater than zero. The wrap attribute is an enumerated
attribute with two keywords and states: the soft keyword which maps to the Soft state, and the hard keyword which maps to the Hard state. The missing value default is the
Soft state. The Soft state indicates that the text in the
textarea is not to be wrapped when it is submitted (though it can still be wrapped in
the rendering). The Hard state indicates that the text in the
textarea is to have newlines added by the user agent so that the text is wrapped when
it is submitted. If the element's wrap attribute is in the Hard state, the cols attribute must be specified. The maxlength attribute is a form control maxlength attribute controlled
by the textarea element's dirty value
flag. If the textarea element has a maximum allowed value length, then the element's children must be such that the code-unit length of the value of the element's textContent IDL attribute is equal to or less than the element's maximum allowed value length. The minlength attribute is a form control minlength attribute controlled
by the textarea element's dirty value
flag. The required attribute is a
boolean attribute. When specified, the user will be

http://developers.whatwg.org/the-button-element.html[4/16/2014 9:34:40 PM]

4.10.6 The button element HTML: The Living Standard - Edition for Web Developers

required to enter a value before


submitting the form. The placeholder attribute represents
a short hint (a word or short phrase) intended to aid the user with data entry when the
control has no value. A hint could be a sample value or a brief description of the expected
format. The placeholder attribute should not be used as
an alternative to a label. For a longer hint or other advisory text, the title attribute is more appropriate. These mechanisms are very similar but subtly different: the hint given by the control's label is shown at all times; the short hint given in the placeholder attribute is shown before the user enters a
value; and the hint in the title attribute is shown when the user
requests further help.
The name attribute represents the element's name.
The dirname attribute controls how the element's directionality is submitted.
The disabled attribute is used to make the control
non-interactive and to prevent its value from being submitted.
The form attribute is used to explicitly associate the textarea element with its form owner.
The autofocus attribute controls focus.
The inputmode attribute controls the user interface's input
modality for the control.
The autocomplete attribute controls how the user agent provides autofill behavior. textarea . type Returns the string "textarea". textarea . value Returns the current value of the element. Can be set, to change the value. Here is an example of a textarea being used for unrestricted free-form text input
in a form: <p>If you have any comments, please let us know: <textarea cols=80 name=comments></textarea></p> To specify a maximum length for the comments, one can use the maxlength attribute: <p>If you have any short comments, please let us know:

http://developers.whatwg.org/the-button-element.html[4/16/2014 9:34:40 PM]

4.10.6 The button element HTML: The Living Standard - Edition for Web Developers

<textarea cols=80 name=comments maxlength=200></textarea></p> To give a default value, text can be included inside the element: <p>If you have any comments, please let us know: <textarea cols=80 name=comments>You rock!</textarea></p> You can also give a minimum length. Here, a letter needs to be filled out by the user; a
template (which is shorter than the minimum length) is provided, but is insufficient to submit
the form: <textarea required minlength="500">Dear Madam Speaker, Regarding your letter dated ... ... Yours Sincerely, ...</textarea> A placeholder can be given as well, to suggest the basic form to the user, without providing
an explicit template: <textarea placeholder="Dear Francine, They closed the parks this week, so we won't be able to meet your there. Should we just have dinner? Love, Daddy"></textarea> To have the browser submit the directionality of
the element along with the value, the dirname attribute can be
specified: <p>If you have any comments, please let us know (you may use either English or Hebrew for your comments): <textarea cols=80 name=comments dirname=comments.dir> </textarea></p>

http://developers.whatwg.org/the-button-element.html[4/16/2014 9:34:40 PM]

4.10.6 The button element HTML: The Living Standard - Edition for Web Developers

The keygen element


Categories: Flow content. Phrasing content. Interactive content. Listed, labelable, submittable, resettable, and reassociateable form-associated element. Palpable content. Contexts in which this element can be used: Where phrasing content is expected. Content model: Empty. Tag omission in text/html: No end tag. Content attributes: Global attributes autofocus Automatically focus the form control when the page is loaded challenge String to package with the generated and signed public key disabled Whether the form control is disabled form Associates the control with a form element keytype The type of cryptographic key to generate name Name of form control to use for form submission and in the form.elements API DOM interface: The keygen element represents a key pair generator control. When the control's form is submitted, the private key is stored in the local keystore, and the public key
is packaged and sent to the server. The challenge attribute may be specified.
Its value will be packaged with the submitted key. The keytype attribute is an
enumerated attribute. The following table lists the keywords and states for the
attribute the keywords in the left column map to the states listed in the cell in the
second column on the same row as the
http://developers.whatwg.org/the-button-element.html[4/16/2014 9:34:40 PM]

4.10.6 The button element HTML: The Living Standard - Edition for Web Developers

keyword. User agents are not required to support these


values, and must only recognize values whose corresponding algorithms they support. Keyword State rsa RSA

The invalid value default state is the unknown state. The missing
value default state is the RSA state, if it is supported, or the unknown state otherwise. This specification does not specify what key types user agents are to support it is possible for a user agent to not support any key types at all. The form attribute is used to explicitly associate the
keygen element with its form owner. The name attribute represents the element's name. The disabled attribute is used to make the control non-interactive and
to prevent its value from being submitted. The autofocus
attribute controls focus. keygen . type Returns the string "keygen ".

This specification does not specify how the private key generated is to be used.
It is expected that after receiving the SignedPublicKeyAndChallenge (SPKAC)
structure, the server will generate a client certificate and offer it back to the user for
download; this certificate, once downloaded and stored in the key store along with the private
key, can then be used to authenticate to services that use TLS and certificate authentication. To generate a key pair, add the private key to the user's key store, and submit the public key
to the server, markup such as the following can be used: <form action="processkey.cgi" method="post" enctype="multipart/form-data"> <p><keygen name="key"></p> <p><input type=submit value="Submit key..."></p> </form> The server will then receive a form submission with a packaged RSA public key as the value of
"key". This can then be used for various purposes, such as generating a
client certificate, as mentioned above.

http://developers.whatwg.org/the-button-element.html[4/16/2014 9:34:40 PM]

4.10.6 The button element HTML: The Living Standard - Edition for Web Developers

The output element


Categories: Flow content. Phrasing content. Listed, labelable, resettable, and reassociateable form-associated element. Palpable content. Contexts in which this element can be used: Where phrasing content is expected. Content model: Phrasing content. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes for Specifies controls from which the output was calculated form Associates the control with a form element name Name of form control to use for form submission and in the form.elements API DOM interface: The output element represents the result of a calculation or user
action. The for content attribute allows an explicit
relationship to be made between the result of a calculation and the elements that represent the
values that went into the calculation or that otherwise influenced the calculation. The for attribute, if specified, must contain a string consisting of an
unordered set of unique space-separated tokens that are case-sensitive,
each of which must have the value of an ID of an element in the
same Document. The form attribute is used to explicitly associate the
output element with its form owner. The name attribute represents the element's name. output . value [ = value ]

http://developers.whatwg.org/the-button-element.html[4/16/2014 9:34:40 PM]

4.10.6 The button element HTML: The Living Standard - Edition for Web Developers

Returns the element's current value. Can be set, to change the value. output . defaultValue [ = value ] Returns the element's current default value. Can be set, to change the default value. output . type Returns the string "output ". A simple calculator could use output for its display of calculated results: <form onsubmit="return false" oninput="o.value = a.valueAsNumber + b.valueAsNumber"> <input name=a type=number step=any> + <input name=b type=number step=any> = <output name=o></output> </form>

The progress element


Categories: Flow content. Phrasing content. Labelable element. Palpable content. Contexts in which this element can be used: Where phrasing content is expected. Content model: Phrasing content, but there must be no progress element descendants. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes value Current value of the element

http://developers.whatwg.org/the-button-element.html[4/16/2014 9:34:40 PM]

4.10.6 The button element HTML: The Living Standard - Edition for Web Developers

max Upper bound of range DOM interface: The progress element represents the completion progress of a task.
The progress is either indeterminate, indicating that progress is being made but that it is not
clear how much more work remains to be done before the task is complete (e.g. because the task is
waiting for a remote host to respond), or the progress is a number in the range zero to a maximum,
giving the fraction of work that has so far been completed. There are two attributes that determine the current task completion represented by the element.
The value attribute specifies how much of the task has been completed, and the max attribute
specifies how much work the task requires in total. The units are arbitrary and not specified. To make a determinate progress bar, add a value attribute with the current progress (either a number from
0.0 to 1.0, or, if the max attribute is specified, a number
from 0 to the value of the max attribute). To make an indeterminate progress bar, remove the value
attribute. Authors are encouraged to also include the current value and the maximum value inline as text
inside the element, so that the progress is made available to users of legacy user agents. Here is a snippet of a Web application that shows the progress of some automated task: <section> <h2>Task Progress</h2> <p>Progress: <progress id="p" max=100><span>0</span>% </progress></p> <script> var progressBar = document.getElementById('p'); function updateProgress(newValue) { progressBar.value = newValue; progressBar.getElementsByTagName('span')[0].textContent = newValue; } </script> </section>

http://developers.whatwg.org/the-button-element.html[4/16/2014 9:34:40 PM]

4.10.6 The button element HTML: The Living Standard - Edition for Web Developers

(The updateProgress() method in this example would be called by some other code
on the page to update the actual progress bar as the task progressed.) The value and max attributes, when present, must have values that are valid floating-point numbers. The value attribute, if present, must have a value equal to or
greater than zero, and less than or equal to the value of the max attribute, if present, or 1.0, otherwise. The max attribute, if present, must have a value greater than
zero. The progress element is the wrong element to use for something that
is just a gauge, as opposed to task progress. For instance, indicating disk space usage using
progress would be inappropriate. Instead, the meter element is available
for such use cases. progress . position For a determinate progress bar (one with known current and maximum values), returns the
result of dividing the current value by the maximum value. For an indeterminate progress bar, returns 1.

The meter element


Categories: Flow content. Phrasing content. Labelable element. Palpable content. Contexts in which this element can be used: Where phrasing content is expected. Content model: Phrasing content, but there must be no meter element descendants. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes

http://developers.whatwg.org/the-button-element.html[4/16/2014 9:34:40 PM]

4.10.6 The button element HTML: The Living Standard - Edition for Web Developers

value Current value of the element min Lower bound of range max Upper bound of range low High limit of low range high Low limit of high range optimum Optimum value in gauge DOM interface: The meter element represents a scalar measurement within a known
range, or a fractional value; for example disk usage, the relevance of a query result, or the
fraction of a voting population to have selected a particular candidate. This is also known as a gauge. The meter element should not be used to indicate progress (as in a
progress bar). For that role, HTML provides a separate progress element. The meter element also does not represent a scalar value of arbitrary
range for example, it would be wrong to use this to report a weight, or height, unless
there is a known maximum value. There are six attributes that determine the semantics of the gauge represented by the
element. The min attribute specifies the lower bound of
the range, and the max attribute specifies the
upper bound. The value attribute specifies the
value to have the gauge indicate as the "measured" value. The other three attributes can be used to segment the gauge's range into "low", "medium", and
"high" parts, and to indicate which part of the gauge is the "optimum" part. The low attribute specifies the range that is considered to
be the "low" part, and the high attribute
specifies the range that is considered to be the "high" part. The optimum attribute gives the position that is "optimum"; if that is higher than the "high" value then this indicates that the higher the value,
the better; if it's lower than the "low" mark then it indicates that lower values are better, and
naturally if it is in between then it indicates that neither high nor low values are good. The value attribute must be specified. The value , min, low, high, max, and optimum attributes,
when present, must have values that are valid
floatinghttp://developers.whatwg.org/the-button-element.html[4/16/2014 9:34:40 PM]

4.10.6 The button element HTML: The Living Standard - Edition for Web Developers

point numbers. In addition, the attributes' values are further constrained: Let value be the value attribute's
number. If the min attribute is specified, then let minimum be that attribute's value; otherwise, let it be zero. If the max attribute is specified, then let maximum be that attribute's value; otherwise, let it be 1.0. The following inequalities must hold, as applicable:

minimum value maximum minimum low maximum (if low is specified) minimum high maximum (if high is specified) minimum optimum maximum (if optimum is specified) low high (if
both low and high are
specified)
If no minimum or maximum is specified, then the range is assumed to be 0..1, and
the value thus has to be within that range. Authors are encouraged to include a textual representation of the gauge's state in the
element's contents, for users of user agents that do not support the meter
element. When used with microdata, the meter element's value attribute provides the element's machine-readable value. The following examples show three gauges that would all be three-quarters full: Storage space usage: <meter value=6 max=8>6 blocks used (out of 8 total)</meter> Voter turnout: <meter value=0.75><img alt="75%" src="graph75.png"></meter> Tickets sold: <meter min="0" max="100" value="75"></meter> The following example is incorrect use of the element, because it doesn't give a range (and
since the default maximum is 1, both of the gauges would end up looking maxed out): <p>The grapefruit pie had a radius of <meter

http://developers.whatwg.org/the-button-element.html[4/16/2014 9:34:40 PM]

4.10.6 The button element HTML: The Living Standard - Edition for Web Developers

value=12>12cm</meter> and a height of <meter value=2>2cm</meter>.</p> <!-- BAD! --> Instead, one would either not include the meter element, or use the meter element with a
defined range to give the dimensions in context compared to other pies: <p>The grapefruit pie had a radius of 12cm and a height of 2cm.</p> <dl> <dt>Radius: <dd> <meter min=0 max=20 value=12>12cm</meter> <dt>Height: <dd> <meter min=0 max=10 value=2>2cm</meter> </dl> There is no explicit way to specify units in the meter element, but the units may
be specified in the title attribute in free-form text. The example above could be extended to mention the units: <dl> <dt>Radius: <dd> <meter min=0 max=20 value=12 title="centimeters">12cm</meter> <dt>Height: <dd> <meter min=0 max=10 value=2 title="centimeters">2cm</meter> </dl> The following markup: <h3>Suggested groups</h3> <menu type="toolbar"> <a href="?cmd=hsg" onclick="hideSuggestedGroups()">Hide suggested groups</a> </menu> <ul> <li> <p><a href="/group/comp.infosystems.www.authoring.stylesheets/view" >comp.infosystems.www.authoring.stylesheets</a> <a href="/group/comp.infosystems.www.authoring.stylesheets/subsc ribe">join</a></p> <p>Group description: <strong>Layout/presentation on the

http://developers.whatwg.org/the-button-element.html[4/16/2014 9:34:40 PM]

4.10.6 The button element HTML: The Living Standard - Edition for Web Developers

WWW.</strong></p> <p><meter value="0.5">Moderate activity,</meter> Usenet, 618 subscribers</p> </li> <li> <p><a href="/group/netscape.public.mozilla.xpinstall/view">netscape .public.mozilla.xpinstall</a> <a href="/group/netscape.public.mozilla.xpinstall/subscribe">joi n</a></p> <p>Group description: <strong>Mozilla XPInstall discussion. </strong></p> <p><meter value="0.25">Low activity,</meter> Usenet, 22 subscribers</p> </li> <li> <p><a href="/group/mozilla.dev.general/view">mozilla.dev.general</a > <a href="/group/mozilla.dev.general/subscribe">join</a> </p> <p><meter value="0.25">Low activity,</meter> Usenet, 66 subscribers</p> </li> </ul> Might be rendered as follows:

User agents combine the value of the title attribute and the other attributes to provide context-sensitive
help or inline text detailing the actual values. For example, the following snippet:

http://developers.whatwg.org/the-button-element.html[4/16/2014 9:34:40 PM]

4.10.6 The button element HTML: The Living Standard - Edition for Web Developers

<meter min=0 max=60 value=23.2 title=seconds></meter> ...might cause the user agent to display a gauge with a tooltip
saying "Value: 23.2 out of 60." on one line and "seconds" on a
second line. The following example shows how a gauge could fall back to localized or pretty-printed
text. <p>Disk usage: <meter min=0 value=170261928 max=233257824>170261928 bytes used out of 233257824 bytes available</meter></p>

The fieldset element


Categories: Flow content. Sectioning root. Listed and reassociateable form-associated element. Palpable content. Contexts in which this element can be used: Where flow content is expected. Content model: Optionally a legend element, followed by flow content. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes disabled Whether the form control is disabled form Associates the control with a form element name Name of form control to use for form submission and in the form.elements API DOM interface: The fieldset element represents a set of form controls optionally
grouped under a common name.

http://developers.whatwg.org/the-button-element.html[4/16/2014 9:34:40 PM]

4.10.6 The button element HTML: The Living Standard - Edition for Web Developers

The name of the group is given by the first legend element that is a child of the
fieldset element, if any. The remainder of the descendants form the group. The disabled attribute, when specified,
causes all the form control descendants of the fieldset element, excluding those that
are descendants of the fieldset element's first legend element child, if
any, to be disabled. The form attribute is used to explicitly associate the
fieldset element with its form owner. The name attribute represents the element's name. fieldset . type Returns the string "fieldset". fieldset . elements Returns an HTMLFormControlsCollection of the form controls in the element. This example shows a fieldset element being used to group a set of related controls: <fieldset> <legend>Display</legend> <p><label><input type=radio name=c value=0 checked> Black on White</label> <p><label><input type=radio name=c value=1> White on Black</label> <p><label><input type=checkbox name=g> Use grayscale</label> <p><label>Enhance contrast <input type=range name=e list=contrast min=0 max=100 value=0 step=1></label> <datalist id=contrast> <option label=Normal value=0> <option label=Maximum value=100> </datalist> </fieldset> The following snippet shows a fieldset with a checkbox in the legend that controls whether or
not the fieldset is enabled. The contents of the fieldset consist of two required text fields and
an optional year/month control. <fieldset name="clubfields" disabled>
http://developers.whatwg.org/the-button-element.html[4/16/2014 9:34:40 PM]

4.10.6 The button element HTML: The Living Standard - Edition for Web Developers

<legend> <label> <input type=checkbox name=club onchange="form.clubfields.disabled = !checked"> Use Club Card </label> </legend> <p><label>Name on card: <input name=clubname required> </label></p> <p><label>Card number: <input name=clubnum required pattern="[-0-9]+"></label></p> <p><label>Expiry date: <input name=clubexp type=month> </label></p> </fieldset> You can also nest fieldset elements. Here is an example expanding on the previous
one that does so: <fieldset name="clubfields" disabled> <legend> <label> <input type=checkbox name=club onchange="form.clubfields.disabled = !checked"> Use Club Card </label> </legend> <p><label>Name on card: <input name=clubname required> </label></p> <fieldset name="numfields"> <legend> <label> <input type=radio checked name=clubtype onchange="form.numfields.disabled = !checked"> My card has numbers on it </label> </legend> <p><label>Card number: <input name=clubnum required pattern="[-0-9]+"></label></p> </fieldset> <fieldset name="letfields" disabled> <legend> <label> <input type=radio name=clubtype onchange="form.letfields.disabled = !checked"> My card has letters on it </label> </legend> <p><label>Card code: <input name=clublet required pattern=" [A-Za-z]+"></label></p>
http://developers.whatwg.org/the-button-element.html[4/16/2014 9:34:40 PM]

4.10.6 The button element HTML: The Living Standard - Edition for Web Developers

</fieldset> </fieldset> In this example, if the outer "Use Club Card" checkbox is not checked, everything inside the
outer fieldset, including the two radio buttons in the legends of the two nested
fieldsets, will be disabled. However, if the checkbox is checked, then the radio
buttons will both be enabled and will let you select which of the two inner
fieldsets is to be enabled.

The legend element


Categories: None. Contexts in which this element can be used: As the first child of a fieldset element. Content model: Phrasing content. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes DOM interface: The legend element represents a caption for the rest of the contents
of the legend element's parent fieldset element. legend . form Returns the element's form element, if any, or null otherwise.

Form control infrastructure

A form control's value


Form controls have a value and a checkedness. (The latter is only used by

http://developers.whatwg.org/the-button-element.html[4/16/2014 9:34:40 PM]

4.10.6 The button element HTML: The Living Standard - Edition for Web Developers

input
elements.) These are used to describe how the user interacts with the control. To define the behaviour of constraint validation in the face of the input element's multiple attribute, input elements
can also have separately defined values.

Mutability
A form control can be designated as mutable. This determines (by means of definitions and requirements in this specification
that rely on whether an element is so designated) whether or not the user can modify the value or checkedness of a
form control, or whether or not a control can be automatically prefilled.

Up next

4.10.18.3 Association of controls and forms

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/the-button-element.html[4/16/2014 9:34:40 PM]

4.10.18.3 Association of controls and forms HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
Association of controls and forms
Attributes common to form controls
Naming form controls: the name attribute
Submitting element directionality: the dirname attribute
Limiting user input length: the maxlength attribute
Setting minimum input length requirements: the minlength attribute
Enabling and disabling form controls: the disabled attribute
Form submission
Autofocusing a form control: the autofocus attribute
Input modalities: the inputmode attribute
Autofilling form controls: the autocomplete attribute
APIs for the text field selections
Constraints
Definitions
The constraint validation API
Security
Form submission
URL-encoded form data
Multipart form data
Plain text form data

Association of controls and forms


A form-associated element can have a relationship with a form
element, which is called the element's form owner. If a form-associated
element is not associated with a form element, its form owner is
said to be null. A form-associated element is, by default, associated with its ancestor form element, but, if it is reassociateable, may have a
form attribute specified to override this. This feature allows authors to work around the lack of support for nested form elements. If a reassociateable form-associated
element has a form attribute specified,

http://developers.whatwg.org/association-of-controls-and-forms.html[4/16/2014 9:34:49 PM]

4.10.18.3 Association of controls and forms HTML: The Living Standard - Edition for Web Developers

then that
attribute's value must be the ID of a form element in
the element's owner Document. element . form Returns the element's form owner. Returns null if there isn't one.

Attributes common to form controls

Naming form controls: the name attribute


The name content attribute gives the name of the
form control, as used in form submission and in the form element's elements object. If the attribute is specified, its value must
not be the empty string. Any non-empty value for name is allowed, but the names
"_charset_ " and " isindex" are special: isindex This value, if used as the name of a Text control
that is the first control in a form that is submitted using the application/x-www-form-urlencoded mechanism, causes
the submission to only include the value of this control, with no name. _charset_ This value, if used as the name of a Hidden
control with no value attribute, is automatically given a
value during submission consisting of the submission character encoding.

Submitting element directionality: the dirname attribute


The dirname attribute on a form control element
enables the submission of the directionality of the element, and gives the name of
the field that contains this value during form submission. If such an attribute is
specified, its value must not be the empty string. In this example, a form contains a text field and a submission button: <form action="addcomment.cgi" method=post> <p><label>Comment: <input type=text name="comment" dirname="comment.dir" required></label></p> <p><button name="mode" type=submit value="add">Post Comment</button></p>

http://developers.whatwg.org/association-of-controls-and-forms.html[4/16/2014 9:34:49 PM]

4.10.18.3 Association of controls and forms HTML: The Living Standard - Edition for Web Developers

</form> When the user submits the form, the user agent includes three fields, one called "comment",
one called "comment.dir", and one called "mode"; so if the user types "Hello", the submission
body might be something like: comment=Hello&comment.dir=ltr&mode=add If the user manually switches to a right-to-left writing direction and enters "", the submission body might be
something like: comment=%D9%85%D8%B1%D8%AD%D8%A8%D8%A7&comment.dir=rtl&mode=a dd

Limiting user input length: the maxlength attribute


A form control maxlength attribute,
controlled by a dirty value flag, declares a limit on the number of characters
a user can input. If an element has its form control maxlength attribute specified, the attribute's value must be a valid
non-negative integer. If the attribute is specified and applying the rules for
parsing non-negative integers to its value results in a number, then that number is the
element's maximum allowed value length. If the attribute is omitted or parsing its
value results in an error, then there is no maximum allowed value length.

Setting minimum input length requirements: the minlength attribute


A form control minlength attribute,
controlled by a dirty value flag, declares a lower bound on the number of
characters a user can input. The minlength attribute does not imply the
required attribute. If the form control has no minlength attribute, then the value can still be omitted; the minlength attribute only kicks in once the user has entered
a value at all. If the empty string is not allowed, then the required
attribute also needs to be set. If an element has its form control minlength attribute specified, the attribute's value must be a valid
non-negative integer. If the attribute is specified and applying the rules for
parsing non-negative integers to its value results in a number, then that number is the
element's minimum allowed value length. If the attribute is omitted or parsing its
value results in an error, then there is no minimum allowed value length. If an element has both a maximum allowed value length and a minimum

http://developers.whatwg.org/association-of-controls-and-forms.html[4/16/2014 9:34:49 PM]

4.10.18.3 Association of controls and forms HTML: The Living Standard - Edition for Web Developers

allowed
value length, the minimum allowed value length must be smaller than or equal
to the maximum allowed value length. In this example, there are four text fields. The first is required, and has to be at least 5
characters long. The other three are optional, but if the user fills one in, the user has to
enter at least 10 characters. <form action="/events/menu.cgi" method="post"> <p><label>Name of Event: <input required minlength=5 maxlength=50 name=event></label></p> <p><label>Describe what you would like for breakfast, if anything: <textarea name="breakfast" minlength="10"></textarea> </label></p> <p><label>Describe what you would like for lunch, if anything: <textarea name="lunch" minlength="10"></textarea></label> </p> <p><label>Describe what you would like for dinner, if anything: <textarea name="dinner" minlength="10"></textarea> </label></p> <p><input type=submit value="Submit Request"></p> </form>

Enabling and disabling form controls: the disabled attribute


The disabled content attribute is a
boolean attribute. A form control is disabled if its disabled attribute is set, or if it is a descendant of a
fieldset element whose disabled attribute
is set and is not a descendant of that fieldset element's first
legend element child, if any.

Form submission
Attributes for form submission can be specified both on form elements
and on submit buttons (elements that represent buttons
that submit forms, e.g. an input element whose type attribute is in the Submit Button state). The attributes for form submission that may be specified on form
elements are action, enctype , method, novalidate, and target. The corresponding attributes for form submission that may be specified on submit buttons are formaction, formenctype, formmethod, formnovalidate , and formtarget . When omitted, they default to the values given on
the corresponding attributes on the form element.

http://developers.whatwg.org/association-of-controls-and-forms.html[4/16/2014 9:34:49 PM]

4.10.18.3 Association of controls and forms HTML: The Living Standard - Edition for Web Developers

The action and formaction content attributes, if specified, must


have a value that is a valid non-empty URL potentially surrounded by spaces. The action of an element is the value of the element's
formaction attribute, if the element is a submit button and has such an attribute, or the value of its form owner's action attribute, if it has
one, or else the empty string. The method and formmethod content attributes are enumerated attributes with the following keywords and
states:

The keyword get, mapping to the


state GET, indicating the HTTP GET
method.

The keyword post, mapping to the


state POST, indicating the HTTP POST
method.

The keyword dialog, mapping to


the state dialog, indicating that submitting
the
form is intended to close the dialog box in which the form finds
itself, if any, and otherwise not submit. The invalid value default for these attributes is the GET state. The missing value default for the method attribute is also the GET state. (There is no missing value default for the
formmethod attribute.) The method of an element is one of those states. If the
element is a submit button and has a formmethod attribute, then the element's method is that attribute's state; otherwise, it is the form
owner's method attribute's state. The enctype and formenctype content attributes are enumerated attributes with the following keywords and
states:

The "application/x-www-form-urlencoded " keyword and corresponding


state.

The "multipart/form-data" keyword and corresponding state. The "text/plain" keyword and corresponding state.
The invalid value default for these attributes is the application/x-www-form-urlencoded state. The missing
value default for the enctype attribute is also the application/x-www-form-urlencoded state. (There is no
missing value default for the formenctype
attribute.) The enctype of an element is one of those three states.
If the element is a submit button and has a formenctype attribute, then the element's enctype is that attribute's state; otherwise, it is the
form owner's enctype attribute's state. The target and formtarget content attributes, if specified, must
have values that are valid browsing context
names or keywords. The target of an element is the value of the element's
formtarget attribute, if the element is a submit button and has such an attribute; or the value of its

http://developers.whatwg.org/association-of-controls-and-forms.html[4/16/2014 9:34:49 PM]

4.10.18.3 Association of controls and forms HTML: The Living Standard - Edition for Web Developers

form owner's target attribute, if it has


such an attribute; or, if the Document contains a base element with a
target attribute, then the value of the target attribute of the first such base element; or,
if there is no such element, the empty string. The novalidate and formnovalidate content attributes are boolean attributes. If present, they indicate that the form is
not to be validated during submission. The no-validate state of an element is true if the
element is a submit button and the element's formnovalidate attribute is present, or if the element's form owner's novalidate attribute is present,
and false otherwise. This attribute is useful to include "save" buttons on forms that have validation constraints,
to allow users to save their progress even though they haven't fully entered the data in the
form. The following example shows a simple form that has two required fields. There are three
buttons: one to submit the form, which requires both fields to be filled in; one to save the form
so that the user can come back and fill it in later; and one to cancel the form altogether. <form action="editor.cgi" method="post"> <p><label>Name: <input required name=fn></label></p> <p><label>Essay: <textarea required name=essay></textarea> </label></p> <p><input type=submit name=submit value="Submit essay"></p> <p><input type=submit formnovalidate name=save value="Save essay"></p> <p><input type=submit formnovalidate name=cancel value="Cancel"></p> </form>

Autofocusing a form control: the autofocus attribute


The autofocus content attribute allows the
author to indicate that a control is to be focused as soon as the page is loaded or as soon as the
dialog within which it finds itself is shown, allowing the user to just start typing
without having to manually focus the main control. The autofocus attribute is a boolean
attribute. An element's nearest ancestor autofocus scoping root element is the element itself
if the element is a dialog element, or else is the element's nearest ancestor
dialog element, if any, or else is the element's root element. There must not be two elements with the same nearest ancestor autofocus scoping root
element that both have the autofocus attribute
specified.

http://developers.whatwg.org/association-of-controls-and-forms.html[4/16/2014 9:34:49 PM]

4.10.18.3 Association of controls and forms HTML: The Living Standard - Edition for Web Developers

In the following snippet, the text control would be focused when


the document was loaded. <input maxlength="256" name="q" value="" autofocus> <input type="submit" value="Search">

Input modalities: the inputmode attribute


The inputmode content attribute is an
enumerated attribute that specifies what kind of input mechanism would be most
helpful for users entering content into the form control. The possible keywords and states for the attributes are listed in the following table. The
keywords are listed in the first column. Each maps to the state given in the cell in the second
column of that keyword's row, and that state has the fallback state given in the cell in the third
column of that row. Keyword State Fallback state verbatim Latin Verbatim latin Default Alphanumeric Latin-script input of non-prose content, e.g. usernames, passwords, product codes. Latin Text Latin Verbatim Latin-script input in the user's preferred language(s), with some typing aids enabled
(e.g. text prediction). Intended for humanto-computer communications, e.g. free-form text
search fields. latinname Latin Name Latin Text Latin-script input in the user's preferred language(s), with typing aids intended for
entering human names enabled (e.g. text prediction from the user's contact list and automatic
capitalisation at every word). Intended for situations such as customer name fields. latinprose Latin Prose Latin Text Latin-script input in the user's preferred language(s), with aggressive typing aids
intended for human-to-human communications enabled (e.g. text prediction and automatic capitalisation at the start of sentences). Intended for situations such as e-mails and instant Description

http://developers.whatwg.org/association-of-controls-and-forms.html[4/16/2014 9:34:49 PM]

4.10.18.3 Association of controls and forms HTML: The Living Standard - Edition for Web Developers

messaging. fullwidthlatin Fullwidth Latin Latin Prose Latin-script input in the user's secondary language(s), using fullwidth characters, with
aggressive typing aids intended for humanto-human communications enabled (e.g. text prediction
and automatic capitalisation at the start of sentences). Intended for latin text embedded
inside CJK text. kana Kana Default Kana or romaji input, typically hiragana input, using full-width characters, with support
for converting to kanji. Intended for Japanese text input. katakana Katakana Kana Katakana input, using full-width characters, with support for converting to kanji.
Intended for Japanese text input. numeric Numeric Default Numeric input, including keys for the digits 0 to 9, the user's preferred thousands
separator character, and the character for indicating negative numbers. Intended for numeric
codes, e.g. credit card numbers. (For numbers, prefer " <input type=number>".) tel Telephone Numeric Telephone number input, including keys for the digits 0 to 9, the "#" character, and the
"*" character. In some locales, this can also include alphabetic mnemonic labels (e.g. in the
US, the key labeled "2" is historically also labeled with the letters A, B, and C). Rarely necessary; use " <input
type=tel>" instead. email E-mail Default Text input in the user's locale, with keys for aiding in the input of email addresses,
such as that for the "@" character and the "." character. Rarely
necessary; use " <input type=email> " instead.

http://developers.whatwg.org/association-of-controls-and-forms.html[4/16/2014 9:34:49 PM]

4.10.18.3 Association of controls and forms HTML: The Living Standard - Edition for Web Developers

url

URL

Default

Text input in the user's locale, with keys for aiding in the input of Web addresses, such
as that for the "/" and "." characters and for quick input of strings commonly found in domain
names such as "www." or ".co.uk". Rarely necessary; use " <input type=url>" instead.

The last three keywords listed above are only provided for completeness,
and are rarely necessary, as dedicated input controls exist for their usual use cases (as
described in the table above). User agents all support the Default input mode state, which corresponds to the
user agent's default input modality. The missing value default is the default input mode state.

Autofilling form controls: the autocomplete attribute


User agents sometimes have features for helping users fill forms in, for example prefilling the
user's address based on earlier user input. The autocomplete content attribute can be used to hint
to the user agent how to, or indeed whether to, provide such a feature. The attribute, if present, must have a value that is a set of space-separated tokens consisting of either a single token that is an ASCII case-insensitive match for the string "off", or a single token that
is an ASCII case-insensitive match for the string "on", or the following, in the order given below: 1. Optionally, a token whose first eight characters are an ASCII case-insensitive match for the string "section-", meaning that
the field belongs to the named group. For example, if there are two shipping addresses in the form, then they could be marked up
as: <fieldset> <legend>Ship the blue gift to...</legend> <p> <label> Address: <p> <label> City: <input name=ba <input name=bc autocomplete="section-blue shipping street-address"> </label> autocomplete="section-blue shipping region"> </label> <p> <label> Postal Code: <input name=bp autocomplete="section-blue shipping postal-code"> </label> </fieldset> <fieldset> <legend>Ship the red gift to...</legend> <p> <label> Address: <input name=ra

http://developers.whatwg.org/association-of-controls-and-forms.html[4/16/2014 9:34:49 PM]

4.10.18.3 Association of controls and forms HTML: The Living Standard - Edition for Web Developers

autocomplete="section-red shipping street-address"> </label> <p> <label> City: <input name=rc autocomplete="section-red shipping region"> </label> <p> <label> Postal Code: <input name=rp autocomplete="section-red shipping country"> </label> </fieldset> 2. Optionally, a token that is an ASCII case-insensitive match for one of the following strings:

"shipping", meaning the field


is part of the shipping address or contact
information

"billing", meaning the field


is part of the billing address or contact
information 3. Either of the following two options:

A token that is an ASCII case-insensitive match for one of the following


autofill field strings:

"name" "honorific-prefix" "given-name" "additional-name" "family-name" "honorific-suffix" "nickname" "organization-title" "organization" "street-address" "address-line1 " "address-line2 " "address-line3 " "locality" "region" "country" "country-name" "postal-code" "cc-name" "cc-given-name " "cc-additional-name" "cc-family-name" "cc-number " "cc-exp" "cc-exp-month" "cc-exp-year" "cc-csc"
http://developers.whatwg.org/association-of-controls-and-forms.html[4/16/2014 9:34:49 PM]

4.10.18.3 Association of controls and forms HTML: The Living Standard - Edition for Web Developers

"cc-type" "language" "bday" "bday-day" "bday-month" "bday-year " "sex" "url" "photo "
(See the table below for descriptions of these values.)

The following, in the given order: Optionally, a token that is an ASCII case-insensitive match for one of the
following strings:

"home", meaning the field is


for contacting someone at their residence "work", meaning the field is
for contacting someone at their workplace "mobile", meaning the field is for contacting someone regardless of
location

"fax", meaning the field


describes a fax machine's contact details "pager ", meaning the field
describes a pager's or beeper's contact
details

A token that is an ASCII case-insensitive match for one of the following


autofill field strings:

"tel" "tel-country-code" "tel-national" "tel-area-code " "tel-local " "tel-local-prefix" "tel-local-suffix" "tel-extension " "email " "impp"
(See the table below for descriptions of these values.) The "off" keyword indicates either
that the control's input data is particularly sensitive (for example the activation code for a
nuclear weapon); or that it is a value that will never be reused (for example a one-time-key for a
bank login) and the user will therefore have to explicitly enter the data each time, instead of
being able to rely on the UA to prefill the value for him; or that the document provides its own
autocomplete mechanism and does not want the user agent to provide autocompletion values. The "on " keyword indicates that the
user agent is allowed to provide the user with autocompletion values, but does not provide any
further information

http://developers.whatwg.org/association-of-controls-and-forms.html[4/16/2014 9:34:49 PM]

4.10.18.3 Association of controls and forms HTML: The Living Standard - Edition for Web Developers

about what kind of data the user might be expected to enter. User agents would
have to use heuristics to decide what autocompletion values to suggest. The autofill fields names listed above indicate that the user
agent is allowed to provide the user with autocompletion values, and specifies what kind of value is expected. The keywords relate to each other as described in the table below. Each field name
listed on a row of this table corresponds to the meaning given in the cell for that row in the
column labeled "Meaning". Some fields correspond to subparts of other fields; for example, a
credit card expiry date can be expressed as one field giving both the month and year of expiry
(" cc-exp "), or as two fields, one giving the
month ("cc-exp-month") and one the year
("cc-exp-year"). In such cases, the names of
the broader fields cover multiple rows, in which the narrower fields are defined. Generally, authors are encouraged to use the broader fields rather than the narrower fields, as the narrower fields tend to expose Western biases. For example, while it is
common in some Western cultures to have a given name and a family name, in that order (and thus
often referred to as a first name and a surname), many cultures put the family name
first and the given name second, and many others simply have one name (a mononym). Having a single field is therefore more flexible. ISO 3166: Codes for the representation of names of countries and their subdivisions. ISO. Tags for Identifying Languages; Matching of Language Tags, A. Phillips, M. Davis. IETF. Field name Meaning Canonical Format "name" Full name Free-form text, no newlines " honorificprefix " "given-name " Given name (in some Western cultures, also known as the first name) " additionalname " "family-name" Additional names (in some Western cultures, also known as middle names, forenames other than the first name) Family name (in some Western cultures, also Free-form text, no Berners-Lee Free-form text, no newlines Free-form text, no newlines John Timothy Prefix or title (e.g. "Mr.", "Ms.", "Dr.", "Mlle") Free-form text, no newlines Sir Sir Timothy John Berners-Lee, OM, KBE, FRS, FREng, FRSA Canonical Format Example

http://developers.whatwg.org/association-of-controls-and-forms.html[4/16/2014 9:34:49 PM]

4.10.18.3 Association of controls and forms HTML: The Living Standard - Edition for Web Developers

known as the last name or surname) " honorificsuffix " "nickname" Nickname, screen name, handle: a typically short name used instead of the full name " organizationtitle " "organization" Job title (e.g. "Software Engineer", "Senior Vice President", "Deputy Managing Director") Company name corresponding to the person, address, or contact information in the other fields associated with this field "street-address " " addressline1 " " addressline2 " " addressline3 " "locality" City, town, village, post town, or other locality within which the relevant street address is found "region " Province such as a state, county, or canton within which the locality is found Street address (multiple lines, newlines preserved) Street address (one line per field) Suffix (e.g. "Jr.", "B.Sc.", "MBASW", "II")

newlines

Free-form text, no newlines

OM, KBE, FRS, FREng, FRSA

Free-form text, no newlines

Tim

Free-form text, no newlines

Professor

Free-form text, no newlines

World Wide Web Consortium

Free-form text

32 Vassar Street
MIT Room 32-G524

Free-form text, no newlines

32 Vassar Street

Free-form text, no newlines

MIT Room 32-G524

Free-form text, no newlines

Free-form text, no newlines

Cambridge

Free-form text, no newlines

MA

http://developers.whatwg.org/association-of-controls-and-forms.html[4/16/2014 9:34:49 PM]

4.10.18.3 Association of controls and forms HTML: The Living Standard - Edition for Web Developers

"country"

Country code

Valid ISO 3166-1alpha-2 country code [ISO3166]

US

"country-name"

Country name

Free-form text, no newlines; derived from country in some cases

US

"postal-code"

Postal code, post code, ZIP code, CEDEX code (if CEDEX, append "CEDEX", and the arrondissement if relevant, to the locality field)

Free-form text, no newlines

02139

"cc-name"

Full name as given on the payment instrument

Free-form text, no newlines

Tim Berners-Lee

" cc-givenname "

Given name as given on the payment instrument (in some Western cultures, also known as the first name)

Free-form text, no newlines

Tim

" ccadditionalname "

Additional names given on the payment instrument (in some Western cultures, also known as middle names, forenames other than the first name)

Free-form text, no newlines

" cc-familyname " "cc-number "

Family name given on the payment instrument (in some Western cultures, also known as the last name or surname) Code identifying the payment instrument (e.g. the credit card number,

Free-form text, no newlines

Berners-Lee

ASCII digits

4114360123456785

http://developers.whatwg.org/association-of-controls-and-forms.html[4/16/2014 9:34:49 PM]

4.10.18.3 Association of controls and forms HTML: The Living Standard - Edition for Web Developers

bank account number) "cc-exp " Expiration date of the payment instrument Valid month string " cc-exp-month " "cc-exp-year" Month component of the expiration date of the payment instrument Valid integer in the range 1..12 Year component of the expiration date of the payment instrument "cc-csc " Valid integer greater than zero Security code for the payment instrument (also known as the card security code (CSC), card validation code (CVC), card verification value (CVV), signature panel code (SPC), credit card ID (CCID), etc) "cc-type" Type of payment instrument Free-form text, no newlines "language" Preferred language Valid BCP 47 language tag [BCP47] "bday" "bday-day" Birthday Valid date string Day component of birthday Valid integer in the range 1..31 "bday-month " Month component of birthday Valid integer in the range 1..12 "bday-year " Year component of birthday Valid integer greater than zero 1955 6 8 1955-06-08 en Visa ASCII digits 419 2014 12 2014-12

http://developers.whatwg.org/association-of-controls-and-forms.html[4/16/2014 9:34:49 PM]

4.10.18.3 Association of controls and forms HTML: The Living Standard - Edition for Web Developers

"sex"

Gender identity (e.g. Female, Fa'afafine)

Free-form text, no newlines

Male

"url"

Home page or other Web page corresponding to the company, person, address, or contact information in the other fields associated with this field

Valid URL

http://www.w3.org/People/Berners-Lee/

"photo "

Photograph, icon, or other image corresponding to the company, person, address, or contact information in the other fields associated with this field

File or Valid URL

http://www.w3.org/Press/Stock/BernersLee/2001-europaeum-eighth.jpg

"tel"

Full telephone number, including country code

ASCII digits and U+0020 SPACE characters, prefixed by a U+002B PLUS SIGN character (+)

+1 617 253 5702

" tel-countrycode "

Country code component of the telephone number

ASCII digits prefixed by a U+002B PLUS SIGN character (+)

+1

" tel-national "

Telephone number without the county code component, with a country-internal prefix applied if applicable

ASCII digits and U+0020 SPACE characters

617 253 5702

http://developers.whatwg.org/association-of-controls-and-forms.html[4/16/2014 9:34:49 PM]

4.10.18.3 Association of controls and forms HTML: The Living Standard - Edition for Web Developers

" tel-areacode " "tel-local "

Area code component of the telephone number, with a country-internal prefix applied if applicable Telephone number without the country code and area code components " tellocalprefix " First part of the component of the telephone number that follows the area code, when that component is split into two components " tellocalsuffix " Second part of the component of the telephone number that follows the area code, when that component is split into two components

ASCII digits

617

ASCII digits

2535702

ASCII digits

253

ASCII digits

5702

"tel-extension " "email "

Telephone number internal extension code E-mail address

ASCII digits Valid email address

1000

timbl@w3.org

"impp"

URL representing an instant messaging protocol endpoint (for example, " aim:goim? screenname=example " or " xmpp:fred@example.net ")

Valid URL

irc://example.org/timbl,isuser

If the autocomplete attribute is omitted, the default


value corresponding to the state of the element's form owner's autocomplete attribute is used instead (either "on" or "off"). If there is no form owner, then the
value "on " is used.

APIs for the text field selections


http://developers.whatwg.org/association-of-controls-and-forms.html[4/16/2014 9:34:49 PM]

4.10.18.3 Association of controls and forms HTML: The Living Standard - Edition for Web Developers

The input and textarea elements define the following members in their DOM interfaces for handling their selection: The setRangeText method uses the following
enumeration: These methods and attributes expose and control the selection of input and textarea text fields. element . select() Selects everything in the text field. element . selectionStart [ = value ] Returns the offset to the start of the selection. Can be set, to change the start of the selection. element . selectionEnd [ = value ] Returns the offset to the end of the selection. Can be set, to change the end of the selection. element . selectionDirection [ = value ] Returns the current direction of the selection. Can be set, to change the direction of the selection. The possible values are "forward ", "backward ", and "none". element . setSelectionRange(start, end [, direction] ) Changes the selection to cover the given substring in the given direction. If the direction
is omitted, it will be reset to be the platform default (none or forward). element . setRangeText(replacement [, start, end [, selectionMode ] ]) Replaces a range of text with the new text. If the start and end arguments are not provided, the range is assumed to be the selection. The final argument determines how the selection should be set after the text has been
replaced. The possible values are: "select" Selects the newly inserted text. "start" Moves the selection to just before the inserted text. "end" Moves the selection to just after the selected text. "preserve" Attempts to preserve the selection. This is the default.

http://developers.whatwg.org/association-of-controls-and-forms.html[4/16/2014 9:34:49 PM]

4.10.18.3 Association of controls and forms HTML: The Living Standard - Edition for Web Developers

Characters with no visible rendering, such as U+200D ZERO WIDTH JOINER, still count as
characters. Thus, for instance, the selection can include just an invisible character, and the
text insertion cursor can be placed to one side or another of such a character. To obtain the currently selected text, the following JavaScript suffices: var selectionText = control.value.substring(control.selectionStart, control.selectionEnd); ...where control is the input or textarea
element. To add some text at the start of a text control, while maintaining the text selection, the
three attributes must be preserved: var oldStart = control.selectionStart; var oldEnd = control.selectionEnd; var oldDirection = control.selectionDirection; var prefix = "http://"; control.value = prefix + control.value; control.setSelectionRange(oldStart + prefix.length, oldEnd + prefix.length, oldDirection); ...where control is the input or textarea
element.

Constraints

Definitions

The constraint validation API


element . willValidate Returns true if the element will be validated when the form is submitted; false otherwise. element . setCustomValidity(message) Sets a custom error, so that the element would fail to validate. The given message is the
message to be shown to the user when reporting the problem to the user. If the argument is the empty string, clears the custom error. element . validity . valueMissing

http://developers.whatwg.org/association-of-controls-and-forms.html[4/16/2014 9:34:49 PM]

4.10.18.3 Association of controls and forms HTML: The Living Standard - Edition for Web Developers

Returns true if the element has no value but is a required field; false otherwise. element . validity . typeMismatch Returns true if the element's value is not in the correct syntax; false otherwise. element . validity . patternMismatch Returns true if the element's value doesn't match the provided pattern; false otherwise. element . validity . tooLong Returns true if the element's value is longer than the provided maximum length; false otherwise. element . validity . tooShort Returns true if the element's value, if it is not the empty string, is shorter than the
provided minimum length; false otherwise. element . validity . rangeUnderflow Returns true if the element's value is lower than the provided minimum; false otherwise. element . validity . rangeOverflow Returns true if the element's value is higher than the provided maximum; false otherwise. element . validity . stepMismatch Returns true if the element's value doesn't fit the rules given by the step attribute; false otherwise. element . validity . badInput Returns true if the user has provided input in the user interface that the user agent is
unable to convert to a value; false otherwise. element . validity . customError Returns true if the element has a custom error; false otherwise. element . validity . valid Returns true if the element's value has no validity problems; false otherwise. valid = element . checkValidity() Returns true if the element's value has no validity problems; false otherwise. Fires an invalid event at the element in the latter case. valid = element . reportValidity() Returns true if the element's value has no validity problems; otherwise, returns false, fires
an invalid event at the element, and (if the event isn't canceled) reports the problem to the user. element . validationMessage Returns the error message that would be shown to the user if the element was

http://developers.whatwg.org/association-of-controls-and-forms.html[4/16/2014 9:34:49 PM]

4.10.18.3 Association of controls and forms HTML: The Living Standard - Edition for Web Developers

to be checked
for validity. In the following example, a script checks the value of a form control each time it is edited,
and whenever it is not a valid value, uses the setCustomValidity() method to set an appropriate
message. <label>Feeling: <input name=f type="text" oninput="check(this)"></label> <script> function check(input) { if (input.value == "good" || input.value == "fine" || input.value == "tired") { input.setCustomValidity('"' + input.value + '" is not a feeling.'); } else { // input is fine -- reset the error message input.setCustomValidity(''); } } </script>

Security
Servers should not rely on client-side validation. Client-side validation can
be intentionally bypassed by hostile users, and unintentionally bypassed by users of older user
agents or automated tools that do not implement these features. The constraint validation features
are only intended to improve the user experience, not to provide any kind of security
mechanism.

Form submission
When a form is submitted, the data in the form is converted into the structure specified by the
enctype, and then sent to the destination specified by the action using the given method. For example, take the following form: <form action="/find.cgi" method=get> <input type=text name=t> <input type=search name=q> <input type=submit> </form> If the user types in "cats" in the first field and "fur" in the second, and then

http://developers.whatwg.org/association-of-controls-and-forms.html[4/16/2014 9:34:49 PM]

4.10.18.3 Association of controls and forms HTML: The Living Standard - Edition for Web Developers

hits the
submit button, then the user agent will load /find.cgi?t=cats&q=fur . On the other hand, consider this form: <form action="/find.cgi" method=post enctype="multipart/formdata"> <input type=text name=t> <input type=search name=q> <input type=submit> </form> Given the same user input, the result on submission is quite different: the user agent instead
does an HTTP POST to the given URL, with as the entity body something like the following text: ------kYFrd4jNJEgCervE Content-Disposition: form-data; name="t" cats ------kYFrd4jNJEgCervE Content-Disposition: form-data; name="q" fur ------kYFrd4jNJEgCervE--

URL-encoded form data


This form data set encoding is in many ways an aberrant monstrosity, the result of
many years of implementation accidents and compromises leading to a set of requirements necessary
for interoperability, but in no way representing good design practices. In particular, readers are
cautioned to pay close attention to the twisted details involving repeated (and in some cases
nested) conversions between character encodings and byte sequences. To decode
application/x-www-form-urlencoded payloads, the following algorithm should be
used. This algorithm uses as inputs the payload itself, payload, consisting of
a Unicode string using only characters in the range U+0000 to U+007F; a default character encoding
encoding; and optionally an isindex flag indicating that
the payload is to be processed as if it had been generated for a form containing an isindex control. The output of this algorithm is a sorted list
of name-value pairs. If the isindex flag is set and the first control really
was an isindex control, then the first name-value pair
will have as its name the empty string. Which default character encoding to use can only be determined on a case-bycase basis, but
generally the best character encoding to use as a default is the

http://developers.whatwg.org/association-of-controls-and-forms.html[4/16/2014 9:34:49 PM]

4.10.18.3 Association of controls and forms HTML: The Living Standard - Edition for Web Developers

one that was used to encode the


page on which the form used to create the payload was itself found. In the absence of a better
default, UTF-8 is suggested. The isindex flag is for legacy use only. Forms in conforming HTML documents
will not generate payloads that need to be decoded with this flag set. 1. Let strings be the result of strictly splitting the string payload on U+0026 AMPERSAND
characters (&). 2. If the isindex flag is set and the first string in strings does not contain a U+003D EQUALS SIGN character (=), insert a U+003D
EQUALS SIGN character (=) at the start of the first string in strings. 3. Let pairs be an empty list of name-value pairs. 4. For each string string in strings, run these
substeps: 1. If string contains a U+003D EQUALS SIGN character (=), then let name be the substring of string from the start of string up to but excluding its first U+003D EQUALS SIGN character (=), and let
value be the substring from the first character, if any, after the first
U+003D EQUALS SIGN character (=) up to the end of string. If the first
U+003D EQUALS SIGN character (=) is the first character, then name will be
the empty string. If it is the last character, then value will be the
empty string. Otherwise, string contains no U+003D EQUALS SIGN characters (=). Let name have the value of string and let value be the empty string. 2. Replace any U+002B PLUS SIGN characters (+) in name and value with U+0020 SPACE characters. 3. Replace any escape in name and value with the
character represented by the escape. This replacement must not be recursive. An escape is a U+0025 PERCENT SIGN character (%) followed by two ASCII hex
digits. The character represented by an escape is the Unicode character whose code point is equal
to the value of the two characters after the U+0025 PERCENT SIGN character (%), interpreted as
a hexadecimal number (in the range 0..255). So for instance the string "A%2BC " would become
"A+C". Similarly, the string "100%25AA%21" becomes
the string "100%AA!". 4. Convert the name and value strings to their byte
representation in ISO8859-1 (i.e. convert the Unicode string to a byte string, mapping code points to byte values directly). 5. Add a pair consisting of name and value to pairs.

http://developers.whatwg.org/association-of-controls-and-forms.html[4/16/2014 9:34:49 PM]

4.10.18.3 Association of controls and forms HTML: The Living Standard - Edition for Web Developers

5. If any of the name-value pairs in pairs have a name component


consisting of the string "_charset_ " encoded in US-ASCII, and the value
component of the first such pair, when decoded as US-ASCII, is the name of a supported character
encoding, then let encoding be that character encoding (replacing the default
passed to the algorithm). 6. Convert the name and value components of each name-value pair in pairs
to Unicode by interpreting the bytes according to the encoding encoding. 7. Return pairs. Parameters on the application/x-www-form-urlencoded MIME type are ignored. In particular, this MIME type does not support the charset parameter.

Multipart form data


For details on how to interpret multipart/form-data payloads, see RFC 2388.

Plain text form data


Payloads using the text/plain format are intended to be human readable. They are
not reliably interpretable by computer, as the format is ambiguous (for example, there is no way
to distinguish a literal newline in a value from the newline at the end of the value).

Up next

4.11 Interactive elements

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/association-of-controls-and-forms.html[4/16/2014 9:34:49 PM]

4.7.11 The map element HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
The map element
The area element
Image maps
MathML
SVG
Dimension attributes

The map element


Categories: Flow content. Phrasing content. Palpable content. Contexts in which this element can be used: Where phrasing content is expected. Content model: Transparent. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes name Name of image map to reference from the usemap attribute DOM interface: The map element, in conjunction with an img element and any
area element descendants, defines an image map. The element
represents its children.

http://developers.whatwg.org/the-map-element.html[4/16/2014 9:34:56 PM]

4.7.11 The map element HTML: The Living Standard - Edition for Web Developers

The name attribute gives the map a name so that


it can be referenced. The attribute must be present and must have a non-empty value with no space characters. The value of the name attribute must not be a compatibilitycaseless match for the value of the name attribute of another map element in the same
document. If the id attribute is also specified, both attributes must have the same value. map . areas Returns an HTMLCollection of the area elements in the
map . map . images Returns an HTMLCollection of the img and object
elements that use the map . Image maps can be defined in conjunction with other content on the page, to ease maintenance.
This example is of a page with an image map at the top of the page and a corresponding set of
text links at the bottom. <!DOCTYPE HTML> <TITLE>Babies: Toys</TITLE> <HEADER> <H1>Toys</H1> <IMG SRC="/images/menu.gif" ALT="Babies navigation menu. Select a department to go to its page." USEMAP="#NAV"> </HEADER> ... <FOOTER> <MAP NAME="NAV"> <P> <A HREF="/clothes/">Clothes</A> <AREA ALT="Clothes" COORDS="0,0,100,50" HREF="/clothes/"> | <A HREF="/toys/">Toys</A> <AREA ALT="Toys" COORDS="0,0,100,50" HREF="/toys/"> | <A HREF="/food/">Food</A> <AREA ALT="Food" COORDS="0,0,100,50" HREF="/food/"> | <A HREF="/books/">Books</A> <AREA ALT="Books" COORDS="0,0,100,50" HREF="/books/">

http://developers.whatwg.org/the-map-element.html[4/16/2014 9:34:56 PM]

4.7.11 The map element HTML: The Living Standard - Edition for Web Developers

</MAP> </FOOTER>

The area element


Categories: Flow content. Phrasing content. Contexts in which this element can be used: Where phrasing content is expected, but only if there is a map element ancestor or a template element ancestor. Content model: Empty. Tag omission in text/html: No end tag. Content attributes: Global attributes alt Replacement text for use when images are not available coords Coordinates for the shape to be created in an image map shape The kind of shape to be created in an image map href Address of the hyperlink target Browsing context for hyperlink navigation download Whether to download the resource instead of navigating to it, and its file name if so ping URLs to ping rel Relationship between the document containing the hyperlink and the destination resource hreflang Language of the linked resource type Hint for the type of the referenced resource DOM interface: The area element represents either a hyperlink with some text and a corresponding area on an image map, or a dead area on an image map.

http://developers.whatwg.org/the-map-element.html[4/16/2014 9:34:56 PM]

4.7.11 The map element HTML: The Living Standard - Edition for Web Developers

An area element with a parent node must have a map element ancestor
or a template element ancestor. If the area element has an href
attribute, then the area element represents a hyperlink. In this case,
the alt attribute must be present. It specifies the
text of the hyperlink. Its value must be text that, when presented with the texts specified for
the other hyperlinks of the image map, and with the alternative text of the image,
but without the image itself, provides the user with the same kind of choice as the hyperlink
would when used without its text but with its shape applied to the image. The alt attribute may be left blank if there is another area
element in the same image map that points to the same resource and has a non-blank
alt attribute. If the area element has no href
attribute, then the area represented by the element cannot be selected, and the alt attribute must be omitted. In both cases, the shape and coords attributes specify the area. The shape attribute is an enumerated
attribute. The following table lists the keywords defined for this attribute. The states
given in the first cell of the rows with keywords give the states to which those keywords map. State Circle state Default state Polygon state Rectangle state Keywords circle default poly rect

The attribute may be omitted. The missing value default is the rectangle state. The coords attribute must, if specified,
contain a valid list of integers. This attribute gives the coordinates for the shape
described by the shape attribute. In the circle state, area elements must
have a coords attribute present, with three integers, the
last of which must be non-negative. The first integer must be the distance in CSS pixels from the
left edge of the image to the center of the circle, the second integer must be the distance in CSS
pixels from the top edge of the image to the center of the circle, and the third integer must be
the radius of the circle, again in CSS pixels. In the default state state, area
elements must not have a coords attribute.

http://developers.whatwg.org/the-map-element.html[4/16/2014 9:34:56 PM]

4.7.11 The map element HTML: The Living Standard - Edition for Web Developers

(The area is the


whole image.) In the polygon state, area elements must
have a coords attribute with at least six integers, and the
number of integers must be even. Each pair of integers must represent a coordinate given as the
distances from the left and the top of the image in CSS pixels respectively, and all the
coordinates together must represent the points of the polygon, in order. In the rectangle state, area elements must
have a coords attribute with exactly four integers, the
first of which must be less than the third, and the second of which must be less than the fourth.
The four points must represent, respectively, the distance from the left edge of the image to the
left side of the rectangle, the distance from the top edge to the top side, the distance from the
left edge to the right side, and the distance from the top edge to the bottom side, all in CSS
pixels. The target, download, ping,
rel, hreflang, and type
attributes must be omitted if the href attribute is not
present. If the itemprop attribute is specified on an
area element, then the href attribute must
also be specified.

Image maps
An image map allows geometric areas on an image to be associated with hyperlinks. An image, in the form of an img element or an object element
representing an image, may be associated with an image map (in the form of a map element) by specifying a usemap attribute on
the img or object element. The usemap attribute, if specified, must be a valid
hash-name reference to a map element. Consider an image that looks as follows:

http://developers.whatwg.org/the-map-element.html[4/16/2014 9:34:56 PM]

4.7.11 The map element HTML: The Living Standard - Edition for Web Developers

If we wanted just the colored areas to be clickable, we could do it as follows: <p> Please select a shape: <img src="shapes.png" usemap="#shapes" alt="Four shapes are available: a red hollow box, a green circle, a blue triangle, and a yellow four-pointed star."> <map name="shapes"> <area shape=rect coords="50,50,100,100"> <!-- the hole in the red box --> <area shape=rect coords="25,25,125,125" href="red.html" alt="Red box."> <area shape=circle coords="200,75,50" href="green.html" alt="Green circle."> <area shape=poly coords="325,25,262,125,388,125" href="blue.html" alt="Blue triangle."> <area shape=poly coords="450,25,435,60,400,75,435,90,450,125,465,90,500,75,465 ,60" href="yellow.html" alt="Yellow star."> </map> </p>

MathML
The math element from the MathML namespace falls into the
embedded content, phrasing content, and flow content
categories for the purposes of the content models in this specification. The semantics of MathML elements are defined by the MathML specification and other
applicable specifications. Here is an example of the use of MathML in an HTML document: <!DOCTYPE html> <html> <head> <title>The quadratic formula</title> </head>

http://developers.whatwg.org/the-map-element.html[4/16/2014 9:34:56 PM]

4.7.11 The map element HTML: The Living Standard - Edition for Web Developers

<body> <h1>The quadratic formula</h1> <p> <math> <mi>x</mi> <mo>=</mo> <mfrac> <mrow> <mo form="prefix"></mo> <mi>b</mi> <mo></mo> <msqrt> <msup> <mi>b</mi> <mn>2</mn> </msup> <mo></mo> <mn>4</mn> <mo>&it;</mo> <mi>a</mi> <mo>&it;</mo> <mi>c</mi> </msqrt> </mrow> <mrow> <mn>2</mn> <mo>&it;</mo> <mi>a</mi> </mrow> </mfrac> </math> </p> </body> </html>

SVG
The svg element from the SVG namespace falls into the
embedded content, phrasing content, and flow content
categories for the purposes of the content models in this specification. When the SVG foreignObject element contains elements from the HTML namespace, such elements must all be flow content. The content model for title elements in the SVG namespace
inside HTML documents is phrasing content. (This further constrains the
requirements given in the SVG specification.) The semantics of SVG elements are defined by the SVG specification and other

http://developers.whatwg.org/the-map-element.html[4/16/2014 9:34:56 PM]

4.7.11 The map element HTML: The Living Standard - Edition for Web Developers

applicable
specifications. [SVG] The SVG specification includes requirements regarding the handling of elements in the DOM that
are not in the SVG namespace, that are in SVG fragments, and that are not included in a foreignObject element. This specification does not define any processing
for elements in SVG fragments that are not in the HTML namespace; they are considered neither
conforming nor non-conforming from the perspective of this specification.

Dimension attributes
The width and height attributes on img,
iframe, embed , object, video, and, when their
type attribute is in the Image Button state, input elements may be
specified to give the dimensions of the visual content of the element (the width and height
respectively, relative to the nominal direction of the output medium), in CSS pixels. The
attributes, if specified, must have values that are valid
non-negative integers. The specified dimensions given may differ from the dimensions specified in the resource itself,
since the resource may have a resolution that differs from the CSS pixel resolution. (On screens,
CSS pixels have a resolution of 96ppi, but in general the CSS pixel resolution depends on the
reading distance.) If both attributes are specified, then one of the following statements must be true:

specified width - 0.5


specified height * target ratio
specified width + 0.5 specified height - 0.5
specified width / target ratio
specified height + 0.5 specified height = specified width = 0
The target ratio is the ratio of the intrinsic width to the intrinsic
height in the resource. The specified width and specified
height are the values of the width and height attributes respectively. The two attributes must be omitted if the resource in question does not have both an intrinsic
width and an intrinsic height. If the two attributes are both zero, it indicates that the element is not intended for the user
(e.g. it might be a part of a service to count page views). The dimension attributes are not intended to be used to stretch the image.

http://developers.whatwg.org/the-map-element.html[4/16/2014 9:34:56 PM]

4.7.11 The map element HTML: The Living Standard - Edition for Web Developers
Up next

4.8 Links

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/the-map-element.html[4/16/2014 9:34:56 PM]

4.10.5 The input element HTML: The Living Standard - Edition for Web Developers

WHAT WG

HTML: The Living Standard


A technical specification for Web developers

Search. Press '/'

The input element


Categories: Flow content. Phrasing content. If the type attribute is not in the Hidden state: Interactive content. If the type attribute is not in the Hidden state: Listed, labelable, submittable, resettable, and reassociateable form-associated element. If the type attribute is in the Hidden state: Listed, submittable, resettable, and reassociateable formassociated element. If the type attribute is not in the Hidden state: Palpable content. Contexts in which this element can be used: Where phrasing content is expected. Content model: Empty. Tag omission in text/html: No end tag. Content attributes: Global attributes accept Hint for expected file type in file upload controls alt Replacement text for use when images are not available autocomplete Hint for form autofill feature autofocus Automatically focus the form control when the page is loaded checked Whether the command or control is checked dirname Name of form field to use for sending the element's directionality in form submission disabled Whether the form control is disabled form Associates the control with a form element formaction URL to use for form submission formenctype Form data set encoding type to use for form submission formmethod HTTP method to use for form submission formnovalidate Bypass form control validation for form submission formtarget Browsing context for form submission height Vertical dimension inputmode Hint for selecting an input modality

http://developers.whatwg.org/the-input-element.html[4/16/2014 9:35:02 PM]

4.10.5 The input element HTML: The Living Standard - Edition for Web Developers

list List of autocomplete options max Maximum value maxlength Maximum length of value min Minimum value minlength Minimum length of value multiple Whether to allow multiple values name Name of form control to use for form submission and in the form.elements API pattern Pattern to be matched by the form control's value placeholder User-visible label to be placed within the form control readonly Whether to allow the value to be edited by the user required Whether the control is required for form submission size Size of the control src Address of the resource step Granularity to be matched by the form control's value type Type of form control value Value of the form control width Horizontal dimension DOM interface: The input element represents a typed data field, usually with a form
control to allow the user to edit the data. The type attribute controls the data type (and
associated control) of the element. It is an enumerated attribute. The following
table lists the keywords and states for the attribute the keywords in the left column map
to the states in the cell in the second column on the same row as the keyword. Keyword hidden text search tel url email password State Hidden Text Search Telephone URL E-mail Password Data type An arbitrary string Text with no line breaks Text with no line breaks Text with no line breaks An absolute URL An e-mail address or list of e-mail addresses Text with no line breaks (sensitive information) Control type n/a A text field Search field A text field A text field A text field A text field that obscures data entry A date and time control A date control

datetime date

Date and Time Date

A date and time (year, month, day, hour, minute, second, fraction of a second) with the time zone set to UTC A date (year, month, day) with no time zone

http://developers.whatwg.org/the-input-element.html[4/16/2014 9:35:02 PM]

4.10.5 The input element HTML: The Living Standard - Edition for Web Developers

month week time datetimelocal number

Month Week Time Local Date and Time Number

A date consisting of a year and a month with no time zone A date consisting of a week-year number and a week number with no time zone A time (hour, minute, seconds, fractional seconds) with no time zone A date and time (year, month, day, hour, minute, second, fraction of a second) with no time zone A numerical value

A month control A week control A time control A date and time control A text field or spinner control A slider control or similar A color well A checkbox A radio button A label and a button A button Either a clickable image, or a button A button A button

range

Range

A numerical value, with the extra semantic that the exact value is not important An sRGB color with 8-bit red, green, and blue components A set of zero or more values from a predefined list An enumerated value Zero or more files each with a MIME type and optionally a file name An enumerated value, with the extra semantic that it must be the last value selected and initiates form submission A coordinate, relative to a particular image's size, with the extra semantic that it must
be the last value selected and initiates form submission n/a n/a

color checkbox radio file submit image

Color Checkbox Radio Button File Upload Submit Button Image Button

reset button

Reset Button Button

The missing value default is the Text state. Which of the accept , alt, autocomplete, checked , dirname, formaction, formenctype, formmethod, formnovalidate , formtarget , height, inputmode , list, max , maxlength , min, minlength , multiple, pattern, placeholder, readonly, required,
size, src, step, and width content attributes, the checked , files , valueAsDate,
valueAsNumber , and list IDL attributes, the select() method, the selectionStart , selectionEnd, and selectionDirection , IDL attributes, the setRangeText() and setSelectionRange() methods, the stepUp() and stepDown()
methods, and the input and change events apply to an input element depends on
the state of its type attribute. The subsections that define
each type also clearly define in normative "bookkeeping" sections which of these feature apply,
and which do not apply, to each type. The behavior of these features depends on
http://developers.whatwg.org/the-input-element.html[4/16/2014 9:35:02 PM]

4.10.5 The input element HTML: The Living Standard - Edition for Web Developers

whether
they apply or not, as defined in their various sections. The following table summarizes which of those
content attributes, IDL attributes, methods, and events apply to each state: Hidden Text, URL, EPassword Date Search Telephone mail and Time, Date, Month,
Week, Time Content attributes accept alt autocomplete checked dirname formaction formenctype formmethod formnovalidate formtarget height inputmode list max maxlength min minlength multiple pattern placeholder readonly required size src
http://developers.whatwg.org/the-input-element.html[4/16/2014 9:35:02 PM]

Local Number Range Color Checkbox, File Submit Image Reset


Radio Date Upload Button Button Button,
Button and Button Time

Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes

Yes Yes Yes Yes Yes Yes Yes Yes Yes

Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes

Yes Yes Yes Yes Yes Yes Yes Yes Yes

Yes Yes Yes Yes Yes Yes Yes

Yes Yes Yes Yes Yes Yes Yes

Yes Yes Yes Yes Yes Yes Yes Yes

Yes Yes Yes Yes Yes

Yes Yes

Yes Yes

Yes Yes Yes

Yes Yes Yes Yes Yes

Yes Yes Yes Yes Yes Yes Yes Yes

4.10.5 The input element HTML: The Living Standard - Edition for Web Developers

step width Yes

IDL attributes and methods checked files valueAsDate valueAsNumber list select() selectionStart selectionEnd selectionDirection setRangeText() Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes

setSelectionRange() stepDown() stepUp() Events input event change event

Yes Yes

Yes Yes

Yes Yes

Yes Yes

Yes Yes

Yes Yes

Yes Yes

Yes Yes

Yes Yes

Yes

Yes

The value content attribute gives the default


value of the input element. The checked content attribute is a
boolean attribute that gives the default checkedness of the input element.
The name attribute represents the element's name.
The dirname attribute controls how the element's directionality is submitted.
The disabled attribute is used to make the control non-interactive and to prevent its value from being submitted.
The form attribute is used to explicitly associate the input element with its form owner.
The autofocus attribute controls focus. The inputmode attribute controls the user interface's input modality for the control.
The autocomplete attribute controls how the user agent provides autofill behavior.

Up next

4.10.5.1 States of the type attribute

This document is a work in progress, if you spot something that you feel isn't quite right,
http://developers.whatwg.org/the-input-element.html[4/16/2014 9:35:02 PM]

4.10.5 The input element HTML: The Living Standard - Edition for Web Developers

please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/the-input-element.html[4/16/2014 9:35:02 PM]

4.11.6 Commands HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
Commands
Facets
The dialog element
Anchor points

Commands

Facets
A command is the abstraction behind menu items, buttons, and
links. Once a command is defined, other parts of the interface can refer to the same command,
allowing many access points to a single feature to share facets such as the Disabled State. Commands are defined to have the following facets: Type The kind of command: "command", meaning it is a normal command; "radio", meaning that
triggering the command will, amongst other things, set the Checked State to true (and probably uncheck some other
commands); or "checkbox", meaning that triggering the command will, amongst other things, toggle
the value of the Checked State. ID The name of the command, for referring to the command from the markup or from script. If a
command has no ID, it is an anonymous command. Label The name of the command as seen by the user.

http://developers.whatwg.org/commands.html[4/16/2014 9:35:07 PM]

4.11.6 Commands HTML: The Living Standard - Edition for Web Developers

Hint A helpful or descriptive string that can be shown to the user. Icon An absolute URL identifying a graphical image that represents the action. A command might not have an Icon. Access Key A key combination selected by the user agent that triggers the command. A command might not
have an Access Key. Hidden State Whether the command is hidden or not (basically, whether it should be shown in menus). Disabled State Whether the command is relevant and can be triggered or not. Checked State Whether the command is checked or not. Action The actual effect that triggering the command will have. This could be a scripted event
handler, a URL to which to navigate, or a form submission. These facets are exposed on elements using the command API: element . commandType Exposes the Type facet of the command. element . id Exposes the ID facet of the command. element . commandLabel Exposes the Label facet of the command. element . title Exposes the Hint facet of the command. element . commandIcon Exposes the Icon facet of the command. element . accessKeyLabel Exposes the Access Key facet of the command. element . commandHidden

http://developers.whatwg.org/commands.html[4/16/2014 9:35:07 PM]

4.11.6 Commands HTML: The Living Standard - Edition for Web Developers

Exposes the Hidden State facet of the command. element . commandDisabled Exposes the Disabled State facet of the command. element . commandChecked Exposes the Checked State facet of the command. element . click() Triggers the Action of the command. document . commands Returns an HTMLCollection of the elements in the Document that
define commands and have IDs. User agents may expose the commands that match the following criteria:

The Hidden State facet is false (visible) The element is in a Document that has an associated browsing
context. Neither the element nor any of its ancestors has a hidden
attribute specified. The element is not a menuitem element, or it is a child of a currently
relevant
menu element, or it has an Access Key. User agents are encouraged to do this especially for commands that have Access Keys, as a way to advertise those keys to the
user. For example, such commands could be listed in the user agent's menu bar.

The dialog element


Categories: Flow content. Sectioning root. Contexts in which this element can be used: Where flow content is expected. Content model: Flow content. Tag omission in text/html: Neither tag is omissible.

http://developers.whatwg.org/commands.html[4/16/2014 9:35:07 PM]

4.11.6 Commands HTML: The Living Standard - Edition for Web Developers

Content attributes: Global attributes open Whether the dialog box is showing DOM interface: The dialog element represents a part of an application that a user interacts with
to perform a task, for example a dialog box, inspector, or window. The open attribute is a boolean
attribute. When specified, it indicates that the dialog element is active and
that the user can interact with it. dialog . show ( [ anchor ] ) Displays the dialog element. The argument, if provided, provides an anchor point to which the element will be fixed. dialog . showModal ( [ anchor ] ) Displays the dialog element and makes it the top-most modal dialog. The argument, if provided, provides an anchor point to which the element will be fixed. This method honors the autofocus attribute. dialog . close ( [ result ] ) Closes the dialog element. The argument, if provided, provides a return value. dialog . returnValue [ = result ] Returns the dialog 's return value. Can be set, to update the return value.

Anchor points
This section will eventually be moved to a CSS specification; it is specified
here only on an interim basis until an editor can be found to own this. 'anchor-point'

http://developers.whatwg.org/commands.html[4/16/2014 9:35:07 PM]

4.11.6 Commands HTML: The Living Standard - Edition for Web Developers

Value: Initial: Applies to: Inherited:

none | <position> none all elements no

Percentages: refer to width or height of box; see prose Media: Computed value: visual The specified value, but with any lengths replaced by their corresponding absolute length

Animatable: no Canonical order: The 'anchor-point' property specifies a point to which dialog boxes are to be aligned. If the value is a <position>, the alignment point is the point given by the value, which
must be interpreted relative to the element's first rendered box's margin box. Percentages must be
calculated relative to the element's first rendered box's margin box (specifically, its width for
the horizontal position and its height for the vertical position). If the value is the keyword 'none', then no explicit alignment point is defined. The user agent
will pick an alignment point automatically if necessary (as described in the definition of the
open() method above). per grammar

Up next

4.12 Scripting

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/commands.html[4/16/2014 9:35:07 PM]

4.10.5.1 States of the type attribute HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
States of the type attribute
Hidden state ( type=hidden)
Text ( type=text) state and Search state (type=search )
Telephone state (type=tel )
URL state (type=url )
E-mail state (type=email)
Password state ( type=password )
Date and Time state ( type=datetime)
Date state (type=date )
Month state (type=month)
Week state (type=week )
Time state ( type=time)
Local Date and Time state (type=datetime-local )
Number state (type=number)
Range state (type=range)
Color state (type=color)
Checkbox state (type=checkbox )
Radio Button state (type=radio)
File Upload state ( type=file)
Submit Button state (type=submit)
Image Button state (type=image)
Reset Button state (type=reset )
Button state ( type=button)

States of the type attribute

Hidden state (type=hidden) The input element represents a value that is not intended to be
examined or

http://developers.whatwg.org/states-of-the-type-attribute.html[4/16/2014 9:35:13 PM]

4.10.5.1 States of the type attribute HTML: The Living Standard - Edition for Web Developers

manipulated by the user. If the name attribute is present and has a value that is a
case-sensitive match for the string "_charset_", then the element's value attribute must be omitted. The
value
IDL attribute applies to this element and is
in mode default. The following content attributes must not be specified and do not
apply to the element:
accept ,
alt,
autocomplete,
checked,
dirname,
formaction, formenctype,
formmethod,
formnovalidate ,
formtarget ,
height, inputmode ,
list,
max ,
maxlength ,
min,
minlength ,
multiple,
pattern, placeholder,
readonly,
required,
size,
src,
step, and
width. The following IDL attributes and methods do not apply to the
element: checked,
files,
list,
selectionStart ,
selectionEnd, selectionDirection ,
valueAsDate, and
valueAsNumber IDL attributes; select(),
setRangeText(),
setSelectionRange() ,
stepDown() , and stepUp() methods. The input and change events do not apply.

Text (type=text ) state and Search state (type=search) The input element represents a one line plain text edit control for
the element's value. The difference between the Text state
and the Search state is primarily stylistic: on
platforms where search fields are distinguished from regular text fields, the Search state might result in an appearance consistent with
the platform's search fields rather than appearing like a regular text field. The value attribute, if specified, must have a value that
contains no U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters. The following common input element content
attributes, IDL attributes, and methods apply to the element:
autocomplete,
dirname,
inputmode ,
list, maxlength ,
minlength,
pattern ,
placeholder,
readonly,
required, and size content attributes;
list,
selectionStart,
selectionEnd , selectionDirection , and
value IDL attributes;
select(), setRangeText() , and
setSelectionRange() methods.

http://developers.whatwg.org/states-of-the-type-attribute.html[4/16/2014 9:35:13 PM]

4.10.5.1 States of the type attribute HTML: The Living Standard - Edition for Web Developers

The value IDL attribute is


in mode value. The input and change events apply. The following content attributes must not be specified and do not
apply to the element:
accept ,
alt,
checked,
formaction ,
formenctype,
formmethod, formnovalidate ,
formtarget,
height ,
max,
min,
multiple,
src,
step, and width . The following IDL attributes and methods do not apply to the
element: checked,
files,
valueAsDate , and
valueAsNumber IDL attributes; stepDown() and
stepUp() methods.

Telephone state (type=tel) The input element represents a control for editing a telephone number
given in the element's value. The value attribute, if specified, must have a value that
contains no U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters. Unlike the URL and E-mail types, the Telephone type does not enforce a particular syntax. This is
intentional; in practice, telephone number fields tend to be free-form fields, because there are a
wide variety of valid phone numbers. Systems that need to enforce a particular format are
encouraged to use the pattern attribute or the setCustomValidity() method to hook into the client-side
validation mechanism. The following common input element content
attributes, IDL attributes, and methods apply to the element:
autocomplete,
list,
maxlength ,
minlength ,
pattern,
placeholder ,
readonly,
required, and
size content attributes; list,
selectionStart,
selectionEnd, selectionDirection , and
value IDL attributes;
select(),
setRangeText(), and
setSelectionRange() methods. The value IDL attribute is
in mode value. The input and change events apply. The following content attributes must not be specified and do not
apply to the element:
accept ,
alt,
checked,
dirname,
formaction,
formenctype, formmethod ,
formnovalidate,
formtarget ,
height ,
inputmode,
max ,
min,

http://developers.whatwg.org/states-of-the-type-attribute.html[4/16/2014 9:35:13 PM]

4.10.5.1 States of the type attribute HTML: The Living Standard - Edition for Web Developers

multiple,
src,
step, and
width. The following IDL attributes and methods do not apply to the
element: checked,
files,
valueAsDate , and
valueAsNumber IDL attributes; stepDown() and
stepUp() methods.

URL state (type=url) The input element represents a control for editing a single
absolute URL given in the element's value. The value attribute, if specified and not empty, must
have a value that is a valid URL potentially surrounded by spaces that is also an
absolute URL. The following common input element content
attributes, IDL attributes, and methods apply to the element:
autocomplete,
list,
maxlength ,
minlength ,
pattern,
placeholder ,
readonly,
required, and
size content attributes; list,
selectionStart,
selectionEnd,
selectionDirection , and
value IDL attributes;
select(),
setRangeText(), and
setSelectionRange() methods. The value IDL attribute is
in mode value. The input and change events apply. The following content attributes must not be specified and do not
apply to the element:
accept ,
alt,
checked,
dirname,
formaction,
formenctype, formmethod ,
formnovalidate,
formtarget ,
height ,
inputmode,
max ,
min, multiple,
src,
step, and
width. The following IDL attributes and methods do not apply to the
element: checked,
files,
valueAsDate , and
valueAsNumber IDL attributes; stepDown() and
stepUp() methods. If a document contained the following markup: <input type="url" name="location" list="urls"> <datalist id="urls"> <option label="MIME: Format of Internet Message Bodies" value="http://tools.ietf.org/html/rfc2045"> <option label="HTML 4.01 Specification" value="http://www.w3.org/TR/html4/">

http://developers.whatwg.org/states-of-the-type-attribute.html[4/16/2014 9:35:13 PM]

4.10.5.1 States of the type attribute HTML: The Living Standard - Edition for Web Developers

<option label="Form Controls" value="http://www.w3.org/TR/xforms/slice8.html#uicommonelems-hint"> <option label="Scalable Vector Graphics (SVG) 1.1 Specification" value="http://www.w3.org/TR/SVG/"> <option label="Feature Sets - SVG 1.1 - 20030114" value="http://www.w3.org/TR/SVG/feature.html"> <option label="The Single UNIX Specification, Version 3" value="http://www.unix-systems.org/version3/"> </datalist> ...and the user had typed "www.w3", and the user agent had also found that the user
had visited http://www.w3.org/Consortium/#membership and http://www.w3.org/TR/XForms/ in the recent past, then the rendering might look like
this:

The first four URLs in this sample consist of the four URLs in the authorspecified list that
match the text the user has entered, sorted in some UAdefined manner (maybe by how frequently
the user refers to those URLs). Note how the UA is using the knowledge that the values are URLs
to allow the user to omit the scheme part and perform intelligent matching on the domain
name. The last two URLs (and probably many more, given the scrollbar's indications of more values
being available) are the matches from the user agent's session history data. This data is not
made available to the page DOM. In this particular case, the UA has no titles to provide for
those values.

E-mail state (type=email ) How the E-mail state operates depends on whether the
multiple attribute is specified or not. When the multiple attribute is not specified on the
element

http://developers.whatwg.org/states-of-the-type-attribute.html[4/16/2014 9:35:13 PM]

4.10.5.1 States of the type attribute HTML: The Living Standard - Edition for Web Developers

The input element represents a control for editing an e-mail


address given in the element's value. The value attribute, if specified and not empty, must
have a value that is a single valid e-mail address. When the multiple attribute is specified on
the element The input element represents a control for adding, removing, and
editing the e-mail addresses given in the element's values. The value attribute, if specified, must have a value
that is a valid e-mail address list. A valid e-mail address is a string that matches the email
production of the following ABNF, the character set for which is Unicode. This ABNF implements the
extensions described in RFC 1123. email label atext let-dig ldh-str = 1*( atext / "." ) "@" label *( "." label ) = let-dig [ [ ldh-str ] let-dig ] ; limited to

a length of 63 characters by RFC 1034 section 3.5 = < as defined in RFC 5322 section 3.2.3 > = < as defined in RFC 1034 section 3.5 > = < as defined in RFC 1034 section 3.5 >

This requirement is a willful violation of RFC 5322, which defines a


syntax for e-mail addresses that is simultaneously too strict (before the "@" character), too
vague (after the "@" character), and too lax (allowing comments, whitespace characters, and quoted
strings in manners unfamiliar to most users) to be of practical use here. The following JavaScript- and Perl-compatible regular expression is an implementation of the
above definition. /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-] {0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[azA-Z0-9])?)*$/ A valid e-mail address list is a set of comma-separated tokens, where
each token is itself a valid e-mail address. The following common input element content
attributes, IDL attributes, and methods apply to the element:
autocomplete,
list,
maxlength ,
minlength ,

http://developers.whatwg.org/states-of-the-type-attribute.html[4/16/2014 9:35:13 PM]

4.10.5.1 States of the type attribute HTML: The Living Standard - Edition for Web Developers

multiple,
pattern ,
placeholder,
readonly,
required, and
size content attributes;
list and
value IDL attributes. The value IDL attribute is
in mode value. The input and change events apply. The following content attributes must not be specified and do not
apply to the element:
accept ,
alt,
checked,
dirname,
formaction,
formenctype, formmethod ,
formnovalidate,
formtarget ,
height ,
inputmode,
max ,
min, src,
step, and
width . The following IDL attributes and methods do not apply to the
element: checked,
files,
selectionStart ,
selectionEnd,
selectionDirection, valueAsDate, and
valueAsNumber IDL attributes;
select(), setRangeText() ,
setSelectionRange(),
stepDown() and
stepUp() methods.

Password state (type=password ) The input element represents a one line plain text edit control for
the element's value. The user agent should obscure the value
so that people other than the user cannot see it. The value attribute, if specified, must have a value that
contains no U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters. The following common input element content
attributes, IDL attributes, and methods apply to the element:
autocomplete,
inputmode,
maxlength , minlength ,
pattern,
placeholder ,
readonly,
required, and
size content attributes;
selectionStart ,
selectionEnd,
selectionDirection, and value IDL attributes;
select(),
setRangeText(), and setSelectionRange() methods. The value IDL attribute is
in mode value. The input and change events apply. The following content attributes must not be specified and do not
apply to the element:
accept ,
alt,
checked,
dirname,
formaction,
formenctype, formmethod ,
formnovalidate,
formtarget ,
height ,
list,
max ,
min, multiple,
src,
step, and
width.

http://developers.whatwg.org/states-of-the-type-attribute.html[4/16/2014 9:35:13 PM]

4.10.5.1 States of the type attribute HTML: The Living Standard - Edition for Web Developers

The following IDL attributes and methods do not apply to the


element: checked,
files,
list,
valueAsDate, and
valueAsNumber IDL attributes; stepDown() and
stepUp() methods.

Date and Time state (type=datetime ) The input element represents a control for setting the element's
value to a string representing a specific global date and time. See the introduction section for a discussion of
the difference between the input format and submission format for date, time, and number form controls. The value attribute, if specified and not empty, must
have a value that is a valid global date and time string. The min attribute, if specified, must have a value that is
a valid global date and time string. The max
attribute, if specified, must have a value that is a valid global date and time
string. The step attribute is expressed in seconds. The default step is 60 seconds. The Date and Time state (and other date- and
time-related states described in subsequent sections) is not intended for the entry of values for
which a precise date and time relative to the contemporary calendar cannot be established. For
example, it would be inappropriate for the entry of times like "one millisecond after the big
bang", "the early part of the Jurassic period", or "a winter around 250 BCE". For the input of dates before the introduction of the Gregorian calendar, authors are
encouraged to not use the Date and Time state (and
the other date- and time-related states described in subsequent sections), as user agents are not
required to support converting dates and times from earlier periods to the Gregorian calendar,
and asking users to do so manually puts an undue burden on users. (This is complicated by the
manner in which the Gregorian calendar was phased in, which occurred at different times in different countries, ranging from partway through the 16th century all the way to early in the
20th.) Instead, authors are encouraged to provide finegrained input controls using the
select element and input elements with the Number state.

http://developers.whatwg.org/states-of-the-type-attribute.html[4/16/2014 9:35:13 PM]

4.10.5.1 States of the type attribute HTML: The Living Standard - Edition for Web Developers

The following common input element content


attributes, IDL attributes, and methods apply to the element:
autocomplete,
list,
max ,
min,
readonly, required, and
step content attributes;
list ,
value ,
valueAsDate, and valueAsNumber IDL attributes;
stepDown() and
stepUp() methods. The value IDL attribute is
in mode value. The input and change events apply. The following content attributes must not be specified and do not
apply to the element:
accept ,
alt,
checked,
dirname,
formaction,
formenctype, formmethod ,
formnovalidate,
formtarget ,
height ,
inputmode, maxlength ,
minlength,
multiple,
pattern,
placeholder,
size,
src, and width . The following IDL attributes and methods do not apply to the
element: checked,
files,
selectionStart ,
selectionEnd, and selectionDirection IDL attributes;
select(),
setRangeText(), and setSelectionRange() methods. The following fragment shows part of a calendar application. A user can specify a date and
time for a meeting (in his local time zone, probably, though the user agent can allow the user to
change that), and since the submitted data includes the time-zone offset, the application can
ensure that the meeting is shown at the correct time regardless of the time zones used by all the
participants. <fieldset> <legend>Add Meeting</legend> <p><label>Meeting name: <input type=text name="meeting.label"></label> <p><label>Meeting time: <input type=datetime name="meeting.start"></label> </fieldset> Had the application used the datetime-local type instead, the calendar application would have also had to explicitly determine which time zone the user intended. For events where the precise time is to vary as the user travels (e.g. "celebrate the new
year!"), and for recurring events that are to stay at the same time for a specific geographic
location even though that location may

http://developers.whatwg.org/states-of-the-type-attribute.html[4/16/2014 9:35:13 PM]

4.10.5.1 States of the type attribute HTML: The Living Standard - Edition for Web Developers

go in and out of daylight savings time (e.g. "bring the


kid to school"), the datetime-local type
combined with a select element (or other similar control) to pick the specific
geographic location to which to anchor the time would be more appropriate.

Date state (type=date ) The input element represents a control for setting the element's
value to a string representing a specific date. See the introduction section for a discussion of
the difference between the input format and submission format for date, time, and number form controls. The value attribute, if specified and not empty, must
have a value that is a valid date string. The min attribute, if specified, must have a value that is
a valid date string. The max attribute, if
specified, must have a value that is a valid date string. The step attribute is expressed in days. The default step is 1 day. See the note on historical dates in the
Date and Time state section. The following common input element content
attributes, IDL attributes, and methods apply to the element:
autocomplete,
list,
max ,
min,
readonly, required, and
step content attributes;
list ,
value ,
valueAsDate, and valueAsNumber IDL attributes;
stepDown() and
stepUp() methods. The value IDL attribute is
in mode value. The input and change events apply. The following content attributes must not be specified and do not
apply to the element:
accept ,
alt,
checked,
dirname,
formaction,
formenctype, formmethod ,
formnovalidate,
formtarget ,
height ,
inputmode, maxlength ,
minlength,
multiple,
pattern,
placeholder,
size,
src, and width . The following IDL attributes and methods do not apply to the
element: checked,
selectionStart,
selectionEnd, and
selectionDirection IDL attributes;
select(),
setRangeText() , and
setSelectionRange()

http://developers.whatwg.org/states-of-the-type-attribute.html[4/16/2014 9:35:13 PM]

4.10.5.1 States of the type attribute HTML: The Living Standard - Edition for Web Developers

methods.

Month state (type=month ) The input element represents a control for setting the element's
value to a string representing a specific month. See the introduction section for a discussion of
the difference between the input format and submission format for date, time, and number form controls. The value attribute, if specified and not empty, must
have a value that is a valid month string. The min attribute, if specified, must have a value that is
a valid month string. The max attribute, if
specified, must have a value that is a valid month string. The step attribute is expressed in months. The default step is 1 month. The following common input element content
attributes, IDL attributes, and methods apply to the element:
autocomplete,
list,
max ,
min,
readonly, required, and
step content attributes;
list ,
value ,
valueAsDate, and valueAsNumber IDL attributes;
stepDown() and
stepUp() methods. The value IDL attribute is
in mode value. The input and change events apply. The following content attributes must not be specified and do not
apply to the element:
accept ,
alt,
checked,
dirname,
formaction,
formenctype, formmethod ,
formnovalidate,
formtarget ,
height ,
inputmode, maxlength ,
minlength,
multiple,
pattern,
placeholder,
size,
src, and width . The following IDL attributes and methods do not apply to the
element: checked,
files,
selectionStart ,
selectionEnd, and selectionDirection IDL attributes;
select(),
setRangeText(), and setSelectionRange() methods.

Week state ( type=week) The input element represents a control for setting the element's
value to a
http://developers.whatwg.org/states-of-the-type-attribute.html[4/16/2014 9:35:13 PM]

4.10.5.1 States of the type attribute HTML: The Living Standard - Edition for Web Developers

string representing a specific week. See the introduction section for a discussion of
the difference between the input format and submission format for date, time, and number form controls. The value attribute, if specified and not empty, must
have a value that is a valid week string. The min attribute, if specified, must have a value that is
a valid week string. The max attribute, if
specified, must have a value that is a valid week string. The step attribute is expressed in weeks. The default step is 1 week. The following common input element content attributes, IDL attributes, and methods apply to the element:
autocomplete,
list,
max ,
min,
readonly, required, and
step content attributes;
list ,
value ,
valueAsDate, and valueAsNumber IDL attributes;
stepDown() and
stepUp() methods. The value IDL attribute is in mode value. The input and change events apply. The following content attributes must not be specified and do not apply to the element:
accept ,
alt,
checked,
dirname,
formaction,
formenctype, formmethod ,
formnovalidate,
formtarget ,
height ,
inputmode, maxlength ,
minlength,
multiple,
pattern,
placeholder,
size,
src, and width . The following IDL attributes and methods do not apply to the element: checked,
files,
selectionStart ,
selectionEnd, and selectionDirection IDL attributes;
select(),
setRangeText(), and setSelectionRange() methods.

Time state (type=time ) The input element represents a control for setting the element's
value to a string representing a specific time. See the introduction section for a discussion of
the difference between the input format and submission format for date, time, and number form controls.

http://developers.whatwg.org/states-of-the-type-attribute.html[4/16/2014 9:35:13 PM]

4.10.5.1 States of the type attribute HTML: The Living Standard - Edition for Web Developers

The value attribute, if specified and not empty, must


have a value that is a valid time string. The min attribute, if specified, must have a value that is
a valid time string. The max attribute, if
specified, must have a value that is a valid time string. The step attribute is expressed in seconds. The default step is 60 seconds. The following common input element content attributes, IDL attributes, and methods apply to the element:
autocomplete,
list,
max ,
min,
readonly, required, and
step content attributes;
list ,
value ,
valueAsDate, and valueAsNumber IDL attributes;
stepDown() and
stepUp() methods. The value IDL attribute is in mode value. The input and change events apply. The following content attributes must not be specified and do not apply to the element:
accept ,
alt,
checked,
dirname,
formaction,
formenctype, formmethod ,
formnovalidate,
formtarget ,
height ,
inputmode, maxlength ,
minlength,
multiple,
pattern,
placeholder,
size,
src, and width . The following IDL attributes and methods do not apply to the element: checked,
files,
selectionStart ,
selectionEnd, and selectionDirection IDL attributes;
select(),
setRangeText(), and setSelectionRange() methods.

Local Date and Time state (type=datetime-local ) The input element represents a control for setting the element's
value to a string representing a local date and time, with no time-zone offset information. See the introduction section for a discussion of
the difference between the input format and submission format for date, time, and number form controls. The value attribute, if specified and not empty, must
have a value that is a valid local date and time string. The min attribute, if specified, must have a value that is
a valid local date and

http://developers.whatwg.org/states-of-the-type-attribute.html[4/16/2014 9:35:13 PM]

4.10.5.1 States of the type attribute HTML: The Living Standard - Edition for Web Developers

time string. The max


attribute, if specified, must have a value that is a valid local date and time
string. The step attribute is expressed in seconds. The default step is 60 seconds. See the note on historical dates in the
Date and Time state section. The following common input element content
attributes, IDL attributes, and methods apply to the element:
autocomplete,
list,
max ,
min,
readonly, required, and
step content attributes;
list ,
value , and
valueAsNumber IDL attributes;
stepDown() and
stepUp() methods. The value IDL attribute is
in mode value. The input and change events apply. The following content attributes must not be specified and do not
apply to the element:
accept ,
alt,
checked,
dirname,
formaction,
formenctype, formmethod ,
formnovalidate,
formtarget ,
height ,
inputmode, maxlength ,
minlength,
multiple,
pattern,
placeholder,
size,
src, and width . The following IDL attributes and methods do not apply to the
element: checked,
files,
selectionStart ,
selectionEnd,
selectionDirection, and
valueAsDate IDL attributes;
select(),
setRangeText() , and setSelectionRange() methods. The following example shows part of a flight booking application. The application uses an
input element with its type attribute set to datetime-local , and it then interprets the
given date and time in the time zone of the selected airport. <fieldset> <legend>Destination</legend> <p><label>Airport: <input type=text name=to list=airports> </label></p> <p><label>Departure time: <input type=datetime-local name=totime step=3600></label></p> </fieldset> <datalist id=airports> <option value=ATL label="Atlanta"> <option value=MEM label="Memphis"> <option value=LHR label="London Heathrow">
http://developers.whatwg.org/states-of-the-type-attribute.html[4/16/2014 9:35:13 PM]

4.10.5.1 States of the type attribute HTML: The Living Standard - Edition for Web Developers

<option value=LAX label="Los Angeles"> <option value=FRA label="Frankfurt"> </datalist> If the application instead used the datetime
type, then the user would have to work out the time-zone conversions himself, which is clearly
not a good user experience!

Number state (type=number) The input element represents a control for setting the element's
value to a string representing a number. This specification does not define what user interface user agents are to use; user agent vendors are encouraged to consider what would best serve their users' needs. For
example, a user agent in Persian or Arabic markets might support Persian and Arabic numeric input
(converting it to the format required for submission as described above). Similarly, a user agent
designed for Romans might display the value in Roman numerals rather than in decimal; or (more
realistically) a user agent designed for the French market might display the value with
apostrophes between thousands and commas before the decimals, and allow the user to enter a value
in that manner, internally converting it to the submission format described above. The value attribute, if specified and not empty, must
have a value that is a valid floating-point number. The min attribute, if specified, must have a value that is
a valid floating-point number. The max attribute,
if specified, must have a value that is a valid floating-point number. The default step is 1 (allowing only
integers to be selected by the user, unless the step
base has a non-integer value). The following common input element content attributes, IDL attributes, and methods apply to the element:
autocomplete,
list,
max ,
min,
placeholder, readonly,
required, and
step content attributes;
list,
value , and valueAsNumber IDL attributes;
stepDown() and
stepUp() methods. The value IDL attribute is in mode value. The input and change events apply.
http://developers.whatwg.org/states-of-the-type-attribute.html[4/16/2014 9:35:13 PM]

4.10.5.1 States of the type attribute HTML: The Living Standard - Edition for Web Developers

The following content attributes must not be specified and do not apply to the element:
accept ,
alt,
checked,
dirname,
formaction,
formenctype, formmethod ,
formnovalidate,
formtarget ,
height ,
inputmode, maxlength ,
minlength,
multiple,
pattern,
size,
src , and
width. The following IDL attributes and methods do not apply to the element: checked,
files,
selectionStart ,
selectionEnd,
selectionDirection, and
valueAsDate IDL attributes;
select(),
setRangeText() , and setSelectionRange() methods. Here is an example of using a numeric input control: <label>How much do you want to charge? $<input type=number min=0 step=0.01 name=price></label> As described above, a user agent might support numeric input in the user's local format,
converting it to the format required for submission as described above. This might include
handling grouping separators (as in "872,000,000,000") and various decimal separators (such as
"3,99" vs "3.99") or using local digits (such as those in Arabic, Devanagari, Persian, and
Thai). The type=number state is not appropriate for input that
happens to only consist of numbers but isn't strictly speaking a number. For example, it would be
inappropriate for credit card numbers or US postal codes. A simple way of determining whether to
use type=number is to consider whether it would make sense for the input
control to have a spinbox interface (e.g. with "up" and "down" arrows). Getting a credit card
number wrong by 1 in the last digit isn't a minor mistake, it's as wrong as getting every digit
incorrect. So it would not make sense for the user to select a credit card number using "up" and
"down" buttons. When a spinbox interface is not appropriate, type=text is
probably the right choice (possibly with a pattern
attribute).

Range state (type=range ) The input element represents a control for setting the element's
value to a string representing a number, but with the caveat
that the exact value is not important, letting UAs provide a simpler interface than they do for
the Number state.

http://developers.whatwg.org/states-of-the-type-attribute.html[4/16/2014 9:35:13 PM]

4.10.5.1 States of the type attribute HTML: The Living Standard - Edition for Web Developers

The value attribute, if specified, must have a value that


is a valid floatingpoint number. The min attribute, if specified, must have a value that is
a valid floating-point number. The default
minimum is 0. The max attribute, if specified, must
have a value that is a valid floating-point number. The default maximum is 100. The default value is the minimum plus half the difference between the minimum and the maximum,
unless the maximum is less than the minimum, in which case the default value is the minimum. The default step is 1 (allowing only
integers, unless the min attribute has a non-integer
value). The following common input element content attributes, IDL attributes, and methods apply to the element:
autocomplete,
list,
max ,
min, and
step content attributes;
list,
value , and
valueAsNumber IDL attributes; stepDown() and
stepUp() methods. The value IDL attribute is in mode value. The input and change events apply. The following content attributes must not be specified and do not apply to the element:
accept ,
alt,
checked,
dirname,
formaction,
formenctype, formmethod ,
formnovalidate,
formtarget ,
height ,
inputmode, maxlength ,
minlength,
multiple,
pattern,
placeholder,
readonly, required,
size,
src , and
width. The following IDL attributes and methods do not apply to the element: checked,
files,
selectionStart ,
selectionEnd,
selectionDirection, and
valueAsDate IDL attributes;
select(),
setRangeText() , and setSelectionRange() methods. Here is an example of a range control using an autocomplete list with the list attribute. This could be useful if there are values along the
full range of the control that are especially important, such as preconfigured light levels or
typical speed limits in a range control used as a speed control. The following markup
fragment: <input type="range" min="-100" max="100" value="0" step="10" name="power" list="powers"> <datalist id="powers">

http://developers.whatwg.org/states-of-the-type-attribute.html[4/16/2014 9:35:13 PM]

4.10.5.1 States of the type attribute HTML: The Living Standard - Edition for Web Developers

<option value="0"> <option value="-30"> <option value="30"> <option value="++50"> </datalist> ...with the following style sheet applied: input { height: 75px; width: 49px; background: #D5CCBB; color: black; } ...might render as:

Note how the UA determined the orientation of the control from the ratio of the
style-sheet-specified height and width properties. The colors were similarly derived from the
style sheet. The tick marks, however, were derived from the markup. In particular, the step attribute has not affected the placement of tick marks, the
UA deciding to only use the author-specified completion values and then adding longer tick marks
at the extremes. Note also how the invalid value ++50 was completely ignored. For another example, consider the following markup fragment: <input name=x type=range min=100 max=700 step=9.09090909 value=509.090909> A user agent could display in a variety of ways, for instance:

Or, alternatively, for instance:

The user agent could pick which one to display based on the dimensions given in the style
sheet. This would allow it to maintain the same resolution
http://developers.whatwg.org/states-of-the-type-attribute.html[4/16/2014 9:35:13 PM]

4.10.5.1 States of the type attribute HTML: The Living Standard - Edition for Web Developers

for the tick marks, despite the


differences in width. Finally, here is an example of a range control with two labeled values: <input type="range" name="a" list="a-values"> <datalist id="a-values"> <option value="10" label="Low"> <option value="90" label="High"> </datalist> With styles that make the control draw vertically, it might look as follows:

Color state ( type=color) The input element represents a color well control, for setting the
element's value to a string representing a simple
color. The value attribute, if specified and not empty, must
have a value that is a valid simple color. The following common input element content attributes and IDL attributes apply to the element:
autocomplete and
list content attributes;
list and value IDL attributes. The value IDL attribute is in mode value. The input and change events apply. The following content attributes must not be specified and do not apply to the element:
accept ,
alt,
checked,
dirname,
formaction,
formenctype, formmethod ,
formnovalidate,
formtarget ,
height ,
inputmode,
max , maxlength ,
min,
minlength ,
multiple,
pattern,
placeholder ,
readonly, required,
size,
src ,
step, and
width .

http://developers.whatwg.org/states-of-the-type-attribute.html[4/16/2014 9:35:13 PM]

4.10.5.1 States of the type attribute HTML: The Living Standard - Edition for Web Developers

The following IDL attributes and methods do not apply to the element: checked,
files,
selectionStart ,
selectionEnd,
selectionDirection, valueAsDate, and
valueAsNumber IDL attributes;
select(), setRangeText() ,
setSelectionRange(),
stepDown() , and
stepUp() methods.

Checkbox state (type=checkbox ) The input element represents a two-state control that represents the element's checkedness state. If the element's checkedness state is true, the control represents a positive
selection, and if it is false, a negative selection. If the element's indeterminate IDL attribute is set to true, then the
control's selection should be obscured as if the control was in a third, indeterminate, state. The control is never a true tri-state control, even if the element's indeterminate IDL attribute is set to true. The indeterminate IDL attribute only gives the appearance of a
third state. input . indeterminate [ = value ] When set, overrides the rendering of checkbox
controls so that the current value is not visible. The following common input element content attributes and IDL attributes apply to the element:
checked, and
required content attributes;
checked and
value IDL attributes. The value IDL attribute is in mode default/on. The change event applies. The following content attributes must not be specified and do not apply to the element:
accept ,
alt,
autocomplete,
dirname,
formaction,
formenctype, formmethod ,
formnovalidate,
formtarget ,
height ,
inputmode,
list,
max, maxlength ,
min,
minlength ,
multiple,
pattern,
placeholder ,
readonly, size,
src,
step, and
width. The following IDL attributes and methods do not apply to the element:
files ,
list,
selectionStart ,
selectionEnd,
selectionDirection, valueAsDate, and
valueAsNumber IDL attributes;
select(),

http://developers.whatwg.org/states-of-the-type-attribute.html[4/16/2014 9:35:13 PM]

4.10.5.1 States of the type attribute HTML: The Living Standard - Edition for Web Developers

setRangeText() ,
setSelectionRange(),
stepDown() , and
stepUp() methods. The input event does not apply.

Radio Button state (type=radio ) The input element represents a control that, when used in conjunction
with other input elements, forms a radio button group in which only one
control can have its checkedness state set to true. If the
element's checkedness state is true, the control
represents the selected control in the group, and if it is false, it indicates a control in the
group that is not selected. The radio button group that contains an input element a also contains all the other input elements b
that fulfill all of the following conditions:

The input element b's type attribute is in the Radio


Button state. Either a and b have the same form owner,
or they both have no form owner. Both a and b are in the same home
subtree. They both have a name attribute, their name attributes are not empty, and the
value of a's name attribute is a compatibility
caseless match for the value of b's name attribute. A document must not contain an input element whose radio button group contains only that element. If none of the radio buttons in a radio button group are checked when
they are inserted into the document, then they will all be initially unchecked in the interface,
until such time as one of them is checked (either by the user or by script). The following common input element content attributes and IDL attributes apply to the element:
checked and
required content attributes;
checked and
value IDL attributes. The value IDL attribute is in mode default/on. The change event applies. The following content attributes must not be specified and do not apply to the element:
accept ,
alt,
autocomplete,
dirname,
formaction,
formenctype, formmethod ,
formnovalidate,
formtarget ,
height ,
inputmode,
list,
max,

http://developers.whatwg.org/states-of-the-type-attribute.html[4/16/2014 9:35:13 PM]

4.10.5.1 States of the type attribute HTML: The Living Standard - Edition for Web Developers

maxlength ,
min,
minlength ,
multiple,
pattern,
placeholder ,
readonly, size,
src,
step, and
width. The following IDL attributes and methods do not apply to the element:
files ,
list,
selectionStart ,
selectionEnd,
selectionDirection, valueAsDate, and
valueAsNumber IDL attributes;
select(), setRangeText() ,
setSelectionRange(),
stepDown() , and
stepUp() methods. The input event does not apply.

File Upload state (type=file ) The input element represents a list of selected files, each file consisting of a file
name, a file type, and a file body (the contents of the file). The accept attribute may be specified to
provide user agents with a hint of what file types will be accepted. If specified, the attribute must consist of a set of comma-separated tokens, each
of which must be an ASCII case-insensitive match for one of the following: The string audio/* Indicates that sound files are accepted. The string video/* Indicates that video files are accepted. The string image/* Indicates that image files are accepted. A valid MIME type with no parameters Indicates that files of the specified type are accepted. A string whose first character is a U+002E FULL STOP character (.) Indicates that files with the specified file extension are accepted. The tokens must not be ASCII case-insensitive matches for any of the other tokens
(i.e. duplicates are not allowed). User agents may use the value of this attribute to display a more appropriate user interface
than a generic file picker. For instance, given the value image/*

http://developers.whatwg.org/states-of-the-type-attribute.html[4/16/2014 9:35:13 PM]

4.10.5.1 States of the type attribute HTML: The Living Standard - Edition for Web Developers

, a user
agent could offer the user the option of using a local camera or selecting a photograph from their
photo collection; given the value audio/*, a user agent could offer the user
the option of recording a clip using a headset microphone. Authors are encouraged to specify both any MIME types and any corresponding
extensions when looking for data in a specific format. For example, consider an application that converts Microsoft Word documents to Open Document
Format files. Since Microsoft Word documents are described with a wide variety of MIME types and
extensions, the site can list several, as follows: <input type="file" accept=".doc,.docx,.xml,application/msword,application/vnd.op enxmlformats-officedocument.wordprocessingml.document"> On platforms that only use file extensions to describe file types, the extensions listed here
can be used to filter the allowed documents, while the MIME types can be used with the system's
type registration table (mapping MIME types to extensions used by the system), if any, to
determine any other extensions to allow. Similarly, on a system that does not have file names or extensions but labels documents with MIME types internally, the MIME types can be used to pick
the allowed files, while the extensions can be used if the system has an extension registration
table that maps known extensions to MIME types used by the system. Extensions tend to be ambiguous (e.g. there are an untold number of formats
that use the ".dat" extension, and users can typically quite easily rename
their files to have a " .doc" extension even if they are not Microsoft Word
documents), and MIME types tend to be unreliable (e.g. many formats have no formally registered
types, and many formats are in practice labeled using a number of different MIME types). Authors
are reminded that, as usual, data received from a client should be treated with caution, as it may
not be in an expected format even if the user is not hostile and the user agent fully obeyed the
accept attribute's requirements. For historical reasons, the value IDL attribute prefixes
the file name with the string "C:\fakepath\". Some legacy user agents
actually included the full path (which was a security vulnerability). As a result of this,
obtaining the file name from the value IDL attribute in a
backwards-compatible way is

http://developers.whatwg.org/states-of-the-type-attribute.html[4/16/2014 9:35:13 PM]

4.10.5.1 States of the type attribute HTML: The Living Standard - Edition for Web Developers

non-trivial. The following function extracts the file name in a


suitably compatible manner: function extractFilename(path) { if (path.substr(0, 12) == "C:\\fakepath\\") return path.substr(12); // modern browser var x; x = path.lastIndexOf('/'); if (x >= 0) // Unix-based path return path.substr(x+1); x = path.lastIndexOf('\\'); if (x >= 0) // Windows-based path return path.substr(x+1); return path; // just the file name } This can be used as follows: <p><input type=file name=image onchange="updateFilename(this.value)"></p> <p>The name of the file you picked is: <span id="filename"> (none)</span></p> <script> function updateFilename(path) { var name = extractFilename(path); document.getElementById('filename').textContent = name; } </script> The following common input element content attributes and IDL attributes apply to the element:
accept,
multiple, and
required content attributes; files and
value IDL attributes. The value IDL attribute is in mode filename. The change event applies. The following content attributes must not be specified and do not apply to the element:
alt ,
autocomplete,
checked,
dirname,
formaction,
formenctype ,
formmethod,
formnovalidate ,
formtarget ,
height,
inputmode ,
list,
max ,
maxlength,
min ,
minlength ,
pattern,
placeholder ,
readonly,
size,
src , step, and
width .

http://developers.whatwg.org/states-of-the-type-attribute.html[4/16/2014 9:35:13 PM]

4.10.5.1 States of the type attribute HTML: The Living Standard - Edition for Web Developers

The element's value attribute must be omitted. The following IDL attributes and methods do not apply to the element: checked,
list,
selectionStart ,
selectionEnd,
selectionDirection, valueAsDate, and
valueAsNumber IDL attributes;
select(), setRangeText() ,
setSelectionRange(),
stepDown() , and
stepUp() methods. The input event does not apply.

Submit Button state (type=submit) The input element represents a button that, when activated, submits
the

form. The element is a button, specifically a submit


button.
The formaction, formenctype, formmethod , formnovalidate, and formtarget attributes are attributes for form
submission. The formnovalidate attribute can be
used to make submit buttons that do not trigger the constraint validation. The following common input element content attributes and IDL attributes apply to the element:
formaction,
formenctype,
formmethod , formnovalidate , and
formtarget content attributes;
value IDL attribute. The value IDL attribute is in mode default. The following content attributes must not be specified and do not apply to the element:
accept ,
alt,
autocomplete,
checked,
dirname,
height, inputmode ,
list,
max ,
maxlength ,
min,
minlength ,
multiple,
pattern, placeholder,
readonly,
required,
size,
src,
step, and
width. The following IDL attributes and methods do not apply to the element: checked,
files,
list,
selectionStart ,
selectionEnd, selectionDirection ,
valueAsDate, and
valueAsNumber IDL attributes; select(),
setRangeText(),
setSelectionRange() ,
stepDown() , and stepUp() methods. The input and change events do not apply.

http://developers.whatwg.org/states-of-the-type-attribute.html[4/16/2014 9:35:13 PM]

4.10.5.1 States of the type attribute HTML: The Living Standard - Edition for Web Developers

Image Button state (type=image ) The input element represents either an image from which a user can
select a coordinate and submit the form, or alternatively a button from which the user can submit
the form. The element is a button, specifically a submit button. The coordinate is sent to the server during form submission by sending two entries for the element, derived from the name
of the control but with ".x " and ".y " appended to the
name with the x and y components of the coordinate
respectively. The image is given by the src attribute. The
src attribute must be present, and must contain a valid
non-empty URL potentially surrounded by spaces referencing a non-interactive, optionally
animated, image resource that is neither paged nor scripted. The alt attribute provides the textual label for
the button for users and user agents who cannot use the image. The alt attribute must be present, and must contain a non-empty string
giving the label that would be appropriate for an equivalent button if the image was
unavailable. The input element supports dimension attributes. The formaction, formenctype, formmethod , formnovalidate, and formtarget attributes are attributes for form
submission. image . width [ = value ] image . height [ = value ] These attributes return the actual rendered dimensions of the image, or zero if the
dimensions are not known. They can be set, to change the corresponding content attributes. The following common input element content attributes and IDL attributes apply to the element:
alt,
formaction,
formenctype,
formmethod, formnovalidate ,
formtarget,
height ,
src, and
width content attributes; value IDL attribute. The value IDL attribute is in mode default. The following content attributes must not be specified and do not apply to the

http://developers.whatwg.org/states-of-the-type-attribute.html[4/16/2014 9:35:13 PM]

4.10.5.1 States of the type attribute HTML: The Living Standard - Edition for Web Developers

element:
accept ,
autocomplete,
checked,
dirname,
inputmode ,
list,
max, maxlength ,
min,
minlength ,
multiple,
pattern,
placeholder ,
readonly, required,
size, and
step. The element's value attribute must be omitted. The following IDL attributes and methods do not apply to the element: checked,
files,
list,
selectionStart ,
selectionEnd, selectionDirection ,
valueAsDate, and
valueAsNumber IDL attributes; select(),
setRangeText(),
setSelectionRange() ,
stepDown() , and stepUp() methods. The input and change events do not apply. Many aspects of this state's behavior are similar to the behavior of the
img element. Readers are encouraged to read that section, where many of the same
requirements are described in more detail. Take the following form: <form action="process.cgi"> <input type=image src=map.png name=where alt="Show location list"> </form> If the user clicked on the image at coordinate (127,40) then the URL used to submit the form
would be "process.cgi?where.x=127&where.y=40 ". (In this example, it's assumed that for users who don't see the map, and who instead just see
a button labeled "Show location list", clicking the button will cause the server to show a list
of locations to pick from instead of the map.)

Reset Button state (type=reset) The input element represents a button that, when activated, resets
the form.

The element is a button.


The value IDL attribute applies to this element and is in mode default. The following content attributes must not be specified and do not apply to the

http://developers.whatwg.org/states-of-the-type-attribute.html[4/16/2014 9:35:13 PM]

4.10.5.1 States of the type attribute HTML: The Living Standard - Edition for Web Developers

element:
accept ,
alt,
autocomplete,
checked,
dirname,
formaction, formenctype,
formmethod,
formnovalidate ,
formtarget ,
height, inputmode ,
list,
max ,
maxlength ,
min,
minlength ,
multiple,
pattern, placeholder,
readonly,
required,
size,
src,
step, and
width. The following IDL attributes and methods do not apply to the element: checked,
files,
list,
selectionStart ,
selectionEnd, selectionDirection ,
valueAsDate, and
valueAsNumber IDL attributes; select(),
setRangeText(),
setSelectionRange() ,
stepDown() , and stepUp() methods. The input and change events do not apply.

Button state (type=button) The input element represents a button with no default behavior. A
label for the button must be provided in the value
attribute, though it may be the empty string. The element is a button. The value IDL attribute applies to this element and is in mode default. The following content attributes must not be specified and do not apply to the element:
accept ,
alt,
autocomplete,
checked,
dirname,
formaction, formenctype,
formmethod,
formnovalidate ,
formtarget ,
height, inputmode ,
list,
max ,
maxlength ,
min,
minlength ,
multiple,
pattern, placeholder,
readonly,
required,
size,
src,
step, and
width. The following IDL attributes and methods do not apply to the element: checked,
files,
list,
selectionStart ,
selectionEnd, selectionDirection ,
valueAsDate, and
valueAsNumber IDL attributes; select(),
setRangeText(),
setSelectionRange() ,
stepDown() , and stepUp() methods. The input and change events do not apply.

Up next

4.10.5.2 Common input element attributes

This document is a work in progress, if you spot something that you feel isn't quite right,

http://developers.whatwg.org/states-of-the-type-attribute.html[4/16/2014 9:35:13 PM]

4.10.5.1 States of the type attribute HTML: The Living Standard - Edition for Web Developers

please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/states-of-the-type-attribute.html[4/16/2014 9:35:13 PM]

4.10.5.2 Common input element attributes HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
Common input element attributes
The maxlength and minlength attributes
The size attribute
The readonly attribute
The required attribute
The multiple attribute
The pattern attribute
The min and max attributes
The step attribute
The list attribute
The placeholder attribute
Common input element APIs

Common input element attributes

The maxlength and minlength attributes The maxlength attribute is a form control maxlength attribute. The minlength attribute is a form control minlength attribute. If the input element has a maximum allowed value length, then the
code-unit length of the value of the element's value attribute must be equal to or less than the element's
maximum allowed value length. The following extract shows how a messaging client's text entry could be arbitrarily
restricted to a fixed number of characters, thus forcing any conversation through this medium to
be terse and discouraging intelligent discourse.

http://developers.whatwg.org/common-input-element-attributes.html[4/16/2014 9:35:21 PM]

4.10.5.2 Common input element attributes HTML: The Living Standard - Edition for Web Developers

<label>What are you doing? <input name=status maxlength=140> </label> Here, a password is given a minimum length: <p><label>Username: <input name=u required></label> <p><label>Password: <input name=p required minlength=12> </label>

The size attribute The size attribute gives the number of


characters that, in a visual rendering, the user agent is to allow the user to see while editing
the element's value. The size attribute, if specified, must have a value that
is a valid non-negative integer greater than zero.

The readonly attribute The readonly attribute is a boolean


attribute that controls whether or not the user can edit the form control. The difference between disabled and readonly is that read-only controls are still focusable, so the
user can still select the text and interact with it, whereas disabled controls are entirely
non-interactive. (For this reason, only text controls can be made read-only: it wouldn't make
sense for checkboxes or buttons, for instances.) In the following example, the existing product identifiers cannot be modified, but they are
still displayed as part of the form, for consistency with the row representing a new product
(where the identifier is not yet filled in). <form action="products.cgi" method="post" enctype="multipart/form-data"> <table> <tr> <th> Product ID <th> Product name <th> Price <th> Action <tr> <td> <input readonly="readonly" name="1.pid" value="H412"> <td> <input required="required" name="1.pname"

http://developers.whatwg.org/common-input-element-attributes.html[4/16/2014 9:35:21 PM]

4.10.5.2 Common input element attributes HTML: The Living Standard - Edition for Web Developers

value="Floor lamp Ulke"> <td> $<input required="required" type="number" min="0" step="0.01" name="1.pprice" value="49.99"> <td> <button formnovalidate="formnovalidate" name="action" value="delete:1">Delete</button> <tr> <td> <input readonly="readonly" name="2.pid" value="FG28"> <td> <input required="required" name="2.pname" value="Table lamp Ulke"> <td> $<input required="required" type="number" min="0" step="0.01" name="2.pprice" value="24.99"> <td> <button formnovalidate="formnovalidate" name="action" value="delete:2">Delete</button> <tr> <td> <input required="required" name="3.pid" value="" pattern="[A-Z0-9]+"> <td> <input required="required" name="3.pname" value=""> <td> $<input required="required" type="number" min="0" step="0.01" name="3.pprice" value=""> <td> <button formnovalidate="formnovalidate" name="action" value="delete:3">Delete</button> </table> <p> <button formnovalidate="formnovalidate" name="action" value="add">Add</button> </p> <p> <button name="action" value="update">Save</button> </p> </form>

The required attribute The required attribute is a boolean


attribute. When specified, the element is required. The following form has two required fields, one for an e-mail address and one for a password.
It also has a third field that is only considered valid if the user types the same password in
the password field and this third field. <h1>Create new account</h1> <form action="/newaccount" method=post oninput="up2.setCustomValidity(up2.value != up.value ? 'Passwords do not match.' : '')">

http://developers.whatwg.org/common-input-element-attributes.html[4/16/2014 9:35:21 PM]

4.10.5.2 Common input element attributes HTML: The Living Standard - Edition for Web Developers

<p> <label for="username">E-mail address:</label> <input id="username" type=email required name=un> <p> <label for="password1">Password:</label> <input id="password1" type=password required name=up> <p> <label for="password2">Confirm password:</label> <input id="password2" type=password name=up2> <p> <input type=submit value="Create account"> </form> For radio buttons, the required attribute is
satisfied if any of the radio buttons in the group is
selected. Thus, in the following example, any of the radio buttons can be checked, not just the
one marked as required: <fieldset> <legend>Did the movie pass the Bechdel test?</legend> <p><label><input type="radio" name="bechdel" value="nocharacters"> No, there are not even two female characters in the movie. </label> <p><label><input type="radio" name="bechdel" value="nonames"> No, the female characters never talk to each other. </label> <p><label><input type="radio" name="bechdel" value="notopic"> No, when female characters talk to each other it's always about a male character. </label> <p><label><input type="radio" name="bechdel" value="yes" required> Yes. </label> <p><label><input type="radio" name="bechdel" value="unknown"> I don't know. </label> </fieldset> To avoid confusion as to whether a radio button group is required or not, authors
are encouraged to specify the attribute on all the radio buttons in a group. Indeed, in general,
authors are encouraged to avoid having radio button groups that do not have any initially checked
controls in the first place, as this is a state that the user cannot return to, and is therefore generally considered a poor user interface.

http://developers.whatwg.org/common-input-element-attributes.html[4/16/2014 9:35:21 PM]

4.10.5.2 Common input element attributes HTML: The Living Standard - Edition for Web Developers

The multiple attribute The multiple attribute is a boolean


attribute that indicates whether the user is to be allowed to specify more than one
value. The following extract shows how an e-mail client's "Cc" field could accept multiple e-mail
addresses. <label>Cc: <input type=email multiple name=cc></label> If the user had, amongst many friends in his user contacts database, two friends "Arthur Dent"
(with address "art@example.net") and "Adam Josh" (with address "adamjosh@example.net"), then,
after the user has typed "a", the user agent might suggest these two e-mail addresses to the
user.

The page could also link in the user's contacts database from the site: <label>Cc: <input type=email multiple name=cc list=contacts> </label> ... <datalist id="contacts"> <option value="hedral@damowmow.com"> <option value="pillar@example.com"> <option value="astrophy@cute.example"> <option value="astronomy@science.example.org"> </datalist> Suppose the user had entered "bob@example.net" into this text field, and then started typing a
second e-mail address starting with "a". The user agent might show both the two friends mentioned
earlier, as well as the "astrophy" and "astronomy" values given in the datalist
element.

http://developers.whatwg.org/common-input-element-attributes.html[4/16/2014 9:35:21 PM]

4.10.5.2 Common input element attributes HTML: The Living Standard - Edition for Web Developers

The following extract shows how an e-mail client's "Attachments" field could accept multiple
files for upload. <label>Attachments: <input type=file multiple name=att> </label>

The pattern attribute The pattern attribute specifies a regular


expression against which the control's value, or, when the
multiple attribute applies and is set, the control's values, are to be checked. If specified, the attribute's value must match the JavaScript Pattern production. When an input element has a pattern
attribute specified, authors should include a title attribute to
give a description of the pattern. User agents may use the contents of this attribute, if it is
present, when informing the user that the pattern is not matched, or at any other suitable time,
such as in a tooltip or read out by assistive technology when the control gains focus. For example, the following snippet: <label> Part number: <input pattern="[0-9][A-Z]{3}" name="part" title="A part number is a digit followed by three uppercase letters."/> </label> ...could cause the UA to display an alert such as: A part number is a digit followed by three uppercase letters.

http://developers.whatwg.org/common-input-element-attributes.html[4/16/2014 9:35:21 PM]

4.10.5.2 Common input element attributes HTML: The Living Standard - Edition for Web Developers

You cannot submit this form when the field is incorrect. When a control has a pattern attribute, the title attribute, if used, must describe the pattern. Additional
information could also be included, so long as it assists the user in filling in the control.
Otherwise, assistive technology would be impaired. For instance, if the title attribute contained the caption of the control, assistive technology could end up saying something like The text you have entered does not
match the required pattern. Birthday, which is not useful. UAs may still show the title in non-error situations (for
example, as a tooltip when hovering over the control), so authors should be careful not to word title s as if an error has necessarily occurred.

The min and max attributes Some form controls can have explicit constraints applied limiting the allowed range of values
that the user can provide. Normally, such a range would be linear and continuous. A form control
can have a periodic domain, however, in which case the
form control's broadest possible range is finite, and authors can specify explicit ranges within
it that span the boundaries. Specifically, the broadest range of a type=time control is midnight to midnight (24 hours), and
authors can set both continuous linear ranges (such as 9pm to 11pm) and discontinuous ranges
spanning midnight (such as 11pm to 1am). The min and max attributes indicate the allowed range of values for
the element. If the element does not have a periodic domain, the
max attribute's value (the maximum) must not be less than the min attribute's value (its minimum). An element has range limitations if it has a defined
minimum or a defined maximum. The following date control limits input to dates that are before the 1980s: <input name=bday type=date max="1979-12-31"> The following number control limits input to whole numbers greater than
http://developers.whatwg.org/common-input-element-attributes.html[4/16/2014 9:35:21 PM]

4.10.5.2 Common input element attributes HTML: The Living Standard - Edition for Web Developers

zero: <input name=quantity required="" type="number" min="1" value="1"> The following time control limits input to those minutes that occur between 9pm and 6am,
defaulting to midnight: <input name="sleepStart" type=time min="21:00" max="06:00" step="60" value="00:00">

The step attribute The step attribute indicates the granularity


that is expected (and required) of the value, by limiting
the allowed values. The step attribute, if specified, must either have a value
that is a valid floating-point number that parses to a number that is greater than zero, or must have a
value that is an ASCII case-insensitive match for the string "any". The following range control only accepts values in the range 0..1, and allows 256 steps in
that range: <input name=opacity type=range min=0 max=1 step=0.00392156863> The following control allows any time in the day to be selected, with any accuracy (e.g.
thousandth-of-a-second accuracy or more): <input name=favtime type=time step=any> Normally, time controls are limited to an accuracy of one minute.

The list attribute The list attribute is used to identify an


element that lists predefined options suggested to the user. If present, its value must be the ID of a datalist
element in the same document. This URL field offers some suggestions.
http://developers.whatwg.org/common-input-element-attributes.html[4/16/2014 9:35:21 PM]

4.10.5.2 Common input element attributes HTML: The Living Standard - Edition for Web Developers

<label>Homepage: <input name=hp type=url list=hpurls></label> <datalist id=hpurls> <option value="http://www.google.com/" label="Google"> <option value="http://www.reddit.com/" label="Reddit"> </datalist> Other URLs from the user's history might show also; this is up to the user agent. This example demonstrates how to design a form that uses the autocompletion list feature while
still degrading usefully in legacy user agents. If the autocompletion list is merely an aid, and is not important to the content, then simply
using a datalist element with children option elements is enough. To
prevent the values from being rendered in legacy user agents, they need to be placed inside the
value attribute instead of inline. <p> <label> Enter a breed: <input type="text" name="breed" list="breeds"> <datalist id="breeds"> <option value="Abyssinian"> <option value="Alpaca"> <!-- ... --> </datalist> </label> </p> However, if the values need to be shown in legacy UAs, then fallback content can be placed
inside the datalist element, as follows: <p> <label> Enter a breed: <input type="text" name="breed" list="breeds"> </label> <datalist id="breeds"> <label>

http://developers.whatwg.org/common-input-element-attributes.html[4/16/2014 9:35:21 PM]

4.10.5.2 Common input element attributes HTML: The Living Standard - Edition for Web Developers

or select one from the list: <select name="breed"> <option value=""> (none selected) <option>Abyssinian <option>Alpaca <!-- ... --> </select> </label> </datalist> </p> The fallback content will only be shown in UAs that don't support datalist. The
options, on the other hand, will be detected by all UAs, even though they are not children of the
datalist element. Note that if an option element used in a datalist is selected, it will be selected by default by legacy UAs
(because it affects the select), but it will not have any effect on the
input element in UAs that support datalist.

The placeholder attribute The placeholder attribute represents a


short hint (a word or short phrase) intended to aid the user with data entry when the
control has no value. A hint could be a sample value or a brief description of the expected
format. The attribute, if specified, must have a value that contains no U+000A LINE FEED (LF) or
U+000D CARRIAGE RETURN (CR) characters. The placeholder attribute should not be used as an
alternative to a label. For a longer hint or other advisory text, the title attribute is more appropriate. These mechanisms are very similar but subtly different: the hint given by the control's label is shown at all times; the short hint given in the placeholder attribute is shown before the user enters a
value; and the hint in the title attribute is shown when the user
requests further help. Here is an example of a mail configuration user interface that uses the placeholder attribute: <fieldset> <legend>Mail Account</legend>

http://developers.whatwg.org/common-input-element-attributes.html[4/16/2014 9:35:21 PM]

4.10.5.2 Common input element attributes HTML: The Living Standard - Edition for Web Developers

<p><label>Name: <input type="text" name="fullname" placeholder="John Ratzenberger"></label></p> <p><label>Address: <input type="email" name="address" placeholder="john@example.net"></label></p> <p><label>Password: <input type="password" name="password"> </label></p> <p><label>Description: <input type="text" name="desc" placeholder="My Email Account"></label></p> </fieldset> In situations where the control's content has one directionality but the placeholder needs to
have a different directionality, Unicode's bidirectionalalgorithm formatting characters can be
used in the attribute value: <input name=t1 type=tel placeholder="&#x202B;1&#x202E;"> <input name=t2 type=tel placeholder="&#x202B;2&#x202E;"> For slightly more clarity, here's the same example using numeric character references instead of inline Arabic: <input name=t1 type=tel placeholder="&#x202B;&#1585;&#1602;&#1605;&#1575;&#1604;&#16 07;&#1575;&#1578;&#1601;1&#x202E;"> <input name=t2 type=tel placeholder="&#x202B;&#1585;&#1602;&#1605;&#1575;&#1604;&#16 07;&#1575;&#1578;&#1601;2&#x202E;">

Common input element APIs


input . value [ = value ] Returns the current value of the form control. Can be set, to change the value. Throws an InvalidStateError exception if it is set to any value other than the
empty string when the control is a file upload control. input . checked [ = value ]

http://developers.whatwg.org/common-input-element-attributes.html[4/16/2014 9:35:21 PM]

4.10.5.2 Common input element attributes HTML: The Living Standard - Edition for Web Developers

Returns the current checkedness of the form


control. Can be set, to change the checkedness. input . files Returns a FileList object listing the selected files of the form control. Returns null if the control isn't a file control. input . valueAsDate [ = value ] Returns a Date object representing the form control's value, if applicable; otherwise, returns null. Can be set, to change the value. Throws an InvalidStateError exception if the control isn't date- or
timebased. input . valueAsNumber [ = value ] Returns a number representing the form control's value,
if applicable; otherwise, returns NaN. Can be set, to change the value. Setting this to NaN will set the underlying value to the
empty string. Throws an InvalidStateError exception if the control is neither date- or time-based nor numeric. input . stepUp( [ n ] ) input . stepDown( [ n ] ) Changes the form control's value by the value given in
the step attribute, multiplied by n.
The default value for n is 1. Throws InvalidStateError exception if the control is neither date- or timebased
nor numeric, or if the step attribute's value is "any ". input . list Returns the datalist element indicated by the list attribute.

Up next

4.10.6 The button element

http://developers.whatwg.org/common-input-element-attributes.html[4/16/2014 9:35:21 PM]

4.10.5.2 Common input element attributes HTML: The Living Standard - Edition for Web Developers

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/common-input-element-attributes.html[4/16/2014 9:35:21 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

WHATWG

HTML: The Living Standard


A technical specification for Web developers
Search. Press '/'

ON THIS PAGE
The video element
The audio element
The source element
The track element
Media elements
Error codes
Location of the media resource
MIME types
Network states
Loading the media resource
Offsets into the media resource
Ready states
Playing the media resource
Seeking
Media resources with multiple media tracks
AudioTrackList and VideoTrackList objects
Selecting specific audio and video tracks declaratively
Synchronising multiple media elements
Introduction
Media controllers
Assigning a media controller declaratively
Timed text tracks
Text track model
Sourcing in-band text tracks
Text track API
Text tracks describing chapters
User interface
Time ranges
Event definitions

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

Event summary
Best practices for authors using media elements

The video element


Categories: Flow content. Phrasing content. Embedded content. If the element has a controls attribute: Interactive content. Palpable content. Contexts in which this element can be used: Where embedded content is expected. Content model: If the element has a src attribute:
zero or more track elements, then transparent, but with no media element descendants. If the element does not have a src attribute: zero or more source elements, then
zero or more track elements, then
transparent, but with no media element descendants. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes src Address of the resource crossorigin How the element handles crossorigin requests poster Poster frame to show prior to video playback preload Hints how much buffering the media resource will likely need autoplay Hint that the media resource can be started automatically when the page is loaded mediagroup Groups media elements together with an implicit MediaController loop Whether to loop the media resource muted Whether to mute the media resource by default

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

controls Show user agent controls width Horizontal dimension height Vertical dimension DOM interface: A video element is used for playing videos or movies, and audio files with captions. Content may be provided inside the video element; it is intended for older Web browsers which do
not support video , so that legacy video plugins can be tried, or to show text to the
users of these older browsers informing them of how to access the video contents. In particular, this content is not intended to address accessibility concerns. To
make video content accessible to the partially sighted, the blind, the hardof-hearing, the deaf,
and those with other physical or cognitive disabilities, a variety of features are available.
Captions can be provided, either embedded in the video stream or as external files using the
track element. Signlanguage tracks can be provided, again either embedded in the
video stream or by synchronizing multiple video elements using the mediagroup attribute or a MediaController
object. Audio descriptions can be provided, either as a separate track embedded in the video
stream, or a separate audio track in an audio element slaved to the same controller as the video element(s), or in text
form using a WebVTT file referenced using the track element and
synthesized into speech by the user agent. WebVTT can also be used to provide chapter titles. For
users who would rather not use a media element at all, transcripts or other textual alternatives
can be provided by simply linking to them in the prose near the video element. The video element is a media element whose media data is
ostensibly video data, possibly with associated audio data. The src, preload,
autoplay, mediagroup, loop, muted , and controls attributes are the attributes common to all media
elements. The poster attribute gives the address of an
image file that the user agent can show while no video data is available. The attribute, if
present, must contain a valid non-empty URL potentially surrounded by spaces. The image given by the poster attribute,
the poster frame, is intended to be

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

a representative frame of the video (typically one of


the first non-blank frames) that gives the user an idea of what the video is like. video . videoWidth video . videoHeight These attributes return the intrinsic dimensions of the video,
or zero if the dimensions are not known. The video element supports dimension attributes. This example shows how to detect when a video has failed to play correctly: <script> function failed(e) { // video playback failed - show a message saying why switch (e.target.error.code) { case e.target.error.MEDIA_ERR_ABORTED: alert('You aborted the video playback.'); break; case e.target.error.MEDIA_ERR_NETWORK: alert('A network error caused the video download to fail part-way.'); break; case e.target.error.MEDIA_ERR_DECODE: alert('The video playback was aborted due to a corruption problem or because the video used features your browser did not support.'); break; case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED: alert('The video could not be loaded, either because the server or network failed or because the format is not supported.'); break; default: alert('An unknown error occurred.'); break; } } </script> <p><video src="tgif.vid" autoplay controls

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

onerror="failed(event)"></video></p> <p><a href="tgif.vid">Download the video file</a>.</p>

The audio element


Categories: Flow content. Phrasing content. Embedded content. If the element has a controls attribute: Interactive content. If the element has a controls attribute: Palpable content. Contexts in which this element can be used: Where embedded content is expected. Content model: If the element has a src attribute: zero or more track elements, then
transparent, but with no media element descendants. If the element does not have a src attribute: zero or more source elements, then
zero or more track elements, then
transparent, but with no media element descendants. Tag omission in text/html: Neither tag is omissible. Content attributes: Global attributes src Address of the resource crossorigin How the element handles crossorigin requests preload Hints how much buffering the media resource will likely need autoplay Hint that the media resource can be started automatically when the page is loaded mediagroup Groups media elements together with an implicit MediaController loop Whether to loop the media resource muted Whether to mute the media resource by default controls Show user agent controls

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

DOM interface: An audio element represents a sound or audio stream. Content may be provided inside the audio element; it is intended for older Web browsers which do
not support audio , so that legacy audio plugins can be tried, or to show text to the
users of these older browsers informing them of how to access the audio contents. In particular, this content is not intended to address accessibility concerns. To
make audio content accessible to the deaf or to those with other physical or cognitive
disabilities, a variety of features are available. If captions or a sign language video are
available, the video element can be used instead of the audio element to
play the audio, allowing users to enable the visual alternatives. Chapter titles can be provided
to aid navigation, using the track element and a WebVTT file. And,
naturally, transcripts or other textual alternatives can be provided by simply linking to them in
the prose near the audio element. [WEBVTT] The audio element is a media element whose media data is
ostensibly audio data. The src, preload,
autoplay, mediagroup, loop, muted , and controls attributes are the attributes common to all media
elements. audio = new Audio ( [ url ] ) Returns a new audio element, with the src
attribute set to the value passed in the argument, if applicable.

The source element


Categories: None. Contexts in which this element can be used: As a child of a media element, before any flow content
or track elements. Content model: Empty. Tag omission in text/html:

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

No end tag. Content attributes: Global attributes src Address of the resource type Type of embedded resource media Applicable media DOM interface: The source element allows authors to specify multiple alternative media resources for media
elements. It does not represent anything on its own. The src attribute gives the address of the
media resource. The value must be a valid non-empty URL potentially surrounded
by spaces. This attribute must be present. Dynamically modifying a source element and its attribute when the
element is already inserted in a video or audio element will have no
effect. To change what is playing, just use the src attribute
on the media element directly, possibly making use of the canPlayType() method to pick from amongst available
resources. Generally, manipulating source elements manually after the document has
been parsed is an unnecessarily complicated approach. The type attribute gives the type of the
media resource, to help the user agent determine if it can play this media
resource before fetching it. If specified, its value must be a valid MIME
type. The codecs parameter, which certain MIME types define, might be
necessary to specify exactly how the resource is encoded. The following list shows some examples of how to use the codecs= MIME parameter in the type attribute. H.264 Constrained baseline profile video (main and extended video compatible) level 3 and Low-Complexity AAC audio in MP4 container <source src='video.mp4' type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'> H.264 Extended profile video (baseline-compatible) level 3 and

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

Low-Complexity AAC audio in MP4 container <source src='video.mp4' type='video/mp4; codecs="avc1.58A01E, mp4a.40.2"'> H.264 Main profile video level 3 and Low-Complexity AAC audio in MP4 container <source src='video.mp4' type='video/mp4; codecs="avc1.4D401E, mp4a.40.2"'> H.264 'High' profile video (incompatible with main, baseline, or extended profiles) level 3 and Low-Complexity AAC audio in MP4 container <source src='video.mp4' type='video/mp4; codecs="avc1.64001E, mp4a.40.2"'> MPEG-4 Visual Simple Profile Level 0 video and Low-Complexity AAC audio in MP4 container <source src='video.mp4' type='video/mp4; codecs="mp4v.20.8, mp4a.40.2"'> MPEG-4 Advanced Simple Profile Level 0 video and LowComplexity AAC audio in MP4 container <source src='video.mp4' type='video/mp4; codecs="mp4v.20.240, mp4a.40.2"'> MPEG-4 Visual Simple Profile Level 0 video and AMR audio in 3GPP container <source src='video.3gp' type='video/3gpp; codecs="mp4v.20.8, samr"'> Theora video and Vorbis audio in Ogg container <source src='video.ogv' type='video/ogg; codecs="theora, vorbis"'> Theora video and Speex audio in Ogg container

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

<source src='video.ogv' type='video/ogg; codecs="theora, speex"'> Vorbis audio alone in Ogg container <source src='audio.ogg' type='audio/ogg; codecs=vorbis'> Speex audio alone in Ogg container <source src='audio.spx' type='audio/ogg; codecs=speex'> FLAC audio alone in Ogg container <source src='audio.oga' type='audio/ogg; codecs=flac'> Dirac video and Vorbis audio in Ogg container <source src='video.ogv' type='video/ogg; codecs="dirac, vorbis"'> The media attribute gives the intended media
type of the media resource, to help the user agent determine if this media
resource is useful to the user before fetching it. Its value must be a valid media
query. The resource
selection algorithm is defined in such a way that when the media attribute is omitted the user agent acts the same as if the
value was " all", i.e. by default the media resource is suitable
for all media. If the author isn't sure if user agents will all be able to render the media resources
provided, the author can listen to the error event on the last source element and trigger fallback behavior: <script> function fallback(video) { // replace <video> with its contents while (video.hasChildNodes()) { if (video.firstChild instanceof HTMLSourceElement) video.removeChild(video.firstChild); else video.parentNode.insertBefore(video.firstChild, video); } video.parentNode.removeChild(video);
http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

} </script> <video controls autoplay> <source src='video.mp4' type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'> <source src='video.ogv' type='video/ogg; codecs="theora, vorbis"' onerror="fallback(parentNode)"> ... </video>

The track element


Categories: None. Contexts in which this element can be used: As a child of a media element, before any flow content. Content model: Empty. Tag omission in text/html: No end tag. Content attributes: Global attributes kind The type of text track src Address of the resource srclang Language of the text track label User-visible label default Enable the track if no other text track is more suitable DOM interface: The track element allows authors to specify explicit external timed text tracks for media elements. It
does not represent anything on its own. The kind attribute is an enumerated
attribute. The following table lists the keywords defined for this attribute. The keyword
given in the first cell of each

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

row maps to the state given in the second cell. Keyword subtitles State Subtitles Brief description
Transcription or translation of the dialogue, suitable for when the sound is available but not understood (e.g. because the user does not understand the language of the media resource's audio track).
Overlaid on the video. captions Captions
Transcription or translation of the dialogue, sound effects, relevant musical cues, and other relevant audio information, suitable for when sound is unavailable or not clearly audible (e.g. because it is muted, drowned-out by ambient noise, or because the user is deaf).
Overlaid on the video; labeled as appropriate for the hard-of-hearing. descriptions Descriptions
Textual descriptions of the video component of the media resource, intended for audio synthesis when the visual component is obscured, unavailable, or not usable (e.g. because the user is interacting with the application without a screen while driving, or because the user is blind). Synthesized as audio. chapters Chapters
Chapter titles, intended to be used for navigating the media resource. Displayed as an interactive (potentially nested) list in the user agent's interface. metadata Metadata
Tracks intended for use from script.
Not displayed by the user agent. The attribute may be omitted. The missing value default is the subtitles state. The src attribute gives the address of the text
track data. The value must be a valid non-empty URL potentially surrounded by spaces.
This attribute must be present.

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

If the element's track URL identifies a WebVTT resource, and the


element's kind attribute is not in the metadata state, then the WebVTT file must be
a WebVTT file using cue text. [WEBVTT] Furthermore, if the element's track URL identifies a WebVTT resource,
and the element's kind attribute is in the chapters state, then the WebVTT file must be
both a WebVTT file using chapter title text and a WebVTT file using only nested
cues. [WEBVTT] The srclang attribute gives the language of
the text track data. The value must be a valid BCP 47 language tag. This attribute must be present
if the element's kind attribute is in the subtitles state. The label attribute gives a user-readable
title for the track. This title is used by user agents when listing subtitle, caption, and audio description tracks in their user interface. The value of the label attribute, if the attribute is
present, must not be the empty string. Furthermore, there must not be two track
element children of the same media element whose kind attributes are in the same state, whose srclang attributes are both missing or have values that
represent the same language, and whose label attributes are
again both missing or both have the same value. The default attribute is a boolean
attribute, which, if specified, indicates that the track is to be enabled if the user's
preferences do not indicate that another track would be more appropriate. Each media element must have no more than one track element child
whose kind attribute is in the subtitles or captions state and whose default attribute is specified. Each media element must have no more than one track element child
whose kind attribute is in the description state and whose default attribute is specified. Each media element must have no more than one track element child
whose kind attribute is in the chapters state and whose default attribute is specified. There is no limit on the number of track elements whose kind attribute is in the metadata state and whose default attribute is specified.

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

track . readyState Returns the text track readiness state,


represented by a number from the following list: track . NONE (0) The text track not loaded state. track . LOADING (1) The text track loading state. track . LOADED (2) The text track loaded state. track . ERROR (3) The text track failed to load state. track . track Returns the TextTrack object corresponding to the text track of the track element. This video has subtitles in several languages: <video src="brave.webm"> <track kind=subtitles src=brave.en.vtt srclang=en label="English"> <track kind=captions src=brave.en.hoh.vtt srclang=en label="English for the Hard of Hearing"> <track kind=subtitles src=brave.fr.vtt srclang=fr lang=fr label="Franais"> <track kind=subtitles src=brave.de.vtt srclang=de lang=de label="Deutsch"> </video> (The lang attributes on the last two describe the language of
the label attribute, not the language of the subtitles
themselves. The language of the subtitles is given by the srclang attribute.)

Media elements
Media elements (audio and video , in
this specification) implement the following interface:
http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

The media element attributes, src, crossorigin, preload, autoplay, mediagroup , loop,
muted , and controls, apply to all media
elements. They are defined in this section. Media elements are used to present audio data, or video and
audio data, to the user. This is referred to as media data in this section, since this
section applies equally to media elements for audio or for
video.
The term media resource is used to refer to the complete set of media data, e.g. the
complete video file, or complete audio file. A media resource can have multiple audio and video tracks. For the purposes of a
media element, the video data of the media resource is only that of the currently selected track (if any) given by the element's videoTracks attribute, and the audio data of the media
resource is the result of mixing all the currently enabled tracks (if any) given by the
element's audioTracks attribute. Both audio and video elements can be used for both audio
and video. The main difference between the two is simply that the audio element has
no playback area for visual content (such as video or captions), whereas the video
element does.

Error codes
media . error Returns a MediaError object representing the current error state of the element. Returns null if there is no error. media . error . code Returns the current error's error code, from the list below. MEDIA_ERR_ABORTED (numeric value 1) The fetching process for the media resource was aborted by the user agent at the
user's request. MEDIA_ERR_NETWORK (numeric value 2) A network error of some description caused the user agent to stop fetching the

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

media
resource, after the resource was established to be usable. MEDIA_ERR_DECODE (numeric value 3) An error of some description occurred while decoding the media resource, after
the resource was established to be usable. MEDIA_ERR_SRC_NOT_SUPPORTED (numeric value 4) The media resource indicated by the src
attribute was not suitable.

Location of the media resource


The src content attribute on media elements gives the address of the media resource (video, audio) to show. The
attribute, if present, must contain a valid non-empty URL potentially surrounded by
spaces. If the itemprop attribute is specified on the media
element, then the src attribute must also be
specified. The crossorigin content attribute on
media elements is a CORS settings attribute. media . currentSrc Returns the address of the current media resource. Returns the empty string when there is no media resource. There are two ways to specify a media resource, the src attribute, or source elements. The attribute
overrides the elements.

MIME types
A media resource can be described in terms of its type, specifically a
MIME type, in some cases with a codecs parameter. (Whether the
codecs parameter is allowed or not depends on the MIME type.) [RFC4281] Types are usually somewhat incomplete descriptions; for example " video/mpeg " doesn't say anything except what the container type is, and even a
type like " video/mp4; codecs="avc1.42E01E, mp4a.40.2"" doesn't include information like the actual bitrate (only the maximum bitrate). Thus, given a type, a user
agent can often only know whether it might be able to play

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

media of that type (with


varying levels of confidence), or whether it definitely cannot play media of that
type. A type that the user agent knows it cannot render is one that describes a resource
that the user agent definitely does not support, for example because it doesn't recognize the
container type, or it doesn't support the listed codecs. The MIME type "application/octet-stream" with no parameters is never
a type that the user agent knows it cannot render. User agents must treat that type
as equivalent to the lack of any explicit Content-Type metadata
when it is used to label a potential media resource. Only the MIME type "application/octet-stream" with no
parameters is special-cased here; if any parameter appears with it, it will be treated just like
any other MIME type. This is a deviation from the rule that unknown MIME type parameters should be ignored. media . canPlayType (type) Returns the empty string (a negative response), "maybe", or "probably" based on how confident
the user agent is that it can play media resources of the given type. This script tests to see if the user agent supports a (fictional) new format to dynamically
decide whether to use a video element or a plugin: <section id="video"> <p><a href="playing-cats.nfv">Download video</a></p> </section> <script> var videoSection = document.getElementById('video'); var videoElement = document.createElement('video'); var support = videoElement.canPlayType('video/x-newfictional-format;codecs="kittens,bunnies"'); if (support != "probably" && "New Fictional Video Plugin" in navigator.plugins) { // not confident of browser support // but we have a plugin // so use plugin instead videoElement = document.createElement("embed"); } else if (support == "") { // no support from browser and no plugin

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

// do nothing videoElement = null; } if (videoElement) { while (videoSection.hasChildNodes()) videoSection.removeChild(videoSection.firstChild); videoElement.setAttribute("src", "playing-cats.nfv"); videoSection.appendChild(videoElement); } </script> The type attribute of the
source element allows the user agent to avoid downloading resources that use formats
it cannot render.

Network states
media . networkState Returns the current state of network activity for the element, from the codes in the list
below. NETWORK_EMPTY (numeric value 0) The element has not yet been initialized. All attributes are in their initial states. NETWORK_IDLE (numeric value 1) The element has selected a resource, but it is not actually using the network at this time. NETWORK_LOADING (numeric value 2) The user agent is actively trying to download data. NETWORK_NO_SOURCE (numeric value 3) The element has not yet found a resource to use.

Loading the media resource


media . load() Causes the element to reset and start selecting and loading a new media resource
from scratch.

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

The preload attribute is an enumerated


attribute. The following table lists the keywords and states for the attribute the
keywords in the left column map to the states in the cell in the second column on the same row as
the keyword. The attribute can be changed even once the media resource is being
buffered or played; the descriptions in the table below are to be interpreted with that in
mind. Keyword none State None Brief description Hints to the user agent that either the author does not expect the user to need the media resource, or that the server wants to minimize unnecessary traffic.
This state does not provide a hint regarding how aggressively to actually download the media resource if buffering starts anyway (e.g. once the user hits "play"). metadata Metadata Hints to the user agent that the author does not expect the user to need the media resource, but that fetching the resource metadata (dimensions, track list, duration, etc), and maybe even the first few frames, is reasonable. If the user agent precisely fetches no more than the metadata, then the media element will end up with its readyState attribute set to HAVE_METADATA ; typically though, some frames will be obtained as well and it will probably be HAVE_CURRENT_DATA or HAVE_FUTURE_DATA . When the media resource is playing, hints to the user agent that bandwidth is to be considered scarce, e.g. suggesting throttling the download so that the media data is obtained at the slowest possible rate that still maintains consistent playback. auto Automatic Hints to the user agent that the user agent can put the user's needs first without risk to the server, up to and including optimistically downloading the entire resource. The empty string is also a valid keyword, and maps to the Automatic state. The attribute's missing value
default is user-agent defined, though the Metadata
http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

state is suggested as a compromise


between reducing server load and providing an optimal user experience. Authors might switch the attribute from "none" or "metadata" to "auto" dynamically once the user begins playback. For
example, on a page with many videos this might be used to indicate that the many videos are not to
be downloaded unless requested, but that once one is requested it is to be downloaded
aggressively. The autoplay attribute can override the
preload attribute (since if the media plays, it naturally
has to buffer first, regardless of the hint given by the preload attribute). Including both is not an error, however.

media . buffered Returns a TimeRanges object that represents the ranges of the media
resource that the user agent has buffered.

Offsets into the media resource


media . duration Returns the length of the media resource, in seconds, assuming that the start of
the media resource is at time zero. Returns NaN if the duration isn't available. Returns Infinity for unbounded streams. media . currentTime [ = value ] Returns the official playback position, in seconds. Can be set, to seek to the given time. Will throw an InvalidStateError exception if there is no selected media resource or if there is a current media controller. The loop attribute is a boolean
attribute that, if specified, indicates that the media element is to seek back
to the start of the media resource upon reaching the end. The loop attribute has no effect while the element has a
current media

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

controller.

Ready states
media . readyState Returns a value that expresses the current state of the element with respect to rendering the
current playback position, from the codes in the list below. HAVE_NOTHING (numeric value 0) No information regarding the media resource is available. No data for the current playback position is available. Media
elements whose networkState attribute are set
to NETWORK_EMPTY are always in the HAVE_NOTHING state. HAVE_METADATA (numeric value 1) Enough of the resource has been obtained that the duration of the resource is available.
In the case of a video element, the dimensions of the video are also available. The
API will no longer throw an exception when seeking. No media data is available for
the immediate current playback position. HAVE_CURRENT_DATA (numeric value 2) Data for the immediate current playback position is available, but either not enough data is available that the user agent could successfully advance the current
playback position in the direction of playback at all without immediately
reverting to the HAVE_METADATA state, or there is no
more data to obtain in the direction of playback. For example, in video this
corresponds to the user agent having data from the current frame, but not the next frame, when
the current playback position is at the end of the current frame; and to when playback has ended. HAVE_FUTURE_DATA (numeric value 3) Data for the immediate current playback position is available, as well as enough data for the user agent to advance the current playback position in the
direction of playback at least a little without immediately reverting to the HAVE_METADATA state, and the text tracks are
ready. For example, in video this corresponds to the user agent having data for at least
the current frame and the next frame when the current playback position is at the
instant in time between the two frames, or to the user agent having the video data for the current frame and audio data to keep playing at least a little when the current playback
position is in the middle of a frame. The user agent cannot be in this

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

state if playback has ended, as the current playback position


can never advance in this case. HAVE_ENOUGH_DATA (numeric value 4) All the conditions described for the HAVE_FUTURE_DATA state are met, and, in addition,
either of the following conditions is also true:

The user agent estimates that data is being fetched at a rate where the current
playback position, if it were to advance at the effective playback rate,
would not overtake the available data before playback reaches the end of the media resource.

The user agent has entered a state where waiting longer will not result in
further data
being obtained, and therefore nothing would be gained by delaying playback any further. (For
example, the buffer might be full.) In practice, the difference between HAVE_METADATA and HAVE_CURRENT_DATA is negligible. Really the only time
the difference is relevant is when painting a video element onto a
canvas , where it distinguishes the case where something will be drawn (HAVE_CURRENT_DATA or greater) from the case where
nothing is drawn (HAVE_METADATA or less). Similarly,
the difference between HAVE_CURRENT_DATA (only
the current frame) and HAVE_FUTURE_DATA (at least
this frame and the next) can be negligible (in the extreme, only one frame). The only time that
distinction really matters is when a page provides an interface for "frame-by-frame"
navigation. It is possible for the ready state of a media element to jump between these states
discontinuously. For example, the state of a media element can jump straight from HAVE_METADATA to HAVE_ENOUGH_DATA without passing through the HAVE_CURRENT_DATA and HAVE_FUTURE_DATA states. The autoplay attribute is a boolean
attribute. When present, the user agent will automatically begin playback of the media resource as
soon as it can do so without stopping. Authors are urged to use the autoplay
attribute rather than using script to trigger automatic playback, as this allows the user to
override the automatic playback when it is not desired, e.g. when using a screen reader. Authors
are also encouraged to consider not using the automatic playback behavior at all, and instead to
let the user agent wait for the user to start playback explicitly.

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

Playing the media resource


media . paused Returns true if playback is paused; false otherwise. media . ended Returns true if playback has reached the end of the media resource. media . defaultPlaybackRate [ = value ] Returns the default rate of playback, for when the user is not fast-forwarding or reversing
through the media resource. Can be set, to change the default rate of playback. The default rate has no direct effect on playback, but if the user switches to a fast-forward
mode, when they return to the normal playback mode, it is expected that the rate of playback
will be returned to the default rate of playback. When the element has a current media controller, the defaultPlaybackRate attribute is ignored and the
current media controller's defaultPlaybackRate is used instead. media . playbackRate [ = value ] Returns the current rate playback, where 1.0 is normal speed. Can be set, to change the rate of playback. When the element has a current media controller, the playbackRate attribute is ignored and the current
media controller's playbackRate is
used instead. media . played Returns a TimeRanges object that represents the ranges of the media
resource that the user agent has played. media . play() Sets the paused attribute to false, loading the
media resource and beginning playback if necessary. If the playback had ended, will
restart it from the start. media . pause () Sets the paused attribute to true, loading the
media resource if necessary.

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

Seeking
media . seeking Returns true if the user agent is currently seeking. media . seekable Returns a TimeRanges object that represents the ranges of the media
resource to which it is possible for the user agent to seek. media . fastSeek( time ) Seeks to near the given time as fast as possible, trading precision for
speed. (To seek to a precise time, use the currentTime attribute.) This does nothing if the media resource has not been loaded.

Media resources with multiple media tracks


A media resource can have multiple embedded audio and video tracks. For example,
in addition to the primary video and audio tracks, a media resource could have
foreign-language dubbed dialogues, director's commentaries, audio descriptions, alternative
angles, or sign-language overlays. media . audioTracks Returns an AudioTrackList object representing the audio tracks available in the
media resource. media . videoTracks Returns a VideoTrackList object representing the video tracks available in the
media resource. In this example, a script defines a function that takes a URL to a video and a reference to an
element where the video is to be placed. That function then tries to load the video, and, once it
is loaded, checks to see if there is a signlanguage track available. If there is, it also
displays that track. Both tracks are just placed in the given container; it's assumed that styles
have been applied to make this work in a pretty way! <script> function loadVideo(url, container) { var controller = new MediaController();

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

var video = document.createElement('video'); video.src = url; video.autoplay = true; video.controls = true; video.controller = controller; container.appendChild(video); video.onloadedmetadata = function (event) { for (var i = 0; i < video.videoTracks.length; i += 1) { if (video.videoTracks[i].kind == 'sign') { var sign = document.createElement('video'); sign.src = url + '#track=' + video.videoTracks[i].id; sign.autoplay = true; sign.controller = controller; container.appendChild(sign); return; } } }; } </script>

AudioTrackList and VideoTrackList objects The AudioTrackList and VideoTrackList interfaces are used by
attributes defined in the previous section. media . audioTracks . length media . videoTracks . length Returns the number of tracks in the list. audioTrack = media . audioTracks [index] videoTrack = media . videoTracks[index] Returns the specified AudioTrack or VideoTrack object. audioTrack = media . audioTracks . getTrackById( id ) videoTrack = media . videoTracks . getTrackById( id ) Returns the AudioTrack or VideoTrack object with the given identifier, or null if no track has that identifier.

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

audioTrack . id videoTrack . id Returns the ID of the given track. This is the ID that can be used with a fragment identifier
if the format supports the Media Fragments URI syntax, and that can be used with
the getTrackById() method. audioTrack . kind videoTrack . kind Returns the category the given track falls into. The possible track categories are given below. audioTrack . label videoTrack . label Returns the label of the given track, if known, or the empty string otherwise. audioTrack . language videoTrack . language Returns the language of the given track, if known, or the empty string otherwise. audioTrack . enabled [ = value ] Returns true if the given track is active, and false otherwise. Can be set, to change whether the track is enabled or not. If multiple audio tracks are
enabled simultaneously, they are mixed. media . videoTracks . selectedIndex Returns the index of the currently selected track, if any, or 1 otherwise. videoTrack . selected [ = value ] Returns true if the given track is active, and false otherwise. Can be set, to change whether the track is selected or not. Either zero or one video track is
selected; selecting a new track while a previous one is selected will unselect the previous
one. Return values for AudioTrack.kind() and VideoTrack.kind() Category Definition Applies Examples to... "alternative" A possible alternative to the main track, e.g. a Audio and video. Ogg: "audio/alternate" or "video/alternate";

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

different take of a song (audio), or a different angle (video).

DASH: "alternate" without "main" and "commentary" roles, and, for audio, without the "dub" role (other roles ignored).

"captions"

A version of the main video track with captions burnt in. (For legacy content; new content would use text tracks.)

Video only.

DASH: "caption" and "main" roles together (other roles ignored).

"descriptions"

An audio description of a video track.

Audio only.

Ogg: "audio/audiodesc".

"main"

The primary audio or video track.

Audio and video.

Ogg: "audio/main" or "video/main"; WebM: the "FlagDefault" element is set; DASH: "main" role without "caption", "subtitle", and "dub" roles (other roles ignored).

"main-desc "

The primary audio track, mixed with audio descriptions.

Audio only.

AC3 audio in MPEG-2 TS: bsmod=2 and full_svc=1.

"sign"

A sign-language interpretation of an audio track.

Video only.

Ogg: "video/sign".

"subtitles "

A version of the main video track with subtitles burnt in. (For

Video only.

DASH: "subtitle" and "main" roles together (other roles ignored).

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

legacy content; new content would use text tracks.) "translation" A translated version of the main audio track. "commentary " Audio only. Ogg: "audio/dub". DASH: "dub" and "main" roles together (other roles ignored). Commentary on the primary audio or video track, e.g. a director's commentary. "" (empty string) No explicit kind, or the kind given by the track's metadata is not recognised by the user agent. Audio and video. Any other track type, track role, or combination of track roles not described above. Audio and video. DASH: "commentary" role without "main" role (other roles ignored).

Selecting specific audio and video tracks declaratively The audioTracks and videoTracks attributes allow scripts to select which track
should play, but it is also possible to select specific tracks declaratively, by specifying
particular tracks in the fragment identifier of the URL of the media
resource. The format of the fragment identifier depends on the MIME type of
the media resource. In this example, a video that uses a format that supports the Media Fragments URI
fragment identifier syntax is embedded in such a way that the alternative angles labeled
"Alternative" are enabled instead of the default video track. [MEDIAFRAG] <video src="myvideo#track=Alternative"></video>

Synchronising multiple media elements

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

Introduction Each media element can have a MediaController. A


MediaController is an object that coordinates the playback of multiple media elements, for instance so that a sign-language interpreter
track can be overlaid on a video track, with the two being kept in sync. By default, a media element has no MediaController. An implicit MediaController can be assigned using the mediagroup content attribute. An explicit
MediaController can be assigned directly using the controller IDL attribute. Media elements with a MediaController are said
to be slaved to their controller. The MediaController modifies the playback
rate and the playback volume of each of the media elements
slaved to it, and ensures that when any of its slaved media
elements unexpectedly stall, the others are stopped at the same time. When a media element is slaved to a MediaController, its playback
rate is fixed to that of the other tracks in the same MediaController, and any looping is disabled.

Media controllers controller = new MediaController() Returns a new MediaController object. media . controller [ = controller ] Returns the current MediaController for the media element, if any;
returns null otherwise. Can be set, to set an explicit MediaController. Doing so removes the mediagroup attribute, if any. controller . readyState Returns the state that the MediaController was in the last time it fired events
as a result of reporting the controller state.
The values of this attribute are the same as for the readyState attribute of media
elements. controller . buffered Returns a TimeRanges object that represents the intersection of the time

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

ranges
for which the user agent has all relevant media data for all the slaved media elements. controller . seekable Returns a TimeRanges object that represents the intersection of the time ranges
into which the user agent can seek for all the slaved media
elements. controller . duration Returns the difference between the earliest playable moment and the latest playable moment
(not considering whether the data in question is actually buffered or directly seekable, but not
including time in the future for infinite streams). Will return zero if there is no media. controller . currentTime [ = value ] Returns the current playback position, in seconds, as a position between zero time and the current duration. Can be set, to seek to the given time. controller . paused Returns true if playback is paused; false otherwise. When this attribute is true, any
media element slaved to this controller will be stopped. controller . playbackState Returns the state that the MediaController was in the last time it fired events
as a result of reporting the controller state.
The value of this attribute is either "playing", indicating that the media is actively
playing, "ended", indicating that the media is
not playing because playback has reached the end of all the slaved media elements,
or "waiting", indicating that the media is not
playing for some other reason (e.g. the MediaController is paused). controller . pause () Sets the paused attribute to true. controller . unpause () Sets the paused attribute to false. controller . play() Sets the paused attribute to false and
invokes the play() method of each slaved media element. controller . played Returns a TimeRanges object that represents the union of the time ranges in

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

all
the slaved media elements that have been played. controller . defaultPlaybackRate [ = value ] Returns the default rate of playback. Can be set, to change the default rate of playback. This default rate has no direct effect on playback, but if the user switches to a fast-forward mode, when they return to the normal playback mode, it is expected that rate of
playback (playbackRate) will be returned
to this default rate. controller . playbackRate [ = value ] Returns the current rate of playback. Can be set, to change the rate of playback. controller . volume [ = value ] Returns the current playback volume multiplier, as a number in the range 0.0 to 1.0, where
0.0 is the quietest and 1.0 the loudest. Can be set, to change the volume multiplier. Throws an IndexSizeError exception if the new value is not in the range 0.0 .. 1.0. controller . muted [ = value ] Returns true if all audio is muted (regardless of other attributes either on the controller
or on any media elements slaved to this controller), and
false otherwise. Can be set, to change whether the audio is muted or not.

Assigning a media controller declaratively The mediagroup content attribute on media elements can be used to link multiple media elements together by implicitly creating a MediaController. The
value is text; media elements with the same value are
automatically linked by the user agent. Multiple media elements referencing the same media
resource will share a single network request. This can be used to efficiently play two
(video) tracks from the same media resource in two different places on the screen. Used with the mediagroup attribute, these elements can
also be kept
http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

synchronised. In this example, a sign-languge interpreter track from a movie file is overlaid on the primary
video track of that same video file using two video elements, some CSS, and an
implicit MediaController: <article> <style scoped> div { margin: 1em auto; position: relative; width: 400px; height: 300px; } video { position; absolute; bottom: 0; right: 0; } video:first-child { width: 100%; height: 100%; } video:last-child { width: 30%; } </style> <div> <video src="movie.vid#track=Video&amp;track=English" autoplay controls mediagroup=movie></video> <video src="movie.vid#track=sign" autoplay mediagroup=movie></video> </div> </article>

Timed text tracks

Text track model A media element can have a group of associated text
tracks, known as the media element's list of text tracks. The text tracks are sorted as follows: 1. The text tracks corresponding to track element
children of the media element, in tree order. 2. Any text tracks added using the addTextTrack() method, in the order they were added, oldest
first. 3. Any media-resource-specific text
tracks (text tracks corresponding to data in the
media resource), in the order defined by the media resource's format specification. A text track consists of:

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

The kind of text track This decides how the track is handled by the user agent. The kind is represented by a string.
The possible strings are:

subtitles captions descriptions chapters metadata


The kind of track can change dynamically, in the case of
a text track corresponding to a track element. A label This is a human-readable string intended to identify the track for the user. The label of a track can change dynamically, in the
case of a text track corresponding to a track element. When a text track label is the empty string, the user agent should automatically
generate an appropriate label from the text track's other properties (e.g. the kind of text
track and the text track's language) for use in its user interface. This automatically-generated
label is not exposed in the API. An in-band metadata track dispatch type This is a string extracted from the media resource specifically for in-band metadata tracks to enable such tracks to be dispatched to different scripts in the document. For example, a traditional TV station broadcast streamed on the Web and augmented with Web-specific interactive features could include text tracks with metadata for ad
targeting, trivia game data during game shows, player states during sports games, recipe
information during food programs, and so forth. As each program starts and ends, new tracks
might be added or removed from the stream, and as each one is added, the user agent could bind
them to dedicated script modules using the value of this attribute. Other than for in-band metadata text tracks, the in-band metadata track dispatch type is the empty string. How this
value is populated for different media formats is described in steps to expose a
media-resource-specific text track.

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

A language This is a string (a BCP 47 language tag) representing the language of the text track's cues.
[BCP47] The language of a text track can change dynamically,
in the case of a text track corresponding to a track element. A readiness state One of the following: Not loaded Indicates that the text track's cues have not been obtained. Loading Indicates that the text track is loading and there have been no fatal errors encountered so
far. Further cues might still be added to the track by the parser. Loaded Indicates that the text track has been loaded with no fatal errors. Failed to load Indicates that the text track was enabled, but when the user agent attempted to obtain it,
this failed in some way (e.g. URL could not be resolved, network error, unknown text track format). Some or all of the cues are
likely missing and will not be obtained. The readiness state of a text
track changes dynamically as the track is obtained. A mode One of the following: Disabled Indicates that the text track is not active. Other than for the purposes of exposing the
track in the DOM, the user agent is ignoring the text track. No cues are active, no events are
fired, and the user agent will not attempt to obtain the track's cues. Hidden Indicates that the text track is active, but that the user agent is not actively displaying
the cues. If no attempt has yet been made to obtain the track's cues, the user agent will
perform such an attempt momentarily. The user agent is maintaining a list of which cues are
active, and events are being fired
http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

accordingly. Showing Indicates that the text track is active. If no attempt has yet been made to obtain the
track's cues, the user agent will perform such an attempt momentarily. The user agent is
maintaining a list of which cues are active, and events are being fired accordingly. In
addition, for text tracks whose kind is subtitles or captions, the cues are being overlaid on the video
as appropriate; for text tracks whose kind is descriptions, the user agent is making the
cues available to the user in a non-visual fashion; and for text tracks whose kind is chapters, the user agent is making available to
the user a mechanism by which the user can navigate to any point in the media resource by selecting a cue. A list of zero or more cues A list of text track cues, along with rules for
updating the text track rendering. For example, for WebVTT, the rules
for updating the display of WebVTT text tracks. [WEBVTT] The list of cues of a text track can change
dynamically, either because the text track has not yet been loaded or is still loading,
or due to DOM manipulation. Each text track has a corresponding TextTrack object. Each media element has a list of pending text tracks, which must
initially be empty, a blocked-on-parser flag, which must initially be false, and a
didperform-automatic-track-selection flag, which must also initially be false. When the user agent is required to populate the list of pending text tracks of a
media element, the user agent must add to the element's list of pending text tracks each text track in the element's list of text tracks whose
text track mode is not disabled and whose
text track readiness state is loading. Whenever a track element's parent node changes, the user agent must remove the
corresponding text track from any list of pending text tracks that it is
in. Whenever a text track's text track readiness state changes to either
loaded or failed to
load, the user agent must remove it from any list of pending text tracks that
it is in. When a media element is created by an HTML parser or XML
parser, the user agent must set the element's blocked-on-parser flag to true.
When a media

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

element is popped off the stack of open elements of an


HTML parser or XML parser, the user agent must honor user
preferences for automatic text track selection, populate the list of pending text
tracks, and set the element's blocked-on-parser flag to false. The text tracks of a media element are ready when both the element's list of pending text
tracks is empty and the element's blocked-on-parser flag is false. Each media element has a pending text track change notification flag,
which must initially be unset. Whenever a text track that is in a media element's list of text
tracks has its text track mode change value, the user agent must run the
following steps for the media element: 1. If the media element's pending text track change notification
flag is set, abort these steps. 2. Set the media element's pending text track change notification
flag. 3. Queue a task that runs the following substeps: 1. Unset the media element's pending text track change notification
flag. 2. Fire a simple event named change at
the media element's textTracks attribute's TextTrackList object. 4. If the media element's show poster flag is not set, run the
time marches on steps. The task source for the tasks listed in this
section is the DOM manipulation task source. A text track cue is the unit of time-sensitive data in a text track,
corresponding for instance for subtitles and captions to the text that appears at a particular time and disappears at another time. Each text track cue consists of: An identifier An arbitrary string. A start time The time, in seconds and fractions of a second, that describes the beginning of the range of
the media data to which the cue applies.

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

An end time The time, in seconds and fractions of a second, that describes the end of the range of the
media data to which the cue applies. A pause-on-exit flag A boolean indicating whether playback of the media resource is to pause when the
end of the range to which the cue applies is reached. Some additional format-specific data Additional fields, as needed for the format. For example, WebVTT has a text track cue
writing direction and so forth. [WEBVTT] The data of the cue The raw data of the cue, and rules for rendering the cue in isolation. The precise nature of this data is defined by the format. For example, WebVTT uses text.

The text track cue start time and text track cue end
time can be negative. (The current playback position can never be negative,
though, so cues entirely before time zero cannot be active.) Each text track cue has a corresponding TextTrackCue object (or more specifically, an object that inherits from TextTrackCue for example, WebVTT
cues use the VTTCue interface). A text track cue's in-memory representation can be dynamically changed through this TextTrackCue API. [WEBVTT] A text track cue is associated with rules for updating the text track
rendering, as defined by the specification for the specific kind of text track
cue. These rules are used specifically when the object representing the cue is added to a TextTrack object using the addCue()
method. In addition, each text track cue has two pieces of dynamic information: The active flag This flag must be initially unset. The flag is used to ensure events are fired appropriately
when the cue becomes active or inactive, and to make sure the right cues are rendered. The user agent must synchronously unset this flag whenever the text track cue is
removed from its text track's text track list of cues; whenever the
text track

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

itself is removed from its media element's list of


text tracks or has its text track mode changed to disabled; and whenever the media element's readyState is changed back to HAVE_NOTHING. When the flag is unset in this way for one
or more cues in text tracks that were showing prior to the relevant incident, the user agent must, after having unset
the flag for all the affected cues, apply the rules for updating the text track
rendering of those text tracks. For example, for text tracks based on WebVTT, the rules for updating
the display of WebVTT text tracks. [WEBVTT] The display state This is used as part of the rendering model, to keep cues in a consistent position. It must
initially be empty. Whenever the text track cue active flag is unset, the user
agent must empty the text track cue display state. The text track cues of a media element's text tracks are ordered relative to each other in the text track
cue order, which is determined as follows: first group the cues by their text track, with the groups being sorted in the same order
as their text tracks appear in the media element's
list of text tracks; then, within each group, cues must be sorted by their start
time, earliest first; then, any cues with the same
start time must be sorted by their end time, latest first; and finally, any cues with identical end times must
be sorted in the order they were last added to their respective text track list of
cues, oldest first (so e.g. for cues from a WebVTT file, that would initially
be the order in which the cues were listed in the file). [WEBVTT]

Sourcing in-band text tracks A media-resource-specific text track is a text track that corresponds
to data found in the media resource.

Text track API media . textTracks . length Returns the number of text tracks associated with the media element (e.g. from track elements). This is the number of text tracks in the media element's list of text tracks. media . textTracks[ n ] Returns the TextTrack object representing the nth text track in the media

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

element's list of text tracks. textTrack = media . textTracks . getTrackById( id ) Returns the TextTrack object with the given identifier, or null if no track has that identifier. track . track Returns the TextTrack object representing the track element's text track. textTrack = media . addTextTrack( kind [, label [, language ] ] ) Creates and returns a new TextTrack object, which is also added to the
media element's list of text tracks. textTrack . kind Returns the text track kind string. textTrack . label Returns the text track label, if there is one, or the empty string otherwise (indicating that a custom label probably needs to be generated from the other attributes of the
object if the object is exposed to the user). textTrack . language Returns the text track language string. textTrack . id Returns the ID of the given track. For in-band tracks, this is the ID that can be used with a fragment identifier if the format
supports the Media Fragments URI syntax, and that can be used with the getTrackById() method. [MEDIAFRAG] For TextTrack objects corresponding to track elements, this is the
ID of the track element. textTrack . inBandMetadataTrackDispatchType Returns the text track in-band metadata track dispatch type string. textTrack . mode [ = value ] Returns the text track mode, represented by a string from the following
list: "disabled" The text track disabled mode. "hidden"

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

The text track hidden mode. "showing" The text track showing mode. Can be set, to change the mode. textTrack . cues Returns the text track list of cues, as a TextTrackCueList object. textTrack . activeCues Returns the text track cues from the text track
list of cues that are currently active (i.e. that start before the current playback
position and end after it), as a TextTrackCueList object. textTrack . addCue ( cue ) Adds the given cue to textTrack's text track list of cues. textTrack . removeCue ( cue ) Removes the given cue from textTrack's text track list of cues. In this example, an audio element is used to play a specific sound-effect from a
sound file containing many sound effects. A cue is used to pause the audio, so that it ends
exactly at the end of the clip, even if the browser is busy running some script. If the page had
relied on script to pause the audio, then the start of the next clip might be heard if the
browser was not able to run the script at the exact time specified. var sfx = new Audio('sfx.wav'); var sounds = sfx.addTextTrack('metadata'); // add sounds we care about function addFX(start, end, name) { var cue = new VTTCue(start, end, ''); cue.id = name; cue.pauseOnExit = true; sounds.addCue(cue); } addFX(12.783, 13.612, 'dog bark'); addFX(13.612, 15.091, 'kitten mew')) function playSound(id) {

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

sfx.currentTime = sounds.getCueById(id).startTime; sfx.play(); } // play a bark as soon as we can sfx.oncanplaythrough = function () { playSound('dog bark'); } // meow when the user tries to leave window.onbeforeunload = function () { playSound('kitten mew'); return 'Are you sure you want to leave this awesome page?'; }

cuelist . length Returns the number of cues in the list. cuelist[index] Returns the text track cue with index index in the list. The cues are sorted in text track cue order. cuelist . getCueById ( id ) Returns the first text track cue (in text track cue order) with text track cue identifier id. Returns null if none of the cues have the given identifier or if the argument is the empty string. cue . track Returns the TextTrack object to which this
text track cue belongs, if any, or null
otherwise. cue . id [ = value ] Returns the text track cue identifier. Can be set. cue . startTime [ = value ] Returns the text track cue start time, in seconds. Can be set. cue . endTime [ = value ]
http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

Returns the text track cue end time, in seconds. Can be set. cue . pauseOnExit [ = value ] Returns true if the text track cue pause-on-exit flag is set, false otherwise. Can be set.

Text tracks describing chapters Chapters are segments of a media resource with a given title. Chapters can be nested, in the same way that sections in a document outline can have subsections. Each text track cue in a text track being used for describing
chapters has three key features: the text track cue start time, giving the start time
of the chapter, the text track cue end time, giving the end time of the chapter, and
the text track cue data giving the chapter title. The following snippet of a WebVTT file shows how nested chapters can be marked
up. The file describes three 50-minute chapters, "Astrophysics", "Computational Physics", and
"General Relativity". The first has three subchapters, the second has four, and the third has
two. [WEBVTT] WEBVTT 00:00:00.000 --> 00:50:00.000 Astrophysics 00:00:00.000 --> 00:10:00.000 Introduction to Astrophysics 00:10:00.000 --> 00:45:00.000 The Solar System 00:00:00.000 --> 00:10:00.000 Coursework Description 00:50:00.000 --> 01:40:00.000 Computational Physics

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

00:50:00.000 --> 00:55:00.000 Introduction to Programming 00:55:00.000 --> 01:30:00.000 Data Structures 01:30:00.000 --> 01:35:00.000 Answers to Last Exam 01:35:00.000 --> 01:40:00.000 Coursework Description 01:40:00.000 --> 02:30:00.000 General Relativity 01:40:00.000 --> 02:00:00.000 Tensor Algebra 02:00:00.000 --> 02:30:00.000 The General Relativistic Field Equations

User interface
The controls attribute is a boolean
attribute. If present, it indicates that the author has not provided a scripted controller
and would like the user agent to provide its own set of controls. media . volume [ = value ] Returns the current playback volume, as a number in the range 0.0 to 1.0, where 0.0 is the
quietest and 1.0 the loudest. Can be set, to change the volume. Throws an IndexSizeError exception if the new value is not in the range 0.0 .. 1.0. media . muted [ = value ] Returns true if audio is muted, overriding the volume
attribute, and false if the volume attribute is being
honored.

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

Can be set, to change whether the audio is muted or not. The muted attribute on media elements is a boolean attribute that controls the default state
of the audio output of the media resource, potentially overriding user
preferences. This attribute has no dynamic effect (it only controls the default state of the element). This video (an advertisement) autoplays, but to avoid annoying users, it does so without
sound, and allows the user to turn the sound on. <video src="adverts.cgi?kind=video" controls autoplay loop muted></video>

Time ranges
Objects implementing the TimeRanges interface
represent a list of ranges (periods) of time. media . length Returns the number of ranges in the object. time = media . start(index) Returns the time for the start of the range with the given index. Throws an IndexSizeError exception if the index is out of range. time = media . end(index) Returns the time for the end of the range with the given index. Throws an IndexSizeError exception if the index is out of range.

Event definitions
event . track Returns the track object (TextTrack , AudioTrack, or
VideoTrack ) to which the event relates.

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

Event summary
The following events fire on media elements as part of the
processing model described above: Event name loadstart Interface Fired when... Event The user agent begins looking for media data, as part of the resource selection algorithm. progress Event The user agent is fetching media data. networkState equals NETWORK_LOADING suspend Event The user agent is intentionally not currently fetching media data. abort Event The user agent stops fetching the media data before it is completely downloaded, but not due to an error. error is an object with the code MEDIA_ERR_ABORTED . networkState equals either NETWORK_EMPTY or NETWORK_IDLE, depending on when the download was aborted. error Event An error occurs while fetching the media data. error is an object with the code MEDIA_ERR_NETWORK or higher. networkState equals either NETWORK_EMPTY or NETWORK_IDLE, depending on when the download was networkState equals NETWORK_IDLE Preconditions networkState equals NETWORK_LOADING

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

aborted. emptied Event A media element whose networkState


was previously not in the NETWORK_EMPTY state has just switched to that state (either because of a fatal error during load that's about to be
reported, or because the load() method was invoked while
the resource selection algorithm was already
running). stalled Event The user agent is trying to fetch media data, but data is unexpectedly not forthcoming. loadedmetadata Event The user agent has just determined the duration and dimensions of the media
resource and the text tracks are ready. loadeddata Event The user agent can render the media data at the current playback
position for the first time. canplay Event The user agent can resume playback of the media data, but estimates that if playback were to be started now, the media readyState newly increased to HAVE_CURRENT_DATA or greater for the first time. readyState newly increased to HAVE_FUTURE_DATA or greater. readyState is newly equal to HAVE_METADATA or greater for the first time. networkState is NETWORK_LOADING. networkState is NETWORK_EMPTY ; all the IDL attributes are in their
initial states.

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

resource could not be rendered at the current playback rate up to its end without having to stop for further buffering of content. canplaythrough Event The user agent estimates that if playback were to be started now, the media
resource could be rendered at the current playback rate all the way to its end without
having to stop for further buffering. playing Event Playback is ready to start after having been paused or delayed due to lack of media
data. readyState is newly equal to or greater than HAVE_FUTURE_DATA and paused is false, or paused is newly false and readyState is equal to or greater than HAVE_FUTURE_DATA. Even if this event fires, the
element might still not be potentially playing, e.g. if the element is blocked on its media controller (e.g. because the current media
controller is paused, or another slaved media element is stalled readyState is newly equal to HAVE_ENOUGH_DATA.

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

somehow, or because the media resource has no data


corresponding to the media controller position), or the element is paused for user interaction or paused for inband content. waiting Event Playback has stopped because the next frame is not available, but the user agent expects that frame to become available in due course. readyState is equal to or less than HAVE_CURRENT_DATA , and paused is false. Either seeking is true, or the current playback position
is not contained in any of the ranges in buffered. It
is possible for playback to stop for other reasons without paused being false, but those reasons do not fire this event
(and when those situations resolve, a separate playing event is not fired either): e.g. the element is newly blocked on its media
controller, or playback ended, or playback
stopped due to errors, or the element has paused for user interaction
http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

or paused for inband content. seeking Event The seeking IDL attribute changed to true. seeked Event The seeking IDL attribute changed to false. ended Event Playback has stopped because the end of the media resource was reached. durationchange Event The duration attribute has just been updated. timeupdate Event The current playback position changed as part of normal playback or in an especially interesting way, for example discontinuously. play Event The element is no longer paused. Fired after the play() method has returned, or when the autoplay attribute
has caused playback to begin. pause Event The element has been paused. Fired after the pause()
method has returned. ratechange Event Either the defaultPlaybackRate or the
playbackRate attribute has just been updated.
http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

currentTime equals the end of the media


resource; ended is true.

paused is newly false.

paused is newly true.

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

volumechange

Event

Either the volume attribute or the muted attribute has changed. Fired after the relevant
attribute's setter has returned.

The following events fire on MediaController objects: Event name emptied Interface Fired when... Event All the slaved media elements newly have readyState set to HAVE_NOTHING or greater, or there are no longer any
slaved media elements. loadedmetadata Event All the slaved media elements newly have readyState set to HAVE_METADATA or greater. loadeddata Event All the slaved media elements newly have readyState set to HAVE_CURRENT_DATA or greater. canplay Event All the slaved media elements newly have readyState set to HAVE_FUTURE_DATA or greater. canplaythrough Event All the slaved media elements newly have readyState set to HAVE_ENOUGH_DATA or greater. playing Event The MediaController is no longer a blocked media controller. ended Event The MediaController has reached the end of all the slaved media
elements. waiting Event The MediaController is now a blocked media controller. ended Event All the slaved media elements have newly ended playback. durationchange Event The duration attribute has just been updated.

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

timeupdate play pause ratechange

Event Event Event Event

The media controller position changed. The paused attribute is newly false. The paused attribute is newly true. Either the defaultPlaybackRate attribute or the playbackRate attribute has just been updated.

volumechange

Event

Either the volume attribute or the muted attribute has just been updated.

The following events fire on AudioTrackList , VideoTrackList, and TextTrackList objects: Event name change addtrack removetrack Interface Event TrackEvent TrackEvent Fired when... One or more tracks in the track list has been enabled or disabled. A track has been added to the track list. A track has been removed from the track list.

Best practices for authors using media elements


Playing audio and video resources on small devices such as set-top boxes or mobile phones is
often constrained by limited hardware resources in the device. For example, a device might only
support three simultaneous videos. For this reason, it is a good practice to release resources
held by media elements when they are done playing, either by
being very careful about removing all references to the element and allowing it to be garbage
collected, or, even better, by removing the element's src
attribute and any source element descendants, and invoking the element's load() method. Similarly, when the playback rate is not exactly 1.0, hardware, software, or format limitations
can cause video frames to be dropped and audio to be choppy or muted.

Up next

4.7.11 The map element

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

4.7.6 The video element HTML: The Living Standard - Edition for Web Developers

This document is a work in progress, if you spot something that you feel isn't quite right, please raise an issue, otherwise you'll find the source on github. This version is maintained by Ian Hickson and Ben Schwarz.

http://developers.whatwg.org/the-video-element.html[4/16/2014 9:35:28 PM]

Anda mungkin juga menyukai