Edition for Web Developers — Last Updated 5 December 2024
innerText
and outerText
propertiesEvery XML and HTML document in an HTML UA is represented by a Document
object.
[DOM]
The Document
object's URL is defined in DOM. It is initially set when
the Document
object is created, but can change during the lifetime of the
Document
object; for example, it changes when the user navigates to a fragment on the page
and when the pushState()
method is called with a new
URL. [DOM]
Interactive user agents typically expose the Document
object's
URL in their user interface. This is the primary
mechanism by which a user can tell if a site is attempting to impersonate another.
The Document
object's origin is defined in DOM. It is initially set when the
Document
object is created, and can change during the lifetime of the
Document
only upon setting document.domain
. A Document
's origin can differ from the origin of its URL;
for example when a child navigable is created, its active document's origin is inherited from its parent's active document's origin, even though its active document's URL is
about:blank
. [DOM]
When a Document
is created by a script using
the createDocument()
or createHTMLDocument()
methods, the
Document
is ready for post-load tasks immediately.
The document's referrer is a string (representing a URL) that
can be set when the Document
is created. If it is not explicitly set, then its value
is the empty string.
Document
objectSupport in all current engines.
DOM defines a Document
interface, which
this specification extends significantly.
Each Document
has a policy container (a policy container), initially a new policy
container, which contains policies which apply to the Document
.
Each Document
has a permissions policy, which
is a permissions policy, which is initially
empty.
Each Document
has a module map,
which is a module map, initially empty.
Each Document
has an opener policy,
which is an opener policy, initially a new opener policy.
Each Document
has an is initial about:blank
, which is a
boolean, initially false.
Each Document
has a during-loading
navigation ID for WebDriver BiDi, which is a navigation ID or null, initially
null.
As the name indicates, this is used for interfacing with the WebDriver
BiDi specification, which needs to be informed about certain occurrences during the early
parts of the Document
's lifecycle, in a way that ties them to the original
navigation ID used when the navigation that created this Document
was
the ongoing navigation. This eventually gets set back to null, after WebDriver
BiDi considers the loading process to be finished. [BIDI]
Each Document
has an about base
URL, which is a URL or null, initially null.
This is only populated for "about:
"-schemed
Document
s.
Each Document
has a bfcache blocking details, which is a
set of not restored reason details,
initially empty.
DocumentOrShadowRoot
interfaceDOM defines the DocumentOrShadowRoot
mixin, which this specification
extends.
document.referrer
Returns the URL 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.
document.
[ = value ]Support in all current engines.
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 an
opaque origin (e.g., in an iframe
with the sandbox
attribute), a
"SecurityError
" DOMException
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/YYYY hh:mm:ss
", in the user's local time zone.
If the last modification date is not known, the current time is returned instead.
Document/DOMContentLoaded_event
Support in all current engines.
document.readyState
Returns "loading
" while the Document
is loading, "interactive
" once it is finished parsing but still loading subresources, and
"complete
" once it has loaded.
The readystatechange
event fires on the
Document
object when this value changes.
The DOMContentLoaded
event fires after the transition to
"interactive
" but before the transition to "complete
", at the point where all subresources apart from async
script
elements have loaded.
Each Document
has a render-blocking element set, a set of
elements, initially the empty set.
A Document
document allows adding render-blocking elements
if document's content type is
"text/html
" and the body element of document is null.
A Document
document is render-blocked if both of the
following are true:
document's render-blocking element set is non-empty, or document allows adding render-blocking elements.
The current high resolution time given document's relevant global object has not exceeded an implementation-defined timeout value.
An element el is render-blocking if el's node document document is render-blocked, and el is in document's render-blocking element set.
To block rendering on an element el:
Let document be el's node document.
If document allows adding render-blocking elements, then append el to document's render-blocking element set.
To unblock rendering on an element el:
Let document be el's node document.
Remove el from document's render-blocking element set.
Whenever a render-blocking element el becomes browsing-context disconnected, or el's blocking attribute's value is changed so that el is no longer potentially render-blocking, then unblock rendering on el.
The html
element of a document is its document element,
if it's an html
element, and 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 for
HTML and as given by the SVG title
element for SVG.
Can be set, to update the document's title. If there is no appropriate element to update, the new value is ignored.
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
" DOMException
.
The body element of a document is the first of the html
element's children that is either a body
element or a frameset
element, or null if there is no such element.
document.images
Returns an HTMLCollection
of the img
elements in the
Document
.
document.embeds
document.plugins
Returns 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
Returns an HTMLCollection
of the form
elements in the
Document
.
document.scripts
Returns 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.
document.currentScript
Returns the script
element, or the SVG script
element,
that is currently executing, as long as the element represents a classic script. 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
or
SVG script
element (e.g., because the running script is an event
handler, or a timeout), or if the currently executing script
or SVG
script
element represents a module script.
This API has fallen out of favor in the implementer and standards community, as
it globally exposes script
or SVG script
elements. As such,
it is not available in newer contexts, such as when running module
scripts or when running scripts in a shadow tree. We are looking into creating
a new solution for identifying the running script in such contexts, which does not make it
globally available: see issue #1013.
The dir
attribute on the
Document
interface is defined along with the dir
content attribute.
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 lang = "en" >
< head >
< title > My Page</ title >
</ head >
< body >
< h1 > Welcome to my page</ h1 >
< 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 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 snippet, intended to represent the heading of a corporate site, is non-conforming because the second line is not intended to be a heading of a subsection, but merely a subheading or subtitle (a subordinate heading for the same section).
< body >
< h1 > ACME Corporation</ h1 >
< h2 > The leaders in arbitrary fast delivery since 1920</ h2 >
...
The hgroup
element can be used for these kinds of situations:
< body >
< hgroup >
< h1 > ACME Corporation</ h1 >
< p > The leaders in arbitrary fast delivery since 1920</ p >
</ hgroup >
...
The document in this next example is similarly non-conforming, despite
being syntactically correct, because the data placed in the cells is clearly
not tabular data, and the cite
element mis-used:
<!DOCTYPE HTML>
< html lang = "en-GB" >
< head > < title > Demonstration </ title > </ head >
< body >
< table >
< tr > < td > My favourite animal is the cat. </ td > </ tr >
< tr >
< td >
—< a href = "https://example.org/~ernest/" >< cite > Ernest</ cite ></ a > ,
in an essay from 1992
</ td >
</ tr >
</ table >
</ body >
</ html >
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 = "https://example.org/~ernest/" > Ernest</ a > ,
in an essay from 1992
</ p >
</ body >
</ html >
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 >
DOM nodes whose node document's browsing context is null are exempt from all document conformance requirements other than the HTML syntax requirements and XML syntax requirements.
In particular, the template
element's template contents's node
document's browsing context is null. For
example, the content model requirements and
attribute value microsyntax requirements do not apply to a template
element's
template contents. In this example an img
element has attribute values
that are placeholders that would be invalid outside a template
element.
< template >
< article >
< img src = "{{src}}" alt = "{{alt}}" >
< h1 ></ h1 >
</ article >
</ template >
However, if the above markup were to omit the </h1>
end tag, that
would be a violation of the HTML syntax, and would thus be flagged as an
error by conformance checkers.
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.
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.
Elements can be referenced (referred to) in some way, either
explicitly or implicitly. One way that an element in the DOM can be explicitly referenced is by
giving an id
attribute to the element, and then creating a
hyperlink with that id
attribute's value as the fragment for the hyperlink's href
attribute value. Hyperlinks are not necessary for a
reference, however; any manner of referring to the element in question will suffice.
Consider the following figure
element, which is given an id
attribute:
< figure id = "module-script-graph" >
< img src = "module-script-graph.svg"
alt = "Module A depends on module B, which depends
on modules C and D." >
< figcaption > Figure 27: a simple module graph</ figcaption >
</ figure >
A hyperlink-based reference could be created
using the a
element, like so:
As we can see in < a href = "#module-script-graph" > figure 27</ a > , ...
However, there are many other ways of referencing the
figure
element, such as:
"As depicted in the figure of modules A, B, C, and D..."
"In Figure 27..." (without a hyperlink)
"From the contents of the 'simple module graph' figure..."
"In the figure below..." (but this is discouraged)
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.
An example of an element that is neither an HTML nor SVG element is one created as follows:
const el = document.createElementNS("some namespace", "example");
console.assert(el.constructor === Element);
Each element in this specification has a definition that includes the following information:
A list of categories to which the element belongs. These are used when defining the content models for each element.
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, all phrasing content is flow content. Thus, elements that are phrasing content will only be listed as "where phrasing content is expected", since this is the more-specific expectation. Anywhere that expects flow content also expects phrasing content, and thus also meets this expectation.
A normative description of what content must be included as children and descendants of the element.
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.
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.)
For authors: Conformance requirements for use of ARIA role
and aria-*
attributes are
defined in ARIA in HTML. [ARIA] [ARIAHTML]
For implementers: User agent requirements for implementing accessibility API semantics are defined in HTML Accessibility API Mappings. [HTMLAAM]
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.
An attribute value is a string. Except where otherwise specified, attribute values on HTML elements may be any string value, including the empty string, and there is no restriction on what text can be specified in such attribute values.
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.
ASCII whitespace is 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.
The Atom Syndication Format defines a content
element. When its type
attribute has the value
xhtml
, The Atom Syndication Format 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 specification. [ATOM]
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' ),
};
When an element's content model is nothing, the
element must contain no Text
nodes (other than inter-element whitespace)
and no element nodes.
Most HTML elements whose content model is "nothing" are also, for convenience, void elements (elements that have no end tag in the HTML syntax). However, these are entirely separate concepts.
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:
Some elements also fall into other categories, which are defined in other parts of this specification.
These categories are related as follows:
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 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.
Elements from other namespaces whose semantics are primarily metadata-related (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#" xml:lang = "en" >
< head >
< title > Hedral's Home Page</ title >
< r:RDF >
< Person xmlns = "http://www.w3.org/2000/10/swap/pim/contact#"
r:about = "https://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
too so sometimes I follow her to play with them.</ p >
</ body >
</ html >
This isn't possible in the HTML serialization, however.
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
header
hgroup
hr
i
iframe
img
input
ins
kbd
label
link
(if it is allowed in the body)main
(if it is a hierarchically correct main
element)map
mark
math
menu
meta
(if the itemprop
attribute is present)meter
nav
noscript
object
ol
output
p
picture
pre
progress
q
ruby
s
samp
script
search
section
select
slot
small
span
strong
sub
sup
svg
table
template
textarea
time
u
ul
var
video
wbr
Sectioning content is content that defines the scope of header
and footer
elements.
Heading content defines the heading of a section (whether explicitly marked up using sectioning content elements, or implied by the heading content itself).
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
br
button
canvas
cite
code
data
datalist
del
dfn
em
embed
i
iframe
img
input
ins
kbd
label
link
(if it is allowed in the body)map
mark
math
meta
(if the itemprop
attribute is present)meter
noscript
object
output
picture
progress
q
ruby
s
samp
script
select
slot
small
span
strong
sub
sup
svg
template
textarea
time
u
var
video
wbr
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 ASCII
whitespace).
Text
nodes and attribute values must consist of scalar
values, excluding noncharacters, and controls other than ASCII whitespace.
This specification includes extra constraints on the exact value of Text
nodes and
attribute values depending on their precise context.
Embedded content is content that imports another resource into the document, or content from another vocabulary that is inserted into the document.
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.
Interactive content is content that is specifically intended for user interaction.
a
(if the href
attribute is present)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 state)label
select
textarea
video
(if the controls
attribute is present)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 attribute specified.
Palpable content makes an element non-empty by providing either
some descendant non-empty text, or else something users can
hear (audio
elements) or view (video
, img
, or
canvas
elements) or otherwise interact with (for example, interactive form
controls).
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
bdi
bdo
blockquote
button
canvas
cite
code
data
del
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 state)ins
kbd
label
main
map
mark
math
menu
(if the element's children include at least one li
element)meter
nav
object
ol
(if the element's children include at least one li
element)output
p
picture
pre
progress
q
ruby
s
samp
search
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
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:
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.
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.
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 >
< h2 > Example of paragraphs</ h2 >
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 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 >< h2 > Example of paragraphs</ h2 >
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 >
< 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 >
< h2 > My Cats</ h2 >
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 = "https://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:
object
element.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 >
< h2 > My Cats</ h2 >
< 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 = "https://sims.example.com/watch?v=LYds5xY4INU" > Use online simulator</ a >
</ ul >
< p > Alternatively, upgrade to the Mellblom Browser.</ p >
</ object >
< p > I'm quite proud of it.</ p >
</ section >
The following attributes are common to and may be specified on all HTML elements:
accesskey
autocapitalize
autocorrect
autofocus
contenteditable
dir
draggable
enterkeyhint
inert
inputmode
is
itemid
itemprop
itemref
itemscope
itemtype
lang
nonce
popover
spellcheck
style
tabindex
title
translate
writingsuggestions
Support in all current engines.
DOM defines the user agent requirements for the class
, id
, and slot
attributes for any element in any namespace.
[DOM]
The class
, id
, and slot
attributes may be specified on all HTML elements.
When specified on HTML elements, the class
attribute 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.
When specified on HTML elements, the id
attribute
value must be unique amongst all the IDs in the element's
tree and must contain at least one character. The value must not contain any
ASCII whitespace.
The id
attribute specifies its element's unique identifier (ID).
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 fragments, as a way to target an element when scripting, and as a way to style a specific element from CSS.
There are no conformance requirements for the slot
attribute
specific to HTML elements.
The slot
attribute is used to assign a
slot to an element: an element with a slot
attribute is
assigned to the slot
created by the slot
element whose name
attribute's value matches that slot
attribute's value — but only
if that slot
element finds itself in the shadow tree whose
root's host has the corresponding
slot
attribute value.
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).
[ARIA]
The following event handler content attributes may be specified on any HTML element:
onauxclick
onbeforeinput
onbeforematch
onbeforetoggle
onblur
*oncancel
oncanplay
oncanplaythrough
onchange
onclick
onclose
oncontextlost
oncontextmenu
oncontextrestored
oncopy
oncuechange
oncut
ondblclick
ondrag
ondragend
ondragenter
ondragleave
ondragover
ondragstart
ondrop
ondurationchange
onemptied
onended
onerror
*onfocus
*onformdata
oninput
oninvalid
onkeydown
onkeypress
onkeyup
onload
*onloadeddata
onloadedmetadata
onloadstart
onmousedown
onmouseenter
onmouseleave
onmousemove
onmouseout
onmouseover
onmouseup
onpaste
onpause
onplay
onplaying
onprogress
onratechange
onreset
onresize
*onscroll
*onscrollend
*onsecuritypolicyviolation
onseeked
onseeking
onselect
onslotchange
onstalled
onsubmit
onsuspend
ontimeupdate
ontoggle
onvolumechange
onwaiting
onwheel
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, state, annotations, and
similar, 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 XML 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.
XML 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. [XML]
There is no way to serialize the xml:space
attribute on HTML elements in the text/html
syntax.
title
attributeSupport in all current engines.
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 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.
lang
and xml:lang
attributesSupport in all current engines.
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. [BCP47]
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 (except for slot
elements in a
shadow tree).
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 XML, 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.
translate
attributeSupport in all current engines.
The translate
attribute is used to specify 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. It is an attribute is an enumerated attribute with the
following keywords and states:
Keyword | State | Brief description |
---|---|---|
yes
| yes | Sets translation mode to translate-enabled. |
(the empty string) | ||
no
| no | Sets translation mode to no-translate. |
The attribute's missing value default and invalid value default are both the inherit state.
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's parent element is
null.
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 name of a computer program.
The following attributes are translatable attributes:
abbr
on th
elementsalt
on area
,
img
, and
input
elementscontent
on meta
elements, if the name
attribute specifies a metadata name whose value is known to be translatabledownload
on a
and
area
elementslabel
on optgroup
,
option
, and
track
elementslang
on HTML elements; must be "translated" to match the language used in the translationplaceholder
on input
and
textarea
elementssrcdoc
on iframe
elements; must be parsed and recursively processedstyle
on HTML elements; must be parsed and
recursively processed (e.g. for the values of 'content' properties)title
on all HTML elementsvalue
on input
elements with a
type
attribute in the Button state
or the Reset Button stateOther specifications may define other attributes that are also translatable
attributes. For example, ARIA would define the aria-label
attribute as translatable.
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:
<!DOCTYPE HTML>
< html lang = en > <!-- default on the document 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 >
dir
attributeSupport in all current engines.
The dir
attribute
is an enumerated attribute with the following keywords and states:
Keyword | State | Brief description |
---|---|---|
ltr
| ltr | The contents of the element are explicitly directionally isolated left-to-right text. |
rtl
| rtl | The contents of the element are explicitly directionally isolated right-to-left text. |
auto
| auto | The contents of the element are explicitly directionally isolated text, but the direction is to be determined programmatically using the contents of the element (as described below). |
The heuristic used by the auto 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 no better server-side heuristic can be applied. [BIDI]
For textarea
and pre
elements, the heuristic is applied on a
per-paragraph level.
The attribute's missing value default and invalid value default are both the undefined state.
The directionality of an element (any element, not just
an HTML element) is either 'ltr' or 'rtl'. To compute the directionality given an element element, switch on
element's dir
attribute state:
Return 'ltr'.
Return 'rtl'.
Let result be the auto directionality of element.
If result is null, then return 'ltr'.
Return result.
bdi
elementLet result be the auto directionality of element.
If result is null, then return 'ltr'.
Return result.
input
element whose type
attribute is in the Telephone stateReturn 'ltr'.
Return the parent directionality of element.
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 end up using the parent directionality.
The auto-directionality form-associated elements are:
input
elements whose type
attribute is
in the , Text, Search,
Telephone, URL, Email, Password, Submit
Button, Reset Button, or Button state, and
textarea
elements.
To compute the auto directionality given an element element:
If element is an auto-directionality form-associated element:
If element is a slot
element whose root is a
shadow root and element's assigned nodes are not empty:
For each node child of element's assigned nodes:
Let childDirection be null.
If child is a Text
node, then set childDirection to
the text node directionality of child.
Otherwise:
Set childDirection to the contained text auto directionality of child with canExcludeRoot set to true.
If childDirection is not null, then return childDirection.
Return null.
Return the contained text auto directionality of element with canExcludeRoot set to false.
To compute the contained text auto directionality of an element element with a boolean canExcludeRoot:
For each node descendant of element's descendants, in tree order:
If any of
is one of
bdi
elementscript
elementstyle
elementtextarea
elementdir
attribute is not in the undefined statethen continue.
If descendant is a slot
element whose root is a
shadow root, then return the directionality of that shadow root's host.
Let result be the text node directionality of descendant.
If result is not null, then return result.
Return null.
To compute the text node directionality given a Text
node
text:
If text's data does not contain a code point whose bidirectional character type is L, AL, or R, then return null. [BIDI]
Let codePoint be the first code point in text's data whose bidirectional character type is L, AL, or R.
If codePoint is of bidirectional character type AL or R, then return 'rtl'.
If codePoint is of bidirectional character type L, then return 'ltr'.
To compute the parent directionality given an element element:
Let parentNode be element's parent node.
If parentNode is a shadow root, then return the directionality of parentNode's host.
If parentNode is an element, then return the directionality of parentNode.
Return '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:
dir
attribute is in the auto
stateFind 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'.
The following attributes are directionality-capable attributes:
abbr
on th
elementsalt
on area
,
img
, and
input
elementscontent
on meta
elements, if the name
attribute specifies a metadata name whose value is primarily intended to be human-readable rather than machine-readablelabel
on optgroup
,
option
, and
track
elementsplaceholder
on input
and
textarea
elementstitle
on all HTML elementsdocument.dir [ = value ]
Support in all current engines.
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 class = "u1" >< b >< bdi > Student</ bdi > :</ b > How do you write "What's your name?" in Arabic?</ p >
< p dir = auto class = "u2" >< b >< bdi > Teacher</ bdi > :</ b > ما اسمك؟</ p >
< p dir = auto class = "u1" >< b >< bdi > Student</ bdi > :</ b > Thanks.</ p >
< p dir = auto class = "u2" >< b >< bdi > Teacher</ bdi > :</ b > That's written "شكرًا".</ p >
< p dir = auto class = "u2" >< b >< bdi > Teacher</ bdi > :</ b > Do you know how to write "Please"?</ p >
< p dir = auto class = "u1" >< b >< bdi > Student</ bdi > :</ b > "من فضلك", 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:
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.
style
attributeSupport in all current engines.
All HTML elements may have the style
content attribute set. This is a style attribute as defined by CSS Style
Attributes. [CSSATTR]
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
attribute.)
element.style
Returns a CSSStyleDeclaration
object for the element's style
attribute.
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 >
data-*
attributesSupport in all current engines.
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 XML-compatible, and contains no ASCII
upper alphas.
All attribute names on HTML elements in HTML documents get ASCII-lowercased automatically, so the restriction on ASCII uppercase letters doesn't affect such documents.
Custom data attributes are intended to store custom data, state, annotations, and similar, 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 not known to the administrators of the site that uses the attributes. For generic extensions that are to be used by multiple independent tools, either this specification should be extended to provide the feature explicitly, or a technology like microdata should be used (with a standardized vocabulary).
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.
Similarly, a page author could write markup that provides information for a translation tool that they are intending to use:
< p > The third < span data-mytrans-de = "Anspruch" > claim</ span > covers the case of < span
translate = "no" > HTML</ span > markup.</ p >
In this example, the "data-mytrans-de
" attribute gives specific text
for the MyTrans product to use when translating the phrase "claim" to German. However, the
standard translate
attribute is used to tell it that in all
languages, "HTML" is to remain unchanged. When a standard attribute is available, there is no
need for a custom data attribute to be used.
In this example, custom data attributes are used to store the result of a feature detection
for PaymentRequest
, which could be used in CSS to style a checkout page
differently.
< script >
if ( 'PaymentRequest' in window) {
document. documentElement. dataset. hasPaymentRequest = '' ;
}
</ script >
Here, the data-has-payment-request
attribute is effectively being used
as a boolean attribute; it is enough to check the presence of the attribute.
However, if the author so wishes, it could later be populated with some value, maybe to indicate
limited functionality of the feature.
Every HTML element may have any number of custom data attributes specified, with any value.
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
).
element.dataset
Returns a DOMStringMap
object for the element's data-*
attributes.
Hyphenated names become camel-cased. For example, data-foo-bar=""
becomes element.dataset.fooBar
.
The DOMStringMap
interface is used for the dataset
attribute. Each DOMStringMap
has an associated element.
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.
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 'data-hp' 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-ability' attribute
}
node. dataset. hp = hp; // setting the 'data-hp' attribute
}
}
innerText
and outerText
propertiesSupport in all current engines.
element.innerText [ = value ]
Returns the element's text content "as rendered".
Can be set, to replace the element's children with the given value, but with line breaks
converted to br
elements.
element.outerText [ = value ]
Support in all current engines.
Returns the element's text content "as rendered".
Can be set, to replace the element with the given value, but with line breaks converted to
br
elements.
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). [BIDI]
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.