[2]One-Page Version html.spec.whatwg.org [3]Multipage Version
/multipage [4]Version for Web Devs /dev [5]PDF Version /print.pdf
[6]Translations 日本語 • 简体中文
[7]FAQ on GitHub [8]Chat on Matrix
[9]Contribute on GitHub whatwg/html repository [10]Commits on GitHub
[11]Snapshot as of this commit [12]Twitter Updates @htmlstandard
[13]Open Issues filed on GitHub [14]Open an Issue whatwg.org/newbug
[15]Tests web-platform-tests html/ [16]Issues for Tests ongoing work
__________________________________________________________________
Table of contents
1. [17]1 Introduction
2. [18]2 Common infrastructure
3. [19]3 Semantics, structure, and APIs of HTML documents
4. [20]4 The elements of HTML
5. [21]5 Microdata
6. [22]6 User interaction
7. [23]7 Loading web pages
8. [24]8 Web application APIs
9. [25]9 Communication
10. [26]10 Web workers
11. [27]11 Worklets
12. [28]12 Web storage
13. [29]13 The HTML syntax
14. [30]14 The XML syntax
15. [31]15 Rendering
16. [32]16 Obsolete features
17. [33]17 IANA considerations
18. [34]Index
19. [35]References
20. [36]Acknowledgments
21. [37]Intellectual property rights
Full table of contents
1. [38]1 Introduction
1. [39]1.1 Where does this specification fit?
2. [40]1.2 Is this HTML5?
3. [41]1.3 Background
4. [42]1.4 Audience
5. [43]1.5 Scope
6. [44]1.6 History
7. [45]1.7 Design notes
1. [46]1.7.1 Serializability of script execution
2. [47]1.7.2 Extensibility
8. [48]1.8 HTML vs XML syntax
9. [49]1.9 Structure of this specification
1. [50]1.9.1 How to read this specification
2. [51]1.9.2 Typographic conventions
10. [52]1.10 A quick introduction to HTML
1. [53]1.10.1 Writing secure applications with HTML
2. [54]1.10.2 Common pitfalls to avoid when using the
scripting APIs
3. [55]1.10.3 How to catch mistakes when writing HTML:
validators and conformance checkers
11. [56]1.11 Conformance requirements for authors
1. [57]1.11.1 Presentational markup
2. [58]1.11.2 Syntax errors
3. [59]1.11.3 Restrictions on content models and on
attribute values
12. [60]1.12 Suggested reading
2. [61]2 Common infrastructure
1. [62]2.1 Terminology
1. [63]2.1.1 Parallelism
2. [64]2.1.2 Resources
3. [65]2.1.3 XML compatibility
4. [66]2.1.4 DOM trees
5. [67]2.1.5 Scripting
6. [68]2.1.6 Plugins
7. [69]2.1.7 Character encodings
8. [70]2.1.8 Conformance classes
9. [71]2.1.9 Dependencies
10. [72]2.1.10 Extensibility
11. [73]2.1.11 Interactions with XPath and XSLT
2. [74]2.2 Policy-controlled features
3. [75]2.3 Common microsyntaxes
1. [76]2.3.1 Common parser idioms
2. [77]2.3.2 Boolean attributes
3. [78]2.3.3 Keywords and enumerated attributes
4. [79]2.3.4 Numbers
1. [80]2.3.4.1 Signed integers
2. [81]2.3.4.2 Non-negative integers
3. [82]2.3.4.3 Floating-point numbers
4. [83]2.3.4.4 Percentages and lengths
5. [84]2.3.4.5 Nonzero percentages and lengths
6. [85]2.3.4.6 Lists of floating-point numbers
7. [86]2.3.4.7 Lists of dimensions
5. [87]2.3.5 Dates and times
1. [88]2.3.5.1 Months
2. [89]2.3.5.2 Dates
3. [90]2.3.5.3 Yearless dates
4. [91]2.3.5.4 Times
5. [92]2.3.5.5 Local dates and times
6. [93]2.3.5.6 Time zones
7. [94]2.3.5.7 Global dates and times
8. [95]2.3.5.8 Weeks
9. [96]2.3.5.9 Durations
10. [97]2.3.5.10 Vaguer moments in time
6. [98]2.3.6 Legacy colors
7. [99]2.3.7 Space-separated tokens
8. [100]2.3.8 Comma-separated tokens
9. [101]2.3.9 References
10. [102]2.3.10 Media queries
11. [103]2.3.11 Unique internal values
4. [104]2.4 URLs
1. [105]2.4.1 Terminology
2. [106]2.4.2 Parsing URLs
3. [107]2.4.3 Dynamic changes to base URLs
5. [108]2.5 Fetching resources
1. [109]2.5.1 Terminology
2. [110]2.5.2 Determining the type of a resource
3. [111]2.5.3 Extracting character encodings from meta
elements
4. [112]2.5.4 CORS settings attributes
5. [113]2.5.5 Referrer policy attributes
6. [114]2.5.6 Nonce attributes
7. [115]2.5.7 Lazy loading attributes
8. [116]2.5.8 Blocking attributes
9. [117]2.5.9 Fetch priority attributes
6. [118]2.6 Common DOM interfaces
1. [119]2.6.1 Reflecting content attributes in IDL
attributes
2. [120]2.6.2 Using reflect in specifications
3. [121]2.6.3 Collections
1. [122]2.6.3.1 The HTMLAllCollection interface
1. [123]2.6.3.1.1 [[Call]] ( thisArgument,
argumentsList )
2. [124]2.6.3.2 The HTMLFormControlsCollection
interface
3. [125]2.6.3.3 The HTMLOptionsCollection interface
4. [126]2.6.4 The DOMStringList interface
7. [127]2.7 Safe passing of structured data
1. [128]2.7.1 Serializable objects
2. [129]2.7.2 Transferable objects
3. [130]2.7.3 StructuredSerializeInternal ( value,
forStorage [ , memory ] )
4. [131]2.7.4 StructuredSerialize ( value )
5. [132]2.7.5 StructuredSerializeForStorage ( value )
6. [133]2.7.6 StructuredDeserialize ( serialized,
targetRealm [ , memory ] )
7. [134]2.7.7 StructuredSerializeWithTransfer ( value,
transferList )
8. [135]2.7.8 StructuredDeserializeWithTransfer (
serializeWithTransferResult, targetRealm )
9. [136]2.7.9 Performing serialization and transferring from
other specifications
10. [137]2.7.10 Structured cloning API
3. [138]3 Semantics, structure, and APIs of HTML documents
1. [139]3.1 Documents
1. [140]3.1.1 The Document object
2. [141]3.1.2 The DocumentOrShadowRoot interface
3. [142]3.1.3 Resource metadata management
4. [143]3.1.4 Reporting document loading status
5. [144]3.1.5 Render-blocking mechanism
6. [145]3.1.6 DOM tree accessors
2. [146]3.2 Elements
1. [147]3.2.1 Semantics
2. [148]3.2.2 Elements in the DOM
3. [149]3.2.3 HTML element constructors
4. [150]3.2.4 Element definitions
1. [151]3.2.4.1 Attributes
5. [152]3.2.5 Content models
1. [153]3.2.5.1 The "nothing" content model
2. [154]3.2.5.2 Kinds of content
1. [155]3.2.5.2.1 Metadata content
2. [156]3.2.5.2.2 Flow content
3. [157]3.2.5.2.3 Sectioning content
4. [158]3.2.5.2.4 Heading content
5. [159]3.2.5.2.5 Phrasing content
6. [160]3.2.5.2.6 Embedded content
7. [161]3.2.5.2.7 Interactive content
8. [162]3.2.5.2.8 Palpable content
9. [163]3.2.5.2.9 Script-supporting elements
3. [164]3.2.5.3 Transparent content models
4. [165]3.2.5.4 Paragraphs
6. [166]3.2.6 Global attributes
1. [167]3.2.6.1 The title attribute
2. [168]3.2.6.2 The lang and xml:lang attributes
3. [169]3.2.6.3 The translate attribute
4. [170]3.2.6.4 The dir attribute
5. [171]3.2.6.5 The style attribute
6. [172]3.2.6.6 Embedding custom non-visible data with
the data-* attributes
7. [173]3.2.7 The innerText and outerText properties
8. [174]3.2.8 Requirements relating to the bidirectional
algorithm
1. [175]3.2.8.1 Authoring conformance criteria for
bidirectional-algorithm formatting characters
2. [176]3.2.8.2 User agent conformance criteria
9. [177]3.2.9 Requirements related to ARIA and to platform
accessibility APIs
4. [178]4 The elements of HTML
1. [179]4.1 The document element
1. [180]4.1.1 The html element
2. [181]4.2 Document metadata
1. [182]4.2.1 The head element
2. [183]4.2.2 The title element
3. [184]4.2.3 The base element
4. [185]4.2.4 The link element
1. [186]4.2.4.1 Processing the media attribute
2. [187]4.2.4.2 Processing the type attribute
3. [188]4.2.4.3 Fetching and processing a resource from
a link element
4. [189]4.2.4.4 Processing `Link` headers
5. [190]4.2.4.5 Early hints
6. [191]4.2.4.6 Providing users with a means to follow
hyperlinks created using the link element
5. [192]4.2.5 The meta element
1. [193]4.2.5.1 Standard metadata names
2. [194]4.2.5.2 Other metadata names
3. [195]4.2.5.3 Pragma directives
4. [196]4.2.5.4 Specifying the document's character
encoding
6. [197]4.2.6 The style element
7. [198]4.2.7 Interactions of styling and scripting
3. [199]4.3 Sections
1. [200]4.3.1 The body element
2. [201]4.3.2 The article element
3. [202]4.3.3 The section element
4. [203]4.3.4 The nav element
5. [204]4.3.5 The aside element
6. [205]4.3.6 The h1, h2, h3, h4, h5, and h6 elements
7. [206]4.3.7 The hgroup element
8. [207]4.3.8 The header element
9. [208]4.3.9 The footer element
10. [209]4.3.10 The address element
11. [210]4.3.11 Headings and outlines
1. [211]4.3.11.1 Sample outlines
2. [212]4.3.11.2 Exposing outlines to users
12. [213]4.3.12 Usage summary
1. [214]4.3.12.1 Article or section?
4. [215]4.4 Grouping content
1. [216]4.4.1 The p element
2. [217]4.4.2 The hr element
3. [218]4.4.3 The pre element
4. [219]4.4.4 The blockquote element
5. [220]4.4.5 The ol element
6. [221]4.4.6 The ul element
7. [222]4.4.7 The menu element
8. [223]4.4.8 The li element
9. [224]4.4.9 The dl element
10. [225]4.4.10 The dt element
11. [226]4.4.11 The dd element
12. [227]4.4.12 The figure element
13. [228]4.4.13 The figcaption element
14. [229]4.4.14 The main element
15. [230]4.4.15 The search element
16. [231]4.4.16 The div element
5. [232]4.5 Text-level semantics
1. [233]4.5.1 The a element
2. [234]4.5.2 The em element
3. [235]4.5.3 The strong element
4. [236]4.5.4 The small element
5. [237]4.5.5 The s element
6. [238]4.5.6 The cite element
7. [239]4.5.7 The q element
8. [240]4.5.8 The dfn element
9. [241]4.5.9 The abbr element
10. [242]4.5.10 The ruby element
11. [243]4.5.11 The rt element
12. [244]4.5.12 The rp element
13. [245]4.5.13 The data element
14. [246]4.5.14 The time element
15. [247]4.5.15 The code element
16. [248]4.5.16 The var element
17. [249]4.5.17 The samp element
18. [250]4.5.18 The kbd element
19. [251]4.5.19 The sub and sup elements
20. [252]4.5.20 The i element
21. [253]4.5.21 The b element
22. [254]4.5.22 The u element
23. [255]4.5.23 The mark element
24. [256]4.5.24 The bdi element
25. [257]4.5.25 The bdo element
26. [258]4.5.26 The span element
27. [259]4.5.27 The br element
28. [260]4.5.28 The wbr element
29. [261]4.5.29 Usage summary
6. [262]4.6 Links
1. [263]4.6.1 Introduction
2. [264]4.6.2 Links created by a and area elements
3. [265]4.6.3 API for a and area elements
4. [266]4.6.4 Following hyperlinks
5. [267]4.6.5 Downloading resources
6. [268]4.6.6 Hyperlink auditing
1. [269]4.6.6.1 The `Ping-From` and `Ping-To` headers
7. [270]4.6.7 Link types
1. [271]4.6.7.1 Link type "alternate"
2. [272]4.6.7.2 Link type "author"
3. [273]4.6.7.3 Link type "bookmark"
4. [274]4.6.7.4 Link type "canonical"
5. [275]4.6.7.5 Link type "dns-prefetch"
6. [276]4.6.7.6 Link type "expect"
7. [277]4.6.7.7 Link type "external"
8. [278]4.6.7.8 Link type "help"
9. [279]4.6.7.9 Link type "icon"
10. [280]4.6.7.10 Link type "license"
11. [281]4.6.7.11 Link type "manifest"
12. [282]4.6.7.12 Link type "modulepreload"
13. [283]4.6.7.13 Link type "nofollow"
14. [284]4.6.7.14 Link type "noopener"
15. [285]4.6.7.15 Link type "noreferrer"
16. [286]4.6.7.16 Link type "opener"
17. [287]4.6.7.17 Link type "pingback"
18. [288]4.6.7.18 Link type "preconnect"
19. [289]4.6.7.19 Link type "prefetch"
20. [290]4.6.7.20 Link type "preload"
21. [291]4.6.7.21 Link type "privacy-policy"
22. [292]4.6.7.22 Link type "search"
23. [293]4.6.7.23 Link type "stylesheet"
24. [294]4.6.7.24 Link type "tag"
25. [295]4.6.7.25 Link Type "terms-of-service"
26. [296]4.6.7.26 Sequential link types
1. [297]4.6.7.26.1 Link type "next"
2. [298]4.6.7.26.2 Link type "prev"
27. [299]4.6.7.27 Other link types
7. [300]4.7 Edits
1. [301]4.7.1 The ins element
2. [302]4.7.2 The del element
3. [303]4.7.3 Attributes common to ins and del elements
4. [304]4.7.4 Edits and paragraphs
5. [305]4.7.5 Edits and lists
6. [306]4.7.6 Edits and tables
8. [307]4.8 Embedded content
1. [308]4.8.1 The picture element
2. [309]4.8.2 The source element
3. [310]4.8.3 The img element
4. [311]4.8.4 Images
1. [312]4.8.4.1 Introduction
1. [313]4.8.4.1.1 Adaptive images
2. [314]4.8.4.2 Attributes common to source, img, and
link elements
1. [315]4.8.4.2.1 Srcset attributes
2. [316]4.8.4.2.2 Sizes attributes
3. [317]4.8.4.3 Processing model
1. [318]4.8.4.3.1 When to obtain images
2. [319]4.8.4.3.2 Reacting to DOM mutations
3. [320]4.8.4.3.3 The list of available images
4. [321]4.8.4.3.4 Decoding images
5. [322]4.8.4.3.5 Updating the image data
6. [323]4.8.4.3.6 Preparing an image for
presentation
7. [324]4.8.4.3.7 Selecting an image source
8. [325]4.8.4.3.8 Creating a source set from
attributes
9. [326]4.8.4.3.9 Updating the source set
10. [327]4.8.4.3.10 Parsing a srcset attribute
11. [328]4.8.4.3.11 Parsing a sizes attribute
12. [329]4.8.4.3.12 Normalizing the source
densities
13. [330]4.8.4.3.13 Reacting to environment changes
4. [331]4.8.4.4 Requirements for providing text to act
as an alternative for images
1. [332]4.8.4.4.1 General guidelines
2. [333]4.8.4.4.2 A link or button containing
nothing but the image
3. [334]4.8.4.4.3 A phrase or paragraph with an
alternative graphical representation: charts,
diagrams, graphs, maps, illustrations
4. [335]4.8.4.4.4 A short phrase or label with an
alternative graphical representation: icons,
logos
5. [336]4.8.4.4.5 Text that has been rendered to a
graphic for typographical effect
6. [337]4.8.4.4.6 A graphical representation of
some of the surrounding text
7. [338]4.8.4.4.7 Ancillary images
8. [339]4.8.4.4.8 A purely decorative image that
doesn't add any information
9. [340]4.8.4.4.9 A group of images that form a
single larger picture with no links
10. [341]4.8.4.4.10 A group of images that form a
single larger picture with links
11. [342]4.8.4.4.11 A key part of the content
12. [343]4.8.4.4.12 An image not intended for the
user
13. [344]4.8.4.4.13 An image in an email or private
document intended for a specific person who is
known to be able to view images
14. [345]4.8.4.4.14 Guidance for markup generators
15. [346]4.8.4.4.15 Guidance for conformance
checkers
5. [347]4.8.5 The iframe element
6. [348]4.8.6 The embed element
7. [349]4.8.7 The object element
8. [350]4.8.8 The video element
9. [351]4.8.9 The audio element
10. [352]4.8.10 The track element
11. [353]4.8.11 Media elements
1. [354]4.8.11.1 Error codes
2. [355]4.8.11.2 Location of the media resource
3. [356]4.8.11.3 MIME types
4. [357]4.8.11.4 Network states
5. [358]4.8.11.5 Loading the media resource
6. [359]4.8.11.6 Offsets into the media resource
7. [360]4.8.11.7 Ready states
8. [361]4.8.11.8 Playing the media resource
9. [362]4.8.11.9 Seeking
10. [363]4.8.11.10 Media resources with multiple media
tracks
1. [364]4.8.11.10.1 AudioTrackList and
VideoTrackList objects
2. [365]4.8.11.10.2 Selecting specific audio and
video tracks declaratively
11. [366]4.8.11.11 Timed text tracks
1. [367]4.8.11.11.1 Text track model
2. [368]4.8.11.11.2 Sourcing in-band text tracks
3. [369]4.8.11.11.3 Sourcing out-of-band text
tracks
4. [370]4.8.11.11.4 Guidelines for exposing cues
in various formats as text track cues
5. [371]4.8.11.11.5 Text track API
6. [372]4.8.11.11.6 Event handlers for objects of
the text track APIs
7. [373]4.8.11.11.7 Best practices for metadata
text tracks
12. [374]4.8.11.12 Identifying a track kind through a
URL
13. [375]4.8.11.13 User interface
14. [376]4.8.11.14 Time ranges
15. [377]4.8.11.15 The TrackEvent interface
16. [378]4.8.11.16 Events summary
17. [379]4.8.11.17 Security and privacy considerations
18. [380]4.8.11.18 Best practices for authors using
media elements
19. [381]4.8.11.19 Best practices for implementers of
media elements
12. [382]4.8.12 The map element
13. [383]4.8.13 The area element
14. [384]4.8.14 Image maps
1. [385]4.8.14.1 Authoring
2. [386]4.8.14.2 Processing model
15. [387]4.8.15 MathML
16. [388]4.8.16 SVG
17. [389]4.8.17 Dimension attributes
9. [390]4.9 Tabular data
1. [391]4.9.1 The table element
1. [392]4.9.1.1 Techniques for describing tables
2. [393]4.9.1.2 Techniques for table design
2. [394]4.9.2 The caption element
3. [395]4.9.3 The colgroup element
4. [396]4.9.4 The col element
5. [397]4.9.5 The tbody element
6. [398]4.9.6 The thead element
7. [399]4.9.7 The tfoot element
8. [400]4.9.8 The tr element
9. [401]4.9.9 The td element
10. [402]4.9.10 The th element
11. [403]4.9.11 Attributes common to td and th elements
12. [404]4.9.12 Processing model
1. [405]4.9.12.1 Forming a table
2. [406]4.9.12.2 Forming relationships between data
cells and header cells
13. [407]4.9.13 Examples
10. [408]4.10 Forms
1. [409]4.10.1 Introduction
1. [410]4.10.1.1 Writing a form's user interface
2. [411]4.10.1.2 Implementing the server-side
processing for a form
3. [412]4.10.1.3 Configuring a form to communicate with
a server
4. [413]4.10.1.4 Client-side form validation
5. [414]4.10.1.5 Enabling client-side automatic filling
of form controls
6. [415]4.10.1.6 Improving the user experience on
mobile devices
7. [416]4.10.1.7 The difference between the field type,
the autofill field name, and the input modality
8. [417]4.10.1.8 Date, time, and number formats
2. [418]4.10.2 Categories
3. [419]4.10.3 The form element
4. [420]4.10.4 The label element
5. [421]4.10.5 The input element
1. [422]4.10.5.1 States of the type attribute
1. [423]4.10.5.1.1 Hidden state (type=hidden)
2. [424]4.10.5.1.2 Text (type=text) state and
Search state (type=search)
3. [425]4.10.5.1.3 Telephone state (type=tel)
4. [426]4.10.5.1.4 URL state (type=url)
5. [427]4.10.5.1.5 Email state (type=email)
6. [428]4.10.5.1.6 Password state (type=password)
7. [429]4.10.5.1.7 Date state (type=date)
8. [430]4.10.5.1.8 Month state (type=month)
9. [431]4.10.5.1.9 Week state (type=week)
10. [432]4.10.5.1.10 Time state (type=time)
11. [433]4.10.5.1.11 Local Date and Time state
(type=datetime-local)
12. [434]4.10.5.1.12 Number state (type=number)
13. [435]4.10.5.1.13 Range state (type=range)
14. [436]4.10.5.1.14 Color state (type=color)
15. [437]4.10.5.1.15 Checkbox state (type=checkbox)
16. [438]4.10.5.1.16 Radio Button state
(type=radio)
17. [439]4.10.5.1.17 File Upload state (type=file)
18. [440]4.10.5.1.18 Submit Button state
(type=submit)
19. [441]4.10.5.1.19 Image Button state
(type=image)
20. [442]4.10.5.1.20 Reset Button state
(type=reset)
21. [443]4.10.5.1.21 Button state (type=button)
2. [444]4.10.5.2 Implementation notes regarding
localization of form controls
3. [445]4.10.5.3 Common input element attributes
1. [446]4.10.5.3.1 The maxlength and minlength
attributes
2. [447]4.10.5.3.2 The size attribute
3. [448]4.10.5.3.3 The readonly attribute
4. [449]4.10.5.3.4 The required attribute
5. [450]4.10.5.3.5 The multiple attribute
6. [451]4.10.5.3.6 The pattern attribute
7. [452]4.10.5.3.7 The min and max attributes
8. [453]4.10.5.3.8 The step attribute
9. [454]4.10.5.3.9 The list attribute
10. [455]4.10.5.3.10 The placeholder attribute
4. [456]4.10.5.4 Common input element APIs
5. [457]4.10.5.5 Common event behaviors
6. [458]4.10.6 The button element
7. [459]4.10.7 The select element
8. [460]4.10.8 The datalist element
9. [461]4.10.9 The optgroup element
10. [462]4.10.10 The option element
11. [463]4.10.11 The textarea element
12. [464]4.10.12 The output element
13. [465]4.10.13 The progress element
14. [466]4.10.14 The meter element
15. [467]4.10.15 The fieldset element
16. [468]4.10.16 The legend element
17. [469]4.10.17 Form control infrastructure
1. [470]4.10.17.1 A form control's value
2. [471]4.10.17.2 Mutability
3. [472]4.10.17.3 Association of controls and forms
18. [473]4.10.18 Attributes common to form controls
1. [474]4.10.18.1 Naming form controls: the name
attribute
2. [475]4.10.18.2 Submitting element directionality:
the dirname attribute
3. [476]4.10.18.3 Limiting user input length: the
maxlength attribute
4. [477]4.10.18.4 Setting minimum input length
requirements: the minlength attribute
5. [478]4.10.18.5 Enabling and disabling form controls:
the disabled attribute
6. [479]4.10.18.6 Form submission attributes
7. [480]4.10.18.7 Autofill
1. [481]4.10.18.7.1 Autofilling form controls: the
autocomplete attribute
2. [482]4.10.18.7.2 Processing model
19. [483]4.10.19 APIs for the text control selections
20. [484]4.10.20 Constraints
1. [485]4.10.20.1 Definitions
2. [486]4.10.20.2 Constraint validation
3. [487]4.10.20.3 The constraint validation API
4. [488]4.10.20.4 Security
21. [489]4.10.21 Form submission
1. [490]4.10.21.1 Introduction
2. [491]4.10.21.2 Implicit submission
3. [492]4.10.21.3 Form submission algorithm
4. [493]4.10.21.4 Constructing the entry list
5. [494]4.10.21.5 Selecting a form submission encoding
6. [495]4.10.21.6 Converting an entry list to a list of
name-value pairs
7. [496]4.10.21.7 URL-encoded form data
8. [497]4.10.21.8 Multipart form data
9. [498]4.10.21.9 Plain text form data
10. [499]4.10.21.10 The SubmitEvent interface
11. [500]4.10.21.11 The FormDataEvent interface
22. [501]4.10.22 Resetting a form
11. [502]4.11 Interactive elements
1. [503]4.11.1 The details element
2. [504]4.11.2 The summary element
3. [505]4.11.3 Commands
1. [506]4.11.3.1 Facets
2. [507]4.11.3.2 Using the a element to define a
command
3. [508]4.11.3.3 Using the button element to define a
command
4. [509]4.11.3.4 Using the input element to define a
command
5. [510]4.11.3.5 Using the option element to define a
command
6. [511]4.11.3.6 Using the accesskey attribute on a
legend element to define a command
7. [512]4.11.3.7 Using the accesskey attribute to
define a command on other elements
4. [513]4.11.4 The dialog element
5. [514]4.11.5 Dialog light dismiss
12. [515]4.12 Scripting
1. [516]4.12.1 The script element
1. [517]4.12.1.1 Processing model
2. [518]4.12.1.2 Scripting languages
3. [519]4.12.1.3 Restrictions for contents of script
elements
4. [520]4.12.1.4 Inline documentation for external
scripts
5. [521]4.12.1.5 Interaction of script elements and
XSLT
2. [522]4.12.2 The noscript element
3. [523]4.12.3 The template element
1. [524]4.12.3.1 Interaction of template elements with
XSLT and XPath
4. [525]4.12.4 The slot element
5. [526]4.12.5 The canvas element
1. [527]4.12.5.1 The 2D rendering context
1. [528]4.12.5.1.1 Implementation notes
2. [529]4.12.5.1.2 The canvas settings
3. [530]4.12.5.1.3 The canvas state
4. [531]4.12.5.1.4 Line styles
5. [532]4.12.5.1.5 Text styles
6. [533]4.12.5.1.6 Building paths
7. [534]4.12.5.1.7 Path2D objects
8. [535]4.12.5.1.8 Transformations
9. [536]4.12.5.1.9 Image sources for 2D rendering
contexts
10. [537]4.12.5.1.10 Fill and stroke styles
11. [538]4.12.5.1.11 Drawing rectangles to the
bitmap
12. [539]4.12.5.1.12 Drawing text to the bitmap
13. [540]4.12.5.1.13 Drawing paths to the canvas
14. [541]4.12.5.1.14 Drawing focus rings
15. [542]4.12.5.1.15 Drawing images
16. [543]4.12.5.1.16 Pixel manipulation
17. [544]4.12.5.1.17 Compositing
18. [545]4.12.5.1.18 Image smoothing
19. [546]4.12.5.1.19 Shadows
20. [547]4.12.5.1.20 Filters
21. [548]4.12.5.1.21 Working with
externally-defined SVG filters
22. [549]4.12.5.1.22 Drawing model
23. [550]4.12.5.1.23 Best practices
24. [551]4.12.5.1.24 Examples
2. [552]4.12.5.2 The ImageBitmap rendering context
1. [553]4.12.5.2.1 Introduction
2. [554]4.12.5.2.2 The ImageBitmapRenderingContext
interface
3. [555]4.12.5.3 The OffscreenCanvas interface
1. [556]4.12.5.3.1 The offscreen 2D rendering
context
4. [557]4.12.5.4 Color spaces and color space
conversion
5. [558]4.12.5.5 Serializing bitmaps to a file
6. [559]4.12.5.6 Security with canvas elements
7. [560]4.12.5.7 Premultiplied alpha and the 2D
rendering context
13. [561]4.13 Custom elements
1. [562]4.13.1 Introduction
1. [563]4.13.1.1 Creating an autonomous custom element
2. [564]4.13.1.2 Creating a form-associated custom
element
3. [565]4.13.1.3 Creating a custom element with default
accessible roles, states, and properties
4. [566]4.13.1.4 Creating a customized built-in element
5. [567]4.13.1.5 Drawbacks of autonomous custom
elements
6. [568]4.13.1.6 Upgrading elements after their
creation
7. [569]4.13.1.7 Exposing custom element states
2. [570]4.13.2 Requirements for custom element constructors
and reactions
1. [571]4.13.2.1 Preserving custom element state when
moved
3. [572]4.13.3 Core concepts
4. [573]4.13.4 The CustomElementRegistry interface
5. [574]4.13.5 Upgrades
6. [575]4.13.6 Custom element reactions
7. [576]4.13.7 Element internals
1. [577]4.13.7.1 The ElementInternals interface
2. [578]4.13.7.2 Shadow root access
3. [579]4.13.7.3 Form-associated custom elements
4. [580]4.13.7.4 Accessibility semantics
5. [581]4.13.7.5 Custom state pseudo-class
14. [582]4.14 Common idioms without dedicated elements
1. [583]4.14.1 Breadcrumb navigation
2. [584]4.14.2 Tag clouds
3. [585]4.14.3 Conversations
4. [586]4.14.4 Footnotes
15. [587]4.15 Disabled elements
16. [588]4.16 Matching HTML elements using selectors and CSS
1. [589]4.16.1 Case-sensitivity of the CSS 'attr()' function
2. [590]4.16.2 Case-sensitivity of selectors
3. [591]4.16.3 Pseudo-classes
5. [592]5 Microdata
1. [593]5.1 Introduction
1. [594]5.1.1 Overview
2. [595]5.1.2 The basic syntax
3. [596]5.1.3 Typed items
4. [597]5.1.4 Global identifiers for items
5. [598]5.1.5 Selecting names when defining vocabularies
2. [599]5.2 Encoding microdata
1. [600]5.2.1 The microdata model
2. [601]5.2.2 Items
3. [602]5.2.3 Names: the itemprop attribute
4. [603]5.2.4 Values
5. [604]5.2.5 Associating names with items
6. [605]5.2.6 Microdata and other namespaces
3. [606]5.3 Sample microdata vocabularies
1. [607]5.3.1 vCard
1. [608]5.3.1.1 Conversion to vCard
2. [609]5.3.1.2 Examples
2. [610]5.3.2 vEvent
1. [611]5.3.2.1 Conversion to iCalendar
2. [612]5.3.2.2 Examples
3. [613]5.3.3 Licensing works
1. [614]5.3.3.1 Examples
4. [615]5.4 Converting HTML to other formats
1. [616]5.4.1 JSON
6. [617]6 User interaction
1. [618]6.1 The hidden attribute
2. [619]6.2 Page visibility
1. [620]6.2.1 The VisibilityStateEntry interface
3. [621]6.3 Inert subtrees
1. [622]6.3.1 Modal dialogs and inert subtrees
2. [623]6.3.2 The inert attribute
4. [624]6.4 Tracking user activation
1. [625]6.4.1 Data model
2. [626]6.4.2 Processing model
3. [627]6.4.3 APIs gated by user activation
4. [628]6.4.4 The UserActivation interface
5. [629]6.4.5 User agent automation
5. [630]6.5 Activation behavior of elements
1. [631]6.5.1 The ToggleEvent interface
2. [632]6.5.2 The CommandEvent interface
6. [633]6.6 Focus
1. [634]6.6.1 Introduction
2. [635]6.6.2 Data model
3. [636]6.6.3 The tabindex attribute
4. [637]6.6.4 Processing model
5. [638]6.6.5 Sequential focus navigation
6. [639]6.6.6 Focus management APIs
7. [640]6.6.7 The autofocus attribute
7. [641]6.7 Assigning keyboard shortcuts
1. [642]6.7.1 Introduction
2. [643]6.7.2 The accesskey attribute
3. [644]6.7.3 Processing model
8. [645]6.8 Editing
1. [646]6.8.1 Making document regions editable: The
contenteditable content attribute
2. [647]6.8.2 Making entire documents editable: the
designMode getter and setter
3. [648]6.8.3 Best practices for in-page editors
4. [649]6.8.4 Editing APIs
5. [650]6.8.5 Spelling and grammar checking
6. [651]6.8.6 Writing suggestions
7. [652]6.8.7 Autocapitalization
8. [653]6.8.8 Autocorrection
9. [654]6.8.9 Input modalities: the inputmode attribute
10. [655]6.8.10 Input modalities: the enterkeyhint attribute
9. [656]6.9 Find-in-page
1. [657]6.9.1 Introduction
2. [658]6.9.2 Interaction with details and
hidden=until-found
3. [659]6.9.3 Interaction with selection
10. [660]6.10 Close requests and close watchers
1. [661]6.10.1 Close requests
2. [662]6.10.2 Close watcher infrastructure
3. [663]6.10.3 The CloseWatcher interface
11. [664]6.11 Drag and drop
1. [665]6.11.1 Introduction
2. [666]6.11.2 The drag data store
3. [667]6.11.3 The DataTransfer interface
1. [668]6.11.3.1 The DataTransferItemList interface
2. [669]6.11.3.2 The DataTransferItem interface
4. [670]6.11.4 The DragEvent interface
5. [671]6.11.5 Processing model
6. [672]6.11.6 Events summary
7. [673]6.11.7 The draggable attribute
8. [674]6.11.8 Security risks in the drag-and-drop model
12. [675]6.12 The popover attribute
1. [676]6.12.1 The popover target attributes
2. [677]6.12.2 Popover light dismiss
7. [678]7 Loading web pages
1. [679]7.1 Supporting concepts
1. [680]7.1.1 Origins
1. [681]7.1.1.1 Sites
2. [682]7.1.1.2 Relaxing the same-origin restriction
2. [683]7.1.2 Origin-keyed agent clusters
3. [684]7.1.3 Cross-origin opener policies
1. [685]7.1.3.1 The headers
2. [686]7.1.3.2 Browsing context group switches due to
opener policy
3. [687]7.1.3.3 Reporting
4. [688]7.1.4 Cross-origin embedder policies
1. [689]7.1.4.1 The headers
2. [690]7.1.4.2 Embedder policy checks
5. [691]7.1.5 Sandboxing
6. [692]7.1.6 Policy containers
2. [693]7.2 APIs related to navigation and session history
1. [694]7.2.1 Security infrastructure for Window,
WindowProxy, and Location objects
1. [695]7.2.1.1 Integration with IDL
2. [696]7.2.1.2 Shared internal slot:
[[CrossOriginPropertyDescriptorMap]]
3. [697]7.2.1.3 Shared abstract operations
1. [698]7.2.1.3.1 CrossOriginProperties ( O )
2. [699]7.2.1.3.2 CrossOriginPropertyFallback ( P
)
3. [700]7.2.1.3.3 IsPlatformObjectSameOrigin ( O )
4. [701]7.2.1.3.4 CrossOriginGetOwnPropertyHelper
( O, P )
5. [702]7.2.1.3.5 CrossOriginGet ( O, P, Receiver
)
6. [703]7.2.1.3.6 CrossOriginSet ( O, P, V,
Receiver )
7. [704]7.2.1.3.7 CrossOriginOwnPropertyKeys ( O )
2. [705]7.2.2 The Window object
1. [706]7.2.2.1 Opening and closing windows
2. [707]7.2.2.2 Indexed access on the Window object
3. [708]7.2.2.3 Named access on the Window object
4. [709]7.2.2.4 Accessing related windows
5. [710]7.2.2.5 Historical browser interface element
APIs
6. [711]7.2.2.6 Script settings for Window objects
3. [712]7.2.3 The WindowProxy exotic object
1. [713]7.2.3.1 [[GetPrototypeOf]] ( )
2. [714]7.2.3.2 [[SetPrototypeOf]] ( V )
3. [715]7.2.3.3 [[IsExtensible]] ( )
4. [716]7.2.3.4 [[PreventExtensions]] ( )
5. [717]7.2.3.5 [[GetOwnProperty]] ( P )
6. [718]7.2.3.6 [[DefineOwnProperty]] ( P, Desc )
7. [719]7.2.3.7 [[Get]] ( P, Receiver )
8. [720]7.2.3.8 [[Set]] ( P, V, Receiver )
9. [721]7.2.3.9 [[Delete]] ( P )
10. [722]7.2.3.10 [[OwnPropertyKeys]] ( )
4. [723]7.2.4 The Location interface
1. [724]7.2.4.1 [[GetPrototypeOf]] ( )
2. [725]7.2.4.2 [[SetPrototypeOf]] ( V )
3. [726]7.2.4.3 [[IsExtensible]] ( )
4. [727]7.2.4.4 [[PreventExtensions]] ( )
5. [728]7.2.4.5 [[GetOwnProperty]] ( P )
6. [729]7.2.4.6 [[DefineOwnProperty]] ( P, Desc )
7. [730]7.2.4.7 [[Get]] ( P, Receiver )
8. [731]7.2.4.8 [[Set]] ( P, V, Receiver )
9. [732]7.2.4.9 [[Delete]] ( P )
10. [733]7.2.4.10 [[OwnPropertyKeys]] ( )
5. [734]7.2.5 The History interface
6. [735]7.2.6 The navigation API
1. [736]7.2.6.1 Introduction
2. [737]7.2.6.2 The Navigation interface
3. [738]7.2.6.3 Core infrastructure
4. [739]7.2.6.4 Initializing and updating the entry
list
5. [740]7.2.6.5 The NavigationHistoryEntry interface
6. [741]7.2.6.6 The history entry list
7. [742]7.2.6.7 Initiating navigations
8. [743]7.2.6.8 Ongoing navigation tracking
9. [744]7.2.6.9 The NavigationActivation interface
10. [745]7.2.6.10 The navigate event
1. [746]7.2.6.10.1 The NavigateEvent interface
2. [747]7.2.6.10.2 The NavigationDestination
interface
3. [748]7.2.6.10.3 Firing the event
4. [749]7.2.6.10.4 Scroll and focus behavior
7. [750]7.2.7 Event interfaces
1. [751]7.2.7.1 The NavigationCurrentEntryChangeEvent
interface
2. [752]7.2.7.2 The PopStateEvent interface
3. [753]7.2.7.3 The HashChangeEvent interface
4. [754]7.2.7.4 The PageSwapEvent interface
5. [755]7.2.7.5 The PageRevealEvent interface
6. [756]7.2.7.6 The PageTransitionEvent interface
7. [757]7.2.7.7 The BeforeUnloadEvent interface
8. [758]7.2.8 The NotRestoredReasons interface
3. [759]7.3 Infrastructure for sequences of documents
1. [760]7.3.1 Navigables
1. [761]7.3.1.1 Traversable navigables
2. [762]7.3.1.2 Top-level traversables
3. [763]7.3.1.3 Child navigables
4. [764]7.3.1.4 Jake diagrams
5. [765]7.3.1.5 Related navigable collections
6. [766]7.3.1.6 Navigable destruction
7. [767]7.3.1.7 Navigable target names
2. [768]7.3.2 Browsing contexts
1. [769]7.3.2.1 Creating browsing contexts
2. [770]7.3.2.2 Related browsing contexts
3. [771]7.3.2.3 Groupings of browsing contexts
3. [772]7.3.3 Fully active documents
4. [773]7.4 Navigation and session history
1. [774]7.4.1 Session history
1. [775]7.4.1.1 Session history entries
2. [776]7.4.1.2 Document state
3. [777]7.4.1.3 Centralized modifications of session
history
4. [778]7.4.1.4 Low-level operations on session history
2. [779]7.4.2 Navigation
1. [780]7.4.2.1 Supporting concepts
2. [781]7.4.2.2 Beginning navigation
3. [782]7.4.2.3 Ending navigation
1. [783]7.4.2.3.1 The usual cross-document
navigation case
2. [784]7.4.2.3.2 The javascript: URL special case
3. [785]7.4.2.3.3 Fragment navigations
4. [786]7.4.2.3.4 Non-fetch schemes and external
software
4. [787]7.4.2.4 Preventing navigation
5. [788]7.4.2.5 Aborting navigation
3. [789]7.4.3 Reloading and traversing
4. [790]7.4.4 Non-fragment synchronous "navigations"
5. [791]7.4.5 Populating a session history entry
6. [792]7.4.6 Applying the history step
1. [793]7.4.6.1 Updating the traversable
2. [794]7.4.6.2 Updating the document
3. [795]7.4.6.3 Revealing the document
4. [796]7.4.6.4 Scrolling to a fragment
5. [797]7.4.6.5 Persisted history entry state
5. [798]7.5 Document lifecycle
1. [799]7.5.1 Shared document creation infrastructure
2. [800]7.5.2 Loading HTML documents
3. [801]7.5.3 Loading XML documents
4. [802]7.5.4 Loading text documents
5. [803]7.5.5 Loading multipart/x-mixed-replace documents
6. [804]7.5.6 Loading media documents
7. [805]7.5.7 Loading a document for inline content that
doesn't have a DOM
8. [806]7.5.8 Finishing the loading process
9. [807]7.5.9 Unloading documents
10. [808]7.5.10 Destroying documents
11. [809]7.5.11 Aborting a document load
6. [810]7.6 The `X-Frame-Options` header
7. [811]7.7 The `Refresh` header
8. [812]7.8 Browser user interface considerations
8. [813]8 Web application APIs
1. [814]8.1 Scripting
1. [815]8.1.1 Introduction
2. [816]8.1.2 Agents and agent clusters
1. [817]8.1.2.1 Integration with the JavaScript agent
formalism
2. [818]8.1.2.2 Integration with the JavaScript agent
cluster formalism
3. [819]8.1.3 Realms and their counterparts
1. [820]8.1.3.1 Environments
2. [821]8.1.3.2 Environment settings objects
3. [822]8.1.3.3 Realms, settings objects, and global
objects
1. [823]8.1.3.3.1 Entry
2. [824]8.1.3.3.2 Incumbent
3. [825]8.1.3.3.3 Current
4. [826]8.1.3.3.4 Relevant
4. [827]8.1.3.4 Enabling and disabling scripting
5. [828]8.1.3.5 Secure contexts
4. [829]8.1.4 Script processing model
1. [830]8.1.4.1 Scripts
2. [831]8.1.4.2 Fetching scripts
3. [832]8.1.4.3 Creating scripts
4. [833]8.1.4.4 Calling scripts
5. [834]8.1.4.5 Killing scripts
6. [835]8.1.4.6 Runtime script errors
7. [836]8.1.4.7 Unhandled promise rejections
8. [837]8.1.4.8 Import map parse results
5. [838]8.1.5 Module specifier resolution
1. [839]8.1.5.1 The resolution algorithm
2. [840]8.1.5.2 Import maps
3. [841]8.1.5.3 Import map processing model
6. [842]8.1.6 JavaScript specification host hooks
1. [843]8.1.6.1 HostEnsureCanAddPrivateElement(O)
2. [844]8.1.6.2 HostEnsureCanCompileStrings(realm,
parameterStrings, bodyString, codeString,
compilationType, parameterArgs, bodyArg)
3. [845]8.1.6.3 HostGetCodeForEval(argument)
4. [846]8.1.6.4 HostPromiseRejectionTracker(promise,
operation)
5. [847]8.1.6.5 HostSystemUTCEpochNanoseconds(global)
6. [848]8.1.6.6 Job-related host hooks
1. [849]8.1.6.6.1 HostCallJobCallback(callback, V,
argumentsList)
2. [850]8.1.6.6.2
HostEnqueueFinalizationRegistryCleanupJob(final
izationRegistry)
3. [851]8.1.6.6.3 HostEnqueueGenericJob(job,
realm)
4. [852]8.1.6.6.4 HostEnqueuePromiseJob(job,
realm)
5. [853]8.1.6.6.5 HostEnqueueTimeoutJob(job,
realm, milliseconds)
6. [854]8.1.6.6.6 HostMakeJobCallback(callable)
7. [855]8.1.6.7 Module-related host hooks
1. [856]8.1.6.7.1
HostGetImportMetaProperties(moduleRecord)
2. [857]8.1.6.7.2
HostGetSupportedImportAttributes()
3. [858]8.1.6.7.3 HostLoadImportedModule(referrer,
moduleRequest, loadState, payload)
7. [859]8.1.7 Event loops
1. [860]8.1.7.1 Definitions
2. [861]8.1.7.2 Queuing tasks
3. [862]8.1.7.3 Processing model
4. [863]8.1.7.4 Generic task sources
5. [864]8.1.7.5 Dealing with the event loop from other
specifications
8. [865]8.1.8 Events
1. [866]8.1.8.1 Event handlers
2. [867]8.1.8.2 Event handlers on elements, Document
objects, and Window objects
1. [868]8.1.8.2.1 IDL definitions
3. [869]8.1.8.3 Event firing
2. [870]8.2 The WindowOrWorkerGlobalScope mixin
3. [871]8.3 Base64 utility methods
4. [872]8.4 Dynamic markup insertion
1. [873]8.4.1 Opening the input stream
2. [874]8.4.2 Closing the input stream
3. [875]8.4.3 document.write()
4. [876]8.4.4 document.writeln()
5. [877]8.5 DOM parsing and serialization APIs
1. [878]8.5.1 The DOMParser interface
2. [879]8.5.2 Unsafe HTML parsing methods
3. [880]8.5.3 HTML serialization methods
4. [881]8.5.4 The innerHTML property
5. [882]8.5.5 The outerHTML property
6. [883]8.5.6 The insertAdjacentHTML() method
7. [884]8.5.7 The createContextualFragment() method
8. [885]8.5.8 The XMLSerializer interface
6. [886]8.6 Timers
7. [887]8.7 Microtask queuing
8. [888]8.8 User prompts
1. [889]8.8.1 Simple dialogs
2. [890]8.8.2 Printing
9. [891]8.9 System state and capabilities
1. [892]8.9.1 The Navigator object
1. [893]8.9.1.1 Client identification
2. [894]8.9.1.2 Language preferences
3. [895]8.9.1.3 Browser state
4. [896]8.9.1.4 Custom scheme handlers: the
registerProtocolHandler() method
1. [897]8.9.1.4.1 Security and privacy
2. [898]8.9.1.4.2 User agent automation
5. [899]8.9.1.5 Cookies
6. [900]8.9.1.6 PDF viewing support
10. [901]8.10 Images
11. [902]8.11 Animation frames
9. [903]9 Communication
1. [904]9.1 The MessageEvent interface
2. [905]9.2 Server-sent events
1. [906]9.2.1 Introduction
2. [907]9.2.2 The EventSource interface
3. [908]9.2.3 Processing model
4. [909]9.2.4 The `Last-Event-ID` header
5. [910]9.2.5 Parsing an event stream
6. [911]9.2.6 Interpreting an event stream
7. [912]9.2.7 Authoring notes
8. [913]9.2.8 Connectionless push and other features
9. [914]9.2.9 Garbage collection
10. [915]9.2.10 Implementation advice
3. [916]9.3 Cross-document messaging
1. [917]9.3.1 Introduction
2. [918]9.3.2 Security
1. [919]9.3.2.1 Authors
2. [920]9.3.2.2 User agents
3. [921]9.3.3 Posting messages
4. [922]9.4 Channel messaging
1. [923]9.4.1 Introduction
1. [924]9.4.1.1 Examples
2. [925]9.4.1.2 Ports as the basis of an
object-capability model on the web
3. [926]9.4.1.3 Ports as the basis of abstracting out
service implementations
2. [927]9.4.2 Message channels
3. [928]9.4.3 The MessageEventTarget mixin
4. [929]9.4.4 Message ports
5. [930]9.4.5 Ports and garbage collection
5. [931]9.5 Broadcasting to other browsing contexts
10. [932]10 Web workers
1. [933]10.1 Introduction
1. [934]10.1.1 Scope
2. [935]10.1.2 Examples
1. [936]10.1.2.1 A background number-crunching worker
2. [937]10.1.2.2 Using a JavaScript module as a worker
3. [938]10.1.2.3 Shared workers introduction
4. [939]10.1.2.4 Shared state using a shared worker
5. [940]10.1.2.5 Delegation
6. [941]10.1.2.6 Providing libraries
3. [942]10.1.3 Tutorials
1. [943]10.1.3.1 Creating a dedicated worker
2. [944]10.1.3.2 Communicating with a dedicated worker
3. [945]10.1.3.3 Shared workers
2. [946]10.2 Infrastructure
1. [947]10.2.1 The global scope
1. [948]10.2.1.1 The WorkerGlobalScope common interface
2. [949]10.2.1.2 Dedicated workers and the
DedicatedWorkerGlobalScope interface
3. [950]10.2.1.3 Shared workers and the
SharedWorkerGlobalScope interface
2. [951]10.2.2 The event loop
3. [952]10.2.3 The worker's lifetime
4. [953]10.2.4 Processing model
5. [954]10.2.5 Runtime script errors
6. [955]10.2.6 Creating workers
1. [956]10.2.6.1 The AbstractWorker mixin
2. [957]10.2.6.2 Script settings for workers
3. [958]10.2.6.3 Dedicated workers and the Worker
interface
4. [959]10.2.6.4 Shared workers and the SharedWorker
interface
7. [960]10.2.7 Concurrent hardware capabilities
3. [961]10.3 APIs available to workers
1. [962]10.3.1 Importing scripts and libraries
2. [963]10.3.2 The WorkerNavigator interface
3. [964]10.3.3 The WorkerLocation interface
11. [965]11 Worklets
1. [966]11.1 Introduction
1. [967]11.1.1 Motivations
2. [968]11.1.2 Code idempotence
3. [969]11.1.3 Speculative evaluation
2. [970]11.2 Examples
1. [971]11.2.1 Loading scripts
2. [972]11.2.2 Registering a class and invoking its methods
3. [973]11.3 Infrastructure
1. [974]11.3.1 The global scope
1. [975]11.3.1.1 Agents and event loops
2. [976]11.3.1.2 Creation and termination
3. [977]11.3.1.3 Script settings for worklets
2. [978]11.3.2 The Worklet class
3. [979]11.3.3 The worklet's lifetime
12. [980]12 Web storage
1. [981]12.1 Introduction
2. [982]12.2 The API
1. [983]12.2.1 The Storage interface
2. [984]12.2.2 The sessionStorage getter
3. [985]12.2.3 The localStorage getter
4. [986]12.2.4 The StorageEvent interface
3. [987]12.3 Privacy
1. [988]12.3.1 User tracking
2. [989]12.3.2 Sensitivity of data
4. [990]12.4 Security
1. [991]12.4.1 DNS spoofing attacks
2. [992]12.4.2 Cross-directory attacks
3. [993]12.4.3 Implementation risks
13. [994]13 The HTML syntax
1. [995]13.1 Writing HTML documents
1. [996]13.1.1 The DOCTYPE
2. [997]13.1.2 Elements
1. [998]13.1.2.1 Start tags
2. [999]13.1.2.2 End tags
3. [1000]13.1.2.3 Attributes
4. [1001]13.1.2.4 Optional tags
5. [1002]13.1.2.5 Restrictions on content models
6. [1003]13.1.2.6 Restrictions on the contents of raw
text and escapable raw text elements
3. [1004]13.1.3 Text
1. [1005]13.1.3.1 Newlines
4. [1006]13.1.4 Character references
5. [1007]13.1.5 CDATA sections
6. [1008]13.1.6 Comments
2. [1009]13.2 Parsing HTML documents
1. [1010]13.2.1 Overview of the parsing model
2. [1011]13.2.2 Parse errors
3. [1012]13.2.3 The input byte stream
1. [1013]13.2.3.1 Parsing with a known character
encoding
2. [1014]13.2.3.2 Determining the character encoding
3. [1015]13.2.3.3 Character encodings
4. [1016]13.2.3.4 Changing the encoding while parsing
5. [1017]13.2.3.5 Preprocessing the input stream
4. [1018]13.2.4 Parse state
1. [1019]13.2.4.1 The insertion mode
2. [1020]13.2.4.2 The stack of open elements
3. [1021]13.2.4.3 The list of active formatting
elements
4. [1022]13.2.4.4 The element pointers
5. [1023]13.2.4.5 Other parsing state flags
5. [1024]13.2.5 Tokenization
1. [1025]13.2.5.1 Data state
2. [1026]13.2.5.2 RCDATA state
3. [1027]13.2.5.3 RAWTEXT state
4. [1028]13.2.5.4 Script data state
5. [1029]13.2.5.5 PLAINTEXT state
6. [1030]13.2.5.6 Tag open state
7. [1031]13.2.5.7 End tag open state
8. [1032]13.2.5.8 Tag name state
9. [1033]13.2.5.9 RCDATA less-than sign state
10. [1034]13.2.5.10 RCDATA end tag open state
11. [1035]13.2.5.11 RCDATA end tag name state
12. [1036]13.2.5.12 RAWTEXT less-than sign state
13. [1037]13.2.5.13 RAWTEXT end tag open state
14. [1038]13.2.5.14 RAWTEXT end tag name state
15. [1039]13.2.5.15 Script data less-than sign state
16. [1040]13.2.5.16 Script data end tag open state
17. [1041]13.2.5.17 Script data end tag name state
18. [1042]13.2.5.18 Script data escape start state
19. [1043]13.2.5.19 Script data escape start dash state
20. [1044]13.2.5.20 Script data escaped state
21. [1045]13.2.5.21 Script data escaped dash state
22. [1046]13.2.5.22 Script data escaped dash dash state
23. [1047]13.2.5.23 Script data escaped less-than sign
state
24. [1048]13.2.5.24 Script data escaped end tag open
state
25. [1049]13.2.5.25 Script data escaped end tag name
state
26. [1050]13.2.5.26 Script data double escape start
state
27. [1051]13.2.5.27 Script data double escaped state
28. [1052]13.2.5.28 Script data double escaped dash
state
29. [1053]13.2.5.29 Script data double escaped dash dash
state
30. [1054]13.2.5.30 Script data double escaped less-than
sign state
31. [1055]13.2.5.31 Script data double escape end state
32. [1056]13.2.5.32 Before attribute name state
33. [1057]13.2.5.33 Attribute name state
34. [1058]13.2.5.34 After attribute name state
35. [1059]13.2.5.35 Before attribute value state
36. [1060]13.2.5.36 Attribute value (double-quoted)
state
37. [1061]13.2.5.37 Attribute value (single-quoted)
state
38. [1062]13.2.5.38 Attribute value (unquoted) state
39. [1063]13.2.5.39 After attribute value (quoted) state
40. [1064]13.2.5.40 Self-closing start tag state
41. [1065]13.2.5.41 Bogus comment state
42. [1066]13.2.5.42 Markup declaration open state
43. [1067]13.2.5.43 Comment start state
44. [1068]13.2.5.44 Comment start dash state
45. [1069]13.2.5.45 Comment state
46. [1070]13.2.5.46 Comment less-than sign state
47. [1071]13.2.5.47 Comment less-than sign bang state
48. [1072]13.2.5.48 Comment less-than sign bang dash
state
49. [1073]13.2.5.49 Comment less-than sign bang dash
dash state
50. [1074]13.2.5.50 Comment end dash state
51. [1075]13.2.5.51 Comment end state
52. [1076]13.2.5.52 Comment end bang state
53. [1077]13.2.5.53 DOCTYPE state
54. [1078]13.2.5.54 Before DOCTYPE name state
55. [1079]13.2.5.55 DOCTYPE name state
56. [1080]13.2.5.56 After DOCTYPE name state
57. [1081]13.2.5.57 After DOCTYPE public keyword state
58. [1082]13.2.5.58 Before DOCTYPE public identifier
state
59. [1083]13.2.5.59 DOCTYPE public identifier
(double-quoted) state
60. [1084]13.2.5.60 DOCTYPE public identifier
(single-quoted) state
61. [1085]13.2.5.61 After DOCTYPE public identifier
state
62. [1086]13.2.5.62 Between DOCTYPE public and system
identifiers state
63. [1087]13.2.5.63 After DOCTYPE system keyword state
64. [1088]13.2.5.64 Before DOCTYPE system identifier
state
65. [1089]13.2.5.65 DOCTYPE system identifier
(double-quoted) state
66. [1090]13.2.5.66 DOCTYPE system identifier
(single-quoted) state
67. [1091]13.2.5.67 After DOCTYPE system identifier
state
68. [1092]13.2.5.68 Bogus DOCTYPE state
69. [1093]13.2.5.69 CDATA section state
70. [1094]13.2.5.70 CDATA section bracket state
71. [1095]13.2.5.71 CDATA section end state
72. [1096]13.2.5.72 Character reference state
73. [1097]13.2.5.73 Named character reference state
74. [1098]13.2.5.74 Ambiguous ampersand state
75. [1099]13.2.5.75 Numeric character reference state
76. [1100]13.2.5.76 Hexadecimal character reference
start state
77. [1101]13.2.5.77 Decimal character reference start
state
78. [1102]13.2.5.78 Hexadecimal character reference
state
79. [1103]13.2.5.79 Decimal character reference state
80. [1104]13.2.5.80 Numeric character reference end
state
6. [1105]13.2.6 Tree construction
1. [1106]13.2.6.1 Creating and inserting nodes
2. [1107]13.2.6.2 Parsing elements that contain only
text
3. [1108]13.2.6.3 Closing elements that have implied
end tags
4. [1109]13.2.6.4 The rules for parsing tokens in HTML
content
1. [1110]13.2.6.4.1 The "initial" insertion mode
2. [1111]13.2.6.4.2 The "before html" insertion
mode
3. [1112]13.2.6.4.3 The "before head" insertion
mode
4. [1113]13.2.6.4.4 The "in head" insertion mode
5. [1114]13.2.6.4.5 The "in head noscript"
insertion mode
6. [1115]13.2.6.4.6 The "after head" insertion
mode
7. [1116]13.2.6.4.7 The "in body" insertion mode
8. [1117]13.2.6.4.8 The "text" insertion mode
9. [1118]13.2.6.4.9 The "in table" insertion mode
10. [1119]13.2.6.4.10 The "in table text" insertion
mode
11. [1120]13.2.6.4.11 The "in caption" insertion
mode
12. [1121]13.2.6.4.12 The "in column group"
insertion mode
13. [1122]13.2.6.4.13 The "in table body" insertion
mode
14. [1123]13.2.6.4.14 The "in row" insertion mode
15. [1124]13.2.6.4.15 The "in cell" insertion mode
16. [1125]13.2.6.4.16 The "in select" insertion
mode
17. [1126]13.2.6.4.17 The "in select in table"
insertion mode
18. [1127]13.2.6.4.18 The "in template" insertion
mode
19. [1128]13.2.6.4.19 The "after body" insertion
mode
20. [1129]13.2.6.4.20 The "in frameset" insertion
mode
21. [1130]13.2.6.4.21 The "after frameset"
insertion mode
22. [1131]13.2.6.4.22 The "after after body"
insertion mode
23. [1132]13.2.6.4.23 The "after after frameset"
insertion mode
5. [1133]13.2.6.5 The rules for parsing tokens in
foreign content
7. [1134]13.2.7 The end
8. [1135]13.2.8 Speculative HTML parsing
9. [1136]13.2.9 Coercing an HTML DOM into an infoset
10. [1137]13.2.10 An introduction to error handling and
strange cases in the parser
1. [1138]13.2.10.1 Misnested tags:
2. [1139]13.2.10.2 Misnested tags:
3. [1140]13.2.10.3 Unexpected markup in tables
4. [1141]13.2.10.4 Scripts that modify the page as it
is being parsed
5. [1142]13.2.10.5 The execution of scripts that are
moving across multiple documents
6. [1143]13.2.10.6 Unclosed formatting elements
3. [1144]13.3 Serializing HTML fragments
4. [1145]13.4 Parsing HTML fragments
5. [1146]13.5 Named character references
14. [1147]14 The XML syntax
1. [1148]14.1 Writing documents in the XML syntax
2. [1149]14.2 Parsing XML documents
3. [1150]14.3 Serializing XML fragments
4. [1151]14.4 Parsing XML fragments
15. [1152]15 Rendering
1. [1153]15.1 Introduction
2. [1154]15.2 The CSS user agent style sheet and presentational
hints
3. [1155]15.3 Non-replaced elements
1. [1156]15.3.1 Hidden elements
2. [1157]15.3.2 The page
3. [1158]15.3.3 Flow content
4. [1159]15.3.4 Phrasing content
5. [1160]15.3.5 Bidirectional text
6. [1161]15.3.6 Sections and headings
7. [1162]15.3.7 Lists
8. [1163]15.3.8 Tables
9. [1164]15.3.9 Margin collapsing quirks
10. [1165]15.3.10 Form controls
11. [1166]15.3.11 The hr element
12. [1167]15.3.12 The fieldset and legend elements
4. [1168]15.4 Replaced elements
1. [1169]15.4.1 Embedded content
2. [1170]15.4.2 Images
3. [1171]15.4.3 Attributes for embedded content and images
4. [1172]15.4.4 Image maps
5. [1173]15.5 Widgets
1. [1174]15.5.1 Native appearance
2. [1175]15.5.2 Writing mode
3. [1176]15.5.3 Button layout
4. [1177]15.5.4 The button element
5. [1178]15.5.5 The details and summary elements
6. [1179]15.5.6 The input element as a text entry widget
7. [1180]15.5.7 The input element as domain-specific widgets
8. [1181]15.5.8 The input element as a range control
9. [1182]15.5.9 The input element as a color well
10. [1183]15.5.10 The input element as a checkbox and radio
button widgets
11. [1184]15.5.11 The input element as a file upload control
12. [1185]15.5.12 The input element as a button
13. [1186]15.5.13 The marquee element
14. [1187]15.5.14 The meter element
15. [1188]15.5.15 The progress element
16. [1189]15.5.16 The select element
17. [1190]15.5.17 The textarea element
6. [1191]15.6 Frames and framesets
7. [1192]15.7 Interactive media
1. [1193]15.7.1 Links, forms, and navigation
2. [1194]15.7.2 The title attribute
3. [1195]15.7.3 Editing hosts
4. [1196]15.7.4 Text rendered in native user interfaces
8. [1197]15.8 Print media
9. [1198]15.9 Unstyled XML documents
16. [1199]16 Obsolete features
1. [1200]16.1 Obsolete but conforming features
1. [1201]16.1.1 Warnings for obsolete but conforming
features
2. [1202]16.2 Non-conforming features
3. [1203]16.3 Requirements for implementations
1. [1204]16.3.1 The marquee element
2. [1205]16.3.2 Frames
3. [1206]16.3.3 Other elements, attributes and APIs
17. [1207]17 IANA considerations
1. [1208]17.1 text/html
2. [1209]17.2 multipart/x-mixed-replace
3. [1210]17.3 application/xhtml+xml
4. [1211]17.4 text/ping
5. [1212]17.5 application/microdata+json
6. [1213]17.6 text/event-stream
7. [1214]17.7 web+ scheme prefix
18. [1215]Index
1. [1216]Elements
2. [1217]Element content categories
3. [1218]Attributes
4. [1219]Element interfaces
5. [1220]All interfaces
6. [1221]Events
7. [1222]HTTP headers
8. [1223]MIME types
19. [1224]References
20. [1225]Acknowledgments
21. [1226]Intellectual property rights
1 Introduction
1.1 Where does this specification fit?
This specification defines a big part of the web platform, in lots of
detail. Its place in the web platform specification stack relative to
other specifications can be best summed up as follows:
CSS SVG MathML Service Workers IDB Fetch CSP AV1 Opus PNG THIS
SPECIFICATION HTTP TLS DOM Unicode Web IDL MIME URL XML JavaScript
Encoding
1.2 Is this HTML5?
This section is non-normative.
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. This document is one such; others are
available from [1227]the WHATWG Standards overview.
1.3 Background
This section is non-normative.
HTML is the World Wide Web's core markup language. Originally, HTML was
primarily designed as a language for semantically describing scientific
documents. Its general design, however, has enabled it to be adapted,
over the subsequent years, to describe a number of other types of
documents and even applications.
1.4 Audience
This section is non-normative.
This specification is intended for authors of documents and scripts
that use the features defined in this specification, implementers of
tools that operate on pages that use the features defined in this
specification, and individuals wishing to establish the correctness of
documents or implementations with respect to the requirements of 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 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.
1.5 Scope
This section is non-normative.
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 (email clients, instant messaging clients, discussion
software), document editing software, etc.
1.6 History
This section is non-normative.
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
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 evolution; the W3C staff and membership voted
to continue developing XML-based 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.
In 2019, the WHATWG and W3C [1228]signed an agreement to collaborate on
a single version of HTML going forward: this document.
1.7 Design notes
This section is non-normative.
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.
1.7.1 Serializability of script execution
This section is non-normative.
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 [1229]workers,
the intent is that the behavior of implementations can be thought of as
completely serializing the execution of all scripts in all globals.
The exception to this general design principle is the JavaScript
[1230]SharedArrayBuffer class. Using [1231]SharedArrayBuffer objects,
it can in fact be observed that scripts in other [1232]agents are
executing simultaneously. Furthermore, due to the JavaScript memory
model, there are situations which not only are un-representable via
serialized script execution, but also un-representable via serialized
statement execution among those scripts.
1.7.2 Extensibility
This section is non-normative.
HTML has a wide array of extensibility mechanisms that can be used for
adding semantics in a safe manner:
* Authors can use the [1233]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 [1234]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 [1235] mechanism to
include page-wide metadata.
* Authors can use the [1236]rel="" mechanism to annotate links with
specific meanings by registering [1237]extensions to the predefined
set of link types. This is also used by microformats.
* Authors can embed raw data using the [1238]
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 [1341]a element in the tree above) can have its "[1342]href"
attribute changed in several ways:
var a = [1343]document.[1344]links[0]; // obtain the first link in the document
a.[1345]href = ʼsample.htmlʼ; // change the destination URL of the link
a.[1346]protocol = ʼhttpsʼ; // change just the scheme part of the URL
a.setAttribute(ʼhrefʼ, ʼhttps://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 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.
Sample styled page
Sample styled page
This page is just a demo.
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.
1.10.1 Writing secure applications with HTML
This section is non-normative.
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
cross-origin actions. [1347][ORIGIN]
Not validating user input
Cross-site scripting (XSS)
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 safelist-based, allowing known-safe
constructs and disallowing all other input. Blocklist-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:
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 code. Here are some that authors are
encouraged to consider when writing safelist filters:
+ When allowing harmless-seeming elements like [1348]img, it is
important to safelist any provided attributes as well. If one
allowed all attributes then an attacker could, for instance,
use the [1349]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 safelisted, as there
are many schemes that can be abused. The most prominent
example is "[1350]javascript:", but user agents can implement
(and indeed, have historically implemented) others.
+ Allowing a [1351]base element to be inserted means any
[1352]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 `[1353]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 [1354]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 [1355]window
object to the value of the [1356]top attribute).
1.10.2 Common pitfalls to avoid when using the scripting APIs
This section is non-normative.
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 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 [1357]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 [1358]img elements and the
[1359]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 [1360]onload handler on an [1361]img element
to catch the [1362]load 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:
However, if the author first created the [1363]img element and then in
a separate script added the event listeners, there's a chance that the
[1364]load event would be fired in between, leading it to be missed:
1.10.3 How to catch mistakes when writing HTML: validators and conformance
checkers
This section is non-normative.
Authors are encouraged to make use of conformance checkers (also known
as validators) to catch common mistakes. The WHATWG maintains a list of
such tools at: [1365]https://whatwg.org/validator/
1.11 Conformance requirements for authors
This section is non-normative.
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
well-defined, 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.
1.11.1 Presentational markup
This section is non-normative.
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.
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. users of 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 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
[1366]style attribute and the [1367]style element. Use of the
[1368]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 [1369]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: [1370]b, [1371]i, [1372]hr, [1373]s, [1374]small,
and [1375]u.
1.11.2 Syntax errors
This section is non-normative.
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 highly unintuitive.
For example, the following markup fragment results in a DOM with
an [1376]hr element that is an earlier sibling of the
corresponding [1377]table element:
...
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 [1378]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
... 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 element or attribute names never contain multiple colons,
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. (Comments containing two consecutive hyphens, or ending
with a hyphen, are exceptions that are allowed in the HTML
syntax.)
Errors that result in disproportionately poor performance
Certain syntax constructs can result in disproportionately poor
performance. To discourage the use of such constructs, they are
typically made non-conforming.
For example, the following markup results in poor performance,
since all the unclosed [1379]i elements have to be reconstructed
in each paragraph, resulting in progressively more elements in
each paragraph:
She dreamt.
She dreamt that she ate breakfast.
Then lunch.
And finally dinner.
The resulting DOM for this fragment would be:
+ [1380]p
o [1381]i
# [1382]#text: She dreamt.
+ [1383]p
o [1384]i
# [1385]i
@ [1386]#text: She dreamt that she ate breakfast.
+ [1387]p
o [1388]i
# [1389]i
@ [1390]i
- [1391]#text: Then lunch.
+ [1392]p
o [1393]i
# [1394]i
@ [1395]i
- [1396]i
= [1397]#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":
To avoid this problem, all named character references are
required to end 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:
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 [1398]no-quirks mode, because the behavior of legacy
user agents in [1399]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. [1400][UTF7]
Cases where the author's intent is unclear
Markup where the author's intent is very unclear is often made
non-conforming. Correcting these errors early makes later
maintenance easier.
For example, it is unclear whether the author intended the
following to be an [1401]h1 heading or an [1402]h2 heading:
Contact details
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, and so forth, that do not
match the names defined in this specification.
For example, if the author typed instead of
,
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.
1.11.3 Restrictions on content models and on attribute values
This section is non-normative.
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
[1403]section element inside a [1404]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 separator cannot simultaneously be a cell, nor
can a radio button be a progress bar.
Another example is the restrictions on the content models of the
[1405]ul element, which only allows [1406]li element children.
Lists by definition consist just of zero or more list items, so
if a [1407]ul element contains something other than an [1408]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, [1409]div elements are rendered as [1410]block
boxes, and [1411]span elements as [1412]inline boxes. Putting a
[1413]block box in an [1414]inline box is unnecessarily
confusing; since either nesting just [1415]div elements, or
nesting just [1416]span elements, or nesting [1417]span elements
inside [1418]div elements all serve the same purpose as nesting
a [1419]div element in a [1420]span element, but only the latter
involves a [1421]block box in an [1422]inline box, the latter
combination is disallowed.
Another example would be the way [1423]interactive content
cannot be nested. For example, a [1424]button element cannot
contain a [1425]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 [1426]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.
For example, the [1427]area element's [1428]shape attribute,
despite accepting both [1429]circ and [1430]circle values in
practice as synonyms, disallows the use of the [1431]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 [1432]form element isn't allowed inside
[1433]phrasing content, because when parsed as HTML, a
[1434]form element's start tag will imply a [1435]p element's
end tag. Thus, the following markup results in two
[1436]paragraphs, not one:
Welcome.
It is parsed exactly like the following:
Welcome.
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
[1437]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 [1438]script element's [1439]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 non-conforming to have executable script in a
[1440]script element when the [1441]src attribute is present.
This means that authors who are validating their documents are
less likely to waste time with this kind of mistake.
Errors that involve areas that affect authors migrating between the
HTML and XML syntaxes
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 the HTML and XML
syntaxes.
For example, there are somewhat complicated rules surrounding
the [1442]lang and [1443]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 [1444]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 query
lists use only valid media query lists reinforces the importance
of following the conformance rules of that specification.
1.12 Suggested reading
This section is non-normative.
The following documents might be of interest to readers of this
specification.
Character Model for the World Wide Web 1.0: Fundamentals
[1445][CHARMOD]
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 [1446][UTR36]
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) [1447][WCAG]
Web Content Accessibility Guidelines (WCAG) 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.
This specification provides guidelines for designing web content
authoring tools that are more accessible for people with
disabilities. An authoring tool that conforms to these guidelines
will promote accessibility by providing an accessible user interface
to authors with disabilities as well as by enabling, supporting, and
promoting the production of accessible web content by all authors.
User Agent Accessibility Guidelines (UAAG) 2.0 [1449][UAAG]
This document provides guidelines for designing user agents that
lower barriers to web accessibility for people with disabilities.
User agents include browsers and other types of software that
retrieve and render web content. A user agent that conforms to these
guidelines will promote accessibility through its own user interface
and through other internal facilities, including its ability to
communicate with other technologies (especially assistive
technologies). Furthermore, all users, not just users with
disabilities, should find conforming user agents to be more usable.
2 Common infrastructure
This specification depends on Infra. [1450][INFRA]
2.1 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
[1451]the HTML syntax or [1452]the XML 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
XML)".
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 [1453]Document objects and their
descendant DOM trees, and to serialized byte streams using the
[1454]HTML syntax or the [1455]XML syntax, depending on context.
In the context of the DOM structures, the terms [1456]HTML document and
[1457]XML document are used as defined in DOM, and refer specifically
to two different modes that [1458]Document objects can find themselves
in. [1459][DOM] (Such uses are always hyperlinked to their definition.)
In the context of byte streams, the term HTML document refers to
resources labeled as [1460]text/html, and the term XML document refers
to resources labeled with an [1461]XML MIME type.
__________________________________________________________________
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.
2.1.1 Parallelism
To run steps in parallel means those steps are to be run, one after
another, at the same time as other logic in the standard (e.g., at the
same time as the [1462]event loop). This standard does not define the
precise mechanism by which this is achieved, be it time-sharing
cooperative multitasking, fibers, threads, processes, using different
hyperthreads, cores, CPUs, machines, etc. By contrast, an operation
that is to run immediately must interrupt the currently running task,
run itself, and then resume the previously running task.
For guidance on writing specifications that leverage parallelism, see
[1463]Dealing with the event loop from other specifications.
To avoid race conditions between different [1464]in parallel algorithms
that operate on the same data, a [1465]parallel queue can be used.
A parallel queue represents a queue of algorithm steps that must be run
in series.
A [1466]parallel queue has an algorithm queue (a [1467]queue),
initially empty.
To enqueue steps to a [1468]parallel queue, [1469]enqueue the algorithm
steps to the [1470]parallel queue's [1471]algorithm queue.
To start a new parallel queue, run the following steps:
1. Let parallelQueue be a new [1472]parallel queue.
2. Run the following steps [1473]in parallel:
1. While true:
1. Let steps be the result of [1474]dequeueing from
parallelQueue's [1475]algorithm queue.
2. If steps is not nothing, then run steps.
3. [1476]Assert: running steps did not throw an exception,
as steps running [1477]in parallel are not allowed to
throw.
Implementations are not expected to implement this as a
continuously running loop. Algorithms in standards are to be
easy to understand and are not necessarily great for battery
life or performance.
3. Return parallelQueue.
Steps running [1478]in parallel can themselves run other steps in
[1479]in parallel. E.g., inside a [1480]parallel queue it can be useful
to run a series of steps in parallel with the queue.
Imagine a standard defined nameList (a [1481]list), along with a method
to add a name to nameList, unless nameList already [1482]contains name,
in which case it rejects.
The following solution suffers from race conditions:
1. Let p be a new promise created in [1483]this's [1484]relevant
realm.
2. Let global be [1485]this's [1486]relevant global object.
3. Run the following steps [1487]in parallel:
1. If nameList [1488]contains name, then [1489]queue a global
task on the [1490]DOM manipulation task source given global to
reject p with a [1491]TypeError, and abort these steps.
2. Do some potentially lengthy work.
3. [1492]Append name to nameList.
4. [1493]Queue a global task on the [1494]DOM manipulation task
source given global to resolve p with undefined.
4. Return p.
Two invocations of the above could run simultaneously, meaning name
isn't in nameList during step 2.1, but it might be added before step
2.3 runs, meaning name ends up in nameList twice.
Parallel queues solve this. The standard would let nameListQueue be the
result of [1495]starting a new parallel queue, then:
1. Let p be a new promise created in [1496]this's [1497]relevant
realm.
2. Let global be [1498]this's [1499]relevant global object.
3. [1500]Enqueue the following steps to nameListQueue:
1. If nameList [1501]contains name, then [1502]queue a global
task on the [1503]DOM manipulation task source given global to
reject p with a [1504]TypeError, and abort these steps.
2. Do some potentially lengthy work.
3. [1505]Append name to nameList.
4. [1506]Queue a global task on the [1507]DOM manipulation task
source given global to resolve p with undefined.
4. Return p.
The steps would now queue and the race is avoided.
2.1.2 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.
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 specifications, refer
to as a representation is referred to in this specification as a
resource. [1508][HTTP]
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.
For [1509]CSS style sheets, we tentatively define here that their
critical subresources are other style sheets imported via @import
rules, including those indirectly imported by other imported style
sheets.
This definition is not fully interoperable; furthermore, some user
agents seem to count resources like background images or web fonts as
critical subresources. Ideally, the CSS Working Group would define
this; see [1510]w3c/csswg-drafts issue #1088 to track progress on that
front.
2.1.3 XML compatibility
To ease migration from HTML to XML, user agents conforming to this
specification will place elements in HTML in the
[1511]http://www.w3.org/1999/xhtml namespace, at least for the purposes
of the DOM and CSS. The term "HTML elements" refers to any element in
that namespace, even in XML documents.
Except where otherwise stated, all elements defined or mentioned in
this specification are in the [1512]HTML namespace
("http://www.w3.org/1999/xhtml"), and all attributes defined or
mentioned in this specification have no namespace.
The term element type is used to refer to the set of elements that have
a given local name and namespace. For example, [1513]button elements
are elements with the element type [1514]button, meaning they have the
local name "button" and (implicitly as defined above) the [1515]HTML
namespace.
Attribute names are said to be XML-compatible if they match the
[1516]Name production defined in XML and they contain no U+003A COLON
characters (:). [1517][XML]
2.1.4 DOM trees
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
user agent must not mutate the DOM in such situations.
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 for an attribute value, [1518]Text node, or
string, means that the [1519]length of the text is zero (i.e., not even
containing [1520]controls or U+0020 SPACE).
An HTML element can have specific HTML element insertion steps, HTML
element post-connection steps, HTML element removing steps, and HTML
element moving steps all defined for the element's [1521]local name.
The [1522]insertion steps for the HTML Standard, given insertedNode,
are defined as the following:
1. If insertedNode is an element whose [1523]namespace is the
[1524]HTML namespace, and this standard defines [1525]HTML element
insertion steps for insertedNode's [1526]local name, then run the
corresponding [1527]HTML element insertion steps given
insertedNode.
2. If insertedNode is a [1528]form-associated element or the ancestor
of a [1529]form-associated element, then:
1. If the [1530]form-associated element's [1531]parser inserted
flag is set, then return.
2. [1532]Reset the form owner of the [1533]form-associated
element.
3. If insertedNode is an [1534]Element that is not on the [1535]stack
of open elements of an [1536]HTML parser, then [1537]process
internal resource links given insertedNode's [1538]node document.
The [1539]post-connection steps for the HTML Standard, given
insertedNode, are defined as the following:
1. If insertedNode is an element whose [1540]namespace is the
[1541]HTML namespace, and this standard defines [1542]HTML element
post-connection steps for insertedNode's [1543]local name, then run
the corresponding [1544]HTML element post-connection steps given
insertedNode.
The [1545]removing steps for the HTML Standard, given removedNode and
oldParent, are defined as the following:
1. Let document be removedNode's [1546]node document.
2. If document's [1547]focused area is removedNode, then set
document's [1548]focused area to document's [1549]viewport, and set
document's [1550]relevant global object's [1551]navigation API's
[1552]focus changed during ongoing navigation to false.
This does not perform the [1553]unfocusing steps, [1554]focusing
steps, or [1555]focus update steps, and thus no [1556]blur or
[1557]change events are fired.
3. If removedNode is an element whose [1558]namespace is the
[1559]HTML namespace, and this standard defines [1560]HTML element
removing steps for removedNode's [1561]local name, then run the
corresponding [1562]HTML element removing steps given removedNode
and oldParent.
4. If removedNode is a [1563]form-associated element or the ancestor
of a [1564]form-associated element, then:
1. If the [1565]form-associated element has a [1566]form owner
and the [1567]form-associated element and its [1568]form owner
are no longer in the same [1569]tree, then [1570]reset the
form owner of the [1571]form-associated element.
5. If removedNode's [1572]popover attribute is not in the [1573]no
popover state, then run the [1574]hide popover algorithm given
removedNode, false, false, and false.
The [1575]moving steps for the HTML Standard, given movedNode, are
defined as the following:
1. If movedNode is an element whose [1576]namespace is the [1577]HTML
namespace, and this standard defines [1578]HTML element moving
steps for movedNode's [1579]local name, then run the corresponding
[1580]HTML element moving steps given movedNode.
2. If movedNode is a [1581]form-associated element or the ancestor of
a [1582]form-associated element, then:
1. If the [1583]form-associated element has a [1584]form owner
and the [1585]form-associated element and its [1586]form owner
are no longer in the same [1587]tree, then [1588]reset the
form owner of the [1589]form-associated element.
A node is inserted into a document when the [1590]insertion steps are
invoked with it as the argument and it is now [1591]in a document tree.
Analogously, a node is removed from a document when the [1592]removing
steps are invoked with it as the argument and it is now no longer
[1593]in a document tree.
A node becomes connected when the [1594]insertion steps are invoked
with it as the argument and it is now [1595]connected. Analogously, a
node becomes disconnected when the [1596]removing steps are invoked
with it as the argument and it is now no longer [1597]connected.
A node is browsing-context connected when it is [1598]connected and its
[1599]shadow-including root's [1600]browsing context is non-null. A
node becomes browsing-context connected when the [1601]insertion steps
are invoked with it as the argument and it is now
[1602]browsing-context connected. A node becomes browsing-context
disconnected either when the [1603]removing steps are invoked with it
as the argument and it is now no longer [1604]browsing-context
connected, or when its [1605]shadow-including root's [1606]browsing
context becomes null.
2.1.5 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 must operate on the actual underlying data, not a snapshot
of the data.
2.1.6 Plugins
The term plugin refers to an [1607]implementation-defined set of
content handlers used by the user agent that can take part in the user
agent's rendering of a [1608]Document object, but that neither act as
[1609]child navigables of the [1610]Document nor introduce any
[1611]Node objects to the [1612]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.
A user agent must not consider the types [1613]text/plain and
[1614]application/octet-stream as having a registered [1615]plugin.
One example of a plugin would be a PDF viewer that is instantiated in a
[1616]navigable 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. [1617][NPAPI]
Browsers should take extreme care when interacting with external
content intended for [1618]plugins. When third-party software is run
with the same privileges as the user agent itself, vulnerabilities in
the third-party software become as dangerous as those in the user
agent.
[1619](This is a tracking vector.) Since different users having
different sets of [1620]plugins provides a tracking vector that
increases the chances of users being uniquely identified, user agents
are encouraged to support the exact same set of [1621]plugins for each
user.
2.1.7 Character encodings
A [1622]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 Encoding. An [1623]encoding has an
[1624]encoding name and one or more [1625]encoding labels, referred to
as the encoding's name and labels in the Encoding standard.
[1626][ENCODING]
2.1.8 Conformance classes
This specification describes the conformance criteria for user agents
(relevant to implementers) and documents (relevant to authors and
authoring tool implementers).
Conforming documents are those that comply with all the conformance
criteria for documents. For readability, some of these conformance
requirements are phrased as conformance requirements on authors; such
requirements are implicitly requirements on documents: by definition,
all documents are assumed to have had an author. (In some cases, that
author may itself be a user agent — such user agents are subject to
additional rules, as explained below.)
For example, if a requirement states that "authors must not use the
foobar element", it would imply that documents are not allowed to
contain elements named foobar.
There is no implied relationship between document conformance
requirements and implementation conformance requirements. User agents
are not free to handle non-conformant documents as they please; the
processing model described in this specification applies to
implementations regardless of the conformity of the input documents.
User agents fall into several (overlapping) categories with different
conformance requirements.
Web browsers and other interactive user agents
Web browsers that support [1627]the XML syntax must process
elements and attributes from the [1628]HTML namespace found in
XML documents as described in this specification, so that users
can interact with them, unless the semantics of those elements
have been overridden by other specifications.
A conforming web browser would, upon finding a [1629]script
element in an XML document, execute the script contained in that
element. However, if the element is found within a
transformation expressed in XSLT (assuming the user agent also
supports XSLT), then the processor would instead treat the
[1630]script element as an opaque element that forms part of the
transform.
Web browsers that support [1631]the HTML syntax must process
documents labeled with an [1632]HTML MIME type as described in
this specification, so that users can interact with them.
User agents that support scripting must also be conforming
implementations of the IDL fragments in this specification, as
described in Web IDL. [1633][WEBIDL]
Unless explicitly stated, specifications that override the
semantics of HTML elements do not override the requirements on
DOM objects representing those elements. For example, the
[1634]script element in the example above would still implement
the [1635]HTMLScriptElement interface.
Non-interactive presentation user agents
User agents that process HTML and XML documents purely to render
non-interactive versions of them must comply to the same
conformance criteria as web browsers, except that they are
exempt from requirements regarding user interaction.
Typical examples of non-interactive presentation user agents are
printers (static UAs) and overhead displays (dynamic UAs). It is
expected that most static non-interactive presentation user
agents will also opt to [1636]lack scripting support.
A non-interactive but dynamic presentation UA would still
execute scripts, allowing forms to be dynamically submitted, and
so forth. However, since the concept of "focus" is irrelevant
when the user cannot interact with the document, the UA would
not need to support any of the focus-related DOM APIs.
Visual user agents that support the suggested default rendering
User agents, whether interactive or not, may be designated
(possibly as a user option) as supporting the suggested default
rendering defined by this specification.
This is not required. In particular, even user agents that do
implement the suggested default rendering are encouraged to
offer settings that override this default to improve the
experience for the user, e.g. changing the color contrast, using
different focus styles, or otherwise making the experience more
accessible and usable to the user.
User agents that are designated as supporting the suggested
default rendering must, while so designated, implement the rules
[1637]the Rendering section defines as the behavior that user
agents are expected to implement.
User agents with no scripting support
Implementations that do not support scripting (or which have
their scripting features disabled entirely) are exempt from
supporting the events and DOM interfaces mentioned in this
specification. For the parts of this specification that are
defined in terms of an events model or in terms of the DOM, such
user agents must still act as if events and the DOM were
supported.
Scripting can form an integral part of an application. Web
browsers that do not support scripting, or that have scripting
disabled, might be unable to fully convey the author's intent.
Conformance checkers
Conformance checkers must verify that a document conforms to the
applicable conformance criteria described in this specification.
Automated conformance checkers are exempt from detecting errors
that require interpretation of the author's intent (for example,
while a document is non-conforming if the content of a
[1638]blockquote element is not a quote, conformance checkers
running without the input of human judgement do not have to
check that [1639]blockquote elements only contain quoted
material).
Conformance checkers must check that the input document conforms
when parsed without a [1640]browsing context (meaning that no
scripts are run, and that the parser's [1641]scripting flag is
disabled), and should also check that the input document
conforms when parsed with a [1642]browsing context in which
scripts execute, and that the scripts never cause non-conforming
states to occur other than transiently during script execution
itself. (This is only a "SHOULD" and not a "MUST" requirement
because it has been proven to be impossible. [1643][COMPUTABLE])
The term "HTML validator" can be used to refer to a conformance
checker that itself conforms to the applicable requirements of
this specification.
XML DTDs cannot express all the conformance requirements of this
specification. Therefore, a validating XML processor and a DTD
cannot constitute a conformance checker. Also, since neither of
the two authoring formats defined in this specification are
applications of SGML, a validating SGML system cannot constitute
a conformance checker either.
To put it another way, there are three types of conformance
criteria:
1. Criteria that can be expressed in a DTD.
2. Criteria that cannot be expressed by a DTD, but can still be
checked by a machine.
3. Criteria that can only be checked by a human.
A conformance checker must check for the first two. A simple
DTD-based validator only checks for the first class of errors
and is therefore not a conforming conformance checker according
to this specification.
Data mining tools
Applications and tools that process HTML and XML documents for
reasons other than to either render the documents or check them
for conformance should act in accordance with the semantics of
the documents that they process.
A tool that generates [1644]document outlines but increases the
nesting level for each paragraph and does not increase the
nesting level for [1645]headings would not be conforming.
Authoring tools and markup generators
Authoring tools and markup generators must generate
[1646]conforming documents. Conformance criteria that apply to
authors also apply to authoring tools, where appropriate.
Authoring tools are exempt from the strict requirements of using
elements only for their specified purpose, but only to the
extent that authoring tools are not yet able to determine author
intent. However, authoring tools must not automatically misuse
elements or encourage their users to do so.
For example, it is not conforming to use an [1647]address
element for arbitrary contact information; that element can only
be used for marking up contact information for its nearest
[1648]article or [1649]body element ancestor. However, since an
authoring tool is likely unable to determine the difference, an
authoring tool is exempt from that requirement. This does not
mean, though, that authoring tools can use [1650]address
elements for any block of italics text (for instance); it just
means that the authoring tool doesn't have to verify that when
the user uses a tool for inserting contact information for an
[1651]article element, that the user really is doing that and
not inserting something else instead.
In terms of conformance checking, an editor has to output
documents that conform to the same extent that a conformance
checker will verify.
When an authoring tool is used to edit a non-conforming
document, it may preserve the conformance errors in sections of
the document that were not edited during the editing session
(i.e. an editing tool is allowed to round-trip erroneous
content). However, an authoring tool must not claim that the
output is conformant if errors have been so preserved.
Authoring tools are expected to come in two broad varieties:
tools that work from structure or semantic data, and tools that
work on a What-You-See-Is-What-You-Get media-specific editing
basis (WYSIWYG).
The former is the preferred mechanism for tools that author
HTML, since the structure in the source information can be used
to make informed choices regarding which HTML elements and
attributes are most appropriate.
However, WYSIWYG tools are legitimate. WYSIWYG tools should use
elements they know are appropriate, and should not use elements
that they do not know to be appropriate. This might in certain
extreme cases mean limiting the use of flow elements to just a
few elements, like [1652]div, [1653]b, [1654]i, and [1655]span
and making liberal use of the [1656]style attribute.
All authoring tools, whether WYSIWYG or not, should make a best
effort attempt at enabling users to create well-structured,
semantically rich, media-independent content.
For compatibility with existing content and prior specifications, this
specification describes two authoring formats: one based on [1657]XML,
and one using a [1658]custom format inspired by SGML (referred to as
[1659]the HTML syntax). Implementations must support at least one of
these two formats, although supporting both is encouraged.
Some conformance requirements are phrased as requirements on elements,
attributes, methods or objects. Such requirements fall into two
categories: those describing content model restrictions, and those
describing implementation behavior. Those in the former category are
requirements on documents and authoring tools. Those in the second
category are requirements on user agents. Similarly, some conformance
requirements are phrased as requirements on authors; such requirements
are to be interpreted as conformance requirements on the documents that
authors produce. (In other words, this specification does not
distinguish between conformance criteria on authors and conformance
criteria on documents.)
2.1.9 Dependencies
This specification relies on several other underlying specifications.
Infra
The following terms are defined in Infra: [1660][INFRA]
+ The general iteration terms [1661]while, [1662]continue, and
[1663]break.
+ [1664]Assert
+ [1665]implementation-defined
+ [1666]willful violation
+ [1667]tracking vector
+ [1668]code point and its synonym [1669]character
+ [1670]surrogate
+ [1671]scalar value
+ [1672]tuple
+ [1673]noncharacter
+ [1674]string, [1675]code unit, [1676]code unit prefix,
[1677]code unit less than, [1678]starts with, [1679]ends with,
[1680]length, and [1681]code point length
+ The string equality operations [1682]is and [1683]identical to
+ [1684]scalar value string
+ [1685]convert
+ [1686]ASCII string
+ [1687]ASCII tab or newline
+ [1688]ASCII whitespace
+ [1689]control
+ [1690]ASCII digit
+ [1691]ASCII upper hex digit
+ [1692]ASCII lower hex digit
+ [1693]ASCII hex digit
+ [1694]ASCII upper alpha
+ [1695]ASCII lower alpha
+ [1696]ASCII alpha
+ [1697]ASCII alphanumeric
+ [1698]isomorphic decode
+ [1699]isomorphic encode
+ [1700]ASCII lowercase
+ [1701]ASCII uppercase
+ [1702]ASCII case-insensitive
+ [1703]strip newlines
+ [1704]normalize newlines
+ [1705]strip leading and trailing ASCII whitespace
+ [1706]strip and collapse ASCII whitespace
+ [1707]split a string on ASCII whitespace
+ [1708]split a string on commas
+ [1709]collect a sequence of code points and its associated
[1710]position variable
+ [1711]skip ASCII whitespace
+ The [1712]ordered map data structure and the associated
definitions for [1713]key, [1714]value, [1715]empty,
[1716]entry, [1717]exists, [1718]getting the value of an
entry, [1719]setting the value of an entry, [1720]removing an
entry, [1721]clear, [1722]getting the keys, [1723]getting the
values, [1724]sorting in descending order, [1725]size, and
[1726]iterate
+ The [1727]list data structure and the associated definitions
for [1728]append, [1729]extend, [1730]prepend, [1731]replace,
[1732]remove, [1733]empty, [1734]contains, [1735]size,
[1736]indices, [1737]is empty, [1738]item, [1739]iterate, and
[1740]clone [1741]sort in ascending order [1742]sort in
descending order
+ The [1743]stack data structure and the associated definitions
for [1744]push and [1745]pop
+ The [1746]queue data structure and the associated definitions
for [1747]enqueue and [1748]dequeue
+ The [1749]ordered set data structure and the associated
definition for [1750]append and [1751]union
+ The [1752]struct specification type and the associated
definition for [1753]item
+ The [1754]byte sequence data structure
+ The [1755]forgiving-base64 encode and [1756]forgiving-base64
decode algorithms
+ [1757]exclusive range
+ [1758]parse a JSON string to an Infra value
+ [1759]HTML namespace
+ [1760]MathML namespace
+ [1761]SVG namespace
+ [1762]XLink namespace
+ [1763]XML namespace
+ [1764]XMLNS namespace
Unicode and Encoding
The Unicode character set is used to represent textual data, and
Encoding defines requirements around [1765]character encodings.
[1766][UNICODE]
This specification [1767]introduces terminology based on the
terms defined in those specifications, as described earlier.
The following terms are used as defined in Encoding:
[1768][ENCODING]
+ [1769]Getting an encoding
+ [1770]Get an output encoding
+ The generic [1771]decode algorithm which takes a byte stream
and an encoding and returns a character stream
+ The [1772]UTF-8 decode algorithm which takes a byte stream and
returns a character stream, additionally stripping one leading
UTF-8 Byte Order Mark (BOM), if any
+ The [1773]UTF-8 decode without BOM algorithm which is
identical to [1774]UTF-8 decode except that it does not strip
one leading UTF-8 Byte Order Mark (BOM)
+ The [1775]encode algorithm which takes a character stream and
an encoding and returns a byte stream
+ The [1776]UTF-8 encode algorithm which takes a character
stream and returns a byte stream
+ The [1777]BOM sniff algorithm which takes a byte stream and
returns an encoding or null.
XML and related specifications
Implementations that support [1778]the XML syntax for HTML must
support some version of XML, as well as its corresponding
namespaces specification, because that syntax uses an XML
serialization with namespaces. [1779][XML] [1780][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 namespace strings.
In [1781]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.
___________________________________________________________
The attribute with the name [1782]space in the [1783]XML
namespace is defined by Extensible Markup Language (XML).
[1784][XML]
The [1785]Name production is defined in XML. [1786][XML]
This specification also references the [1787]
processing instruction, defined in Associating Style Sheets with
XML documents. [1788][XMLSSPI]
This specification also non-normatively mentions the
XSLTProcessor interface and its transformToFragment() and
transformToDocument() methods. [1789][XSLTP]
URLs
The following terms are defined in URL: [1790][URL]
+ [1791]host
+ [1792]public suffix
+ [1793]domain
+ [1794]IP address
+ [1795]URL
+ [1796]Origin of URLs
+ [1797]Absolute URL
+ [1798]Relative URL
+ [1799]registrable domain
+ The [1800]URL parser
+ The [1801]basic URL parser and its [1802]url and [1803]state
override arguments, as well as these parser states:
o [1804]scheme start state
o [1805]host state
o [1806]hostname state
o [1807]port state
o [1808]path start state
o [1809]query state
o [1810]fragment state
+ [1811]URL record, as well as its individual components:
o [1812]scheme
o [1813]username
o [1814]password
o [1815]host
o [1816]port
o [1817]path
o [1818]query
o [1819]fragment
o [1820]blob URL entry
+ [1821]valid URL string
+ The [1822]cannot have a username/password/port concept
+ The [1823]opaque path concept
+ [1824]URL serializer and its [1825]exclude fragment argument
+ [1826]URL path serializer
+ The [1827]host parser
+ The [1828]host serializer
+ [1829]Host equals
+ [1830]URL equals and its [1831]exclude fragments argument
+ [1832]serialize an integer
+ [1833]Default encode set
+ [1834]component percent-encode set
+ [1835]UTF-8 percent-encode
+ [1836]percent-decode
+ [1837]set the username
+ [1838]set the password
+ The [1839]application/x-www-form-urlencoded format
+ The [1840]application/x-www-form-urlencoded serializer
+ [1841]is special
A number of schemes and protocols are referenced by this
specification also:
+ The [1842]about: scheme [1843][ABOUT]
+ The [1844]blob: scheme [1845][FILEAPI]
+ The [1846]data: scheme [1847][RFC2397]
+ The [1848]http: scheme [1849][HTTP]
+ The [1850]https: scheme [1851][HTTP]
+ The [1852]mailto: scheme [1853][MAILTO]
+ The [1854]sms: scheme [1855][SMS]
+ The [1856]urn: scheme [1857][URN]
[1858]Media fragment syntax is defined in Media Fragments URI.
[1859][MEDIAFRAG]
HTTP and related specifications
The following terms are defined in the HTTP specifications:
[1860][HTTP]
The following terms are defined in MIME Sniffing:
[1882][MIMESNIFF]
+ [1883]MIME type
+ [1884]MIME type essence
+ [1885]valid MIME type string
+ [1886]valid MIME type string with no parameters
+ [1887]HTML MIME type
+ [1888]JavaScript MIME type and [1889]JavaScript MIME type
essence match
+ [1890]JSON MIME type
+ [1891]XML MIME type
+ [1892]image MIME type
+ [1893]audio or video MIME type
+ [1894]font MIME type
+ [1895]parse a MIME type
+ [1896]is MIME type supported by the user agent?
Fetch
The following terms are defined in Fetch: [1897][FETCH]
+ [1898]ABNF
+ about:blank
+ An [1899]HTTP(S) scheme
+ A URL which [1900]is local
+ A [1901]local scheme
+ A [1902]fetch scheme
+ [1903]CORS protocol
+ [1904]default `User-Agent` value
+ [1905]extract a MIME type
+ [1906]legacy extract an encoding
+ [1907]fetch
+ [1908]fetch controller
+ [1909]process the next manual redirect
+ [1910]ok status
+ [1911]navigation request
+ [1912]network error
+ [1913]aborted network error
+ `[1914]Origin` header
+ `[1915]Cross-Origin-Resource-Policy` header
+ [1916]getting a structured field value
+ [1917]header list
+ [1918]set
+ [1919]get, decode, and split
+ [1920]abort
+ [1921]cross-origin resource policy check
+ the [1922]RequestCredentials enumeration
+ the [1923]RequestDestination enumeration
+ the [1924]fetch() method
+ [1925]report timing
+ [1926]serialize a response URL for reporting
+ [1927]safely extracting a body
+ [1928]incrementally reading a body
+ [1929]processResponseConsumeBody
+ [1930]processResponseEndOfBody
+ [1931]processResponse
+ [1932]useParallelQueue
+ [1933]processEarlyHintsResponse
+ [1934]connection pool
+ [1935]obtain a connection
+ [1936]determine the network partition key
+ [1937]extract full timing info
+ [1938]as a body
+ [1939]response body info
+ [1940]resolve an origin
+ [1941]response and its associated:
o [1942]type
o [1943]URL
o [1944]URL list
o [1945]status
o [1946]header list
o [1947]body
o [1948]body info
o [1949]internal response
o [1950]location URL
o [1951]timing info
o [1952]service worker timing info
o [1953]has-cross-origin-redirects
o [1954]timing allow passed
o [1955]extract content-range values
+ [1956]request and its associated:
o [1957]URL
o [1958]method
o [1959]header list
o [1960]body
o [1961]client
o [1962]URL list
o [1963]current URL
o [1964]reserved client
o [1965]replaces client id
o [1966]initiator
o [1967]destination
o [1968]potential destination
o [1969]translating a [1970]potential destination
o [1971]script-like [1972]destinations
o [1973]priority
o [1974]origin
o [1975]referrer
o [1976]synchronous flag
o [1977]mode
o [1978]credentials mode
o [1979]use-URL-credentials flag
o [1980]unsafe-request flag
o [1981]cache mode
o [1982]redirect count
o [1983]redirect mode
o [1984]policy container
o [1985]referrer policy
o [1986]cryptographic nonce metadata
o [1987]integrity metadata
o [1988]parser metadata
o [1989]reload-navigation flag
o [1990]history-navigation flag
o [1991]user-activation
o [1992]render-blocking
o [1993]initiator type
o [1994]add a range header
+ [1995]fetch timing info and its associated:
o [1996]start time
o [1997]end time
The following terms are defined in Referrer Policy:
[1998][REFERRERPOLICY]
+ [1999]referrer policy
+ The `[2000]Referrer-Policy` HTTP header
+ The [2001]parse a referrer policy from a `Referrer-Policy`
header algorithm
+ The "[2002]no-referrer", "[2003]no-referrer-when-downgrade",
"[2004]origin-when-cross-origin", and "[2005]unsafe-url"
referrer policies
+ The [2006]default referrer policy
The following terms are defined in Mixed Content: [2007][MIX]
+ [2008]a priori authenticated URL
The following terms are defined in Subresource Integrity:
[2009][SRI]
+ [2010]parse integrity metadata
+ [2011]the requirements of the integrity attribute
+ [2012]get the strongest metadata from set
Paint Timing
The following terms are defined in Paint Timing:
[2013][PAINTTIMING]
+ [2014]mark paint timing
Navigation Timing
The following terms are defined in Navigation Timing:
[2015][NAVIGATIONTIMING]
+ [2016]create the navigation timing entry
+ [2017]queue the navigation timing entry
+ [2018]NavigationTimingType and its "[2019]navigate",
"[2020]reload", and "[2021]back_forward" values.
Resource Timing
The following terms are defined in Resource Timing:
[2022][RESOURCETIMING]
+ [2023]Mark resource timing
Performance Timeline
The following terms are defined in Performance Timeline:
[2024][PERFORMANCETIMELINE]
+ [2025]PerformanceEntry and its [2026]name, [2027]entryType,
[2028]startTime, and [2029]duration attributes.
+ [2030]Queue a performance entry
Long Animation Frames
The following terms are defined in Long Animation Frames:
[2031][LONGANIMATIONFRAMES]
+ [2032]record task start time
+ [2033]record task end time
+ [2034]record rendering time
+ [2035]record classic script creation time
+ [2036]record classic script execution start time
+ [2037]record module script execution start time
+ [2038]Record pause duration
+ [2039]record timing info for timer handler
+ [2040]record timing info for microtask checkpoint
Long Tasks
The following terms are defined in Long Tasks: [2041][LONGTASKS]
+ [2042]report long tasks
Web IDL
The IDL fragments in this specification must be interpreted as
required for conforming IDL fragments, as described in Web IDL.
[2043][WEBIDL]
The following terms are defined in Web IDL:
+ [2044]this
+ [2045]extended attribute
+ [2046]named constructor
+ [2047]constructor operation
+ [2048]overridden constructor steps
+ [2049]internally create a new object implementing the
interface
+ [2050]array index property name
+ [2051]buffer source byte length
+ [2052]supports indexed properties
+ [2053]supported property indices
+ [2054]determine the value of an indexed property
+ [2055]set the value of an existing indexed property
+ [2056]set the value of a new indexed property
+ [2057]support named properties
+ [2058]supported property names
+ [2059]determine the value of a named property
+ [2060]set the value of an existing named property
+ [2061]set the value of a new named property
+ [2062]delete an existing named property
+ [2063]perform a security check
+ [2064]platform object
+ [2065]legacy platform object
+ [2066]primary interface
+ [2067]interface object
+ [2068]named properties object
+ [2069]include
+ [2070]inherit
+ [2071]interface prototype object
+ [2072]implements
+ [2073]associated realm
+ [2074][[Realm]] field of a platform object
+ [2075][[GetOwnProperty]] internal method of a named properties
object
+ [2076]callback context
+ [2077]frozen array and [2078]creating a frozen array
+ [2079]create a new object implementing the interface
+ [2080]callback this value
+ [2081]converting between Web IDL types and JS types
+ [2082]invoking and [2083]constructing callback functions
+ [2084]overload resolution algorithm
+ [2085]exposed
+ [2086]a promise resolved with
+ [2087]a promise rejected with
+ [2088]wait for all
+ [2089]upon rejection
+ [2090]upon fulfillment
+ [2091]mark as handled
+ [2092][Global]
+ [2093][LegacyFactoryFunction]
+ [2094][LegacyLenientThis]
+ [2095][LegacyNullToEmptyString]
+ [2096][LegacyOverrideBuiltIns]
+ [2097]LegacyPlatformObjectGetOwnProperty
+ [2098][LegacyTreatNonObjectAsNull]
+ [2099][LegacyUnenumerableNamedProperties]
+ [2100][LegacyUnforgeable]
+ [2101]set entries
Web IDL also defines the following types that are used in Web
IDL fragments in this specification:
The term [2118]throw in this specification is used as defined in
Web IDL. The [2119]DOMException type and the following exception
names are defined by Web IDL and used by this specification:
When this specification requires a user agent to create a Date
object representing a particular time (which could be the
special value Not-a-Number), the milliseconds component of that
time, if any, must be truncated to an integer, and the time
value of the newly created [2136]Date object must represent the
resulting truncated time.
For instance, given the time 23045 millionths of a second after
01:00 UTC on January 1st 2000, i.e. the time
2000-01-01T00:00:00.023045Z, then the [2137]Date object created
representing that time would represent the same time as that
created representing the time 2000-01-01T00:00:00.023Z, 45
millionths earlier. If the given time is NaN, then the result is
a [2138]Date object that represents a time value NaN (indicating
that the object does not represent a specific instant of time).
JavaScript
Some parts of the language described by this specification only
support JavaScript as the underlying scripting language.
[2139][JAVASCRIPT]
The term "JavaScript" is used to refer to ECMA-262, rather than
the official term ECMAScript, since the term JavaScript is more
widely known.
The following terms are defined in the JavaScript specification
and used in this specification:
+ [2140]active function object
+ [2141]agent and [2142]agent cluster
+ [2143]automatic semicolon insertion
+ [2144]candidate execution
+ The [2145]current realm
+ [2146]clamping a mathematical value
+ [2147]early error
+ [2148]forward progress
+ [2149]invariants of the essential internal methods
+ [2150]JavaScript execution context
+ [2151]JavaScript execution context stack
+ [2152]realm
+ [2153]JobCallback Record
+ [2154]NewTarget
+ [2155]running JavaScript execution context
+ [2156]surrounding agent
+ [2157]abstract closure
+ [2158]immutable prototype exotic object
+ [2159]Well-Known Symbols, including %Symbol.hasInstance%,
%Symbol.isConcatSpreadable%, %Symbol.toPrimitive%, and
%Symbol.toStringTag%
+ [2160]Well-Known Intrinsic Objects, including
[2161]%Array.prototype%, [2162]%Error.prototype%,
%EvalError.prototype%, [2163]%Function.prototype%,
[2164]%Object.prototype%, [2165]%Object.prototype.valueOf%,
%RangeError.prototype%, %ReferenceError.prototype%,
%SyntaxError.prototype%, %TypeError.prototype%, and
%URIError.prototype%
+ The [2166]FunctionBody production
+ The [2167]Module production
+ The [2168]Pattern production
+ The [2169]Script production
+ The [2170]BigInt, [2171]Boolean, [2172]Number, [2173]String,
[2174]Symbol, and [2175]Object ECMAScript language types
+ The [2176]Completion Record specification type
+ The [2177]List and [2178]Record specification types
+ The [2179]Property Descriptor specification type
+ The [2180]ModuleRequest Record specification type
+ The [2181]Script Record specification type
+ The [2182]Synthetic Module Record specification type
+ The [2183]Cyclic Module Record specification type
+ The [2184]Source Text Module Record specification type and its
[2185]Evaluate, [2186]Link and [2187]LoadRequestedModules
methods
+ The [2188]ArrayCreate abstract operation
+ The [2189]Call abstract operation
+ The [2190]ClearKeptObjects abstract operation
+ The [2191]CleanupFinalizationRegistry abstract operation
+ The [2192]Construct abstract operation
+ The [2193]CopyDataBlockBytes abstract operation
+ The [2194]CreateBuiltinFunction abstract operation
+ The [2195]CreateByteDataBlock abstract operation
+ The [2196]CreateDataProperty abstract operation
+ The [2197]CreateDefaultExportSyntheticModule abstract
operation
+ The [2198]DefinePropertyOrThrow abstract operation
+ The [2199]DetachArrayBuffer abstract operation
+ The [2200]EnumerableOwnProperties abstract operation
+ The [2201]FinishLoadingImportedModule abstract operation
+ The [2202]OrdinaryFunctionCreate abstract operation
+ The [2203]Get abstract operation
+ The [2204]GetActiveScriptOrModule abstract operation
+ The [2205]GetFunctionRealm abstract operation
+ The [2206]HasOwnProperty abstract operation
+ The [2207]HostCallJobCallback abstract operation
+ The [2208]HostEnqueueFinalizationRegistryCleanupJob abstract
operation
+ The [2209]HostEnqueueGenericJob abstract operation
+ The [2210]HostEnqueuePromiseJob abstract operation
+ The [2211]HostEnqueueTimeoutJob abstract operation
+ The [2212]HostEnsureCanAddPrivateElement abstract operation
+ The [2213]HostGetSupportedImportAttributes abstract operation
+ The [2214]HostLoadImportedModule abstract operation
+ The [2215]HostMakeJobCallback abstract operation
+ The [2216]HostPromiseRejectionTracker abstract operation
+ The [2217]InitializeHostDefinedRealm abstract operation
+ The [2218]IsArrayBufferViewOutOfBounds abstract operation
+ The [2219]IsAccessorDescriptor abstract operation
+ The [2220]IsCallable abstract operation
+ The [2221]IsConstructor abstract operation
+ The [2222]IsDataDescriptor abstract operation
+ The [2223]IsDetachedBuffer abstract operation
+ The [2224]IsSharedArrayBuffer abstract operation
+ The [2225]NewObjectEnvironment abstract operation
+ The [2226]NormalCompletion abstract operation
+ The [2227]OrdinaryGetPrototypeOf abstract operation
+ The [2228]OrdinarySetPrototypeOf abstract operation
+ The [2229]OrdinaryIsExtensible abstract operation
+ The [2230]OrdinaryPreventExtensions abstract operation
+ The [2231]OrdinaryGetOwnProperty abstract operation
+ The [2232]OrdinaryDefineOwnProperty abstract operation
+ The [2233]OrdinaryGet abstract operation
+ The [2234]OrdinarySet abstract operation
+ The [2235]OrdinaryDelete abstract operation
+ The [2236]OrdinaryOwnPropertyKeys abstract operation
+ The [2237]OrdinaryObjectCreate abstract operation
+ The [2238]ParseJSONModule abstract operation
+ The [2239]ParseModule abstract operation
+ The [2240]ParseScript abstract operation
+ The [2241]NewPromiseReactionJob abstract operation
+ The [2242]NewPromiseResolveThenableJob abstract operation
+ The [2243]RegExpBuiltinExec abstract operation
+ The [2244]RegExpCreate abstract operation
+ The [2245]RunJobs abstract operation
+ The [2246]SameValue abstract operation
+ The [2247]ScriptEvaluation abstract operation
+ The [2248]SetSyntheticModuleExport abstract operation
+ The [2249]SetImmutablePrototype abstract operation
+ The [2250]ToBoolean abstract operation
+ The [2251]ToString abstract operation
+ The [2252]ToUint32 abstract operation
+ The [2253]TypedArrayCreate abstract operation
+ The [2254]IsLooselyEqual abstract operation
+ The [2255]IsStrictlyEqual abstract operation
+ The [2256]Atomics object
+ The [2257]Atomics.waitAsync object
+ The [2258]Date class
+ The [2259]FinalizationRegistry class
+ The [2260]RegExp class
+ The [2261]SharedArrayBuffer class
+ The [2262]SyntaxError class
+ The [2263]TypeError class
+ The [2264]RangeError class
+ The [2265]WeakRef class
+ The [2266]eval() function
+ The [2267]WeakRef.prototype.deref() function
+ The [2268][[IsHTMLDDA]] internal slot
+ [2269]import()
+ [2270]import.meta
+ The [2271]HostGetImportMetaProperties abstract operation
+ The [2272]typeof operator
+ The [2273]delete operator
+ [2274]The TypedArray Constructors table
Users agents that support JavaScript must also implement the
Dynamic Code Brand Checks proposal. The following terms are
defined there, and used in this specification:
[2275][JSDYNAMICCODEBRANDCHECKS]
+ The [2276]HostEnsureCanCompileStrings abstract operation
+ The [2277]HostGetCodeForEval abstract operation
Users agents that support JavaScript must also implement
ECMAScript Internationalization API. [2278][JSINTL]
User agents that support JavaScript must also implement the
Temporal proposal. The following terms are defined there, and
used in this specification: [2279][JSTEMPORAL]
+ The [2280]HostSystemUTCEpochNanoseconds abstract operation
+ The [2281]nsMaxInstant and [2282]nsMinInstant values
WebAssembly
The following term is defined in WebAssembly JavaScript
Interface: [2283][WASMJS]
+ [2284]WebAssembly.Module
DOM
The Document Object Model (DOM) is a representation — a model —
of a document and its content. The DOM is not just an API; the
conformance criteria of HTML implementations are defined, in
this specification, in terms of operations on the DOM.
[2285][DOM]
Implementations must support DOM and the events defined in UI
Events, because this specification is defined in terms of the
DOM, and some of the features are defined as extensions to the
DOM interfaces. [2286][DOM] [2287][UIEVENTS]
In particular, the following features are defined in DOM:
[2288][DOM]
+ [2289]Attr interface
+ [2290]CharacterData interface
+ [2291]Comment interface
+ [2292]DOMImplementation interface
+ [2293]Document interface and its [2294]doctype attribute
+ [2295]DocumentOrShadowRoot interface
+ [2296]DocumentFragment interface
+ [2297]DocumentType interface
+ [2298]ChildNode interface
+ [2299]Element interface
+ [2300]attachShadow() method.
+ An element's [2301]shadow root
+ A [2302]shadow root's [2303]mode
+ A [2304]shadow root's [2305]declarative member
+ The [2306]attach a shadow root algorithm
+ The [2307]retargeting algorithm
+ [2308]Node interface
+ [2309]NodeList interface
+ [2310]ProcessingInstruction interface
+ [2311]ShadowRoot interface
+ [2312]Text interface
+ [2313]Range interface
+ [2314]node document concept
+ [2315]document type concept
+ [2316]host concept
+ The [2317]shadow root concept, and its [2318]delegates focus,
[2319]available to element internals, [2320]clonable,
[2321]serializable, [2322]custom element registry, and
[2323]keep custom element registry null.
+ The [2324]shadow host concept
+ [2325]HTMLCollection interface, its [2326]length attribute,
and its [2327]item() and [2328]namedItem() methods
+ The terms [2329]collection and [2330]represented by the
collection
+ [2331]DOMTokenList interface, and its [2332]value attribute
and [2333]supports operation
+ [2334]createDocument() method
+ [2335]createHTMLDocument() method
+ [2336]createElement() method
+ [2337]createElementNS() method
+ [2338]getElementById() method
+ [2339]getElementsByClassName() method
+ [2340]append() method
+ [2341]appendChild() method
+ [2342]cloneNode() method
+ [2343]moveBefore() method
+ [2344]importNode() method
+ [2345]preventDefault() method
+ [2346]id attribute
+ [2347]setAttribute() method
+ [2348]textContent attribute
+ The [2349]tree, [2350]shadow tree, and [2351]node tree
concepts
+ The [2352]tree order and [2353]shadow-including tree order
concepts
+ The [2354]element concept
+ The [2355]child concept
+ The [2356]root and [2357]shadow-including root concepts
+ The [2358]inclusive ancestor, [2359]descendant,
[2360]shadow-including ancestor, [2361]shadow-including
descendant, [2362]shadow-including inclusive descendant, and
[2363]shadow-including inclusive ancestor concepts
+ The [2364]first child, [2365]next sibling, [2366]previous
sibling, and [2367]parent concepts
+ The [2368]parent element concept
+ The [2369]document element concept
+ The [2370]in a document tree, [2371]in a document (legacy),
and [2372]connected concepts
+ The [2373]slot concept, and its [2374]name and [2375]assigned
nodes
+ The [2376]assigned slot concept
+ The [2377]slot assignment concept
+ The [2378]slottable concept
+ The [2379]assign slottables for a tree algorithm
+ The [2380]slotchange event
+ The [2381]inclusive descendant concept
+ The [2382]find flattened slottables algorithm
+ The [2383]manual slot assignment concept
+ The [2384]assign a slot algorithm
+ The [2385]pre-insert, [2386]insert, [2387]append,
[2388]replace, [2389]replace all, [2390]string replace all,
[2391]remove, and [2392]adopt algorithms for nodes
+ The [2393]descendant concept
+ The [2394]insertion steps,
+ The [2395]post-connection steps, [2396]removing steps,
[2397]moving steps, [2398]adopting steps, and [2399]children
changed steps hooks for elements
+ The [2400]change, [2401]append, [2402]remove, [2403]replace,
[2404]get an attribute by namespace and local name, [2405]set
value, and [2406]remove an attribute by namespace and local
name algorithms for attributes
+ The [2407]attribute change steps hook for attributes
+ The [2408]value concept for attributes
+ The [2409]local name concept for attributes
+ The [2410]attribute list concept
+ The [2411]data of a [2412]CharacterData node and its
[2413]replace data algorithm
+ The [2414]child text content of a node
+ The [2415]descendant text content of a node
+ The [2416]name, [2417]public ID, and [2418]system ID of a
doctype
+ [2419]Event interface
+ [2420]Event and derived interfaces constructor behavior
+ [2421]EventTarget interface
+ The [2422]activation behavior hook
+ The [2423]legacy-pre-activation behavior hook
+ The [2424]legacy-canceled-activation behavior hook
+ The [2425]create an event algorithm
+ The [2426]fire an event algorithm
+ The [2427]canceled flag
+ The [2428]dispatch flag
+ The [2429]dispatch algorithm
+ [2430]EventInit dictionary type
+ [2431]type attribute
+ An event's [2432]target
+ [2433]currentTarget attribute
+ [2434]bubbles attribute
+ [2435]cancelable attribute
+ [2436]composed attribute
+ [2437]composed flag
+ [2438]isTrusted attribute
+ [2439]initEvent() method
+ [2440]add an event listener
+ [2441]addEventListener() method
+ The [2442]remove an event listener and [2443]remove all event
listeners algorithms
+ [2444]EventListener callback interface
+ The [2445]type of an event
+ An [2446]event listener and its [2447]type and [2448]callback
+ The [2449]encoding (herein the character encoding),
[2450]mode, [2451]custom element registry, [2452]allow
declarative shadow roots, and [2453]content type of a
[2454]Document
+ The distinction between [2455]XML documents and [2456]HTML
documents
+ The terms [2457]quirks mode, [2458]limited-quirks mode, and
[2459]no-quirks mode
+ The algorithm [2460]clone a node with its arguments
[2461]document, [2462]subtree, [2463]parent, and
[2464]fallbackRegistry, and the concept of [2465]cloning steps
+ The concept of base URL change steps and the definition of
what happens when an element is affected by a base URL change
+ The concept of an element's [2466]unique identifier (ID)
+ The concept of an element's [2467]classes
+ The term [2468]supported tokens
+ The concept of a DOM [2469]range, and the terms [2470]start
node, [2471]start, [2472]end, and [2473]boundary point as
applied to ranges.
+ The [2474]create an element algorithm
+ The [2475]element interface concept
+ The concepts of [2476]custom element state, and of
[2477]defined and [2478]custom elements
+ An element's [2479]namespace, [2480]namespace prefix,
[2481]local name, [2482]custom element registry, [2483]custom
element definition, and [2484]is value
+ [2485]MutationObserver interface and [2486]mutation observers
in general
+ [2487]AbortController and its [2488]signal
+ [2489]AbortSignal
+ [2490]aborted
+ [2491]signal abort
+ [2492]add
+ The [2493]get an attribute by name algorithm
The following features are defined in UI Events:
[2494][UIEVENTS]
This specification sometimes uses the term name to refer to the
event's [2538]type; as in, "an event named click" or "if the
event name is keypress". The terms "name" and "type" for events
are synonymous.
The following features are defined in DOM Parsing and
Serialization: [2539][DOMPARSING]
+ [2540]XML serialization
The following features are defined in Selection API:
[2541][SELECTION]
+ [2542]selection
+ [2543]Selection
User agents are encouraged to implement the features described
in execCommand. [2544][EXECCOMMAND]
The following features are defined in Fullscreen API:
[2545][FULLSCREEN]
+ [2546]requestFullscreen()
+ [2547]fullscreenchange
+ [2548]run the fullscreen steps
+ [2549]fully exit fullscreen
+ [2550]fullscreen element
+ [2551]fullscreen flag
High Resolution Time provides the following features:
[2552][HRT]
+ [2553]current high resolution time
+ [2554]relative high resolution time
+ [2555]unsafe shared current time
+ [2556]shared monotonic clock
+ [2557]unsafe moment
+ [2558]duration from
+ [2559]coarsen time
+ [2560]current wall time
+ [2561]Unix epoch
+ [2562]DOMHighResTimeStamp
File API
This specification uses the following features defined in File
API: [2563][FILEAPI]
+ The [2564]Blob interface and its [2565]type attribute
+ The [2566]File interface and its [2567]name and
[2568]lastModified attributes
+ The [2569]FileList interface
+ The concept of a [2570]Blob's [2571]snapshot state
+ The concept of read errors
+ [2572]Blob URL Store
+ [2573]blob URL entry and its [2574]environment
+ The [2575]obtain a blob object algorithm
Indexed Database API
The following terms are defined in Indexed Database API:
[2576][INDEXEDDB]
Media Source Extensions
The following terms are defined in Media Source Extensions:
[2579][MEDIASOURCE]
+ [2580]MediaSource interface
+ [2581]detaching from a media element
Media Capture and Streams
The following terms are defined in Media Capture and Streams:
[2582][MEDIASTREAM]
+ [2583]MediaStream interface
+ [2584]MediaStreamTrack
+ [2585]live state
+ [2586]getUserMedia()
Reporting
The following terms are defined in Reporting: [2587][REPORTING]
+ [2588]Queue a report
+ [2589]report type
+ [2590]visible to ReportingObservers
XMLHttpRequest
The following features and terms are defined in XMLHttpRequest:
[2591][XHR]
+ The [2592]XMLHttpRequest interface, and its [2593]responseXML
attribute
+ The [2594]ProgressEvent interface, and its
[2595]lengthComputable, [2596]loaded, and [2597]total
attributes
+ The [2598]FormData interface, and its associated [2599]entry
list
Battery Status
The following features are defined in Battery Status API:
[2600][BATTERY]
+ [2601]getBattery() method
Media Queries
Implementations must support Media Queries. The
[2602] feature is defined therein. [2603][MQ]
CSS modules
While support for CSS as a whole is not required of
implementations of this specification (though it is encouraged,
at least for web browsers), some features are defined in terms
of specific CSS requirements.
When this specification requires that something be [2604]parsed
according to a particular CSS grammar, the relevant algorithm in
CSS Syntax must be followed, including error handling rules.
[2605][CSSSYNTAX]
For example, user agents are required to close all open
constructs upon finding the end of a style sheet unexpectedly.
Thus, when parsing the string "rgb(0,0,0" (with a missing
close-parenthesis) for a color value, the close parenthesis is
implied by this error handling rule, and a value is obtained
(the color 'black'). However, the similar construct "rgb(0,0,"
(with both a missing parenthesis and a missing "blue" value)
cannot be parsed, as closing the open construct does not result
in a viable value.
The following terms and features are defined in Cascading Style
Sheets (CSS): [2606][CSS]
+ [2607]viewport
+ [2608]line box
+ [2609]out-of-flow
+ [2610]in-flow
+ [2611]collapsing margins
+ [2612]containing block
+ [2613]inline box
+ [2614]block box
+ The [2615]'top', [2616]'bottom', [2617]'left', and
[2618]'right' properties
+ The [2619]'float' property
+ The [2620]'clear' property
+ The [2621]'width' property
+ The [2622]'height' property
+ The [2623]'min-width' property
+ The [2624]'min-height' property
+ The [2625]'max-width' property
+ The [2626]'max-height' property
+ The [2627]'line-height' property
+ The [2628]'vertical-align' property
+ The [2629]'content' property
+ The [2630]'inline-block' value of the [2631]'display' property
+ The [2632]'visibility' property
The basic version of the [2633]'display' property is defined in
CSS, and the property is extended by other CSS modules.
[2634][CSS] [2635][CSSRUBY] [2636][CSSTABLE]
The following terms and features are defined in CSS Box Model:
[2637][CSSBOX]
+ [2638]content area
+ [2639]content box
+ [2640]border box
+ [2641]margin box
+ [2642]border edge
+ [2643]margin edge
+ The [2644]'margin-top', [2645]'margin-bottom',
[2646]'margin-left', and [2647]'margin-right' properties
+ The [2648]'padding-top', [2649]'padding-bottom',
[2650]'padding-left', and [2651]'padding-right' properties
The following features are defined in CSS Logical Properties:
[2652][CSSLOGICAL]
+ The [2653]'margin-block', [2654]'margin-block-start',
[2655]'margin-block-end', [2656]'margin-inline',
[2657]'margin-inline-start', and [2658]'margin-inline-end'
properties
+ The [2659]'padding-block', [2660]'padding-block-start',
[2661]'padding-block-end', [2662]'padding-inline',
[2663]'padding-inline-start', and [2664]'padding-inline-end'
properties
+ The [2665]'border-block-width',
[2666]'border-block-start-width',
[2667]'border-block-end-width', [2668]'border-inline-width',
[2669]'border-inline-start-width',
[2670]'border-inline-end-width', [2671]'border-block-style',
[2672]'border-block-start-style',
[2673]'border-block-end-style', [2674]'border-inline-style',
[2675]'border-inline-start-style',
[2676]'border-inline-end-style',
[2677]'border-block-start-color',
[2678]'border-block-end-color',
[2679]'border-inline-start-color',
[2680]'border-inline-end-color',
[2681]'border-start-start-radius',
[2682]'border-start-end-radius',
[2683]'border-end-start-radius', and
[2684]'border-end-end-radius' properties
+ The [2685]'block-size' property
+ The [2686]'inline-size' property
+ The [2687]'inset-block-start' property
+ The [2688]'inset-block-end' property
The following terms and features are defined in CSS Color:
[2689][CSSCOLOR]
+ [2690]named color
+ [2691]
+ The [2692]'color' property
+ The [2693]'currentcolor' value
+ [2694]opaque black
+ [2695]transparent black
+ [2696]'srgb' color space
+ [2697]'display-p3' color space
+ [2698]'relative-colorimetric' rendering intent
+ [2699]parse a CSS value
+ [2700]serialize a CSS value including
[2701]HTML-compatible serialization is requested
+ [2702]Converting Colors
+ [2703]'color()'
The following terms are defined in CSS Images: [2704][CSSIMAGES]
The term [2713]paint source is used as defined in CSS Images
Level 4 to define the interaction of certain HTML elements with
the CSS 'element()' function. [2714][CSSIMAGES4]
The following features are defined in CSS Backgrounds and
Borders: [2715][CSSBG]
+ The [2716]'background-color', [2717]'background-image',
[2718]'background-repeat', [2719]'background-attachment',
[2720]'background-position', [2721]'background-clip',
[2722]'background-origin', and [2723]'background-size'
properties
+ The [2724]'border-radius', [2725]'border-top-left-radius',
[2726]'border-top-right-radius',
[2727]'border-bottom-right-radius',
[2728]'border-bottom-left-radius' properties
+ The [2729]'border-image-source', [2730]'border-image-slice',
[2731]'border-image-width', [2732]'border-image-outset', and
[2733]'border-image-repeat' properties
CSS Backgrounds and Borders also defines the following border
properties: [2734][CSSBG]
CAPTION: Border properties
Top Bottom Left Right
Width [2735]'border-top-width' [2736]'border-bottom-width'
[2737]'border-left-width' [2738]'border-right-width'
Style [2739]'border-top-style' [2740]'border-bottom-style'
[2741]'border-left-style' [2742]'border-right-style'
Color [2743]'border-top-color' [2744]'border-bottom-color'
[2745]'border-left-color' [2746]'border-right-color'
The following features are defined in CSS Box Alignment:
[2747][CSSALIGN]
+ The [2748]'align-content' property
+ The [2749]'align-items' property
+ The [2750]'align-self' property
+ The [2751]'justify-self' property
+ The [2752]'justify-content' property
+ The [2753]'justify-items' property
The following terms and features are defined in CSS Display:
[2754][CSSDISPLAY]
+ [2755]outer display type
+ [2756]inner display type
+ [2757]block-level
+ [2758]block container
+ [2759]formatting context
+ [2760]block formatting context
+ [2761]inline formatting context
+ [2762]replaced element
+ [2763]CSS box
The following features are defined in CSS Flexible Box Layout:
[2764][CSSFLEXBOX]
+ The [2765]'flex-direction' property
+ The [2766]'flex-wrap' property
The following terms and features are defined in CSS Fonts:
[2767][CSSFONTS]
+ [2768]first available font
+ The [2769]'font-family' property
+ The [2770]'font-weight' property
+ The [2771]'font-size' property
+ The [2772]'font' property
+ The [2773]'font-kerning' property
+ The [2774]'font-stretch' property
+ The [2775]'font-variant-caps' property
+ The [2776]'small-caps' value
+ The [2777]'all-small-caps' value
+ The [2778]'petite-caps' value
+ The [2779]'all-petite-caps' value
+ The [2780]'unicase' value
+ The [2781]'titling-caps' value
+ The [2782]'ultra-condensed' value
+ The [2783]'extra-condensed' value
+ The [2784]'condensed' value
+ The [2785]'semi-condensed' value
+ The [2786]'semi-expanded' value
+ The [2787]'expanded' value
+ The [2788]'extra-expanded' value
+ The [2789]'ultra-expanded' value
The following features are defined in CSS Grid Layout:
[2790][CSSGRID]
+ The [2791]'grid-auto-columns' property
+ The [2792]'grid-auto-flow' property
+ The [2793]'grid-auto-rows' property
+ The [2794]'grid-column-gap' property
+ The [2795]'grid-row-gap' property
+ The [2796]'grid-template-areas' property
+ The [2797]'grid-template-columns' property
+ The [2798]'grid-template-rows' property
The following terms are defined in CSS Inline Layout:
[2799][CSSINLINE]
The following features are defined in CSS Lists and Counters.
[2811][CSSLISTS]
+ [2812]list item
+ The [2813]'counter-reset' property
+ The [2814]'counter-set' property
+ The [2815]'list-style-type' property
The following features are defined in CSS Overflow.
[2816][CSSOVERFLOW]
+ The [2817]'overflow' property and its [2818]'hidden' value
+ The [2819]'text-overflow' property
+ The term [2820]scroll container
The following terms and features are defined in CSS Positioned
Layout: [2821][CSSPOSITION]
+ [2822]absolutely-positioned
+ The [2823]'position' property and its [2824]'static' value
+ The [2825]top layer (an [2826]ordered set)
+ [2827]add an element to the top layer
+ [2828]request an element to be removed from the top layer
+ [2829]remove an element from the top layer immediately
+ [2830]process top layer removals
The following features are defined in CSS Multi-column Layout.
[2831][CSSMULTICOL]
+ The [2832]'column-count' property
+ The [2833]'column-fill' property
+ The [2834]'column-gap' property
+ The [2835]'column-rule' property
+ The [2836]'column-width' property
The [2837]'ruby-base' value of the [2838]'display' property is
defined in CSS Ruby Layout. [2839][CSSRUBY]
The following features are defined in CSS Table:
[2840][CSSTABLE]
+ The [2841]'border-spacing' property
+ The [2842]'border-collapse' property
+ The [2843]'table-cell', [2844]'table-row',
[2845]'table-caption', and [2846]'table' values of the
[2847]'display' property
The following features are defined in CSS Text: [2848][CSSTEXT]
+ The [2849]content language concept
+ The [2850]'text-transform' property
+ The [2851]'white-space' property
+ The [2852]'text-align' property
+ The [2853]'letter-spacing' property
+ The [2854]'word-spacing' property
The following features are defined in CSS Writing Modes:
[2855][CSSWM]
+ The [2856]'direction' property
+ The [2857]'unicode-bidi' property
+ The [2858]'writing-mode' property
+ The [2859]block flow direction, [2860]block axis, [2861]inline
axis, [2862]block size, [2863]inline size, [2864]block-start,
[2865]block-end, [2866]inline-start, [2867]inline-end,
[2868]line-left, and [2869]line-right concepts
The following features are defined in CSS Basic User Interface:
[2870][CSSUI]
+ The [2871]'outline' property
+ The [2872]'cursor' property
+ The [2873]'appearance' property, its [2874]
non-terminal value type, its [2875]'textfield' value, and its
[2876]'menulist-button' value.
+ The [2877]'field-sizing' property, and its [2878]'content'
value.
+ The concept [2879]widget
+ The concept [2880]native appearance
+ The concept [2881]primitive appearance
+ The concept [2882]element with default preferred size
+ The [2883]non-devolvable widget and [2884]devolvable widget
classification, and the related [2885]devolved widget state.
+ The [2886]'pointer-events' property
+ The [2887]'user-select' property
The algorithm to [2888]update animations and send events is
defined in Web Animations. [2889][WEBANIMATIONS]
Implementations that support scripting must support the CSS
Object Model. The following features and terms are defined in
the CSSOM specifications: [2890][CSSOM] [2891][CSSOMVIEW]
+ [2892]Screen interface
+ [2893]LinkStyle interface
+ [2894]CSSStyleDeclaration interface
+ [2895]style IDL attribute
+ [2896]cssText attribute of [2897]CSSStyleDeclaration
+ [2898]StyleSheet interface
+ [2899]CSSStyleSheet interface
+ [2900]create a CSS style sheet
+ [2901]remove a CSS style sheet
+ [2902]associated CSS style sheet
+ [2903]create a constructed CSSStyleSheet
+ [2904]synchronously replace the rules of a CSSStyleSheet
+ [2905]disable a CSS style sheet
+ [2906]CSS style sheets and their properties:
o [2907]type
o [2908]location
o [2909]parent CSS style sheet
o [2910]owner node
o [2911]owner CSS rule
o [2912]media
o [2913]title
o [2914]alternate flag
o [2915]disabled flag
o [2916]CSS rules
o [2917]origin-clean flag
+ [2918]CSS style sheet set
+ [2919]CSS style sheet set name
+ [2920]preferred CSS style sheet set name
+ [2921]change the preferred CSS style sheet set name
+ [2922]Serializing a CSS value
+ [2923]run the resize steps
+ [2924]run the scroll steps
+ [2925]evaluate media queries and report changes
+ [2926]Scroll a target into view
+ [2927]Scroll to the beginning of the document
+ The [2928]resize event
+ The [2929]scroll event
+ The [2930]scrollend event
+ [2931]set up browsing context features
+ The [2932]clientX and [2933]clientY extension attributes of
the [2934]MouseEvent interface
The following features and terms are defined in CSS Syntax:
[2935][CSSSYNTAX]
+ [2936]conformant style sheet
+ [2937]parse a list of component values
+ [2938]parse a comma-separated list of component values
+ [2939]component value
+ [2940]environment encoding
+ [2941]
The following terms are defined in Selectors: [2942][SELECTORS]
The following features are defined in CSS Values and Units:
[2949][CSSVALUES]
+ [2950]
+ The [2951]'em' unit
+ The [2952]'ex' unit
+ The [2953]'vw' unit
+ The [2954]'in' unit
+ The [2955]'px' unit
+ The [2956]'pt' unit
+ The [2957]'attr()' function
+ The [2958]math functions
The following features are defined in CSS View Transitions:
[2959][CSSVIEWTRANSITIONS]
The term [2968]style attribute is defined in CSS Style
Attributes. [2969][CSSATTR]
The following terms are defined in the CSS Cascading and
Inheritance: [2970][CSSCASCADE]
+ [2971]cascaded value
+ [2972]specified value
+ [2973]computed value
+ [2974]used value
+ [2975]cascade origin
+ [2976]Author Origin
+ [2977]User Origin
+ [2978]User Agent Origin
+ [2979]Animation Origin
+ [2980]Transition Origin
+ [2981]initial value
The [2982]CanvasRenderingContext2D object's use of fonts depends
on the features described in the CSS Fonts and Font Loading
specifications, including in particular FontFace objects and the
[2983]font source concept. [2984][CSSFONTS] [2985][CSSFONTLOAD]
The following interfaces and terms are defined in Geometry
Interfaces: [2986][GEOMETRY]
+ [2987]DOMMatrix interface, and associated [2988]m11 element,
[2989]m12 element, [2990]m21 element, [2991]m22 element,
[2992]m41 element, and [2993]m42 element
+ [2994]DOMMatrix2DInit and [2995]DOMMatrixInit dictionaries
+ The [2996]create a DOMMatrix from a dictionary and
[2997]create a DOMMatrix from a 2D dictionary algorithms for
[2998]DOMMatrix2DInit or [2999]DOMMatrixInit
+ The [3000]DOMPointInit dictionary, and associated [3001]x and
[3002]y members
+ [3003]Matrix multiplication
The following terms are defined in the CSS Scoping:
[3004][CSSSCOPING]
+ [3005]flat tree
The following terms and features are defined in CSS Color
Adjustment: [3006][CSSCOLORADJUST]
The following terms are defined in CSS Containment:
[3012][CSSCONTAIN]
+ [3013]skips its contents
+ [3014]relevant to the user
+ [3015]proximity to the viewport
+ [3016]layout containment
+ [3017]'content-visibility' property
+ [3018]'auto' value for [3019]'content-visibility'
The following terms are defined in CSS Anchor Positioning:
[3020][CSSANCHOR]
+ [3021]implicit anchor element
Intersection Observer
The following term is defined in Intersection Observer:
[3022][INTERSECTIONOBSERVER]
WebGPU
The following interfaces are defined in WebGPU: [3040][WEBGPU]
+ [3041]GPUCanvasContext interface
WebVTT
Implementations may support WebVTT as a text track format for
subtitles, captions, metadata, etc., for media resources.
[3042][WEBVTT]
The following terms, used in this specification, are defined in
WebVTT:
+ [3043]WebVTT file
+ [3044]WebVTT file using cue text
+ [3045]WebVTT file using only nested cues
+ [3046]WebVTT parser
+ The [3047]rules for updating the display of WebVTT text tracks
+ The WebVTT [3048]text track cue writing direction
+ [3049]VTTCue interface
ARIA
The role attribute is defined in Accessible Rich Internet
Applications (ARIA), as are the following roles: [3050][ARIA]
+ [3051]button
+ [3052]presentation
In addition, the following aria-* content attributes are defined
in ARIA: [3053][ARIA]
Finally, the following terms are defined in ARIA: [3058][ARIA]
+ [3059]role
+ [3060]accessible name
+ The [3061]ARIAMixin interface, with its associated
[3062]ARIAMixin getter steps and [3063]ARIAMixin setter steps
hooks, and its [3064]role and [3065]aria* attributes
Content Security Policy
The following terms are defined in Content Security Policy:
[3066][CSP]
+ [3067]Content Security Policy
+ [3068]disposition
+ [3069]directive set
+ [3070]Content Security Policy directive
+ [3071]CSP list
+ The [3072]Content Security Policy syntax
+ [3073]enforce the policy
+ The [3074]parse a serialized Content Security Policy algorithm
+ The [3075]Run CSP initialization for a Document algorithm
+ The [3076]Run CSP initialization for a global object algorithm
+ The [3077]Should element's inline behavior be blocked by
Content Security Policy? algorithm
+ The [3078]Should navigation request of type be blocked by
Content Security Policy? algorithm
+ The [3079]Should navigation response to navigation request of
type in target be blocked by Content Security Policy?
algorithm
+ The [3080]report-uri directive
+ The [3081]EnsureCSPDoesNotBlockStringCompilation abstract
operation
+ The [3082]Is base allowed for Document? algorithm
+ The [3083]frame-ancestors directive
+ The [3084]sandbox directive
+ The [3085]contains a header-delivered Content Security Policy
property.
+ The [3086]Parse a response's Content Security Policies
algorithm.
+ [3087]SecurityPolicyViolationEvent interface
+ The [3088]securitypolicyviolation event
Service Workers
The following terms are defined in Service Workers: [3089][SW]
Secure Contexts
The following algorithms are defined in Secure Contexts:
[3102][SECURE-CONTEXTS]
+ [3103]Is url potentially trustworthy?
Permissions Policy
The following terms are defined in Permissions Policy:
[3104][PERMISSIONSPOLICY]
+ [3105]permissions policy
+ [3106]policy-controlled feature
+ [3107]container policy
+ [3108]serialized permissions policy
+ [3109]default allowlist
+ The [3110]creating a permissions policy algorithm
+ The [3111]creating a permissions policy from a response
algorithm
+ The [3112]is feature enabled by policy for origin algorithm
+ The [3113]process permissions policy attributes algorithm
Payment Request API
The following feature is defined in Payment Request API:
[3114][PAYMENTREQUEST]
+ [3115]PaymentRequest interface
MathML
While support for MathML as a whole is not required by this
specification (though it is encouraged, at least for web
browsers), certain features depend upon small parts of MathML
being implemented. [3116][MATHML]
The following features are defined in Mathematical Markup
Language (MathML):
+ [3117]MathML annotation-xml element
+ [3118]MathML math element
+ [3119]MathML merror element
+ [3120]MathML mi element
+ [3121]MathML mn element
+ [3122]MathML mo element
+ [3123]MathML ms element
+ [3124]MathML mtext element
SVG
While support for SVG as a whole is not required by this
specification (though it is encouraged, at least for web
browsers), certain features depend upon parts of SVG being
implemented.
User agents that implement SVG must implement the SVG 2
specification, and not any earlier revisions.
The following features are defined in the SVG 2 specification:
[3125][SVG]
+ [3126]SVGElement interface
+ [3127]SVGImageElement interface
+ [3128]SVGScriptElement interface
+ [3129]SVGSVGElement interface
+ [3130]SVG a element
+ [3131]SVG desc element
+ [3132]SVG foreignObject element
+ [3133]SVG image element
+ [3134]SVG script element
+ [3135]SVG svg element
+ [3136]SVG title element
+ [3137]SVG use element
+ [3138]SVG text-rendering property
Filter Effects
The following features are defined in Filter Effects:
[3139][FILTERS]
+ [3140]
Compositing
The following features are defined in Compositing and Blending:
[3141][COMPOSITE]
Cooperative Scheduling of Background Tasks
The following features are defined in Cooperative Scheduling of
Background Tasks: [3146][REQUESTIDLECALLBACK]
+ [3147]requestIdleCallback()
+ [3148]start an idle period algorithm
Screen Orientation
The following terms are defined in Screen Orientation:
[3149][SCREENORIENTATION]
+ [3150]screen orientation change steps
Storage
The following terms are defined in Storage: [3151][STORAGE]
+ [3152]obtain a local storage bottle map
+ [3153]obtain a session storage bottle map
+ [3154]obtain a storage key for non-storage purposes
+ [3155]storage key equal
+ [3156]storage proxy map
+ [3157]legacy-clone a traversable storage shed
Web App Manifest
The following features are defined in Web App Manifest:
[3158][MANIFEST]
+ [3159]application manifest
+ [3160]installed web application
+ [3161]process the manifest
WebAssembly JavaScript Interface: ESM Integration
The following terms are defined in WebAssembly JavaScript
Interface: ESM Integration: [3162][WASMESM]
+ [3163]WebAssembly Module Record
+ [3164]parse a WebAssembly module
WebCodecs
The following features are defined in WebCodecs:
[3165][WEBCODECS]
Web Authentication: An API for accessing Public Key Credentials
The following terms are defined in Web Authentication: An API
for accessing Public Key Credentials: [3211][WEBAUTHN]
+ [3212]public key credential
Credential Management
The following terms are defined in Credential Management:
[3213][CREDMAN]
This specification does not require support of any particular network
protocol, style sheet language, scripting language, or any of the DOM
specifications beyond those required in the list above. However, the
language described by this specification is biased towards CSS as the
styling language, JavaScript as the scripting language, and HTTP as the
network protocol, and several features assume that those languages and
protocols are in use.
A user agent that implements the HTTP protocol must implement HTTP
State Management Mechanism (Cookies) as well. [3251][HTTP]
[3252][COOKIES]
This specification might have certain additional requirements on
character encodings, image formats, audio formats, and video formats in
the respective sections.
2.1.10 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.
All extensions must be defined so that the use of extensions neither
contradicts nor causes the non-conformance of functionality defined in
the specification.
For example, while strongly discouraged from doing so, an
implementation could add a new IDL attribute "typeTime" to a control
that returned the time it took the user to select the current value of
a control (say). On the other hand, defining a new control that appears
in a form's [3253]elements array would be in violation of the above
requirement, as it would violate the definition of [3254]elements given
in this specification.
__________________________________________________________________
When vendor-neutral extensions to this specification are needed, either
this 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.
__________________________________________________________________
User agents must treat elements and attributes that they do not
understand as semantically neutral; leaving them in the DOM (for DOM
processors), and styling them according to CSS (for CSS processors),
but not inferring any meaning from them.
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.
2.1.11 Interactions with XPath and XSLT
Implementations of XPath 1.0 that operate on [3255]HTML documents
parsed or created in the manners described in this specification (e.g.
as part of the document.evaluate() API) must act as if the following
edit was applied to the XPath 1.0 specification.
First, remove this paragraph:
A [3256]QName in the node test is expanded into an
[3257]expanded-name using the namespace declarations from the
expression context. This is the same way expansion is done for
element type names in start and end-tags except that the default
namespace declared with xmlns is not used: if the [3258]QName does
not have a prefix, then the namespace URI is null (this is the same
way attribute names are expanded). It is an error if the [3259]QName
has a prefix for which there is no namespace declaration in the
expression context.
Then, insert in its place the following:
A QName in the node test is expanded into an expanded-name using the
namespace declarations from the expression context. If the QName has
a prefix, then there must be a namespace declaration for this prefix
in the expression context, and the corresponding namespace URI is
the one that is associated with this prefix. It is an error if the
QName has a prefix for which there is no namespace declaration in
the expression context.
If the QName has no prefix and the principal node type of the axis
is element, then the default element namespace is used. Otherwise,
if the QName has no prefix, the namespace URI is null. The default
element namespace is a member of the context for the XPath
expression. The value of the default element namespace when
executing an XPath expression through the DOM3 XPath API is
determined in the following way:
1. If the context node is from an HTML DOM, the default element
namespace is "http://www.w3.org/1999/xhtml".
2. Otherwise, the default element namespace URI is null.
This is equivalent to adding the default element namespace feature
of XPath 2.0 to XPath 1.0, and using the HTML namespace as the
default element namespace for HTML documents. It is motivated by the
desire to have implementations be compatible with legacy HTML
content while still supporting the changes that this specification
introduces to HTML regarding the namespace used for HTML elements,
and by the desire to use XPath 1.0 rather than XPath 2.0.
This change is a [3260]willful violation of the XPath 1.0
specification, motivated by desire to have implementations be
compatible with legacy content while still supporting the changes that
this specification introduces to HTML regarding which namespace is used
for HTML elements. [3261][XPATH10]
__________________________________________________________________
XSLT 1.0 processors outputting to a DOM when the output method is
"html" (either explicitly or via the defaulting rule in XSLT 1.0) are
affected as follows:
If the transformation program outputs an element in no namespace, the
processor must, prior to constructing the corresponding DOM element
node, change the namespace of the element to the [3262]HTML namespace,
[3263]ASCII-lowercase the element's local name, and
[3264]ASCII-lowercase the names of any non-namespaced attributes on the
element.
This requirement is a [3265]willful violation of the XSLT 1.0
specification, required because this specification changes the
namespaces and case-sensitivity rules of HTML in a manner that would
otherwise be incompatible with DOM-based XSLT transformations.
(Processors that serialize the output are unaffected.) [3266][XSLT10]
__________________________________________________________________
This specification does not specify precisely how XSLT processing
interacts with the [3267]HTML parser infrastructure (for example,
whether an XSLT processor acts as if it puts any elements into a
[3268]stack of open elements). However, XSLT processors must [3269]stop
parsing if they successfully complete, and must [3270]update the
current document readiness first to "interactive" and then to
"complete" if they are aborted.
__________________________________________________________________
This specification does not specify how XSLT interacts with the
[3271]navigation algorithm, how it fits in with the [3272]event loop,
nor how error pages are to be handled (e.g. whether XSLT errors are to
replace an incremental XSLT output, or are rendered inline, etc.).
There are also additional non-normative comments regarding the
interaction of XSLT and HTML [3273]in the script element section, and
of XSLT, XPath, and HTML [3274]in the template element section.
2.2 Policy-controlled features
(BUTTON) ⚠MDN
[3275]Headers/Permissions-Policy/document-domain
Support in one engine only.
Firefox🔰 74+SafariNoChrome🔰 88+
__________________________________________________________________
* "autoplay", which has a [3279]default allowlist of 'self'.
* "cross-origin-isolated", which has a [3280]default allowlist of
'self'.
* "focus-without-user-activation", which has a [3281]default
allowlist of 'self'.
2.3 Common microsyntaxes
There are various places in HTML that accept particular data types,
such as dates or numbers. This section describes what the conformance
criteria for content in those formats is, and how to parse them.
Implementers are strongly urged to carefully examine any third-party
libraries they might consider using to implement the parsing of
syntaxes described below. For example, date libraries are likely to
implement error handling behavior that differs from what is required in
this specification, since error-handling behavior is often not defined
in specifications that describe date syntaxes similar to those used in
this specification, and thus implementations tend to vary greatly in
how they handle errors.
2.3.1 Common parser idioms
Some of the micro-parsers described below follow the pattern of having
an input variable that holds the string being parsed, and having a
position variable pointing at the next character to parse in input.
2.3.2 Boolean attributes
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 [3282]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
[3283]checked and [3284]disabled attributes are the boolean attributes.
This could be equivalently written as this:
You can also mix styles; the following is still equivalent:
2.3.3 Keywords and enumerated attributes
Some attributes, called enumerated attributes, take on a finite set of
states. The state for such an attribute is derived by combining the
attribute's value, a set of keyword/state mappings given in the
specification of each attribute, and two possible special states that
can also be given in the specification of the attribute. These special
states are the invalid value default and the missing value default.
Multiple keywords can map to the same state.
The empty string can be a valid keyword. Note that the [3285]missing
value default applies only when the attribute is missing, not when it
is present with an empty string value.
To determine the state of an attribute, use the following steps:
1. If the attribute is not specified:
1. If the attribute has a [3286]missing value default state
defined, then return that [3287]missing value default state.
2. Otherwise, return no state.
2. If the attribute's value is an [3288]ASCII case-insensitive match
for one of the keywords defined for the attribute, then return the
state represented by that keyword.
3. If the attribute has an [3289]invalid value default state defined,
then return that [3290]invalid value default state.
4. Return no state.
For authoring conformance purposes, if an enumerated attribute is
specified, the attribute's value must be an [3291]ASCII
case-insensitive match for one of the conforming keywords for that
attribute, with no leading or trailing whitespace.
For [3292]reflection purposes, states which have any keywords mapping
to them are said to have a canonical keyword. This is determined as
follows:
* If there is only one keyword mapping to the given state, then it is
that keyword.
* If there is only one conforming keyword mapping to the given state,
then it is that conforming keyword.
* Otherwise, the canonical keyword for the state will be explicitly
given in the specification for the attribute.
2.3.4 Numbers
2.3.4.1 Signed integers
A string is a valid integer if it consists of one or more [3293]ASCII
digits, optionally prefixed with a U+002D HYPHEN-MINUS character (-).
A [3294]valid integer without a U+002D HYPHEN-MINUS (-) prefix
represents the number that is represented in base ten by that string of
digits. A [3295]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.
The rules for parsing integers are as given in the following algorithm.
When invoked, the steps must be followed in the order given, aborting
at the first step that returns a value. This algorithm will return
either an integer or an error.
1. Let input be the string being parsed.
2. Let position be a pointer into input, initially pointing at the
start of the string.
3. Let sign have the value "positive".
4. [3296]Skip ASCII whitespace within input given position.
5. If position is past the end of input, return an error.
6. If the character indicated by position (the first character) is a
U+002D HYPHEN-MINUS character (-):
1. Let sign be "negative".
2. Advance position to the next character.
3. If position is past the end of input, return an error.
Otherwise, if the character indicated by position (the first
character) is a U+002B PLUS SIGN character (+):
1. Advance position to the next character. (The "+" is ignored,
but it is not conforming.)
2. If position is past the end of input, return an error.
7. If the character indicated by position is not an [3297]ASCII digit,
then return an error.
8. [3298]Collect a sequence of code points that are [3299]ASCII digits
from input given position, and interpret the resulting sequence as
a base-ten integer. Let value be that integer.
9. If sign is "positive", return value, otherwise return the result of
subtracting value from zero.
2.3.4.2 Non-negative integers
A string is a valid non-negative integer if it consists of one or more
[3300]ASCII digits.
A [3301]valid non-negative integer represents the number that is
represented in base ten by that string of digits.
The rules for parsing non-negative integers are as given in the
following algorithm. When invoked, the steps must be followed in the
order given, aborting at the first step that returns a value. This
algorithm will return either zero, a positive integer, or an error.
1. Let input be the string being parsed.
2. Let value be the result of parsing input using the [3302]rules for
parsing integers.
3. If value is an error, return an error.
4. If value is less than zero, return an error.
5. Return value.
2.3.4.3 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 [3303]ASCII digits.
2. Both of the following, in the given order:
1. A single U+002E FULL STOP character (.).
2. A series of one or more [3304]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 [3305]ASCII digits.
A [3306]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 [3307]valid
floating-point numbers.
The [3308]valid floating-point number concept is typically only used to
restrict what is allowed for authors, while the user agent requirements
use the [3309]rules for parsing floating-point number values below
(e.g., the [3310]max attribute of the [3311]progress element). However,
in some cases the user agent requirements include checking if a string
is a [3312]valid floating-point number (e.g., the [3313]value
sanitization algorithm for the [3314]Number state of the [3315]input
element, or the [3316]parse a srcset attribute algorithm).
The best representation of the number n as a floating-point number is
the string obtained from running [3317]ToString(n). The abstract
operation [3318]ToString is not uniquely determined. When there are
multiple possible strings that could be obtained from [3319]ToString
for a particular value, the user agent must always return the same
string for that value (though it may differ from the value used by
other user agents).
The rules for parsing floating-point number values are as given in the
following algorithm. This algorithm must be aborted at the first step
that returns something. This algorithm will return either a number or
an error.
1. Let input be the string being parsed.
2. Let position be a pointer into input, initially pointing at the
start of the string.
3. Let value have the value 1.
4. Let divisor have the value 1.
5. Let exponent have the value 1.
6. [3320]Skip ASCII whitespace within input given position.
7. If position is past the end of input, return an error.
8. If the character indicated by position is a U+002D HYPHEN-MINUS
character (-):
1. Change value and divisor to −1.
2. Advance position to the next character.
3. If position is past the end of input, return an error.
Otherwise, if the character indicated by position (the first
character) is a U+002B PLUS SIGN character (+):
1. Advance position to the next character. (The "+" is ignored,
but it is not conforming.)
2. If position is past the end of input, return an error.
9. If the character indicated by position is a U+002E FULL STOP (.),
and that is not the last character in input, and the character
after the character indicated by position is an [3321]ASCII digit,
then set value to zero and jump to the step labeled fraction.
10. If the character indicated by position is not an [3322]ASCII digit,
then return an error.
11. [3323]Collect a sequence of code points that are [3324]ASCII digits
from input given position, and interpret the resulting sequence as
a base-ten integer. Multiply value by that integer.
12. If position is past the end of input, jump to the step labeled
conversion.
13. Fraction: If the character indicated by position is a U+002E FULL
STOP (.), run these substeps:
1. Advance position to the next character.
2. If position is past the end of input, or if the character
indicated by position is not an [3325]ASCII digit, U+0065
LATIN SMALL LETTER E (e), or U+0045 LATIN CAPITAL LETTER E
(E), then jump to the step labeled conversion.
3. If the character indicated by position is a U+0065 LATIN SMALL
LETTER E character (e) or a U+0045 LATIN CAPITAL LETTER E
character (E), skip the remainder of these substeps.
4. Fraction loop: Multiply divisor by ten.
5. Add the value of the character indicated by position,
interpreted as a base-ten digit (0..9) and divided by divisor,
to value.
6. Advance position to the next character.
7. If position is past the end of input, then jump to the step
labeled conversion.
8. If the character indicated by position is an [3326]ASCII
digit, jump back to the step labeled fraction loop in these
substeps.
14. If the character indicated by position is U+0065 (e) or a U+0045
(E), then:
1. Advance position to the next character.
2. If position is past the end of input, then jump to the step
labeled conversion.
3. If the character indicated by position is a U+002D
HYPHEN-MINUS character (-):
1. Change exponent to −1.
2. Advance position to the next character.
3. If position is past the end of input, then jump to the
step labeled conversion.
Otherwise, if the character indicated by position is a U+002B
PLUS SIGN character (+):
1. Advance position to the next character.
2. If position is past the end of input, then jump to the
step labeled conversion.
4. If the character indicated by position is not an [3327]ASCII
digit, then jump to the step labeled conversion.
5. [3328]Collect a sequence of code points that are [3329]ASCII
digits from input given position, and interpret the resulting
sequence as a base-ten integer. Multiply exponent by that
integer.
6. Multiply value by ten raised to the exponentth power.
15. Conversion: Let S be the set of finite IEEE 754 double-precision
floating-point values except −0, but with two special values added:
2^1024 and −2^1024.
16. Let rounded-value be the number in S that is closest to value,
selecting the number with an even significand if there are two
equally close values. (The two special values 2^1024 and −2^1024
are considered to have even significands for this purpose.)
17. If rounded-value is 2^1024 or −2^1024, return an error.
18. Return rounded-value.
2.3.4.4 Percentages and lengths
The rules for parsing dimension values are as given in the following
algorithm. When invoked, the steps must be followed in the order given,
aborting at the first step that returns a value. This algorithm will
return either a number greater than or equal to 0.0, or failure; if a
number is returned, then it is further categorized as either a
percentage or a length.
1. Let input be the string being parsed.
2. Let position be a [3330]position variable for input, initially
pointing at the start of input.
3. [3331]Skip ASCII whitespace within input given position.
4. If position is past the end of input or the code point at position
within input is not an [3332]ASCII digit, then return failure.
5. [3333]Collect a sequence of code points that are [3334]ASCII digits
from input given position, and interpret the resulting sequence as
a base-ten integer. Let value be that number.
6. If position is past the end of input, then return value as a
length.
7. If the code point at position within input is U+002E (.), then:
1. Advance position by 1.
2. If position is past the end of input or the code point at
position within input is not an [3335]ASCII digit, then return
the [3336]current dimension value with value, input, and
position.
3. Let divisor have the value 1.
4. While true:
1. Multiply divisor by ten.
2. Add the value of the code point at position within input,
interpreted as a base-ten digit (0..9) and divided by
divisor, to value.
3. Advance position by 1.
4. If position is past the end of input, then return value
as a length.
5. If the code point at position within input is not an
[3337]ASCII digit, then [3338]break.
8. Return the [3339]current dimension value with value, input, and
position.
The current dimension value, given value, input, and position, is
determined as follows:
1. If position is past the end of input, then return value as a
length.
2. If the code point at position within input is U+0025 (%), then
return value as a percentage.
3. Return value as a length.
2.3.4.5 Nonzero percentages and lengths
The rules for parsing nonzero dimension values are as given in the
following algorithm. When invoked, the steps must be followed in the
order given, aborting at the first step that returns a value. This
algorithm will return either a number greater than 0.0, or an error; if
a number is returned, then it is further categorized as either a
percentage or a length.
1. Let input be the string being parsed.
2. Let value be the result of parsing input using the [3340]rules for
parsing dimension values.
3. If value is an error, return an error.
4. If value is zero, return an error.
5. If value is a percentage, return value as a percentage.
6. Return value as a length.
2.3.4.6 Lists of floating-point numbers
A valid list of floating-point numbers is a number of [3341]valid
floating-point numbers separated by U+002C COMMA characters, with no
other characters (e.g. no [3342]ASCII whitespace). In addition, there
might be restrictions on the number of floating-point numbers that can
be given, or on the range of values allowed.
The rules for parsing a list of floating-point numbers are as follows:
1. Let input be the string being parsed.
2. Let position be a pointer into input, initially pointing at the
start of the string.
3. Let numbers be an initially empty list of floating-point numbers.
This list will be the result of this algorithm.
4. [3343]Collect a sequence of code points that are [3344]ASCII
whitespace, U+002C COMMA, or U+003B SEMICOLON characters from input
given position. This skips past any leading delimiters.
5. While position is not past the end of input:
1. [3345]Collect a sequence of code points that are not
[3346]ASCII whitespace, U+002C COMMA, U+003B SEMICOLON,
[3347]ASCII digits, U+002E FULL STOP, or U+002D HYPHEN-MINUS
characters from input given position. This skips past leading
garbage.
2. [3348]Collect a sequence of code points that are not
[3349]ASCII whitespace, U+002C COMMA, or U+003B SEMICOLON
characters from input given position, and let unparsed number
be the result.
3. Let number be the result of parsing unparsed number using the
[3350]rules for parsing floating-point number values.
4. If number is an error, set number to zero.
5. Append number to numbers.
6. [3351]Collect a sequence of code points that are [3352]ASCII
whitespace, U+002C COMMA, or U+003B SEMICOLON characters from
input given position. This skips past the delimiter.
6. Return numbers.
2.3.4.7 Lists of dimensions
The rules for parsing a list of dimensions are as follows. These rules
return a list of zero or more pairs consisting of a number and a unit,
the unit being one of percentage, relative, and absolute.
1. Let raw input be the string being parsed.
2. If the last character in raw input is a U+002C COMMA character (,),
then remove that character from raw input.
3. [3353]Split the string raw input on commas. Let raw tokens be the
resulting list of tokens.
4. Let result be an empty list of number/unit pairs.
5. For each token in raw tokens, run the following substeps:
1. Let input be the token.
2. Let position be a pointer into input, initially pointing at
the start of the string.
3. Let value be the number 0.
4. Let unit be absolute.
5. If position is past the end of input, set unit to relative and
jump to the last substep.
6. If the character at position is an [3354]ASCII digit,
[3355]collect a sequence of code points that are [3356]ASCII
digits from input given position, interpret the resulting
sequence as an integer in base ten, and increment value by
that integer.
7. If the character at position is U+002E (.), then:
1. [3357]Collect a sequence of code points consisting of
[3358]ASCII whitespace and [3359]ASCII digits from input
given position. Let s be the resulting sequence.
2. Remove all [3360]ASCII whitespace in s.
3. If s is not the empty string, then:
1. Let length be the number of characters in s (after
the spaces were removed).
2. Let fraction be the result of interpreting s as a
base-ten integer, and then dividing that number by
10^length.
3. Increment value by fraction.
8. [3361]Skip ASCII whitespace within input given position.
9. If the character at position is a U+0025 PERCENT SIGN
character (%), then set unit to percentage.
Otherwise, if the character at position is a U+002A ASTERISK
character (*), then set unit to relative.
10. Add an entry to result consisting of the number given by value
and the unit given by unit.
6. Return the list result.
2.3.5 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. [3362][GREGORIAN]
When [3363]ASCII digits are used in the date and time syntaxes defined
in this section, they express numbers in base ten.
While the formats described here are intended to be subsets of the
corresponding ISO8601 formats, this specification defines parsing rules
in much more detail than ISO8601. Implementers are therefore encouraged
to carefully examine any date parsing libraries before using them to
implement the parsing rules described below; ISO8601 libraries might
not parse dates and times in exactly the same manner. [3364][ISO8601]
Where this specification refers to the proleptic Gregorian calendar, it
means the modern Gregorian calendar, extrapolated backwards to year 1.
A date in the [3365]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. [3366][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
[3367]date, time, and number formats in forms (for authors),
[3368]implementation notes regarding localization of form controls, and
the [3369]time element.
2.3.5.1 Months
A month consists of a specific [3370]proleptic-Gregorian date with no
time-zone information and no date information beyond a year and a
month. [3371][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 [3372]ASCII digits, representing year, where year > 0
2. A U+002D HYPHEN-MINUS character (-)
3. Two [3373]ASCII digits, representing the month month, in the range
1 ≤ month ≤ 12
The rules to parse a month string are as follows. This will return
either a year and month, or nothing. If at any point the algorithm says
that it "fails", this means that it is aborted at that point and
returns nothing.
1. Let input be the string being parsed.
2. Let position be a pointer into input, initially pointing at the
start of the string.
3. [3374]Parse a month component to obtain year and month. If this
returns nothing, then fail.
4. If position is not beyond the end of input, then fail.
5. Return year and month.
The rules to parse a month component, given an input string and a
position, are as follows. This will return either a year and a month,
or nothing. If at any point the algorithm says that it "fails", this
means that it is aborted at that point and returns nothing.
1. [3375]Collect a sequence of code points that are [3376]ASCII digits
from input given position. If the collected sequence is not at
least four characters long, then fail. Otherwise, interpret the
resulting sequence as a base-ten integer. Let year be that number.
2. If year is not a number greater than zero, then fail.
3. If position is beyond the end of input or if the character at
position is not a U+002D HYPHEN-MINUS character, then fail.
Otherwise, move position forwards one character.
4. [3377]Collect a sequence of code points that are [3378]ASCII digits
from input given position. If the collected sequence is not exactly
two characters long, then fail. Otherwise, interpret the resulting
sequence as a base-ten integer. Let month be that number.
5. If month is not a number in the range 1 ≤ month ≤ 12, then fail.
6. Return year and month.
2.3.5.2 Dates
A date consists of a specific [3379]proleptic-Gregorian date with no
time-zone information, consisting of a year, a month, and a day.
[3380][GREGORIAN]
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 [3381]valid month string, representing year and month
2. A U+002D HYPHEN-MINUS character (-)
3. Two [3382]ASCII digits, representing day, in the range
1 ≤ day ≤ maxday where maxday is the [3383]number of days in the
month month and year year
The rules to parse a date string are as follows. This will return
either a date, or nothing. If at any point the algorithm says that it
"fails", this means that it is aborted at that point and returns
nothing.
1. Let input be the string being parsed.
2. Let position be a pointer into input, initially pointing at the
start of the string.
3. [3384]Parse a date component to obtain year, month, and day. If
this returns nothing, then fail.
4. If position is not beyond the end of input, then fail.
5. Let date be the date with year year, month month, and day day.
6. Return date.
The rules to parse a date component, given an input string and a
position, are as follows. This will return either a year, a month, and
a day, or nothing. If at any point the algorithm says that it "fails",
this means that it is aborted at that point and returns nothing.
1. [3385]Parse a month component to obtain year and month. If this
returns nothing, then fail.
2. Let maxday be the [3386]number of days in month month of year year.
3. If position is beyond the end of input or if the character at
position is not a U+002D HYPHEN-MINUS character, then fail.
Otherwise, move position forwards one character.
4. [3387]Collect a sequence of code points that are [3388]ASCII digits
from input given position. If the collected sequence is not exactly
two characters long, then fail. Otherwise, interpret the resulting
sequence as a base-ten integer. Let day be that number.
5. If day is not a number in the range 1 ≤ day ≤ maxday, then fail.
6. Return year, month, and day.
2.3.5.3 Yearless dates
A yearless date consists of a Gregorian month and a day within that
month, but with no associated year. [3389][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 [3390]ASCII digits, representing the month month, in the range
1 ≤ month ≤ 12
3. A U+002D HYPHEN-MINUS character (-)
4. Two [3391]ASCII digits, representing day, in the range
1 ≤ day ≤ maxday where maxday is the [3392]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.
The rules to parse a yearless date string are as follows. This will
return either a month and a day, or nothing. If at any point the
algorithm says that it "fails", this means that it is aborted at that
point and returns nothing.
1. Let input be the string being parsed.
2. Let position be a pointer into input, initially pointing at the
start of the string.
3. [3393]Parse a yearless date component to obtain month and day. If
this returns nothing, then fail.
4. If position is not beyond the end of input, then fail.
5. Return month and day.
The rules to parse a yearless date component, given an input string and
a position, are as follows. This will return either a month and a day,
or nothing. If at any point the algorithm says that it "fails", this
means that it is aborted at that point and returns nothing.
1. [3394]Collect a sequence of code points that are U+002D
HYPHEN-MINUS characters (-) from input given position. If the
collected sequence is not exactly zero or two characters long, then
fail.
2. [3395]Collect a sequence of code points that are [3396]ASCII digits
from input given position. If the collected sequence is not exactly
two characters long, then fail. Otherwise, interpret the resulting
sequence as a base-ten integer. Let month be that number.
3. If month is not a number in the range 1 ≤ month ≤ 12, then fail.
4. Let maxday be the [3397]number of days in month month of any
arbitrary leap year (e.g. 4 or 2000).
5. If position is beyond the end of input or if the character at
position is not a U+002D HYPHEN-MINUS character, then fail.
Otherwise, move position forwards one character.
6. [3398]Collect a sequence of code points that are [3399]ASCII digits
from input given position. If the collected sequence is not exactly
two characters long, then fail. Otherwise, interpret the resulting
sequence as a base-ten integer. Let day be that number.
7. If day is not a number in the range 1 ≤ day ≤ maxday, then fail.
8. Return month and day.
2.3.5.4 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 [3400]ASCII digits, representing hour, in the range
0 ≤ hour ≤ 23
2. A U+003A COLON character (:)
3. Two [3401]ASCII digits, representing minute, in the range
0 ≤ minute ≤ 59
4. If second is nonzero, or optionally if second is zero:
1. A U+003A COLON character (:)
2. Two [3402]ASCII digits, representing the integer part of
second, in the range 0 ≤ s ≤ 59
3. If second is not an integer, or optionally if second is an
integer:
1. A U+002E FULL STOP character (.)
2. One, two, or three [3403]ASCII digits, representing the
fractional part of second
The second component cannot be 60 or 61; leap seconds cannot be
represented.
The rules to parse a time string are as follows. This will return
either a time, or nothing. If at any point the algorithm says that it
"fails", this means that it is aborted at that point and returns
nothing.
1. Let input be the string being parsed.
2. Let position be a pointer into input, initially pointing at the
start of the string.
3. [3404]Parse a time component to obtain hour, minute, and second. If
this returns nothing, then fail.
4. If position is not beyond the end of input, then fail.
5. Let time be the time with hour hour, minute minute, and second
second.
6. Return time.
The rules to parse a time component, given an input string and a
position, are as follows. This will return either an hour, a minute,
and a second, or nothing. If at any point the algorithm says that it
"fails", this means that it is aborted at that point and returns
nothing.
1. [3405]Collect a sequence of code points that are [3406]ASCII digits
from input given position. If the collected sequence is not exactly
two characters long, then fail. Otherwise, interpret the resulting
sequence as a base-ten integer. Let hour be that number.
2. If hour is not a number in the range 0 ≤ hour ≤ 23, then fail.
3. If position is beyond the end of input or if the character at
position is not a U+003A COLON character, then fail. Otherwise,
move position forwards one character.
4. [3407]Collect a sequence of code points that are [3408]ASCII digits
from input given position. If the collected sequence is not exactly
two characters long, then fail. Otherwise, interpret the resulting
sequence as a base-ten integer. Let minute be that number.
5. If minute is not a number in the range 0 ≤ minute ≤ 59, then fail.
6. Let second be 0.
7. If position is not beyond the end of input and the character at
position is U+003A (:), then:
1. Advance position to the next character in input.
2. If position is beyond the end of input, or at the last
character in input, or if the next two characters in input
starting at position are not both [3409]ASCII digits, then
fail.
3. [3410]Collect a sequence of code points that are either
[3411]ASCII digits or U+002E FULL STOP characters from input
given position. If the collected sequence is three characters
long, or if it is longer than three characters long and the
third character is not a U+002E FULL STOP character, or if it
has more than one U+002E FULL STOP character, then fail.
Otherwise, interpret the resulting sequence as a base-ten
number (possibly with a fractional part). Set second to that
number.
4. If second is not a number in the range 0 ≤ second < 60, then
fail.
8. Return hour, minute, and second.
2.3.5.5 Local dates and times
A local date and time consists of a specific [3412]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. [3413][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 [3414]valid date string representing the date
2. A U+0054 LATIN CAPITAL LETTER T character (T) or a U+0020 SPACE
character
3. A [3415]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 [3416]valid date string representing the date
2. A U+0054 LATIN CAPITAL LETTER T character (T)
3. A [3417]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)
The rules to parse a local date and time string are as follows. This
will return either a date and time, or nothing. If at any point the
algorithm says that it "fails", this means that it is aborted at that
point and returns nothing.
1. Let input be the string being parsed.
2. Let position be a pointer into input, initially pointing at the
start of the string.
3. [3418]Parse a date component to obtain year, month, and day. If
this returns nothing, then fail.
4. If position is beyond the end of input or if the character at
position is neither a U+0054 LATIN CAPITAL LETTER T character (T)
nor a U+0020 SPACE character, then fail. Otherwise, move position
forwards one character.
5. [3419]Parse a time component to obtain hour, minute, and second. If
this returns nothing, then fail.
6. If position is not beyond the end of input, then fail.
7. Let date be the date with year year, month month, and day day.
8. Let time be the time with hour hour, minute minute, and second
second.
9. Return date and time.
2.3.5.6 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:
* 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:
1. 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
2. Two [3420]ASCII digits, representing the hours component hour
of the time-zone offset, in the range 0 ≤ hour ≤ 23
3. Optionally, a U+003A COLON character (:)
4. Two [3421]ASCII digits, representing the minutes component
minute of the time-zone offset, in the range 0 ≤ minute ≤ 59
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 [3422]global date and time
section below for details on using time-zone offsets with historical
times that predate the formation of formal time zones.
The rules to parse a time-zone offset string are as follows. This will
return either a time-zone offset, or nothing. If at any point the
algorithm says that it "fails", this means that it is aborted at that
point and returns nothing.
1. Let input be the string being parsed.
2. Let position be a pointer into input, initially pointing at the
start of the string.
3. [3423]Parse a time-zone offset component to obtain timezone[hours]
and timezone[minutes]. If this returns nothing, then fail.
4. If position is not beyond the end of input, then fail.
5. Return the time-zone offset that is timezone[hours] hours and
timezone[minutes] minutes from UTC.
The rules to parse a time-zone offset component, given an input string
and a position, are as follows. This will return either time-zone hours
and time-zone minutes, or nothing. If at any point the algorithm says
that it "fails", this means that it is aborted at that point and
returns nothing.
1. If the character at position is a U+005A LATIN CAPITAL LETTER Z
character (Z), then:
1. Let timezone[hours] be 0.
2. Let timezone[minutes] be 0.
3. Advance position to the next character in input.
Otherwise, if the character at position is either a U+002B PLUS
SIGN (+) or a U+002D HYPHEN-MINUS (-), then:
1. If the character at position is a U+002B PLUS SIGN (+), let
sign be "positive". Otherwise, it's a U+002D HYPHEN-MINUS (-);
let sign be "negative".
2. Advance position to the next character in input.
3. [3424]Collect a sequence of code points that are [3425]ASCII
digits from input given position. Let s be the collected
sequence.
4. If s is exactly two characters long, then:
1. Interpret s as a base-ten integer. Let timezone[hours] be
that number.
2. If position is beyond the end of input or if the
character at position is not a U+003A COLON character,
then fail. Otherwise, move position forwards one
character.
3. [3426]Collect a sequence of code points that are
[3427]ASCII digits from input given position. If the
collected sequence is not exactly two characters long,
then fail. Otherwise, interpret the resulting sequence as
a base-ten integer. Let timezone[minutes] be that number.
If s is exactly four characters long, then:
1. Interpret the first two characters of s as a base-ten
integer. Let timezone[hours] be that number.
2. Interpret the last two characters of s as a base-ten
integer. Let timezone[minutes] be that number.
Otherwise, fail.
5. If timezone[hours] is not a number in the range
0 ≤ timezone[hours] ≤ 23, then fail.
6. If sign is "negative", then negate timezone[hours].
7. If timezone[minutes] is not a number in the range
0 ≤ timezone[minutes] ≤ 59, then fail.
8. If sign is "negative", then negate timezone[minutes].
Otherwise, fail.
2. Return timezone[hours] and timezone[minutes].
2.3.5.7 Global dates and times
A global date and time consists of a specific [3428]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. [3429][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 [3430]valid date string representing the date
2. A U+0054 LATIN CAPITAL LETTER T character (T) or a U+0020 SPACE
character
3. A [3431]valid time string representing the time
4. A [3432]valid time-zone offset string representing the time-zone
offset
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 interpreted 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 [3433]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-12-13" 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-21 12: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 [3434]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 time was not well coordinated or measured
until relatively recent decades.
* Time-zone offsets differ based on daylight saving time.
The rules to parse a global date and time string are as follows. This
will return either a time in UTC, with associated time-zone offset
information for round-tripping or display purposes, or nothing. If at
any point the algorithm says that it "fails", this means that it is
aborted at that point and returns nothing.
1. Let input be the string being parsed.
2. Let position be a pointer into input, initially pointing at the
start of the string.
3. [3435]Parse a date component to obtain year, month, and day. If
this returns nothing, then fail.
4. If position is beyond the end of input or if the character at
position is neither a U+0054 LATIN CAPITAL LETTER T character (T)
nor a U+0020 SPACE character, then fail. Otherwise, move position
forwards one character.
5. [3436]Parse a time component to obtain hour, minute, and second. If
this returns nothing, then fail.
6. If position is beyond the end of input, then fail.
7. [3437]Parse a time-zone offset component to obtain timezone[hours]
and timezone[minutes]. If this returns nothing, then fail.
8. If position is not beyond the end of input, then fail.
9. Let time be the moment in time at year year, month month, day day,
hours hour, minute minute, second second, subtracting
timezone[hours] hours and timezone[minutes] minutes. That moment in
time is a moment in the UTC time zone.
10. Let timezone be timezone[hours] hours and timezone[minutes] minutes
from UTC.
11. Return time and timezone.
2.3.5.8 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. [3438][GREGORIAN]
A week-year with a number year has 53 weeks if it corresponds to either
a year year in the [3439]proleptic Gregorian calendar that has a
Thursday as its first day (January 1st), or a year year in the
[3440]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 [3441]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 [3442]week as defined here is equivalent to ISO
weeks as defined in ISO 8601. [3443][ISO8601]
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 [3444]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 [3445]ASCII digits, representing the week week, in the range
1 ≤ week ≤ maxweek, where maxweek is the [3446]week number of the
last day of week-year year
The rules to parse a week string are as follows. This will return
either a week-year number and week number, or nothing. If at any point
the algorithm says that it "fails", this means that it is aborted at
that point and returns nothing.
1. Let input be the string being parsed.
2. Let position be a pointer into input, initially pointing at the
start of the string.
3. [3447]Collect a sequence of code points that are [3448]ASCII digits
from input given position. If the collected sequence is not at
least four characters long, then fail. Otherwise, interpret the
resulting sequence as a base-ten integer. Let year be that number.
4. If year is not a number greater than zero, then fail.
5. If position is beyond the end of input or if the character at
position is not a U+002D HYPHEN-MINUS character, then fail.
Otherwise, move position forwards one character.
6. If position is beyond the end of input or if the character at
position is not a U+0057 LATIN CAPITAL LETTER W character (W), then
fail. Otherwise, move position forwards one character.
7. [3449]Collect a sequence of code points that are [3450]ASCII digits
from input given position. If the collected sequence is not exactly
two characters long, then fail. Otherwise, interpret the resulting
sequence as a base-ten integer. Let week be that number.
8. Let maxweek be the [3451]week number of the last day of year year.
9. If week is not a number in the range 1 ≤ week ≤ maxweek, then fail.
10. If position is not beyond the end of input, then fail.
11. Return the week-year number year and the week number week.
2.3.5.9 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 [3452]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 [3453]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:
1. One or more [3454]ASCII digits followed by a U+0044 LATIN
CAPITAL LETTER D character, representing a number of days.
2. A U+0054 LATIN CAPITAL LETTER T character followed by one or
more of the following subcomponents, in the order given:
1. One or more [3455]ASCII digits followed by a U+0048 LATIN
CAPITAL LETTER H character, representing a number of
hours.
2. One or more [3456]ASCII digits followed by a U+004D LATIN
CAPITAL LETTER M character, representing a number of
minutes.
3. The following components:
1. One or more [3457]ASCII digits, representing a
number of seconds.
2. Optionally, a U+002E FULL STOP character (.)
followed by one, two, or three [3458]ASCII digits,
representing a fraction of a second.
3. 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. [3459][ISO8601]
* One or more [3460]duration time components, each with a different
[3461]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:
1. Zero or more [3462]ASCII whitespace.
2. One or more [3463]ASCII digits, representing a number of time
units, scaled by the [3464]duration time component scale
specified (see below) to represent a number of seconds.
3. If the [3465]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 [3466]ASCII
digits, representing a fraction of a second.
4. Zero or more [3467]ASCII whitespace.
5. One of the following characters, representing the duration
time component scale of the time unit used in the numeric part
of the [3468]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
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.
6. Zero or more [3469]ASCII whitespace.
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.
The rules to parse a duration string are as follows. This will return
either a [3470]duration or nothing. If at any point the algorithm says
that it "fails", this means that it is aborted at that point and
returns nothing.
1. Let input be the string being parsed.
2. Let position be a pointer into input, initially pointing at the
start of the string.
3. Let months, seconds, and component count all be zero.
4. Let M-disambiguator be minutes.
This flag's other value is months. It is used to disambiguate the
"M" unit in ISO8601 durations, which use the same unit for months
and minutes. Months are not allowed, but are parsed for future
compatibility and to avoid misinterpreting ISO8601 durations that
would be valid in other contexts.
5. [3471]Skip ASCII whitespace within input given position.
6. If position is past the end of input, then fail.
7. If the character in input pointed to by position is a U+0050 LATIN
CAPITAL LETTER P character, then advance position to the next
character, set M-disambiguator to months, and [3472]skip ASCII
whitespace within input given position.
8. While true:
1. Let units be undefined. It will be assigned one of the
following values: years, months, weeks, days, hours, minutes,
and seconds.
2. Let next character be undefined. It is used to process
characters from the input.
3. If position is past the end of input, then break.
4. If the character in input pointed to by position is a U+0054
LATIN CAPITAL LETTER T character, then advance position to the
next character, set M-disambiguator to minutes, [3473]skip
ASCII whitespace within input given position, and
[3474]continue.
5. Set next character to the character in input pointed to by
position.
6. If next character is a U+002E FULL STOP character (.), then
let N equal zero. (Do not advance position. That is taken care
of below.)
Otherwise, if next character is an [3475]ASCII digit, then
[3476]collect a sequence of code points that are [3477]ASCII
digits from input given position, interpret the resulting
sequence as a base-ten integer, and let N be that number.
Otherwise, next character is not part of a number; fail.
7. If position is past the end of input, then fail.
8. Set next character to the character in input pointed to by
position, and this time advance position to the next
character. (If next character was a U+002E FULL STOP character
(.) before, it will still be that character this time.)
9. If next character is U+002E (.), then:
1. [3478]Collect a sequence of code points that are
[3479]ASCII digits from input given position. Let s be
the resulting sequence.
2. If s is the empty string, then fail.
3. Let length be the number of characters in s.
4. Let fraction be the result of interpreting s as a
base-ten integer, and then dividing that number by
10^length.
5. Increment N by fraction.
6. [3480]Skip ASCII whitespace within input given position.
7. If position is past the end of input, then fail.
8. Set next character to the character in input pointed to
by position, and advance position to the next character.
9. If next character is neither a U+0053 LATIN CAPITAL
LETTER S character nor a U+0073 LATIN SMALL LETTER S
character, then fail.
10. Set units to seconds.
Otherwise:
1. If next character is [3481]ASCII whitespace, then
[3482]skip ASCII whitespace within input given position,
set next character to the character in input pointed to
by position, and advance position to the next character.
2. If next character is a U+0059 LATIN CAPITAL LETTER Y
character, or a U+0079 LATIN SMALL LETTER Y character,
set units to years and set M-disambiguator to months.
If next character is a U+004D LATIN CAPITAL LETTER M
character or a U+006D LATIN SMALL LETTER M character, and
M-disambiguator is months, then set units to months.
If next character is a U+0057 LATIN CAPITAL LETTER W
character or a U+0077 LATIN SMALL LETTER W character, set
units to weeks and set M-disambiguator to minutes.
If next character is a U+0044 LATIN CAPITAL LETTER D
character or a U+0064 LATIN SMALL LETTER D character, set
units to days and set M-disambiguator to minutes.
If next character is a U+0048 LATIN CAPITAL LETTER H
character or a U+0068 LATIN SMALL LETTER H character, set
units to hours and set M-disambiguator to minutes.
If next character is a U+004D LATIN CAPITAL LETTER M
character or a U+006D LATIN SMALL LETTER M character, and
M-disambiguator is minutes, then set units to minutes.
If next character is a U+0053 LATIN CAPITAL LETTER S
character or a U+0073 LATIN SMALL LETTER S character, set
units to seconds and set M-disambiguator to minutes.
Otherwise, if next character is none of the above
characters, then fail.
10. Increment component count.
11. Let multiplier be 1.
12. If units is years, multiply multiplier by 12 and set units to
months.
13. If units is months, add the product of N and multiplier to
months.
Otherwise:
1. If units is weeks, multiply multiplier by 7 and set units
to days.
2. If units is days, multiply multiplier by 24 and set units
to hours.
3. If units is hours, multiply multiplier by 60 and set
units to minutes.
4. If units is minutes, multiply multiplier by 60 and set
units to seconds.
5. Forcibly, units is now seconds. Add the product of N and
multiplier to seconds.
14. [3483]Skip ASCII whitespace within input given position.
9. If component count is zero, fail.
10. If months is not zero, fail.
11. Return the [3484]duration consisting of seconds seconds.
2.3.5.10 Vaguer moments in time
A string is a valid date string with optional time if it is also one of
the following:
* A [3485]valid date string
* A [3486]valid global date and time string
__________________________________________________________________
The rules to parse a date or time string are as follows. The algorithm
will return either a [3487]date, a [3488]time, a [3489]global date and
time, or nothing. If at any point the algorithm says that it "fails",
this means that it is aborted at that point and returns nothing.
1. Let input be the string being parsed.
2. Let position be a pointer into input, initially pointing at the
start of the string.
3. Set start position to the same position as position.
4. Set the date present and time present flags to true.
5. [3490]Parse a date component to obtain year, month, and day. If
this fails, then set the date present flag to false.
6. If date present is true, and position is not beyond the end of
input, and the character at position is either a U+0054 LATIN
CAPITAL LETTER T character (T) or a U+0020 SPACE character, then
advance position to the next character in input.
Otherwise, if date present is true, and either position is beyond
the end of input or the character at position is neither a U+0054
LATIN CAPITAL LETTER T character (T) nor a U+0020 SPACE character,
then set time present to false.
Otherwise, if date present is false, set position back to the same
position as start position.
7. If the time present flag is true, then [3491]parse a time component
to obtain hour, minute, and second. If this returns nothing, then
fail.
8. If the date present and time present flags are both true, but
position is beyond the end of input, then fail.
9. If the date present and time present flags are both true,
[3492]parse a time-zone offset component to obtain timezone[hours]
and timezone[minutes]. If this returns nothing, then fail.
10. If position is not beyond the end of input, then fail.
11. If the date present flag is true and the time present flag is
false, then let date be the date with year year, month month, and
day day, and return date.
Otherwise, if the time present flag is true and the date present
flag is false, then let time be the time with hour hour, minute
minute, and second second, and return time.
Otherwise, let time be the moment in time at year year, month
month, day day, hours hour, minute minute, second second,
subtracting timezone[hours] hours and timezone[minutes] minutes,
that moment in time being a moment in the UTC time zone; let
timezone be timezone[hours] hours and timezone[minutes] minutes
from UTC; and return time and timezone.
2.3.6 Legacy colors
Some obsolete legacy attributes parse colors using the rules for
parsing a legacy color value, given a string input. They will return
either a CSS color or failure.
1. If input is the empty string, then return failure.
2. [3493]Strip leading and trailing ASCII whitespace from input.
3. If input is an [3494]ASCII case-insensitive match for
"transparent", then return failure.
4. If input is an [3495]ASCII case-insensitive match for one of the
[3496]named colors, then return the CSS color corresponding to that
keyword. [3497][CSSCOLOR]
[3498]CSS2 System Colors are not recognized.
5. If input's [3499]code point length is four, and the first character
in input is U+0023 (#), and the last three characters of input are
all [3500]ASCII hex digits, then:
1. Let result be a CSS color.
2. Interpret the second character of input as a hexadecimal
digit; let the red component of result be the resulting number
multiplied by 17.
3. Interpret the third character of input as a hexadecimal digit;
let the green component of result be the resulting number
multiplied by 17.
4. Interpret the fourth character of input as a hexadecimal
digit; let the blue component of result be the resulting
number multiplied by 17.
5. Return result.
6. Replace any [3501]code points greater than U+FFFF in input (i.e.,
any characters that are not in the basic multilingual plane) with
"00".
7. If input's [3502]code point length is greater than 128, truncate
input, leaving only the first 128 characters.
8. If the first character in input is U+0023 (#), then remove it.
9. Replace any character in input that is not an [3503]ASCII hex digit
with U+0030 (0).
10. While input's [3504]code point length is zero or not a multiple of
three, append U+0030 (0) to input.
11. Split input into three strings of equal [3505]code point length, to
obtain three components. Let length be the [3506]code point length
that all of those components have (one third the [3507]code point
length of input).
12. If length is greater than 8, then remove the leading length-8
characters in each component, and let length be 8.
13. While length is greater than two and the first character in each
component is U+0030 (0), remove that character and reduce length by
one.
14. If length is still greater than two, truncate each component,
leaving only the first two characters in each.
15. Let result be a CSS color.
16. Interpret the first component as a hexadecimal number; let the red
component of result be the resulting number.
17. Interpret the second component as a hexadecimal number; let the
green component of result be the resulting number.
18. Interpret the third component as a hexadecimal number; let the blue
component of result be the resulting number.
19. Return result.
2.3.7 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 [3508]ASCII
whitespace, where words consist of any string of one or more
characters, none of which are [3509]ASCII whitespace.
A string containing a [3510]set of space-separated tokens may have
leading or trailing [3511]ASCII whitespace.
An unordered set of unique space-separated tokens is a [3512]set of
space-separated tokens where none of the tokens are duplicated.
An ordered set of unique space-separated tokens is a [3513]set of
space-separated tokens where none of the tokens are duplicated but
where the order of the tokens is meaningful.
[3514]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 [3515]set of space-separated tokens are to be compared
(e.g. case-sensitively or not) is defined on a per-set basis.
2.3.8 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 [3516]ASCII whitespace, nor
containing any U+002C COMMA characters (,), and optionally surrounded
by [3517]ASCII whitespace.
For instance, the string " a ,b,,d d " consists of four tokens: "a",
"b", the empty string, and "d d". Leading and trailing whitespace
around each token doesn't count as part of the token, and the empty
string can be a token.
[3518]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.
2.3.9 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 same [3519]tree.
The rules for parsing a hash-name reference to an element of type type,
given a context node scope, are as follows:
1. If the string being parsed does not contain a U+0023 NUMBER SIGN
character, or if the first such character in the string is the last
character in the string, then return null.
2. Let s be the string from the character immediately after the first
U+0023 NUMBER SIGN character in the string being parsed up to the
end of that string.
3. Return the first element of type type in scope's [3520]tree, in
[3521]tree order, that has an [3522]id or name attribute whose
value is s, or null if there is no such element.
Although [3523]id attributes are accounted for when parsing, they
are not used in determining whether a value is a [3524]valid
hash-name reference. That is, a hash-name reference that refers to
an element based on [3525]id is a conformance error (unless that
element also has a name attribute with the same value).
2.3.10 Media queries
A string is a valid media query list if it matches the
production of Media Queries. [3526][MQ]
A string matches the environment of the user if it is the empty string,
a string consisting of only [3527]ASCII whitespace, or is a media query
list that matches the user's environment according to the definitions
given in Media Queries. [3528][MQ]
2.3.11 Unique internal values
A unique internal value is a value that is serializable, comparable by
value, and never exposed to script.
To create a new unique internal value, return a [3529]unique internal
value that has never previously been returned by this algorithm.
2.4 URLs
2.4.1 Terminology
A string is a valid non-empty URL if it is a [3530]valid URL string but
it is not the empty string.
A string is a valid URL potentially surrounded by spaces if, after
[3531]stripping leading and trailing ASCII whitespace from it, it is a
[3532]valid URL string.
A string is a valid non-empty URL potentially surrounded by spaces if,
after [3533]stripping leading and trailing ASCII whitespace from it, it
is a [3534]valid non-empty URL.
This specification defines the URL about:legacy-compat as a reserved,
though unresolvable, [3535]about: URL, for use in [3536]DOCTYPEs in
[3537]HTML documents when needed for compatibility with XML tools.
[3538][ABOUT]
This specification defines the URL about:html-kind as a reserved,
though unresolvable, [3539]about: URL, that is used as an identifier
for kinds of media tracks. [3540][ABOUT]
This specification defines the URL about:srcdoc as a reserved, though
unresolvable, [3541]about: URL, that is used as the [3542]URL of
[3543]iframe srcdoc documents. [3544][ABOUT]
The fallback base URL of a [3545]Document object document is the
[3546]URL record obtained by running these steps:
1. If document is [3547]an iframe srcdoc document, then:
1. [3548]Assert: document's [3549]about base URL is non-null.
2. Return document's [3550]about base URL.
2. If document's [3551]URL [3552]matches about:blank and document's
[3553]about base URL is non-null, then return document's
[3554]about base URL.
3. Return document's [3555]URL.
The document base URL of a [3556]Document object is the [3557]URL
record obtained by running these steps:
1. If there is no [3558]base element that has an [3559]href attribute
in the [3560]Document, then return the [3561]Document's
[3562]fallback base URL.
2. Otherwise, return the [3563]frozen base URL of the first [3564]base
element in the [3565]Document that has an [3566]href attribute, in
[3567]tree order.
__________________________________________________________________
A [3568]URL matches about:blank if its [3569]scheme is "about", its
[3570]path contains a single string "blank", its [3571]username and
[3572]password are the empty string, and its [3573]host is null.
Such a URL's [3574]query and [3575]fragment can be non-null. For
example, the [3576]URL record created by [3577]parsing
"about:blank?foo#bar" [3578]matches about:blank.
A [3579]URL matches about:srcdoc if its [3580]scheme is "about", its
[3581]path contains a single string "srcdoc", its [3582]query is null,
its [3583]username and [3584]password are the empty string, and its
[3585]host is null.
The reason that [3586]matches about:srcdoc ensures that the [3587]URL's
[3588]query is null is because it is not possible to create [3589]an
iframe srcdoc document whose [3590]URL has a non-null [3591]query,
unlike [3592]Documents whose [3593]URL [3594]matches about:blank. In
other words, the set of all [3595]URLs that [3596]match about:srcdoc
only vary in their [3597]fragment.
2.4.2 Parsing URLs
Parsing a URL is the process of taking a string and obtaining the
[3598]URL record that it represents. While this process is defined in
URL, the HTML standard defines several wrappers to abstract base URLs
and encodings. [3599][URL]
Most new APIs are to use [3600]parse a URL. Older APIs and HTML
elements might have reason to use [3601]encoding-parse a URL. When a
custom base URL is needed or no base URL is desired, the [3602]URL
parser can of course be used directly as well.
To parse a URL, given a string url, relative to a [3603]Document object
or [3604]environment settings object environment, run these steps. They
return failure or a [3605]URL.
1. Let baseURL be environment's [3606]base URL, if environment is a
[3607]Document object; otherwise environment's [3608]API base URL.
2. Return the result of applying the [3609]URL parser to url, with
baseURL.
To encoding-parse a URL, given a string url, relative to a
[3610]Document object or [3611]environment settings object environment,
run these steps. They return failure or a [3612]URL.
1. Let encoding be [3613]UTF-8.
2. If environment is a [3614]Document object, then set encoding to
environment's [3615]character encoding.
3. Otherwise, if environment's [3616]relevant global object is a
[3617]Window object, set encoding to environment's [3618]relevant
global object's [3619]associated Document's [3620]character
encoding.
4. Let baseURL be environment's [3621]base URL, if environment is a
[3622]Document object; otherwise environment's [3623]API base URL.
5. Return the result of applying the [3624]URL parser to url, with
baseURL and encoding.
To encoding-parse-and-serialize a URL, given a string url, relative to
a [3625]Document object or [3626]environment settings object
environment, run these steps. They return failure or a string.
1. Let url be the result of [3627]encoding-parsing a URL given url,
relative to environment.
2. If url is failure, then return failure.
3. Return the result of applying the [3628]URL serializer to url.
2.4.3 Dynamic changes to base URLs
When a document's [3629]document base URL changes, all elements in that
document are [3630]affected by a base URL change.
The following are [3631]base URL change steps, which run when an
element is [3632]affected by a base URL change (as defined by DOM):
If the element creates a [3633]hyperlink
If the [3634]URL identified by the hyperlink is being shown to
the user, or if any data derived from that [3635]URL is
affecting the display, then the [3636]href attribute's value
should be [3637]reparsed, relative to the element's [3638]node
document and the UI updated appropriately.
For example, the CSS [3639]:link/[3640]:visited
[3641]pseudo-classes might have been affected.
If the hyperlink has a [3642]ping attribute and its [3643]URL(s)
are being shown to the user, then the [3644]ping attribute's
tokens should be [3645]reparsed, relative to the element's
[3646]node document and the UI updated appropriately.
If the element is a [3647]q, [3648]blockquote, [3649]ins, or [3650]del
element with a cite attribute
If the [3651]URL identified by the cite attribute is being shown
to the user, or if any data derived from that [3652]URL is
affecting the display, then the cite attribute's value should be
[3653]reparsed, relative to the element's [3654]node document
and the UI updated appropriately.
Otherwise
The element is not directly affected.
For instance, changing the base URL doesn't affect the image
displayed by [3655]img elements, although subsequent accesses of
the [3656]src IDL attribute from script will return a new
[3657]absolute URL that might no longer correspond to the image
being shown.
2.5 Fetching resources
2.5.1 Terminology
A [3658]response whose [3659]type is "basic", "cors", or "default" is
CORS-same-origin. [3660][FETCH]
A [3661]response whose [3662]type is "opaque" or "opaqueredirect" is
CORS-cross-origin.
A [3663]response's unsafe response is its [3664]internal response if it
has one, and the [3665]response itself otherwise.
To create a potential-CORS request, given a url, destination,
corsAttributeState, and an optional same-origin fallback flag, run
these steps:
1. Let mode be "no-cors" if corsAttributeState is [3666]No CORS, and
"cors" otherwise.
2. If same-origin fallback flag is set and mode is "no-cors", set mode
to "same-origin".
3. Let credentialsMode be "include".
4. If corsAttributeState is [3667]Anonymous, set credentialsMode to
"same-origin".
5. Return a new [3668]request whose [3669]URL is url,
[3670]destination is destination, [3671]mode is mode,
[3672]credentials mode is credentialsMode, and whose
[3673]use-URL-credentials flag is set.
2.5.2 Determining the type of a resource
The Content-Type metadata of a resource must be obtained and
interpreted in a manner consistent with the requirements of MIME
Sniffing. [3674][MIMESNIFF]
The [3675]computed MIME type of a resource must be found in a manner
consistent with the requirements given in MIME Sniffing.
[3676][MIMESNIFF]
The [3677]rules for sniffing images specifically, the [3678]rules for
distinguishing if a resource is text or binary, and the [3679]rules for
sniffing audio and video specifically are also defined in MIME
Sniffing. These rules return a [3680]MIME type as their result.
[3681][MIMESNIFF]
It is imperative that the rules in MIME Sniffing be followed exactly.
When a user agent uses different heuristics for content type detection
than the server expects, security problems can occur. For more details,
see MIME Sniffing. [3682][MIMESNIFF]
2.5.3 Extracting character encodings from [3683]meta elements
The algorithm for extracting a character encoding from a meta element,
given a string s, is as follows. It returns either a character encoding
or nothing.
1. Let position be a pointer into s, initially pointing at the start
of the string.
2. Loop: Find the first seven characters in s after position that are
an [3684]ASCII case-insensitive match for the word "charset". If no
such match is found, return nothing.
3. Skip any [3685]ASCII whitespace that immediately follow the word
"charset" (there might not be any).
4. If the next character is not a U+003D EQUALS SIGN (=), then move
position to point just before that next character, and jump back to
the step labeled loop.
5. Skip any [3686]ASCII whitespace that immediately follow the equals
sign (there might not be any).
6. Process the next character as follows:
If it is a U+0022 QUOTATION MARK character (") and there is a
later U+0022 QUOTATION MARK character (") in s
If it is a U+0027 APOSTROPHE character (') and there is a later
U+0027 APOSTROPHE character (') in s
Return the result of [3687]getting an encoding from the
substring that is between this character and the next
earliest occurrence of this character.
If it is an unmatched U+0022 QUOTATION MARK character (")
If it is an unmatched U+0027 APOSTROPHE character (')
If there is no next character
Return nothing.
Otherwise
Return the result of [3688]getting an encoding from the
substring that consists of this character up to but not
including the first [3689]ASCII whitespace or U+003B
SEMICOLON character (;), or the end of s, whichever comes
first.
This algorithm is distinct from those in the HTTP specifications (for
example, HTTP doesn't allow the use of single quotes and requires
supporting a backslash-escape mechanism that is not supported by this
algorithm). While the algorithm is used in contexts that, historically,
were related to HTTP, the syntax as supported by implementations
diverged some time ago. [3690][HTTP]
2.5.4 CORS settings attributes
(BUTTON) ✔MDN
[3691]Attributes/crossorigin
Support in all current engines.
Firefox8+Safari6+Chrome13+
__________________________________________________________________
A CORS settings attribute is an [3692]enumerated attribute with the
following keywords and states:
Keyword State Brief description
anonymous Anonymous [3693]Requests for the element will have their
[3694]mode set to "cors" and their [3695]credentials mode set to
"same-origin".
(the empty string)
use-credentials Use Credentials [3696]Requests for the element will
have their [3697]mode set to "cors" and their [3698]credentials mode
set to "include".
The attribute's [3699]missing value default is the No CORS state, and
its [3700]invalid value default is the [3701]Anonymous state. For the
purposes of [3702]reflection, the [3703]canonical keyword for the
[3704]Anonymous state is the [3705]anonymous keyword.
The majority of fetches governed by [3706]CORS settings attributes will
be done via the [3707]create a potential-CORS request algorithm.
For more modern features, where the request's [3708]mode is always
"cors", certain [3709]CORS settings attributes have been repurposed to
have a slightly different meaning, wherein they only impact the
[3710]request's [3711]credentials mode. To perform this translation, we
define the CORS settings attribute credentials mode for a given
[3712]CORS settings attribute to be determined by switching on the
attribute's state:
[3713]No CORS
[3714]Anonymous
"same-origin"
[3715]Use Credentials
"include"
2.5.5 Referrer policy attributes
A referrer policy attribute is an [3716]enumerated attribute. Each
[3717]referrer policy, including the empty string, is a keyword for
this attribute, mapping to a state of the same name.
The attribute's [3718]missing value default and [3719]invalid value
default are both the empty string state.
The impact of these states on the processing model of various
[3720]fetches is defined in more detail throughout this specification,
in Fetch, and in Referrer Policy. [3721][FETCH] [3722][REFERRERPOLICY]
Several signals can contribute to which processing model is used for a
given [3723]fetch; a [3724]referrer policy attribute is only one of
them. In general, the order in which these signals are processed are:
1. First, the presence of a [3725]noreferrer link type;
2. Then, the value of a [3726]referrer policy attribute;
3. Then, the presence of any [3727]meta element with [3728]name
attribute set to [3729]referrer.
4. Finally, the `[3730]Referrer-Policy` HTTP header.
2.5.6 Nonce attributes
(BUTTON) ✔MDN
[3731]Global_attributes/nonce
Support in all current engines.
Firefox31+SafariYesChromeYes
__________________________________________________________________
A nonce content attribute represents a cryptographic nonce ("number
used once") which can be used by Content Security Policy to determine
whether or not a given fetch will be allowed to proceed. The value is
text. [3732][CSP]
Elements that have a [3733]nonce content attribute ensure that the
cryptographic nonce is only exposed to script (and not to side-channels
like CSS attribute selectors) by taking the value from the content
attribute, moving it into an internal slot named
[[CryptographicNonce]], exposing it to script via the
[3734]HTMLOrSVGElement interface mixin, and setting the content
attribute to the empty string. Unless otherwise specified, the slot's
value is the empty string.
element.[3735]nonce
Returns the value set for element's cryptographic nonce. If the
setter was not used, this will be the value originally found in
the [3736]nonce content attribute.
element.[3737]nonce = value
Updates element's cryptographic nonce value.
The nonce IDL attribute must, on getting, return the value of this
element's [3739][[CryptographicNonce]]; and on setting, set this
element's [3740][[CryptographicNonce]] to the given value.
Note how the setter for the [3741]nonce IDL attribute does not update
the corresponding content attribute. This, as well as the below setting
of the [3742]nonce content attribute to the empty string when an
element [3743]becomes browsing-context connected, is meant to prevent
exfiltration of the nonce value through mechanisms that can easily read
content attributes, such as selectors. Learn more in [3744]issue #2369,
where this behavior was introduced.
The following [3745]attribute change steps are used for the [3746]nonce
content attribute:
1. If element does not [3747]include [3748]HTMLOrSVGElement, then
return.
2. If localName is not [3749]nonce or namespace is not null, then
return.
3. If value is null, then set element's [3750][[CryptographicNonce]]
to the empty string.
4. Otherwise, set element's [3751][[CryptographicNonce]] to value.
Whenever an element [3752]including [3753]HTMLOrSVGElement
[3754]becomes browsing-context connected, the user agent must execute
the following steps on the element:
1. Let CSP list be element's [3755]shadow-including root's
[3756]policy container's [3757]CSP list.
2. If CSP list [3758]contains a header-delivered Content Security
Policy, and element has a [3759]nonce content attribute whose value
is not the empty string, then:
1. Let nonce be element's [3760][[CryptographicNonce]].
2. [3761]Set an attribute value for element using "[3762]nonce"
and the empty string.
3. Set element's [3763][[CryptographicNonce]] to nonce.
If element's [3764][[CryptographicNonce]] were not restored it
would be the empty string at this point.
The [3765]cloning steps for elements that [3766]include
[3767]HTMLOrSVGElement given node, copy, and subtree are to set copy's
[3768][[CryptographicNonce]] to node's [3769][[CryptographicNonce]].
2.5.7 Lazy loading attributes
(BUTTON) ✔MDN
[3770]Lazy_loading
Support in all current engines.
Firefox75+Safari15.4+Chrome77+
__________________________________________________________________
A lazy loading attribute is an [3771]enumerated attribute with the
following keywords and states:
Keyword State Brief description
lazy Lazy Used to defer fetching a resource until some conditions are
met.
eager Eager Used to fetch a resource immediately; the default state.
The attribute directs the user agent to fetch a resource immediately or
to defer fetching until some conditions associated with the element are
met, according to the attribute's current state.
The attribute's [3772]missing value default and [3773]invalid value
default are both the [3774]Eager state.
__________________________________________________________________
The will lazy load element steps, given an element element, are as
follows:
1. If [3775]scripting is disabled for element, then return false.
This is an anti-tracking measure, because if a user agent supported
lazy loading when scripting is disabled, it would still be possible
for a site to track a user's approximate scroll position throughout
a session, by strategically placing images in a page's markup such
that a server can track how many images are requested and when.
2. If element's [3776]lazy loading attribute is in the [3777]Lazy
state, then return true.
3. Return false.
Each [3778]img and [3779]iframe element has associated lazy load
resumption steps, initially null.
For [3780]img and [3781]iframe elements that [3782]will lazy load,
these steps are run from the [3783]lazy load intersection observer's
callback or when their [3784]lazy loading attribute is set to the
[3785]Eager state. This causes the element to continue loading.
Each [3786]Document has a lazy load intersection observer, initially
set to null but can be set to an [3787]IntersectionObserver instance.
To start intersection-observing a lazy loading element element, run
these steps:
1. Let doc be element's [3788]node document.
2. If doc's [3789]lazy load intersection observer is null, set it to a
new [3790]IntersectionObserver instance, initialized as follows:
The intention is to use the original value of the
[3791]IntersectionObserver constructor. However, we're forced to
use the JavaScript-exposed constructor in this specification, until
Intersection Observer exposes low-level hooks for use in
specifications. See bug [3792]w3c/IntersectionObserver#464 which
tracks this. [3793][INTERSECTIONOBSERVER]
+ The callback is these steps, with arguments entries and
observer:
1. For each entry in entries using a method of iteration
which does not trigger developer-modifiable array
accessors or iteration hooks:
1. Let resumptionSteps be null.
2. If entry.[3794]isIntersecting is true, then set
resumptionSteps to entry.[3795]target's [3796]lazy
load resumption steps.
3. If resumptionSteps is null, then return.
4. [3797]Stop intersection-observing a lazy loading
element for entry.[3798]target.
5. Set entry.[3799]target's [3800]lazy load resumption
steps to null.
6. Invoke resumptionSteps.
The intention is to use the original value of the
[3801]isIntersecting and [3802]target getters. See
[3803]w3c/IntersectionObserver#464.
[3804][INTERSECTIONOBSERVER]
+ The options is an [3805]IntersectionObserverInit dictionary
with the following dictionary members: «[ "scrollMargin" →
[3806]lazy load scroll margin ]»
This allows for fetching the image during scrolling, when it
does not yet — but is about to — intersect the viewport.
The [3807]lazy load scroll margin suggestions imply dynamic
changes to the value, but the [3808]IntersectionObserver API
does not support changing the scroll margin. See issue
[3809]w3c/IntersectionObserver#428.
3. Call doc's [3810]lazy load intersection observer's [3811]observe
method with element as the argument.
The intention is to use the original value of the [3812]observe
method. See [3813]w3c/IntersectionObserver#464.
[3814][INTERSECTIONOBSERVER]
To stop intersection-observing a lazy loading element element, run
these steps:
1. Let doc be element's [3815]node document.
2. [3816]Assert: doc's [3817]lazy load intersection observer is not
null.
3. Call doc's [3818]lazy load intersection observer's [3819]unobserve
method with element as the argument.
The intention is to use the original value of the [3820]unobserve
method. See [3821]w3c/IntersectionObserver#464.
[3822][INTERSECTIONOBSERVER]
[3823](This is a tracking vector.) The lazy load scroll margin is an
[3824]implementation-defined value, but with the following suggestions
to consider:
* Set a minimum value that most often results in the resources being
loaded before they intersect the viewport under normal usage
patterns for the given device.
* The typical scrolling speed: increase the value for devices with
faster typical scrolling speeds.
* The current scrolling speed or momentum: the UA can attempt to
predict where the scrolling will likely stop, and adjust the value
accordingly.
* The network quality: increase the value for slow or high-latency
connections.
* User preferences can influence the value.
It is important [3825]for privacy that the [3826]lazy load scroll
margin not leak additional information. For example, the typical
scrolling speed on the current device could be imprecise so as to not
introduce a new fingerprinting vector.
2.5.8 Blocking attributes
A blocking attribute explicitly indicates that certain operations
should be blocked on the fetching of an external resource. The
operations that can be blocked are represented by possible blocking
tokens, which are strings listed by the following table:
Possible blocking token Description
"render" The element is [3827]potentially render-blocking.
In the future, there might be more [3828]possible blocking tokens.
A [3829]blocking attribute must have a value that is an [3830]unordered
set of unique space-separated tokens, each of which are [3831]possible
blocking tokens. The [3832]supported tokens of a [3833]blocking
attribute are the [3834]possible blocking tokens. Any element can have
at most one [3835]blocking attribute.
The blocking tokens set for an element el are the result of the
following steps:
1. Let value be the value of el's [3836]blocking attribute, or the
empty string if no such attribute exists.
2. Set value to value, [3837]converted to ASCII lowercase.
3. Let rawTokens be the result of [3838]splitting value on ASCII
whitespace.
4. Return a set containing the elements of rawTokens that are
[3839]possible blocking tokens.
An element is potentially render-blocking if its [3840]blocking tokens
set contains "[3841]render", or if it is implicitly potentially
render-blocking, which will be defined at the individual elements. By
default, an element is not [3842]implicitly potentially
render-blocking.
2.5.9 Fetch priority attributes
A fetch priority attribute is an [3843]enumerated attribute with the
following keywords and states:
Keyword State Brief description
high high Signals a high-priority [3844]fetch relative to other
resources with the same [3845]destination.
low low Signals a low-priority [3846]fetch relative to other resources
with the same [3847]destination.
auto auto Signals automatic determination of [3848]fetch priority
relative to other resources with the same [3849]destination.
The attribute's [3850]missing value default and [3851]invalid value
default are both the [3852]auto state.
2.6 Common DOM interfaces
2.6.1 Reflecting content attributes in IDL attributes
The building blocks for reflecting are as follows:
* A reflected target is an element or [3853]ElementInternals object.
It is typically clear from context and typically identical to the
interface of the [3854]reflected IDL attribute. It is always
identical to that interface when it is an [3855]ElementInternals
object.
* A reflected IDL attribute is an attribute interface member.
* A reflected content attribute name is a string. When the
[3856]reflected target is an element, it represents the local name
of a content attribute whose namespace is null. When the
[3857]reflected target is an [3858]ElementInternals object, it
represents a key of the [3859]reflected target's [3860]target
element's [3861]internal content attribute map.
A [3862]reflected IDL attribute can be defined to reflect a
[3863]reflected content attribute name of a [3864]reflected target. In
general this means that the IDL attribute getter returns the current
value of the content attribute, and the setter changes the value of the
content attribute to the given value.
If the [3865]reflected target is an element, then the [3866]reflected
IDL attribute can additionally declare to support ElementInternals.
This means that the [3867]ElementInternals interface also has a
[3868]reflected IDL attribute, with the same identifier, and that
[3869]reflected IDL attribute [3870]reflects the same [3871]reflected
content attribute name.
The fooBar IDL attribute must [3872]reflect the foobar content
attribute and [3873]support ElementInternals.
[3874]Reflected targets have these associated algorithms:
* get the element: takes no arguments; returns an element.
* get the content attribute: takes no arguments; returns null or a
string.
* set the content attribute: takes a string value; returns nothing.
* delete the content attribute: takes no arguments; returns nothing.
For a [3875]reflected target that is an element element, these are
defined as follows:
[3876]get the element
1. Return element.
[3877]get the content attribute
1. Let attribute be the result of running [3878]get an attribute
by namespace and local name given null, the [3879]reflected
content attribute name, and element.
2. If attribute is null, then return null.
3. Return attribute's [3880]value.
[3881]set the content attribute with a string value
1. [3882]Set an attribute value given element, the
[3883]reflected content attribute name, and value.
[3884]delete the content attribute
1. [3885]Remove an attribute by namespace and local name given
null, the [3886]reflected content attribute name, and element.
For a [3887]reflected target that is an [3888]ElementInternals object
elementInternals, they are defined as follows:
This results in somewhat redundant data structures for
[3909]ElementInternals objects as their [3910]target element's
[3911]internal content attribute map cannot be directly manipulated and
as such reflection is only happening in a single direction. This
approach was nevertheless chosen to make it less error-prone to define
IDL attributes that are shared between [3912]reflected targets and
benefit from common API semantics.
__________________________________________________________________
IDL attributes of type [3913]DOMString or [3914]DOMString? that
[3915]reflect [3916]enumerated content attributes can be limited to
only known values. Per the processing models below, those will cause
the getters for such IDL attributes to only return keywords for those
enumerated attributes, or the empty string or null.
If a [3917]reflected IDL attribute has the type [3918]DOMString:
* The getter steps are:
1. Let element be the result of running [3919]this's [3920]get
the element.
2. Let contentAttributeValue be the result of running
[3921]this's [3922]get the content attribute.
3. Let attributeDefinition be the attribute definition of
element's content attribute whose namespace is null and local
name is the [3923]reflected content attribute name.
4. If attributeDefinition indicates it is an [3924]enumerated
attribute and the [3925]reflected IDL attribute is defined to
be [3926]limited to only known values:
1. If contentAttributeValue does not correspond to any state
of attributeDefinition (e.g., it is null and there is no
[3927]missing value default), or if it is in a state of
attributeDefinition with no associated keyword value,
then return the empty string.
2. Return the [3928]canonical keyword for the state of
attributeDefinition that contentAttributeValue
corresponds to.
5. If contentAttributeValue is null, then return the empty
string.
6. Return contentAttributeValue.
* The setter steps are to run [3929]this's [3930]set the content
attribute with the given value.
If a [3931]reflected IDL attribute has the type [3932]DOMString?:
* The getter steps are:
1. Let element be the result of running [3933]this's [3934]get
the element.
2. Let contentAttributeValue be the result of running
[3935]this's [3936]get the content attribute.
3. Let attributeDefinition be the attribute definition of
element's content attribute whose namespace is null and local
name is the [3937]reflected content attribute name.
4. If attributeDefinition indicates it is an [3938]enumerated
attribute:
1. [3939]Assert: the [3940]reflected IDL attribute is
[3941]limited to only known values.
2. [3942]Assert: contentAttributeValue corresponds to a
state of attributeDefinition.
3. If contentAttributeValue corresponds to a state of
attributeDefinition with no associated keyword value,
then return null.
4. Return the [3943]canonical keyword for the state of
attributeDefinition that contentAttributeValue
corresponds to.
5. Return contentAttributeValue.
* The setter steps are:
1. If the given value is null, then run [3944]this's [3945]delete
the content attribute.
2. Otherwise, run [3946]this's [3947]set the content attribute
with the given value.
If a [3948]reflected IDL attribute has the type [3949]USVString:
* The getter steps are:
1. Let element be the result of running [3950]this's [3951]get
the element.
2. Let contentAttributeValue be the result of running
[3952]this's [3953]get the content attribute.
3. Let attributeDefinition be the attribute definition of
element's content attribute whose namespace is null and local
name is the [3954]reflected content attribute name.
4. If attributeDefinition indicates it contains a [3955]URL:
1. If contentAttributeValue is null, then return the empty
string.
2. Let urlString be the result of
[3956]encoding-parsing-and-serializing a URL given
contentAttributeValue, relative to element's [3957]node
document.
3. If urlString is not failure, then return urlString.
5. Return contentAttributeValue, [3958]converted to a scalar
value string.
* The setter steps are to run [3959]this's [3960]set the content
attribute with the given value.
If a [3961]reflected IDL attribute has the type [3962]boolean:
* The getter steps are:
1. Let contentAttributeValue be the result of running
[3963]this's [3964]get the content attribute.
2. If contentAttributeValue is null, then return false.
3. Return true.
* The setter steps are:
1. If the given value is false, then run [3965]this's
[3966]delete the content attribute.
2. If the given value is true, then run [3967]this's [3968]set
the content attribute with the empty string.
This corresponds to the rules for [3969]boolean content attributes.
If a [3970]reflected IDL attribute has the type [3971]long, optionally
limited to only non-negative numbers and optionally with a default
value defaultValue:
* The getter steps are:
1. Let contentAttributeValue be the result of running
[3972]this's [3973]get the content attribute.
2. If contentAttributeValue is not null:
1. Let parsedValue be the result of [3974]integer parsing
contentAttributeValue if the [3975]reflected IDL
attribute is not [3976]limited to only non-negative
numbers; otherwise the result of [3977]non-negative
integer parsing contentAttributeValue.
2. If parsedValue is not an error and is within the
[3978]long range, then return parsedValue.
3. If the [3979]reflected IDL attribute has a [3980]default
value, then return defaultValue.
4. If the [3981]reflected IDL attribute is [3982]limited to only
non-negative numbers, then return −1.
5. Return 0.
* The setter steps are:
1. If the [3983]reflected IDL attribute is [3984]limited to only
non-negative numbers and the given value is negative, then
throw an [3985]"IndexSizeError" [3986]DOMException.
2. Run [3987]this's [3988]set the content attribute with the
given value converted to the shortest possible string
representing the number as a [3989]valid integer.
If a [3990]reflected IDL attribute has the type [3991]unsigned long,
optionally limited to only positive numbers, limited to only positive
numbers with fallback, or clamped to the range [clampedMin,
clampedMax], and optionally with a [3992]default value defaultValue:
* The getter steps are:
1. Let contentAttributeValue be the result of running
[3993]this's [3994]get the content attribute.
2. Let minimum be 0.
3. If the [3995]reflected IDL attribute is [3996]limited to only
positive numbers or [3997]limited to only positive numbers
with fallback, then set minimum to 1.
4. If the [3998]reflected IDL attribute is [3999]clamped to the
range, then set minimum to clampedMin.
5. Let maximum be 2147483647 if the [4000]reflected IDL attribute
is not [4001]clamped to the range; otherwise clampedMax.
6. If contentAttributeValue is not null:
1. Let parsedValue be the result of [4002]non-negative
integer parsing contentAttributeValue.
2. If parsedValue is not an error and is in the range
minimum to maximum, inclusive, then return parsedValue.
3. If parsedValue is not an error and the [4003]reflected
IDL attribute is [4004]clamped to the range:
1. If parsedValue is less than minimum, then return
minimum.
2. Return maximum.
7. If the [4005]reflected IDL attribute has a [4006]default
value, then return defaultValue.
8. Return minimum.
* The setter steps are:
1. If the [4007]reflected IDL attribute is [4008]limited to only
positive numbers and the given value is 0, then throw an
[4009]"IndexSizeError" [4010]DOMException.
2. Let minimum be 0.
3. If the [4011]reflected IDL attribute is [4012]limited to only
positive numbers or [4013]limited to only positive numbers
with fallback, then set minimum to 1.
4. Let newValue be minimum.
5. If the [4014]reflected IDL attribute has a [4015]default
value, then set newValue to defaultValue.
6. If the given value is in the range minimum to 2147483647,
inclusive, then set newValue to it.
7. Run [4016]this's [4017]set the content attribute with newValue
converted to the shortest possible string representing the
number as a [4018]valid non-negative integer.
[4019]Clamped to the range has no effect on the setter steps.
If a [4020]reflected IDL attribute has the type [4021]double,
optionally [4022]limited to only positive numbers and optionally with a
[4023]default value defaultValue:
* The getter steps are:
1. Let contentAttributeValue be the result of running
[4024]this's [4025]get the content attribute.
2. If contentAttributeValue is not null:
1. Let parsedValue be the result of [4026]floating-point
number parsing contentAttributeValue.
2. If parsedValue is not an error and is greater than 0,
then return parsedValue.
3. If parsedValue is not an error and the [4027]reflected
IDL attribute is not [4028]limited to only positive
numbers, then return parsedValue.
3. If the [4029]reflected IDL attribute has a [4030]default
value, then return defaultValue.
4. Return 0.
* The setter steps are:
1. If the [4031]reflected IDL attribute is [4032]limited to only
positive numbers and the given value is not greater than 0,
then return.
2. Run [4033]this's [4034]set the content attribute with the
given value, converted to the [4035]best representation of the
number as a floating-point number.
The values Infinity and Not-a-Number (NaN) values throw an exception on
setting, as defined in Web IDL. [4036][WEBIDL]
If a [4037]reflected IDL attribute has the type [4038]DOMTokenList,
then its getter steps are to return a [4039]DOMTokenList object whose
associated element is [4040]this and associated attribute's local name
is the [4041]reflected content attribute name. Specification authors
cannot use [4042]support ElementInternals for IDL attributes of this
type.
If a [4043]reflected IDL attribute has the type T?, where T is either
[4044]Element or an interface that inherits from [4045]Element, then
with attr being the [4046]reflected content attribute name:
* Its [4047]reflected target has an explicitly set attr-element,
which is a weak reference to an element or null. It is initially
null.
* Its [4048]reflected target reflectedTarget has a get the
attr-associated element algorithm, that runs these steps:
1. Let element be the result of running reflectedTarget's
[4049]get the element.
2. Let contentAttributeValue be the result of running
reflectedTarget's [4050]get the content attribute.
3. If reflectedTarget's [4051]explicitly set attr-element is not
null:
1. If reflectedTarget's [4052]explicitly set attr-element is
a [4053]descendant of any of element's
[4054]shadow-including ancestors, then return
reflectedTarget's [4055]explicitly set attr-element.
2. Return null.
4. Otherwise, if contentAttributeValue is not null, return the
first element candidate, in [4056]tree order, that meets the
following criteria:
o candidate's [4057]root is the same as element's
[4058]root;
o candidate's [4059]ID is contentAttributeValue; and
o candidate [4060]implements T.
If no such element exists, then return null.
5. Return null.
* The getter steps are to return the result of running [4061]this's
[4062]get the attr-associated element.
* The setter steps are:
1. If the given value is null, then:
1. Set [4063]this's [4064]explicitly set attr-element to
null.
2. Run [4065]this's [4066]delete the content attribute.
3. Return.
2. Run [4067]this's [4068]set the content attribute with the
empty string.
3. Set [4069]this's [4070]explicitly set attr-element to a weak
reference to the given value.
* For element [4071]reflected targets only: the following
[4072]attribute change steps, given element, localName, oldValue,
value, and namespace, are used to synchronize between the content
attribute and the IDL attribute:
1. If localName is not attr or namespace is not null, then
return.
2. Set element's [4073]explicitly set attr-element to null.
[4074]Reflected IDL attributes of this type are strongly encouraged to
have their identifier end in "Element" for consistency.
If a [4075]reflected IDL attribute has the type FrozenArray?, where
T is either [4076]Element or an interface that inherits from
[4077]Element, then with attr being the [4078]reflected content
attribute name:
* Its [4079]reflected target has an explicitly set attr-elements,
which is either a [4080]list of weak references to elements or
null. It is initially null.
* Its [4081]reflected target has a cached attr-associated elements,
which is a [4082]list of elements. It is initially « ».
* Its [4083]reflected target has a cached attr-associated elements
object, which is a FrozenArray?. It is initially null.
* Its [4084]reflected target reflectedTarget has a get the
attr-associated elements algorithm, which runs these steps:
1. Let elements be an empty [4085]list.
2. Let element be the result of running reflectedTarget's
[4086]get the element.
3. If reflectedTarget's [4087]explicitly set attr-elements is not
null:
1. [4088]For each attrElement in reflectedTarget's
[4089]explicitly set attr-elements:
1. If attrElement is not a [4090]descendant of any of
element's [4091]shadow-including ancestors, then
[4092]continue.
2. [4093]Append attrElement to elements.
4. Otherwise:
1. Let contentAttributeValue be the result of running
reflectedTarget's [4094]get the content attribute.
2. If contentAttributeValue is null, then return null.
3. Let tokens be contentAttributeValue, [4095]split on ASCII
whitespace.
4. [4096]For each id of tokens:
1. Let candidate be the first element, in [4097]tree
order, that meets the following criteria:
@ candidate's [4098]root is the same as element's
[4099]root;
@ candidate's [4100]ID is id; and
@ candidate [4101]implements T.
If no such element exists, then [4102]continue.
2. [4103]Append candidate to elements.
5. Return elements.
* The getter steps are:
1. Let elements be the result of running [4104]this's [4105]get
the attr-associated elements.
2. If the contents of elements is equal to the contents of
[4106]this's [4107]cached attr-associated elements, then
return [4108]this's [4109]cached attr-associated elements
object.
3. Let elementsAsFrozenArray be elements, [4110]converted to a
FrozenArray?.
4. Set [4111]this's [4112]cached attr-associated elements to
elements.
5. Set [4113]this's [4114]cached attr-associated elements object
to elementsAsFrozenArray.
6. Return elementsAsFrozenArray.
This extra caching layer is necessary to preserve the invariant
that element.reflectedElements === element.reflectedElements.
* The setter steps are:
1. If the given value is null:
1. Set [4115]this's [4116]explicitly set attr-elements to
null.
2. Run [4117]this's [4118]delete the content attribute.
3. Return.
2. Run [4119]this's [4120]set the content attribute with the
empty string.
3. Let elements be an empty [4121]list.
4. [4122]For each element in the given value:
1. [4123]Append a weak reference to element to elements.
5. Set [4124]this's [4125]explicitly set attr-elements to
elements.
* For element [4126]reflected targets only: the following
[4127]attribute change steps, given element, localName, oldValue,
value, and namespace, are used to synchronize between the content
attribute and the IDL attribute:
1. If localName is not attr or namespace is not null, then
return.
2. Set element's [4128]explicitly set attr-elements to null.
[4129]Reflected IDL attributes of this type are strongly encouraged to
have their identifier end in "Elements" for consistency.
2.6.2 Using reflect in specifications
[4130]Reflection is primarily about improving web developer ergonomics
by giving them typed access to content attributes through
[4131]reflected IDL attributes. The ultimate source of truth, which the
web platform builds upon, is the content attributes themselves. That
is, specification authors must not use the [4132]reflected IDL
attribute getter or setter steps, but instead must use the content
attribute presence and value. (Or an abstraction on top, such as the
state of an [4133]enumerated attribute.)
Two important exceptions to this are [4134]reflected IDL attributes
whose type is one of the following:
* T?, where T is either [4135]Element or an interface that inherits
from [4136]Element
* FrozenArray?, where T is either [4137]Element or an interface
that inherits from [4138]Element
For those, specification authors must use the [4139]reflected target's
[4140]get the attr-associated element and [4141]get the attr-associated
elements, respectively. The content attribute presence and value must
not be used as they cannot be fully synchronized with the
[4142]reflected IDL attribute.
A [4143]reflected target's [4144]explicitly set attr-element,
[4145]explicitly set attr-elements, [4146]cached attr-associated
elements, and [4147]cached attr-associated elements object are to be
treated as internal implementation details and not to be built upon.
2.6.3 Collections
The [4148]HTMLFormControlsCollection and [4149]HTMLOptionsCollection
interfaces are [4150]collections derived from the [4151]HTMLCollection
interface. The [4152]HTMLAllCollection interface is a [4153]collection,
but is not so derived.
2.6.3.1 The [4154]HTMLAllCollection interface
The [4155]HTMLAllCollection interface is used for the legacy
[4156]document.all attribute. It operates similarly to
[4157]HTMLCollection; the main differences are that it allows a
staggering variety of different (ab)uses of its methods to all end up
returning something, and that it can be called as a function as an
alternative to property access.
All [4158]HTMLAllCollection objects are rooted at a [4159]Document and
have a filter that matches all elements, so the elements
[4160]represented by the collection of an [4161]HTMLAllCollection
object consist of all the descendant elements of the root
[4162]Document.
Objects that implement the [4163]HTMLAllCollection interface are
[4164]legacy platform objects with an additional [[Call]] internal
method described in the [4165]section below. They also have an
[4166][[IsHTMLDDA]] internal slot.
Objects that implement the [4167]HTMLAllCollection interface have
several unusual behaviors, due of the fact that they have an
[4168][[IsHTMLDDA]] internal slot:
* The [4169]ToBoolean abstract operation in JavaScript returns false
when given objects implementing the [4170]HTMLAllCollection
interface.
* The [4171]IsLooselyEqual abstract operation, when given objects
implementing the [4172]HTMLAllCollection interface, returns true
when compared to the undefined and null values. (Comparisons using
the [4173]IsStrictlyEqual abstract operation, and IsLooselyEqual
comparisons to other values such as strings or objects, are
unaffected.)
* The [4174]typeof operator in JavaScript returns the string
"undefined" when applied to objects implementing the
[4175]HTMLAllCollection interface.
These special behaviors are motivated by a desire for compatibility
with two classes of legacy content: one that uses the presence of
[4176]document.all as a way to detect legacy user agents, and one that
only supports those legacy user agents and uses the [4177]document.all
object without testing for its presence first. [4178][JAVASCRIPT]
[Exposed=Window,
[4179]LegacyUnenumerableNamedProperties]
interface HTMLAllCollection {
readonly attribute unsigned long [4180]length;
getter [4181]Element (unsigned long index);
getter ([4182]HTMLCollection or [4183]Element)? [4184]namedItem(DOMString name
);
([4185]HTMLCollection or [4186]Element)? [4187]item(optional DOMString nameOrI
ndex);
// Note: HTMLAllCollection objects have a [4188]custom [[Call]] internal metho
d and an [4189][[IsHTMLDDA]] internal slot.
};
The object's [4190]supported property indices are as defined for
[4191]HTMLCollection objects.
The [4192]supported property names consist of the non-empty values of
all the [4193]id attributes of all the elements [4194]represented by
the collection, and the non-empty values of all the name attributes of
all the [4195]"all"-named elements [4196]represented by the collection,
in [4197]tree order, ignoring later duplicates, with the [4198]id of an
element preceding its name if it contributes both, they differ from
each other, and neither is the duplicate of an earlier entry.
The length getter steps are to return the number of nodes
[4199]represented by the collection.
The indexed property getter must return the result of [4200]getting the
"all"-indexed element from [4201]this given the passed index.
The namedItem(name) method steps are to return the result of
[4202]getting the "all"-named element(s) from [4203]this given name.
The item(nameOrIndex) method steps are:
1. If nameOrIndex was not provided, return null.
2. Return the result of [4204]getting the "all"-indexed or named
element(s) from [4205]this, given nameOrIndex.
__________________________________________________________________
The following elements are "all"-named elements: [4206]a, [4207]button,
[4208]embed, [4209]form, [4210]frame, [4211]frameset, [4212]iframe,
[4213]img, [4214]input, [4215]map, [4216]meta, [4217]object,
[4218]select, and [4219]textarea
To get the "all"-indexed element from an [4220]HTMLAllCollection
collection given an index index, return the index^th element in
collection, or null if there is no such index^th element.
To get the "all"-named element(s) from an [4221]HTMLAllCollection
collection given a name name, perform the following steps:
1. If name is the empty string, return null.
2. Let subCollection be an [4222]HTMLCollection object rooted at the
same [4223]Document as collection, whose filter matches only
elements that are either:
+ [4224]"all"-named elements with a name attribute equal to
name, or,
+ elements with an [4225]ID equal to name.
3. If there is exactly one element in subCollection, then return that
element.
4. Otherwise, if subCollection is empty, return null.
5. Otherwise, return subCollection.
To get the "all"-indexed or named element(s) from an
[4226]HTMLAllCollection collection given nameOrIndex:
1. If nameOrIndex, [4227]converted to a JavaScript String value, is an
[4228]array index property name, return the result of [4229]getting
the "all"-indexed element from collection given the number
represented by nameOrIndex.
2. Return the result of [4230]getting the "all"-named element(s) from
collection given nameOrIndex.
1. If argumentsList's [4231]size is zero, or if argumentsList[0] is
undefined, return null.
2. Let nameOrIndex be the result of [4232]converting argumentsList[0]
to a [4233]DOMString.
3. Let result be the result of [4234]getting the "all"-indexed or
named element(s) from this [4235]HTMLAllCollection given
nameOrIndex.
4. Return the result of [4236]converting result to an ECMAScript
value.
The thisArgument is ignored, and thus code such as
Function.prototype.call.call(document.all, null, "x") will still search
for elements. (document.all.call does not exist, since document.all
does not inherit from Function.prototype.)
2.6.3.2 The [4237]HTMLFormControlsCollection interface
The [4238]HTMLFormControlsCollection interface is used for
[4239]collections of [4240]listed elements in [4241]form elements.
(BUTTON) ✔MDN
[4242]HTMLFormControlsCollection
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
collection.[4253]length
Returns the number of elements in collection.
element = collection.[4254]item(index)
element = collection[index]
Returns the item at index index in collection. The items are
sorted in [4255]tree order.
radioNodeList = collection.[4258]namedItem(name)
element = collection[name]
radioNodeList = collection[name]
Returns the item with [4259]ID or [4260]name name from
collection.
If there are multiple matching items, then a [4261]RadioNodeList
object containing all those elements is returned.
radioNodeList.[4262]value
Returns the value of the first checked radio button represented
by radioNodeList.
radioNodeList.[4263]value = value
Checks the first radio button represented by radioNodeList that
has value value.
The object's [4264]supported property indices are as defined for
[4265]HTMLCollection objects.
The [4266]supported property names consist of the non-empty values of
all the [4267]id and [4268]name attributes of all the elements
[4269]represented by the collection, in [4270]tree order, ignoring
later duplicates, with the [4271]id of an element preceding its
[4272]name if it contributes both, they differ from each other, and
neither is the duplicate of an earlier entry.
The namedItem(name) method must act according to the following
algorithm:
1. If name is the empty string, return null and stop the algorithm.
2. If, at the time the method is called, there is exactly one node in
the collection that has either an [4273]id attribute or a
[4274]name attribute equal to name, then return that node and stop
the algorithm.
3. Otherwise, if there are no nodes in the collection that have either
an [4275]id attribute or a [4276]name attribute equal to name, then
return null and stop the algorithm.
4. Otherwise, create a new [4277]RadioNodeList object representing a
[4278]live view of the [4279]HTMLFormControlsCollection object,
further filtered so that the only nodes in the [4280]RadioNodeList
object are those that have either an [4281]id attribute or a
[4282]name attribute equal to name. The nodes in the
[4283]RadioNodeList object must be sorted in [4284]tree order.
5. Return that [4285]RadioNodeList object.
__________________________________________________________________
Members of the [4286]RadioNodeList interface inherited from the
[4287]NodeList interface must behave as they would on a [4288]NodeList
object.
(BUTTON) ✔MDN
[4289]RadioNodeList/value
Support in all current engines.
Firefox33+Safari7+Chrome21+
__________________________________________________________________
The value IDL attribute on the [4290]RadioNodeList object, on getting,
must return the value returned by running the following steps:
1. Let element be the first element in [4291]tree order represented by
the [4292]RadioNodeList object that is an [4293]input element whose
[4294]type attribute is in the [4295]Radio Button state and whose
[4296]checkedness is true. Otherwise, let it be null.
2. If element is null, return the empty string.
3. If element is an element with no [4297]value attribute, return the
string "on".
4. Otherwise, return the value of element's [4298]value attribute.
On setting, the [4299]value IDL attribute must run the following steps:
1. If the new value is the string "on": let element be the first
element in [4300]tree order represented by the [4301]RadioNodeList
object that is an [4302]input element whose [4303]type attribute is
in the [4304]Radio Button state and whose [4305]value content
attribute is either absent, or present and equal to the new value,
if any. If no such element exists, then instead let element be
null.
Otherwise: let element be the first element in [4306]tree order
represented by the [4307]RadioNodeList object that is an
[4308]input element whose [4309]type attribute is in the
[4310]Radio Button state and whose [4311]value content attribute is
present and equal to the new value, if any. If no such element
exists, then instead let element be null.
2. If element is not null, then set its [4312]checkedness to true.
2.6.3.3 The [4313]HTMLOptionsCollection interface
(BUTTON) ✔MDN
[4314]HTMLOptionsCollection
Support in all current engines.
Firefox1+Safari3+Chrome1+
__________________________________________________________________
The [4315]HTMLOptionsCollection interface is used for [4316]collections
of [4317]option elements. It is always rooted on a [4318]select element
and has attributes and methods that manipulate that element's
descendants.
[Exposed=Window]
interface HTMLOptionsCollection : [4319]HTMLCollection {
// inherits [4320]item(), [4321]namedItem()
[[4322]CEReactions] attribute unsigned long [4323]length; // shadows inherited
[4324]length
[[4325]CEReactions] [4326]setter undefined (unsigned long index, [4327]HTMLOpt
ionElement? option);
[[4328]CEReactions] undefined [4329]add(([4330]HTMLOptionElement or [4331]HTML
OptGroupElement) element, optional ([4332]HTMLElement or long)? before = null);
[[4333]CEReactions] undefined [4334]remove(long index);
attribute long [4335]selectedIndex;
};
collection.[4336]length
Returns the number of elements in collection.
collection.[4337]length = value
When set to a smaller number than the existing length, truncates
the number of [4338]option elements in the container
corresponding to collection.
When set to a greater number than the existing length, if that
number is less than or equal to 100000, adds new blank
[4339]option elements to the container corresponding to
collection.
element = collection.[4340]item(index)
element = collection[index]
Returns the item at index index in collection. The items are
sorted in [4341]tree order.
collection[index] = element
When index is a greater number than the number of items in
collection, adds new blank [4342]option elements in the
corresponding container.
When set to null, removes the item at index index from
collection.
When set to an [4343]option element, adds or replaces it at
index index in collection.
element = collection.[4344]namedItem(name)
element = collection[name]
Returns the item with [4345]ID or [4346]name name from
collection.
If there are multiple matching items, then the first is
returned.
collection.[4347]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
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.
Throws a [4348]"HierarchyRequestError" [4349]DOMException if
element is an ancestor of the element into which it is to be
inserted.
collection.[4350]remove(index)
Removes the item with index index from collection.
collection.[4351]selectedIndex
Returns the index of the first selected item, if any, or −1 if
there is no selected item.
collection.[4352]selectedIndex = index
Changes the selection to the [4353]option element at index index
in collection.
The object's [4354]supported property indices are as defined for
[4355]HTMLCollection objects.
The length getter steps are to return the number of nodes
[4356]represented by the collection.
The [4357]length setter steps are:
1. Let current be the number of nodes [4358]represented by the
collection.
2. If the given value is greater than current, then:
1. If the given value is greater than 100,000, then return.
2. Let n be value − current.
3. Append n new [4359]option elements with no attributes and no
child nodes to the [4360]select element on which [4361]this is
rooted.
3. If the given value is less than current, then:
1. Let n be current − value.
2. Remove the last n nodes in the collection from their parent
nodes.
Setting [4362]length never removes or adds any [4363]optgroup elements,
and never adds new children to existing [4364]optgroup elements (though
it can remove children from them).
The [4365]supported property names consist of the non-empty values of
all the [4366]id and [4367]name attributes of all the elements
[4368]represented by the collection, in [4369]tree order, ignoring
later duplicates, with the [4370]id of an element preceding its
[4371]name if it contributes both, they differ from each other, and
neither is the duplicate of an earlier entry.
When the user agent is to [4372]set the value of a new indexed property
or [4373]set the value of an existing indexed property for a given
property index index to a new value value, it must run the following
algorithm:
1. If value is null, invoke the steps for the [4374]remove method with
index as the argument, and return.
2. Let length be the number of nodes [4375]represented by the
collection.
3. Let n be index minus length.
4. If n is greater than zero, then [4376]append a
[4377]DocumentFragment consisting of n-1 new [4378]option elements
with no attributes and no child nodes to the [4379]select element
on which the [4380]HTMLOptionsCollection is rooted.
5. If n is greater than or equal to zero, [4381]append value to the
[4382]select element. Otherwise, [4383]replace the indexth element
in the collection by value.
The add(element, before) method must act according to the following
algorithm:
1. If element is an ancestor of the [4384]select element on which the
[4385]HTMLOptionsCollection is rooted, then throw a
[4386]"HierarchyRequestError" [4387]DOMException.
2. If before is an element, but that element isn't a descendant of the
[4388]select element on which the [4389]HTMLOptionsCollection is
rooted, then throw a [4390]"NotFoundError" [4391]DOMException.
3. If element and before are the same element, then return.
4. If before is a node, then let reference be that node. Otherwise, if
before is an integer, and there is a beforeth node in the
collection, let reference be that node. Otherwise, let reference be
null.
5. If reference is not null, let parent be the parent node of
reference. Otherwise, let parent be the [4392]select element on
which the [4393]HTMLOptionsCollection is rooted.
6. [4394]Pre-insert element into parent node before reference.
The remove(index) method must act according to the following algorithm:
1. If the number of nodes [4395]represented by the collection is zero,
return.
2. If index is not a number greater than or equal to 0 and less than
the number of nodes [4396]represented by the collection, return.
3. Let element be the indexth element in the collection.
4. Remove element from its parent node.
The selectedIndex IDL attribute must act like the identically named
attribute on the [4397]select element on which the
[4398]HTMLOptionsCollection is rooted
2.6.4 The [4399]DOMStringList interface
(BUTTON) ✔MDN
[4400]DOMStringList
Support in all current engines.
Firefox1+Safari5.1+Chrome1+
__________________________________________________________________
The [4401]DOMStringList interface is a non-fashionable retro way of
representing a list of strings.
[Exposed=(Window,Worker)]
interface DOMStringList {
readonly attribute unsigned long [4402]length;
getter DOMString? [4403]item(unsigned long index);
boolean [4404]contains(DOMString string);
};
New APIs must use sequence or equivalent rather than
[4405]DOMStringList.
strings.[4406]length
Returns the number of strings in strings.
strings[index]
strings.[4407]item(index)
Returns the string with index index from strings.
strings.[4408]contains(string)
Returns true if strings contains string, and false otherwise.
Each [4409]DOMStringList object has an associated [4410]list.
The [4411]DOMStringList interface [4412]supports indexed properties.
The [4413]supported property indices are the [4414]indices of
[4415]this's associated list.
(BUTTON) ✔MDN
[4416]DOMStringList/length
Support in all current engines.
Firefox1+Safari5.1+Chrome1+
__________________________________________________________________
The item(index) method steps are to return the indexth item in
[4420]this's associated list, or null if index plus one is greater than
[4421]this's associated list's [4422]size.
(BUTTON) ✔MDN
[4423]DOMStringList/contains
Support in all current engines.
Firefox1.5+Safari5.1+Chrome1+
__________________________________________________________________
The contains(string) method steps are to return true if [4424]this's
associated list [4425]contains string, and false otherwise.
2.7 Safe passing of structured data
To support passing JavaScript objects, including [4426]platform
objects, across [4427]realm boundaries, this specification defines the
following infrastructure for serializing and deserializing objects,
including in some cases transferring the underlying data instead of
copying it. Collectively this serialization/deserialization process is
known as "structured cloning", although most APIs perform separate
serialization and deserialization steps. (With the notable exception
being the [4428]structuredClone() method.)
This section uses the terminology and typographic conventions from the
JavaScript specification. [4429][JAVASCRIPT]
[4437]Serializable objects support being serialized, and later
deserialized, in a way that is independent of any given [4438]realm.
This allows them to be stored on disk and later restored, or cloned
across [4439]agent and even [4440]agent cluster boundaries.
Not all objects are [4441]serializable objects, and not all aspects of
objects that are [4442]serializable objects are necessarily preserved
when they are serialized.
[4443]Platform objects can be [4444]serializable objects if their
[4445]primary interface is decorated with the [Serializable] IDL
[4446]extended attribute. Such interfaces must also define the
following algorithms:
serialization steps, taking a [4447]platform object value, a
[4448]Record serialized, and a boolean forStorage
A set of steps that serializes the data in value into fields of
serialized. The resulting data serialized into serialized must
be independent of any [4449]realm.
These steps may throw an exception if serialization is not
possible.
These steps may perform a [4450]sub-serialization to serialize
nested data structures. They should not call
[4451]StructuredSerialize directly, as doing so will omit the
important memory argument.
The introduction of these steps should omit mention of the
forStorage argument if it is not relevant to the algorithm.
deserialization steps, taking a [4452]Record serialized, a
[4453]platform object value, and a [4454]realm targetRealm
A set of steps that deserializes the data in serialized, using
it to set up value as appropriate. value will be a newly-created
instance of the [4455]platform object type in question, with
none of its internal data set up; setting that up is the job of
these steps.
These steps may throw an exception if deserialization is not
possible.
These steps may perform a [4456]sub-deserialization to
deserialize nested data structures. They should not call
[4457]StructuredDeserialize directly, as doing so will omit the
important targetRealm and memory arguments.
It is up to the definition of individual platform objects to determine
what data is serialized and deserialized by these steps. Typically the
steps are very symmetric.
The [4458][Serializable] extended attribute must take no arguments, and
must only appear on an interface. It must not appear more than once on
an interface.
For a given [4459]platform object, only the object's [4460]primary
interface is considered during the (de)serialization process. Thus, if
inheritance is involved in defining the interface, each
[4461][Serializable]-annotated interface in the inheritance chain needs
to define standalone [4462]serialization steps and
[4463]deserialization steps, including taking into account any
important data that might come from inherited interfaces.
Let's say we were defining a platform object Person, which had
associated with it two pieces of associated data:
* a name value, which is a string; and
* a best friend value, which is either another Person instance or
null.
We could then define Person instances to be [4464]serializable objects
by annotating the Person interface with the [4465][Serializable]
[4466]extended attribute, and defining the following accompanying
algorithms:
[4467]serialization steps
1. Set serialized.[[Name]] to value's associated name value.
2. Let serializedBestFriend be the [4468]sub-serialization of
value's associated best friend value.
3. Set serialized.[[BestFriend]] to serializedBestFriend.
[4469]deserialization steps
1. Set value's associated name value to serialized.[[Name]].
2. Let deserializedBestFriend be the [4470]sub-deserialization of
serialized.[[BestFriend]].
3. Set value's associated best friend value to
deserializedBestFriend.
Objects defined in the JavaScript specification are handled by the
[4471]StructuredSerialize abstract operation directly.
Originally, this specification defined the concept of "cloneable
objects", which could be cloned from one [4472]realm to another.
However, to better specify the behavior of certain more complex
situations, the model was updated to make the serialization and
deserialization explicit.
2.7.2 Transferable objects
[4473]Transferable objects support being transferred across
[4474]agents. Transferring is effectively recreating the object while
sharing a reference to the underlying data and then detaching the
object being transferred. This is useful to transfer ownership of
expensive resources. Not all objects are [4475]transferable objects and
not all aspects of objects that are [4476]transferable objects are
necessarily preserved when transferred.
Transferring is an irreversible and non-idempotent operation. Once an
object has been transferred, it cannot be transferred, or indeed used,
again.
[4477]Platform objects can be [4478]transferable objects if their
[4479]primary interface is decorated with the [Transferable] IDL
[4480]extended attribute. Such interfaces must also define the
following algorithms:
transfer steps, taking a [4481]platform object value and a [4482]Record
dataHolder
A set of steps that transfers the data in value into fields of
dataHolder. The resulting data held in dataHolder must be
independent of any [4483]realm.
These steps may throw an exception if transferral is not
possible.
transfer-receiving steps, taking a [4484]Record dataHolder and a
[4485]platform object value
A set of steps that receives the data in dataHolder, using it to
set up value as appropriate. value will be a newly-created
instance of the [4486]platform object type in question, with
none of its internal data set up; setting that up is the job of
these steps.
These steps may throw an exception if it is not possible to
receive the transfer.
It is up to the definition of individual platform objects to determine
what data is transferred by these steps. Typically the steps are very
symmetric.
The [4487][Transferable] extended attribute must take no arguments, and
must only appear on an interface. It must not appear more than once on
an interface.
For a given [4488]platform object, only the object's [4489]primary
interface is considered during the transferring process. Thus, if
inheritance is involved in defining the interface, each
[4490][Transferable]-annotated interface in the inheritance chain needs
to define standalone [4491]transfer steps and [4492]transfer-receiving
steps, including taking into account any important data that might come
from inherited interfaces.
[4493]Platform objects that are [4494]transferable objects have a
[[Detached]] internal slot. This is used to ensure that once a platform
object has been transferred, it cannot be transferred again.
Objects defined in the JavaScript specification are handled by the
[4495]StructuredSerializeWithTransfer abstract operation directly.
The [4496]StructuredSerializeInternal abstract operation takes as input
a JavaScript value value and serializes it to a [4497]realm-independent
form, represented here as a [4498]Record. This serialized form has all
the information necessary to later deserialize into a new JavaScript
value in a different realm.
This process can throw an exception, for example when trying to
serialize un-serializable objects.
1. If memory was not supplied, let memory be an empty [4499]map.
The purpose of the memory map is to avoid serializing objects
twice. This ends up preserving cycles and the identity of duplicate
objects in graphs.
2. If memory[value] [4500]exists, then return memory[value].
3. Let deep be false.
4. If value is undefined, null, [4501]a Boolean, [4502]a Number,
[4503]a BigInt, or [4504]a String, then return { [[Type]]:
"primitive", [[Value]]: value }.
5. If value [4505]is a Symbol, then throw a [4506]"DataCloneError"
[4507]DOMException.
6. Let serialized be an uninitialized value.
7. If value has a [[BooleanData]] internal slot, then set serialized
to { [[Type]]: "Boolean", [[BooleanData]]: value.[[BooleanData]] }.
8. Otherwise, if value has a [[NumberData]] internal slot, then set
serialized to { [[Type]]: "Number", [[NumberData]]:
value.[[NumberData]] }.
9. Otherwise, if value has a [[BigIntData]] internal slot, then set
serialized to { [[Type]]: "BigInt", [[BigIntData]]:
value.[[BigIntData]] }.
10. Otherwise, if value has a [[StringData]] internal slot, then set
serialized to { [[Type]]: "String", [[StringData]]:
value.[[StringData]] }.
11. Otherwise, if value has a [[DateValue]] internal slot, then set
serialized to { [[Type]]: "Date", [[DateValue]]:
value.[[DateValue]] }.
12. Otherwise, if value has a [[RegExpMatcher]] internal slot, then set
serialized to { [[Type]]: "RegExp", [[RegExpMatcher]]:
value.[[RegExpMatcher]], [[OriginalSource]]:
value.[[OriginalSource]], [[OriginalFlags]]:
value.[[OriginalFlags]] }.
13. Otherwise, if value has an [[ArrayBufferData]] internal slot, then:
1. If [4508]IsSharedArrayBuffer(value) is true, then:
1. If the [4509]current settings object's [4510]cross-origin
isolated capability is false, then throw a
[4511]"DataCloneError" [4512]DOMException.
This check is only needed when serializing (and not when
deserializing) as the [4513]cross-origin isolated
capability cannot change over time and a
[4514]SharedArrayBuffer cannot leave an [4515]agent
cluster.
2. If forStorage is true, then throw a
[4516]"DataCloneError" [4517]DOMException.
3. If value has an [[ArrayBufferMaxByteLength]] internal
slot, then set serialized to { [[Type]]:
"GrowableSharedArrayBuffer", [[ArrayBufferData]]:
value.[[ArrayBufferData]], [[ArrayBufferByteLengthData]]:
value.[[ArrayBufferByteLengthData]],
[[ArrayBufferMaxByteLength]]:
value.[[ArrayBufferMaxByteLength]], [[AgentCluster]]: the
[4518]surrounding agent's [4519]agent cluster }.
4. Otherwise, set serialized to { [[Type]]:
"SharedArrayBuffer", [[ArrayBufferData]]:
value.[[ArrayBufferData]], [[ArrayBufferByteLength]]:
value.[[ArrayBufferByteLength]], [[AgentCluster]]: the
[4520]surrounding agent's [4521]agent cluster }.
2. Otherwise:
1. If [4522]IsDetachedBuffer(value) is true, then throw a
[4523]"DataCloneError" [4524]DOMException.
2. Let size be value.[[ArrayBufferByteLength]].
3. Let dataCopy be ? [4525]CreateByteDataBlock(size).
This can throw a [4526]RangeError exception upon
allocation failure.
4. Perform [4527]CopyDataBlockBytes(dataCopy, 0,
value.[[ArrayBufferData]], 0, size).
5. If value has an [[ArrayBufferMaxByteLength]] internal
slot, then set serialized to { [[Type]]:
"ResizableArrayBuffer", [[ArrayBufferData]]: dataCopy,
[[ArrayBufferByteLength]]: size,
[[ArrayBufferMaxByteLength]]:
value.[[ArrayBufferMaxByteLength]] }.
6. Otherwise, set serialized to { [[Type]]: "ArrayBuffer",
[[ArrayBufferData]]: dataCopy, [[ArrayBufferByteLength]]:
size }.
14. Otherwise, if value has a [[ViewedArrayBuffer]] internal slot,
then:
1. If [4528]IsArrayBufferViewOutOfBounds(value) is true, then
throw a [4529]"DataCloneError" [4530]DOMException.
2. Let buffer be the value of value's [[ViewedArrayBuffer]]
internal slot.
3. Let bufferSerialized be ?
[4531]StructuredSerializeInternal(buffer, forStorage, memory).
4. [4532]Assert: bufferSerialized.[[Type]] is "ArrayBuffer",
"ResizableArrayBuffer", "SharedArrayBuffer", or
"GrowableSharedArrayBuffer".
5. If value has a [[DataView]] internal slot, then set serialized
to { [[Type]]: "ArrayBufferView", [[Constructor]]: "DataView",
[[ArrayBufferSerialized]]: bufferSerialized, [[ByteLength]]:
value.[[ByteLength]], [[ByteOffset]]: value.[[ByteOffset]] }.
6. Otherwise:
1. [4533]Assert: value has a [[TypedArrayName]] internal
slot.
2. Set serialized to { [[Type]]: "ArrayBufferView",
[[Constructor]]: value.[[TypedArrayName]],
[[ArrayBufferSerialized]]: bufferSerialized,
[[ByteLength]]: value.[[ByteLength]], [[ByteOffset]]:
value.[[ByteOffset]], [[ArrayLength]]:
value.[[ArrayLength]] }.
15. Otherwise, if value has [[MapData]] internal slot, then:
1. Set serialized to { [[Type]]: "Map", [[MapData]]: a new empty
[4534]List }.
2. Set deep to true.
16. Otherwise, if value has [[SetData]] internal slot, then:
1. Set serialized to { [[Type]]: "Set", [[SetData]]: a new empty
[4535]List }.
2. Set deep to true.
17. Otherwise, if value has an [[ErrorData]] internal slot and value is
not a [4536]platform object, then:
1. Let name be ? [4537]Get(value, "name").
2. If name is not one of "Error", "EvalError", "RangeError",
"ReferenceError", "SyntaxError", "TypeError", or "URIError",
then set name to "Error".
3. Let valueMessageDesc be ? value.[[GetOwnProperty]]("message").
4. Let message be undefined if
[4538]IsDataDescriptor(valueMessageDesc) is false, and ?
[4539]ToString(valueMessageDesc.[[Value]]) otherwise.
5. Set serialized to { [[Type]]: "Error", [[Name]]: name,
[[Message]]: message }.
6. User agents should attach a serialized representation of any
interesting accompanying data which are not yet specified,
notably the stack property, to serialized.
See the Error Stacks proposal for in-progress work on
specifying this data. [4540][JSERRORSTACKS]
18. Otherwise, if value is an Array exotic object, then:
1. Let valueLenDescriptor be ?
[4541]OrdinaryGetOwnProperty(value, "length").
2. Let valueLen be valueLenDescriptor.[[Value]].
3. Set serialized to { [[Type]]: "Array", [[Length]]: valueLen,
[[Properties]]: a new empty [4542]List }.
4. Set deep to true.
19. Otherwise, if value is a [4543]platform object that is a
[4544]serializable object:
1. If value has a [4545][[Detached]] internal slot whose value is
true, then throw a [4546]"DataCloneError" [4547]DOMException.
2. Let typeString be the identifier of the [4548]primary
interface of value.
3. Set serialized to { [[Type]]: typeString }.
4. Set deep to true.
20. Otherwise, if value is a [4549]platform object, then throw a
[4550]"DataCloneError" [4551]DOMException.
21. Otherwise, if [4552]IsCallable(value) is true, then throw a
[4553]"DataCloneError" [4554]DOMException.
22. Otherwise, if value has any internal slot other than [[Prototype]],
[[Extensible]], or [[PrivateElements]], then throw a
[4555]"DataCloneError" [4556]DOMException.
For instance, a [[PromiseState]] or [[WeakMapData]] internal slot.
23. Otherwise, if value is an exotic object and value is not the
[4557]%Object.prototype% intrinsic object associated with any
[4558]realm, then throw a [4559]"DataCloneError"
[4560]DOMException.
For instance, a proxy object.
24. Otherwise:
1. Set serialized to { [[Type]]: "Object", [[Properties]]: a new
empty [4561]List }.
2. Set deep to true.
[4562]%Object.prototype% will end up being handled via this step
and subsequent steps. The end result is that its exoticness is
ignored, and after deserialization the result will be an empty
object (not an [4563]immutable prototype exotic object).
25. [4564]Set memory[value] to serialized.
26. If deep is true, then:
1. If value has a [[MapData]] internal slot, then:
1. Let copiedList be a new empty [4565]List.
2. [4566]For each [4567]Record { [[Key]], [[Value]] } entry
of value.[[MapData]]:
1. Let copiedEntry be a new [4568]Record { [[Key]]:
entry.[[Key]], [[Value]]: entry.[[Value]] }.
2. If copiedEntry.[[Key]] is not the special value
empty, [4569]append copiedEntry to copiedList.
3. [4570]For each [4571]Record { [[Key]], [[Value]] } entry
of copiedList:
1. Let serializedKey be ?
[4572]StructuredSerializeInternal(entry.[[Key]],
forStorage, memory).
2. Let serializedValue be ?
[4573]StructuredSerializeInternal(entry.[[Value]],
forStorage, memory).
3. [4574]Append { [[Key]]: serializedKey, [[Value]]:
serializedValue } to serialized.[[MapData]].
2. Otherwise, if value has a [[SetData]] internal slot, then:
1. Let copiedList be a new empty [4575]List.
2. [4576]For each entry of value.[[SetData]]:
1. If entry is not the special value empty,
[4577]append entry to copiedList.
3. [4578]For each entry of copiedList:
1. Let serializedEntry be ?
[4579]StructuredSerializeInternal(entry, forStorage,
memory).
2. [4580]Append serializedEntry to
serialized.[[SetData]].
3. Otherwise, if value is a [4581]platform object that is a
[4582]serializable object, then perform the
[4583]serialization steps for value's [4584]primary interface,
given value, serialized, and forStorage.
The [4585]serialization steps may need to perform a
sub-serialization. This is an operation which takes as input a
value subValue, and returns
[4586]StructuredSerializeInternal(subValue, forStorage,
memory). (In other words, a [4587]sub-serialization is a
specialization of [4588]StructuredSerializeInternal to be
consistent within this invocation.)
4. Otherwise, for each key in !
[4589]EnumerableOwnProperties(value, key):
1. If ! [4590]HasOwnProperty(value, key) is true, then:
1. Let inputValue be ? value.[[Get]](key, value).
2. Let outputValue be ?
[4591]StructuredSerializeInternal(inputValue,
forStorage, memory).
3. [4592]Append { [[Key]]: key, [[Value]]: outputValue
} to serialized.[[Properties]].
27. Return serialized.
It's important to realize that the [4593]Records produced by
[4594]StructuredSerializeInternal might contain "pointers" to other
records that create circular references. For example, when we pass the
following JavaScript object into [4595]StructuredSerializeInternal:
const o = {};
o.myself = o;
it produces the following result:
{
[[Type]]: "Object",
[[Properties]]: «
{
[[Key]]: "myself",
[[Value]]:
}
»
}
The [4598]StructuredDeserialize abstract operation takes as input a
[4599]Record serialized, which was previously produced by
[4600]StructuredSerialize or [4601]StructuredSerializeForStorage, and
deserializes it into a new JavaScript value, created in targetRealm.
This process can throw an exception, for example when trying to
allocate memory for the new objects (especially ArrayBuffer objects).
1. If memory was not supplied, let memory be an empty [4602]map.
The purpose of the memory map is to avoid deserializing objects
twice. This ends up preserving cycles and the identity of duplicate
objects in graphs.
2. If memory[serialized] [4603]exists, then return memory[serialized].
3. Let deep be false.
4. Let value be an uninitialized value.
5. If serialized.[[Type]] is "primitive", then set value to
serialized.[[Value]].
6. Otherwise, if serialized.[[Type]] is "Boolean", then set value to a
new Boolean object in targetRealm whose [[BooleanData]] internal
slot value is serialized.[[BooleanData]].
7. Otherwise, if serialized.[[Type]] is "Number", then set value to a
new Number object in targetRealm whose [[NumberData]] internal slot
value is serialized.[[NumberData]].
8. Otherwise, if serialized.[[Type]] is "BigInt", then set value to a
new BigInt object in targetRealm whose [[BigIntData]] internal slot
value is serialized.[[BigIntData]].
9. Otherwise, if serialized.[[Type]] is "String", then set value to a
new String object in targetRealm whose [[StringData]] internal slot
value is serialized.[[StringData]].
10. Otherwise, if serialized.[[Type]] is "Date", then set value to a
new Date object in targetRealm whose [[DateValue]] internal slot
value is serialized.[[DateValue]].
11. Otherwise, if serialized.[[Type]] is "RegExp", then set value to a
new RegExp object in targetRealm whose [[RegExpMatcher]] internal
slot value is serialized.[[RegExpMatcher]], whose
[[OriginalSource]] internal slot value is
serialized.[[OriginalSource]], and whose [[OriginalFlags]] internal
slot value is serialized.[[OriginalFlags]].
12. Otherwise, if serialized.[[Type]] is "SharedArrayBuffer", then:
1. If targetRealm's corresponding [4604]agent cluster is not
serialized.[[AgentCluster]], then throw a
[4605]"DataCloneError" [4606]DOMException.
2. Otherwise, set value to a new SharedArrayBuffer object in
targetRealm whose [[ArrayBufferData]] internal slot value is
serialized.[[ArrayBufferData]] and whose
[[ArrayBufferByteLength]] internal slot value is
serialized.[[ArrayBufferByteLength]].
13. Otherwise, if serialized.[[Type]] is "GrowableSharedArrayBuffer",
then:
1. If targetRealm's corresponding [4607]agent cluster is not
serialized.[[AgentCluster]], then throw a
[4608]"DataCloneError" [4609]DOMException.
2. Otherwise, set value to a new SharedArrayBuffer object in
targetRealm whose [[ArrayBufferData]] internal slot value is
serialized.[[ArrayBufferData]], whose
[[ArrayBufferByteLengthData]] internal slot value is
serialized.[[ArrayBufferByteLengthData]], and whose
[[ArrayBufferMaxByteLength]] internal slot value is
serialized.[[ArrayBufferMaxByteLength]].
14. Otherwise, if serialized.[[Type]] is "ArrayBuffer", then set value
to a new ArrayBuffer object in targetRealm whose
[[ArrayBufferData]] internal slot value is
serialized.[[ArrayBufferData]], and whose [[ArrayBufferByteLength]]
internal slot value is serialized.[[ArrayBufferByteLength]].
If this throws an exception, catch it, and then throw a
[4610]"DataCloneError" [4611]DOMException.
This step might throw an exception if there is not enough memory
available to create such an ArrayBuffer object.
15. Otherwise, if serialized.[[Type]] is "ResizableArrayBuffer", then
set value to a new ArrayBuffer object in targetRealm whose
[[ArrayBufferData]] internal slot value is
serialized.[[ArrayBufferData]], whose [[ArrayBufferByteLength]]
internal slot value is serialized.[[ArrayBufferByteLength]], and
whose [[ArrayBufferMaxByteLength]] internal slot value is
serialized.[[ArrayBufferMaxByteLength]].
If this throws an exception, catch it, and then throw a
[4612]"DataCloneError" [4613]DOMException.
This step might throw an exception if there is not enough memory
available to create such an ArrayBuffer object.
16. Otherwise, if serialized.[[Type]] is "ArrayBufferView", then:
1. Let deserializedArrayBuffer be ?
[4614]StructuredDeserialize(serialized.[[ArrayBufferSerialized
]], targetRealm, memory).
2. If serialized.[[Constructor]] is "DataView", then set value to
a new DataView object in targetRealm whose
[[ViewedArrayBuffer]] internal slot value is
deserializedArrayBuffer, whose [[ByteLength]] internal slot
value is serialized.[[ByteLength]], and whose [[ByteOffset]]
internal slot value is serialized.[[ByteOffset]].
3. Otherwise, set value to a new typed array object in
targetRealm, using the constructor given by
serialized.[[Constructor]], whose [[ViewedArrayBuffer]]
internal slot value is deserializedArrayBuffer, whose
[[TypedArrayName]] internal slot value is
serialized.[[Constructor]], whose [[ByteLength]] internal slot
value is serialized.[[ByteLength]], whose [[ByteOffset]]
internal slot value is serialized.[[ByteOffset]], and whose
[[ArrayLength]] internal slot value is
serialized.[[ArrayLength]].
17. Otherwise, if serialized.[[Type]] is "Map", then:
1. Set value to a new Map object in targetRealm whose [[MapData]]
internal slot value is a new empty [4615]List.
2. Set deep to true.
18. Otherwise, if serialized.[[Type]] is "Set", then:
1. Set value to a new Set object in targetRealm whose [[SetData]]
internal slot value is a new empty [4616]List.
2. Set deep to true.
19. Otherwise, if serialized.[[Type]] is "Array", then:
1. Let outputProto be
targetRealm.[[Intrinsics]].[[[4617]%Array.prototype%]].
2. Set value to ! [4618]ArrayCreate(serialized.[[Length]],
outputProto).
3. Set deep to true.
20. Otherwise, if serialized.[[Type]] is "Object", then:
1. Set value to a new Object in targetRealm.
2. Set deep to true.
21. Otherwise, if serialized.[[Type]] is "Error", then:
1. Let prototype be [4619]%Error.prototype%.
2. If serialized.[[Name]] is "EvalError", then set prototype to
[4620]%EvalError.prototype%.
3. If serialized.[[Name]] is "RangeError", then set prototype to
[4621]%RangeError.prototype%.
4. If serialized.[[Name]] is "ReferenceError", then set prototype
to [4622]%ReferenceError.prototype%.
5. If serialized.[[Name]] is "SyntaxError", then set prototype to
[4623]%SyntaxError.prototype%.
6. If serialized.[[Name]] is "TypeError", then set prototype to
[4624]%TypeError.prototype%.
7. If serialized.[[Name]] is "URIError", then set prototype to
[4625]%URIError.prototype%.
8. Let message be serialized.[[Message]].
9. Set value to [4626]OrdinaryObjectCreate(prototype, «
[[ErrorData]] »).
10. Let messageDesc be [4627]PropertyDescriptor{ [[Value]]:
message, [[Writable]]: true, [[Enumerable]]: false,
[[Configurable]]: true }.
11. If message is not undefined, then perform !
[4628]OrdinaryDefineOwnProperty(value, "message",
messageDesc).
12. Any interesting accompanying data attached to serialized
should be deserialized and attached to value.
22. Otherwise:
1. Let interfaceName be serialized.[[Type]].
2. If the interface identified by interfaceName is not
[4629]exposed in targetRealm, then throw a
[4630]"DataCloneError" [4631]DOMException.
3. Set value to a new instance of the interface identified by
interfaceName, created in targetRealm.
4. Set deep to true.
23. [4632]Set memory[serialized] to value.
24. If deep is true, then:
1. If serialized.[[Type]] is "Map", then:
1. [4633]For each [4634]Record { [[Key]], [[Value]] } entry
of serialized.[[MapData]]:
1. Let deserializedKey be ?
[4635]StructuredDeserialize(entry.[[Key]],
targetRealm, memory).
2. Let deserializedValue be ?
[4636]StructuredDeserialize(entry.[[Value]],
targetRealm, memory).
3. [4637]Append { [[Key]]: deserializedKey, [[Value]]:
deserializedValue } to value.[[MapData]].
2. Otherwise, if serialized.[[Type]] is "Set", then:
1. [4638]For each entry of serialized.[[SetData]]:
1. Let deserializedEntry be ?
[4639]StructuredDeserialize(entry, targetRealm,
memory).
2. [4640]Append deserializedEntry to value.[[SetData]].
3. Otherwise, if serialized.[[Type]] is "Array" or "Object",
then:
1. [4641]For each [4642]Record { [[Key]], [[Value]] } entry
of serialized.[[Properties]]:
1. Let deserializedValue be ?
[4643]StructuredDeserialize(entry.[[Value]],
targetRealm, memory).
2. Let result be ! [4644]CreateDataProperty(value,
entry.[[Key]], deserializedValue).
3. [4645]Assert: result is true.
4. Otherwise:
1. Perform the appropriate [4646]deserialization steps for
the interface identified by serialized.[[Type]], given
serialized, value, and targetRealm.
The [4647]deserialization steps may need to perform a
sub-deserialization. This is an operation which takes as
input a previously-serialized [4648]Record subSerialized,
and returns [4649]StructuredDeserialize(subSerialized,
targetRealm, memory). (In other words, a
[4650]sub-deserialization is a specialization of
[4651]StructuredDeserialize to be consistent within this
invocation.)
25. Return value.
1. Let memory be an empty [4652]map.
In addition to how it is used normally by
[4653]StructuredSerializeInternal, in this algorithm memory is also
used to ensure that [4654]StructuredSerializeInternal ignores items
in transferList, and let us do our own handling instead.
2. [4655]For each transferable of transferList:
1. If transferable has neither an [[ArrayBufferData]] internal
slot nor a [4656][[Detached]] internal slot, then throw a
[4657]"DataCloneError" [4658]DOMException.
2. If transferable has an [[ArrayBufferData]] internal slot and
[4659]IsSharedArrayBuffer(transferable) is true, then throw a
[4660]"DataCloneError" [4661]DOMException.
3. If memory[transferable] [4662]exists, then throw a
[4663]"DataCloneError" [4664]DOMException.
4. [4665]Set memory[transferable] to { [[Type]]: an uninitialized
value }.
transferable is not transferred yet as transferring has side
effects and [4666]StructuredSerializeInternal needs to be able
to throw first.
3. Let serialized be ? [4667]StructuredSerializeInternal(value, false,
memory).
4. Let transferDataHolders be a new empty [4668]List.
5. [4669]For each transferable of transferList:
1. If transferable has an [[ArrayBufferData]] internal slot and
[4670]IsDetachedBuffer(transferable) is true, then throw a
[4671]"DataCloneError" [4672]DOMException.
2. If transferable has a [4673][[Detached]] internal slot and
transferable.[4674][[Detached]] is true, then throw a
[4675]"DataCloneError" [4676]DOMException.
3. Let dataHolder be memory[transferable].
4. If transferable has an [[ArrayBufferData]] internal slot,
then:
1. If transferable has an [[ArrayBufferMaxByteLength]]
internal slot, then:
1. Set dataHolder.[[Type]] to "ResizableArrayBuffer".
2. Set dataHolder.[[ArrayBufferData]] to
transferable.[[ArrayBufferData]].
3. Set dataHolder.[[ArrayBufferByteLength]] to
transferable.[[ArrayBufferByteLength]].
4. Set dataHolder.[[ArrayBufferMaxByteLength]] to
transferable.[[ArrayBufferMaxByteLength]].
2. Otherwise:
1. Set dataHolder.[[Type]] to "ArrayBuffer".
2. Set dataHolder.[[ArrayBufferData]] to
transferable.[[ArrayBufferData]].
3. Set dataHolder.[[ArrayBufferByteLength]] to
transferable.[[ArrayBufferByteLength]].
3. Perform ? [4677]DetachArrayBuffer(transferable).
Specifications can use the [[ArrayBufferDetachKey]]
internal slot to prevent [4678]ArrayBuffers from being
detached. This is used in WebAssembly JavaScript
Interface, for example. [4679][WASMJS]
5. Otherwise:
1. [4680]Assert: transferable is a [4681]platform object
that is a [4682]transferable object.
2. Let interfaceName be the identifier of the [4683]primary
interface of transferable.
3. Set dataHolder.[[Type]] to interfaceName.
4. Perform the appropriate [4684]transfer steps for the
interface identified by interfaceName, given transferable
and dataHolder.
5. Set transferable.[4685][[Detached]] to true.
6. [4686]Append dataHolder to transferDataHolders.
6. Return { [[Serialized]]: serialized, [[TransferDataHolders]]:
transferDataHolders }.
1. Let memory be an empty [4687]map.
Analogous to [4688]StructuredSerializeWithTransfer, in addition to
how it is used normally by [4689]StructuredDeserialize, in this
algorithm memory is also used to ensure that
[4690]StructuredDeserialize ignores items in
serializeWithTransferResult.[[TransferDataHolders]], and let us do
our own handling instead.
2. Let transferredValues be a new empty [4691]List.
3. [4692]For each transferDataHolder of
serializeWithTransferResult.[[TransferDataHolders]]:
1. Let value be an uninitialized value.
2. If transferDataHolder.[[Type]] is "ArrayBuffer", then set
value to a new ArrayBuffer object in targetRealm whose
[[ArrayBufferData]] internal slot value is
transferDataHolder.[[ArrayBufferData]], and whose
[[ArrayBufferByteLength]] internal slot value is
transferDataHolder.[[ArrayBufferByteLength]].
In cases where the original memory occupied by
[[ArrayBufferData]] is accessible during the deserialization,
this step is unlikely to throw an exception, as no new memory
needs to be allocated: the memory occupied by
[[ArrayBufferData]] is instead just getting transferred into
the new ArrayBuffer. This could be true, for example, when
both the source and target realms are in the same process.
3. Otherwise, if transferDataHolder.[[Type]] is
"ResizableArrayBuffer", then set value to a new ArrayBuffer
object in targetRealm whose [[ArrayBufferData]] internal slot
value is transferDataHolder.[[ArrayBufferData]], whose
[[ArrayBufferByteLength]] internal slot value is
transferDataHolder.[[ArrayBufferByteLength]], and whose
[[ArrayBufferMaxByteLength]] internal slot value is
transferDataHolder.[[ArrayBufferMaxByteLength]].
For the same reason as the previous step, this step is also
unlikely to throw an exception.
4. Otherwise:
1. Let interfaceName be transferDataHolder.[[Type]].
2. If the interface identified by interfaceName is not
exposed in targetRealm, then throw a
[4693]"DataCloneError" [4694]DOMException.
3. Set value to a new instance of the interface identified
by interfaceName, created in targetRealm.
4. Perform the appropriate [4695]transfer-receiving steps
for the interface identified by interfaceName given
transferDataHolder and value.
5. [4696]Set memory[transferDataHolder] to value.
6. [4697]Append value to transferredValues.
4. Let deserialized be ?
[4698]StructuredDeserialize(serializeWithTransferResult.[[Serialize
d]], targetRealm, memory).
5. Return { [[Deserialized]]: deserialized, [[TransferredValues]]:
transferredValues }.
2.7.9 Performing serialization and transferring from other
specifications
Other specifications may use the abstract operations defined here. The
following provides some guidance on when each abstract operation is
typically useful, with examples.
[4699]StructuredSerializeWithTransfer
[4700]StructuredDeserializeWithTransfer
Cloning a value to another [4701]realm, with a transfer list,
but where the target realm is not known ahead of time. In this
case the serialization step can be performed immediately, with
the deserialization step delayed until the target realm becomes
known.
[4702]messagePort.postMessage() uses this pair of abstract
operations, as the destination realm is not known until the
[4703]MessagePort [4704]has been shipped.
[4705]StructuredSerialize
[4706]StructuredSerializeForStorage
[4707]StructuredDeserialize
Creating a [4708]realm-independent snapshot of a given value
which can be saved for an indefinite amount of time, and then
reified back into a JavaScript value later, possibly multiple
times.
[4709]StructuredSerializeForStorage can be used for situations
where the serialization is anticipated to be stored in a
persistent manner, instead of passed between realms. It throws
when attempting to serialize [4710]SharedArrayBuffer objects,
since storing shared memory does not make sense. Similarly, it
can throw or possibly have different behavior when given a
[4711]platform object with custom [4712]serialization steps when
the forStorage argument is true.
[4713]history.pushState() and [4714]history.replaceState() use
[4715]StructuredSerializeForStorage on author-supplied state
objects, storing them as [4716]serialized state in the
appropriate [4717]session history entry. Then,
[4718]StructuredDeserialize is used so that the
[4719]history.state property can return a clone of the
originally-supplied state object.
[4720]broadcastChannel.postMessage() uses
[4721]StructuredSerialize on its input, then uses
[4722]StructuredDeserialize multiple times on the result to
produce a fresh clone for each destination being broadcast to.
Note that transferring does not make sense in multi-destination
situations.
Any API for persisting JavaScript values to the filesystem would
also use [4723]StructuredSerializeForStorage on its input and
[4724]StructuredDeserialize on its output.
In general, call sites may pass in Web IDL values instead of JavaScript
values; this is to be understood to perform an implicit
[4725]conversion to the JavaScript value before invoking these
algorithms.
__________________________________________________________________
Call sites that are not invoked as a result of author code
synchronously calling into a user agent method must take care to
properly [4726]prepare to run script and [4727]prepare to run a
callback before invoking [4728]StructuredSerialize,
[4729]StructuredSerializeForStorage, or
[4730]StructuredSerializeWithTransfer abstract operations, if they are
being performed on arbitrary objects. This is necessary because the
serialization process can invoke author-defined accessors as part of
its final deep-serialization steps, and these accessors could call into
operations that rely on the [4731]entry and [4732]incumbent concepts
being properly set up.
[4733]window.postMessage() performs
[4734]StructuredSerializeWithTransfer on its arguments, but is careful
to do so immediately, inside the synchronous portion of its algorithm.
Thus it is able to use the algorithms without needing to [4735]prepare
to run script and [4736]prepare to run a callback.
In contrast, a hypothetical API that used [4737]StructuredSerialize to
serialize some author-supplied object periodically, directly from a
[4738]task on the [4739]event loop, would need to ensure it performs
the appropriate preparations beforehand. As of this time, we know of no
such APIs on the platform; usually it is simpler to perform the
serialization ahead of time, as a synchronous consequence of author
code.
2.7.10 Structured cloning API
result = self.[4740]structuredClone(value[, { [4741]transfer }])
Takes the input value and returns a deep copy by performing the
structured clone algorithm. [4742]Transferable objects listed in
the [4743]transfer array are transferred, not just cloned,
meaning that they are no longer usable in the input value.
Throws a [4744]"DataCloneError" [4745]DOMException if any part
of the input value is not [4746]serializable.
(BUTTON) ✔MDN
[4747]structuredClone
Support in all current engines.
Firefox94+Safari15.4+Chrome98+
__________________________________________________________________
The structuredClone(value, options) method steps are:
1. Let serialized be ? [4748]StructuredSerializeWithTransfer(value,
options["[4749]transfer"]).
2. Let deserializeRecord be ?
[4750]StructuredDeserializeWithTransfer(serialized, [4751]this's
[4752]relevant realm).
3. Return deserializeRecord.[[Deserialized]].
3 Semantics, structure, and APIs of HTML documents
3.1 Documents
Every XML and HTML document in an HTML UA is represented by a
[4753]Document object. [4754][DOM]
The [4755]Document object's [4756]URL is defined in DOM. It is
initially set when the [4757]Document object is created, but can change
during the lifetime of the [4758]Document object; for example, it
changes when the user [4759]navigates to a [4760]fragment on the page
and when the [4761]pushState() method is called with a new [4762]URL.
[4763][DOM]
Interactive user agents typically expose the [4764]Document object's
[4765]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 [4766]Document object's [4767]origin is defined in DOM. It is
initially set when the [4768]Document object is created, and can change
during the lifetime of the [4769]Document only upon setting
[4770]document.domain. A [4771]Document's [4772]origin can differ from
the [4773]origin of its [4774]URL; for example when a [4775]child
navigable is [4776]created, its [4777]active document's [4778]origin is
inherited from its [4779]parent's [4780]active document's [4781]origin,
even though its [4782]active document's [4783]URL is [4784]about:blank.
[4785][DOM]
When a [4786]Document is created by a [4787]script using the
[4788]createDocument() or [4789]createHTMLDocument() methods, the
[4790]Document is [4791]ready for post-load tasks immediately.
The document's referrer is a string (representing a [4792]URL) that can
be set when the [4793]Document is created. If it is not explicitly set,
then its value is the empty string.
3.1.1 The [4794]Document object
(BUTTON) ✔MDN
[4795]Document
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
// special [4871]event handler IDL attributes that only apply to Document obje
cts
[[4872]LegacyLenientThis] attribute [4873]EventHandler [4874]onreadystatechang
e;
attribute [4875]EventHandler [4876]onvisibilitychange;
// [4877]also has obsolete members
};
[4878]Document includes [4879]GlobalEventHandlers;
Each [4880]Document has a policy container (a [4881]policy container),
initially a new policy container, which contains policies which apply
to the [4882]Document.
Each [4883]Document has a permissions policy, which is a
[4884]permissions policy, which is initially empty.
Each [4885]Document has a module map, which is a [4886]module map,
initially empty.
Each [4887]Document has an opener policy, which is an [4888]opener
policy, initially a new opener policy.
Each [4889]Document has an is initial about:blank, which is a boolean,
initially false.
Each [4890]Document has a during-loading navigation ID for WebDriver
BiDi, which is a [4891]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 [4892]Document's lifecycle,
in a way that ties them to the original [4893]navigation ID used when
the navigation that created this [4894]Document was the [4895]ongoing
navigation. This eventually gets set back to null, after WebDriver BiDi
considers the loading process to be finished. [4896][BIDI]
Each [4897]Document has an about base URL, which is a [4898]URL or
null, initially null.
This is only populated for "about:"-schemed [4899]Documents.
Each [4900]Document has a bfcache blocking details, which is a
[4901]set of [4902]not restored reason details, initially empty.
Each [4903]Document has an open dialogs list, which is a [4904]list of
[4905]dialog elements, initially empty.
3.1.2 The [4906]DocumentOrShadowRoot interface
DOM defines the [4907]DocumentOrShadowRoot mixin, which this
specification extends.
partial interface mixin DocumentOrShadowRoot {
readonly attribute [4908]Element? [4909]activeElement;
};
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android10.1+
Returns the [4912]URL of the [4913]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 [4914]noreferrer link type can be used to block the
referrer.
The referrer attribute must return [4915]the document's referrer.
__________________________________________________________________
document.[4916]cookie [ = value ]
Returns the HTTP cookies that apply to the [4917]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 [4918]sandboxed into an opaque origin (e.g.,
in an [4919]iframe with the [4920]sandbox attribute), a
[4921]"SecurityError" [4922]DOMException will be thrown on
getting and setting.
(BUTTON) ✔MDN
[4923]Document/cookie
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
The cookie attribute represents the cookies of the resource identified
by the document's [4924]URL.
A [4925]Document object that falls into one of the following conditions
is a cookie-averse Document object:
* A [4926]Document object whose [4927]browsing context is null.
* A [4928]Document whose [4929]URL's [4930]scheme is not an
[4931]HTTP(S) scheme.
[4932](This is a tracking vector.) On getting, if the document is a
[4933]cookie-averse Document object, then the user agent must return
the empty string. Otherwise, if the [4934]Document's [4935]origin is an
[4936]opaque origin, the user agent must throw a [4937]"SecurityError"
[4938]DOMException. Otherwise, the user agent must return the
[4939]cookie-string for the document's [4940]URL for a "non-HTTP" API,
decoded using [4941]UTF-8 decode without BOM. [4942][COOKIES]
On setting, if the document is a [4943]cookie-averse Document object,
then the user agent must do nothing. Otherwise, if the [4944]Document's
[4945]origin is an [4946]opaque origin, the user agent must throw a
[4947]"SecurityError" [4948]DOMException. Otherwise, the user agent
must act as it would when [4949]receiving a set-cookie-string for the
document's [4950]URL via a "non-HTTP" API, consisting of the new value
[4951]encoded as UTF-8. [4952][COOKIES] [4953][ENCODING]
Since the [4954]cookie attribute is accessible across frames, the path
restrictions on cookies are only a tool to help manage which cookies
are sent to which parts of the site, and are not in any way a security
feature.
The [4955]cookie attribute's getter and setter synchronously access
shared state. Since there is no locking mechanism, other browsing
contexts in a multiprocess user agent can modify cookies while scripts
are running. A site could, for instance, try to read a cookie,
increment its value, then write it back out, using the new value of the
cookie as a unique identifier for the session; if the site does this
twice in two different browser windows at the same time, it might end
up using the same "unique" identifier for both sessions, with
potentially disastrous effects.
__________________________________________________________________
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android12.1+
Returns the date of the last modification to the document, as
reported by the server, in the form "MM/DD/YYYY hh:mm:ss", in
the user's local time zone.
If the last modification date is not known, the current time is
returned instead.
The lastModified attribute, on getting, must return the date and time
of the [4958]Document's source file's last modification, in the user's
local time zone, in the following format:
1. The month component of the date.
2. A U+002F SOLIDUS character (/).
3. The day component of the date.
4. A U+002F SOLIDUS character (/).
5. The year component of the date.
6. A U+0020 SPACE character.
7. The hours component of the time.
8. A U+003A COLON character (:).
9. The minutes component of the time.
10. A U+003A COLON character (:).
11. The seconds component of the time.
All the numeric components above, other than the year, must be given as
two [4959]ASCII digits representing the number in base ten, zero-padded
if necessary. The year must be given as the shortest possible string of
four or more [4960]ASCII digits representing the number in base ten,
zero-padded if necessary.
The [4961]Document's source file's last modification date and time must
be derived from relevant features of the networking protocols used,
e.g. from the value of the HTTP `[4962]Last-Modified` header of the
document, or from metadata in the file system for local files. If the
last modification date and time are not known, the attribute must
return the current date and time in the above format.
3.1.4 Reporting document loading status
document.[4963]readyState
Returns "loading" while the [4964]Document is loading,
"interactive" once it is finished parsing but still loading
subresources, and "complete" once it has loaded.
The [4965]readystatechange event fires on the [4966]Document
object when this value changes.
The [4967]DOMContentLoaded event fires after the transition to
"interactive" but before the transition to "complete", at the
point where all subresources apart from [4968]async [4969]script
elements have loaded.
(BUTTON) ✔MDN
[4970]Document/readyState
Support in all current engines.
Firefox3.6+Safari1+Chrome1+
__________________________________________________________________
Each [4971]Document has a current document readiness, a string,
initially "complete".
For [4972]Document objects created via the [4973]create and initialize
a Document object algorithm, this will be immediately reset to
"loading" before any script can observe the value of
[4974]document.readyState. This default applies to other cases such as
[4975]initial about:blank [4976]Documents or [4977]Documents without a
[4978]browsing context.
The readyState getter steps are to return [4979]this's [4980]current
document readiness.
To update the current document readiness for [4981]Document document to
readinessValue:
1. If document's [4982]current document readiness equals
readinessValue, then return.
2. Set document's [4983]current document readiness to readinessValue.
3. If document is associated with an [4984]HTML parser, then:
1. Let now be the [4985]current high resolution time given
document's [4986]relevant global object.
2. If readinessValue is "complete", and document's [4987]load
timing info's [4988]DOM complete time is 0, then set
document's [4989]load timing info's [4990]DOM complete time to
now.
3. Otherwise, if readinessValue is "interactive", and document's
[4991]load timing info's [4992]DOM interactive time is 0, then
set document's [4993]load timing info's [4994]DOM interactive
time to now.
4. [4995]Fire an event named [4996]readystatechange at document.
__________________________________________________________________
A [4997]Document is said to have an active parser if it is associated
with an [4998]HTML parser or an [4999]XML parser that has not yet been
[5000]stopped or [5001]aborted.
__________________________________________________________________
A [5002]Document has a [5003]document load timing info load timing
info.
A [5004]Document has a [5005]document unload timing info previous
document unload timing.
A [5006]Document has a boolean was created via cross-origin redirects,
initially false.
The document load timing info [5007]struct has the following
[5008]items:
navigation start time (default 0)
A number
DOM interactive time (default 0)
DOM content loaded event start time (default 0)
DOM content loaded event end time (default 0)
DOM complete time (default 0)
load event start time (default 0)
load event end time (default 0)
[5009]DOMHighResTimeStamp values
The document unload timing info [5010]struct has the following
[5011]items:
unload event start time (default 0)
unload event end time (default 0)
[5012]DOMHighResTimeStamp values
3.1.5 Render-blocking mechanism
Each [5013]Document has a render-blocking element set, a [5014]set of
elements, initially the empty set.
A [5015]Document document allows adding render-blocking elements if
document's [5016]content type is "[5017]text/html" and [5018]the body
element of document is null.
A [5019]Document document is render-blocked if both of the following
are true:
* document's [5020]render-blocking element set is non-empty, or
document [5021]allows adding render-blocking elements.
* The [5022]current high resolution time given document's
[5023]relevant global object has not exceeded an
[5024]implementation-defined timeout value.
An element el is render-blocking if el's [5025]node document document
is [5026]render-blocked, and el is in document's [5027]render-blocking
element set.
To block rendering on an element el:
1. Let document be el's [5028]node document.
2. If document [5029]allows adding render-blocking elements, then
[5030]append el to document's [5031]render-blocking element set.
To unblock rendering on an element el:
1. Let document be el's [5032]node document.
2. [5033]Remove el from document's [5034]render-blocking element set.
Whenever a [5035]render-blocking element el [5036]becomes
browsing-context disconnected, or el's [5037]blocking attribute's value
is changed so that el is no longer [5038]potentially render-blocking,
then [5039]unblock rendering on el.
3.1.6 DOM tree accessors
The html element of a document is its [5040]document element, if it's
an [5041]html element, and null otherwise.
__________________________________________________________________
The head element of a document is the first [5045]head element that is
a child of [5046]the html element, if there is one, or null otherwise.
The head attribute, on getting, must return [5047]the head element of
the document (a [5048]head element or null).
__________________________________________________________________
document.[5049]title [ = value ]
Returns the document's title, as given by [5050]the title
element for HTML and as given by the [5051]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 [5052]title element in the
document (in [5053]tree order), if there is one, or null otherwise.
(BUTTON) ✔MDN
[5054]Document/title
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
The title attribute must, on getting, run the following algorithm:
1. If the [5055]document element is an [5056]SVG svg element, then let
value be the [5057]child text content of the first [5058]SVG title
element that is a child of the [5059]document element.
2. Otherwise, let value be the [5060]child text content of [5061]the
title element, or the empty string if [5062]the title element is
null.
3. [5063]Strip and collapse ASCII whitespace in value.
4. Return value.
On setting, the steps corresponding to the first matching condition in
the following list must be run:
If the [5064]document element is an [5065]SVG svg element
1. If there is an [5066]SVG title element that is a child of the
[5067]document element, let element be the first such element.
2. Otherwise:
1. Let element be the result of [5068]creating an element
given the [5069]document element's [5070]node document,
"title", and the [5071]SVG namespace.
2. Insert element as the [5072]first child of the
[5073]document element.
3. [5074]String replace all with the given value within element.
If the [5075]document element is in the [5076]HTML namespace
1. If [5077]the title element is null and [5078]the head element
is null, then return.
2. If [5079]the title element is non-null, let element be
[5080]the title element.
3. Otherwise:
1. Let element be the result of [5081]creating an element
given the [5082]document element's [5083]node document,
"title", and the [5084]HTML namespace.
2. [5085]Append element to [5086]the head element.
4. [5087]String replace all with the given value within element.
Otherwise
Do nothing.
__________________________________________________________________
If the new value is not a [5092]body or [5093]frameset element,
this will throw a [5094]"HierarchyRequestError"
[5095]DOMException.
The body element of a document is the first of [5096]the html element's
children that is either a [5097]body element or a [5098]frameset
element, or null if there is no such element.
The body attribute, on getting, must return [5099]the body element of
the document (either a [5100]body element, a [5101]frameset element, or
null). On setting, the following algorithm must be run:
1. If the new value is not a [5102]body or [5103]frameset element,
then throw a [5104]"HierarchyRequestError" [5105]DOMException.
2. Otherwise, if the new value is the same as [5106]the body element,
return.
3. Otherwise, if [5107]the body element is not null, then
[5108]replace [5109]the body element with the new value within
[5110]the body element's parent and return.
4. Otherwise, if there is no [5111]document element, throw a
[5112]"HierarchyRequestError" [5113]DOMException.
5. Otherwise, [5114]the body element is null, but there's a
[5115]document element. [5116]Append the new value to the
[5117]document element.
The value returned by the [5118]body getter is not always the one
passed to the setter.
In this example, the setter successfully inserts a [5119]body element
(though this is non-conforming since SVG does not allow a [5120]body as
child of [5121]SVG svg). However the getter will return null because
the document element is not [5122]html.
__________________________________________________________________
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android12.1+
Returns an [5125]HTMLCollection of the [5126]img elements in the
[5127]Document.
Firefox Android?Safari iOS10.3+Chrome Android?WebView
Android?Samsung Internet?Opera Android47+
Returns an [5132]HTMLCollection of the [5133]embed elements in
the [5134]Document.
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android12.1+
Returns an [5137]HTMLCollection of the [5138]a and [5139]area
elements in the [5140]Document that have [5141]href attributes.
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android12.1+
Returns an [5144]HTMLCollection of the [5145]form elements in
the [5146]Document.
Firefox Android?Safari iOS1+Chrome Android?WebView
Android?Samsung Internet?Opera Android12.1+
Returns an [5149]HTMLCollection of the [5150]script elements in
the [5151]Document.
The images attribute must return an [5152]HTMLCollection rooted at the
[5153]Document node, whose filter matches only [5154]img elements.
The embeds attribute must return an [5155]HTMLCollection rooted at the
[5156]Document node, whose filter matches only [5157]embed elements.
The plugins attribute must return the same object as that returned by
the [5158]embeds attribute.
The links attribute must return an [5159]HTMLCollection rooted at the
[5160]Document node, whose filter matches only [5161]a elements with
[5162]href attributes and [5163]area elements with [5164]href
attributes.
The forms attribute must return an [5165]HTMLCollection rooted at the
[5166]Document node, whose filter matches only [5167]form elements.
The scripts attribute must return an [5168]HTMLCollection rooted at the
[5169]Document node, whose filter matches only [5170]script elements.
__________________________________________________________________
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android10.1+
Returns a [5173]NodeList of elements in the [5174]Document that
have a name attribute with the value name.
The getElementsByName(elementName) method steps are to return a
[5175]live [5176]NodeList containing all the [5177]HTML elements in
that document that have a name attribute whose value is [5178]identical
to the elementName argument, in [5179]tree order. When the method is
invoked on a [5180]Document object again with the same argument, the
user agent may return the same as the object returned by the earlier
call. In other cases, a new [5181]NodeList object must be returned.
__________________________________________________________________
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
Returns the [5184]script element, or the [5185]SVG script
element, that is currently executing, as long as the element
represents a [5186]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 [5187]Document is not currently executing a
[5188]script or [5189]SVG script element (e.g., because the
running script is an event handler, or a timeout), or if the
currently executing [5190]script or [5191]SVG script element
represents a [5192]module script.
The currentScript attribute, on getting, must return the value to which
it was most recently set. When the [5193]Document is created, the
[5194]currentScript must be initialized to null.
This API has fallen out of favor in the implementer and standards
community, as it globally exposes [5195]script or [5196]SVG script
elements. As such, it is not available in newer contexts, such as when
running [5197]module scripts or when running scripts in a [5198]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 [5199]issue #1013.
__________________________________________________________________
The [5200]Document interface [5201]supports named properties. The
[5202]supported property names of a [5203]Document object document at
any moment consist of the following, in [5204]tree order according to
the element that contributed them, ignoring later duplicates, and with
values from [5205]id attributes coming before values from name
attributes when the same element contributes both:
* the value of the name content attribute for all [5206]exposed
[5207]embed, [5208]form, [5209]iframe, [5210]img, and [5211]exposed
[5212]object elements that have a non-empty name content attribute
and are [5213]in a document tree with document as their [5214]root;
* the value of the [5215]id content attribute for all [5216]exposed
[5217]object elements that have a non-empty [5218]id content
attribute and are [5219]in a document tree with document as their
[5220]root; and
* the value of the [5221]id content attribute for all [5222]img
elements that have both a non-empty [5223]id content attribute and
a non-empty name content attribute, and are [5224]in a document
tree with document as their [5225]root.
To [5226]determine the value of a named property name for a
[5227]Document, the user agent must return the value obtained using the
following steps:
1. Let elements be the list of [5228]named elements with the name name
that are [5229]in a document tree with the [5230]Document as their
[5231]root.
There will be at least one such element, since the algorithm would
otherwise not have been [5232]invoked by Web IDL.
2. If elements has only one element, and that element is an
[5233]iframe element, and that [5234]iframe element's [5235]content
navigable is not null, then return the [5236]active WindowProxy of
the element's [5237]content navigable.
3. Otherwise, if elements has only one element, return that element.
4. Otherwise, return an [5238]HTMLCollection rooted at the
[5239]Document node, whose filter matches only [5240]named elements
with the name name.
Named elements with the name name, for the purposes of the above
algorithm, are those that are either:
* [5241]Exposed [5242]embed, [5243]form, [5244]iframe, [5245]img, or
[5246]exposed [5247]object elements that have a name content
attribute whose value is name, or
* [5248]Exposed [5249]object elements that have an [5250]id content
attribute whose value is name, or
* [5251]img elements that have an [5252]id content attribute whose
value is name, and that have a non-empty name content attribute
present also.
An [5253]embed or [5254]object element is said to be exposed if it has
no [5255]exposed [5256]object ancestor, and, for [5257]object elements,
is additionally either not showing its [5258]fallback content or has no
[5259]object or [5260]embed descendants.
__________________________________________________________________
The [5261]dir attribute on the [5262]Document interface is defined
along with the [5263]dir content attribute.
3.2 Elements
3.2.1 Semantics
Elements, attributes, and attribute values in HTML are defined (by this
specification) to have certain meanings (semantics). For example, the
[5264]ol element represents an ordered list, and the [5265]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:
My Page
Welcome to my page
I like cars and lorries and have a big Jeep!
Where I live
I live in a small hut on a mountain!
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).
ACME Corporation
The leaders in arbitrary fast delivery since 1920
...
The [5266]hgroup element can be used for these kinds of situations:
ACME Corporation
The leaders in arbitrary fast delivery since 1920
...
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 [5267]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.
Authors must not use elements, attributes, or attribute values that are
not permitted by this specification or [5268]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:
Here would be an alternative and correct way to mark this up:
DOM nodes whose [5269]node document's [5270]browsing context is null
are exempt from all document conformance requirements other than the
[5271]HTML syntax requirements and [5272]XML syntax requirements.
In particular, the [5273]template element's [5274]template contents's
[5275]node document's [5276]browsing context is null. For example, the
[5277]content model requirements and attribute value microsyntax
requirements do not apply to a [5278]template element's [5279]template
contents. In this example an [5280]img element has attribute values
that are placeholders that would be invalid outside a [5281]template
element.
However, if the above markup were to omit the end tag, that would
be a violation of the [5282]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 must update their
presentation of the document as this occurs.
HTML has a [5283]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.
3.2.2 Elements in the DOM
The nodes representing [5284]HTML elements in the DOM must implement,
and expose to scripts, the interfaces listed for them in the relevant
sections of this specification. This includes [5285]HTML elements in
[5286]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 [5287]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 [5288]id attribute to the element, and then
creating a [5289]hyperlink with that [5290]id attribute's value as the
[5291]fragment for the [5292]hyperlink's [5293]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 [5294]figure element, which is given an [5295]id
attribute:
Figure 27: a simple module graph
A [5296]hyperlink-based [5297]reference could be created using the
[5298]a element, like so:
As we can see in figure 27, ...
However, there are many other ways of [5299]referencing the
[5300]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 [5301]this is discouraged)
The basic interface, from which all the [5302]HTML elements' interfaces
inherit, and which must be used by elements that have no additional
requirements, is the [5303]HTMLElement interface.
(BUTTON) ✔MDN
[5304]HTMLElement
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
[5352]HTMLElement includes [5353]GlobalEventHandlers;
[5354]HTMLElement includes [5355]ElementContentEditable;
[5356]HTMLElement includes [5357]HTMLOrSVGElement;
The [5361]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.
__________________________________________________________________
The [5362]element interface for an element with name name in the
[5363]HTML namespace is determined as follows:
1. If name is [5364]applet, [5365]bgsound, [5366]blink, [5367]isindex,
[5368]keygen, [5369]multicol, [5370]nextid, or [5371]spacer, then
return [5372]HTMLUnknownElement.
2. If name is [5373]acronym, [5374]basefont, [5375]big, [5376]center,
[5377]nobr, [5378]noembed, [5379]noframes, [5380]plaintext,
[5381]rb, [5382]rtc, [5383]strike, or [5384]tt, then return
[5385]HTMLElement.
3. If name is [5386]listing or [5387]xmp, then return
[5388]HTMLPreElement.
4. Otherwise, if this specification defines an interface appropriate
for the [5389]element type corresponding to the local name name,
then return that interface.
5. If [5390]other applicable specifications define an appropriate
interface for name, then return the interface they define.
6. If name is a [5391]valid custom element name, then return
[5392]HTMLElement.
7. Return [5393]HTMLUnknownElement.
The use of [5394]HTMLElement instead of [5395]HTMLUnknownElement in the
case of [5396]valid custom element names is done to ensure that any
potential future [5397]upgrades only cause a linear transition of the
element's prototype chain, from [5398]HTMLElement to a subclass,
instead of a lateral one, from [5399]HTMLUnknownElement to an unrelated
subclass.
Features shared between HTML and SVG elements use the
[5400]HTMLOrSVGElement interface mixin: [5401][SVG]
interface mixin HTMLOrSVGElement {
[SameObject] readonly attribute [5402]DOMStringMap [5403]dataset;
attribute DOMString [5404]nonce; // [5405]intentionally no [CEReactions]
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);
3.2.3 HTML element constructors
To support the [5413]custom elements feature, all HTML elements have
special constructor behavior. This is indicated via the
[HTMLConstructor] IDL [5414]extended attribute. It indicates that the
interface object for the given interface will have a specific behavior
when called, as defined in detail below.
The [5415][HTMLConstructor] extended attribute must take no arguments,
and must only appear on [5416]constructor operations. It must appear
only once on a constructor operation, and the interface must contain
only the single, annotated constructor operation, and no others. The
annotated constructor operation must be declared to take no arguments.
Interfaces declared with constructor operations that are annotated with
the [5417][HTMLConstructor] extended attribute have the following
[5418]overridden constructor steps:
1. If [5419]NewTarget is equal to the [5420]active function object,
then throw a [5421]TypeError.
This can occur when a custom element is defined using an
[5422]element interface as its constructor:
customElements.define("bad-1", HTMLButtonElement);
new HTMLButtonElement(); // (1)
document.createElement("bad-1"); // (2)
In this case, during the execution of [5423]HTMLButtonElement
(either explicitly, as in (1), or implicitly, as in (2)), both the
[5424]active function object and [5425]NewTarget are
[5426]HTMLButtonElement. If this check was not present, it would be
possible to create an instance of [5427]HTMLButtonElement whose
local name was bad-1.
2. Let registry be null.
3. If the [5428]surrounding agent's [5429]active custom element
constructor map[[5430]NewTarget] [5431]exists:
1. Set registry to the [5432]surrounding agent's [5433]active
custom element constructor map[[5434]NewTarget].
2. [5435]Remove the [5436]surrounding agent's [5437]active custom
element constructor map[[5438]NewTarget].
4. Otherwise, set registry to [5439]current global object's
[5440]associated Document's [5441]custom element registry.
5. Let definition be the item in registry's [5442]custom element
definition set with [5443]constructor equal to [5444]NewTarget. If
there is no such item, then throw a [5445]TypeError.
Since there can be no item in registry's [5446]custom element
definition set with a [5447]constructor of undefined, this step
also prevents HTML element constructors from being called as
functions (since in that case [5448]NewTarget will be undefined).
6. Let isValue be null.
7. If definition's [5449]local name is equal to definition's
[5450]name (i.e., definition is for an [5451]autonomous custom
element):
1. If the [5452]active function object is not [5453]HTMLElement,
then throw a [5454]TypeError.
This can occur when a custom element is defined to not extend
any local names, but inherits from a non-[5455]HTMLElement
class:
customElements.define("bad-2", class Bad2 extends HTMLParagraphElement {});
In this case, during the (implicit) super() call that occurs
when constructing an instance of Bad2, the [5456]active
function object is [5457]HTMLParagraphElement, not
[5458]HTMLElement.
8. Otherwise (i.e., if definition is for a [5459]customized built-in
element):
1. Let valid local names be the list of local names for elements
defined in this specification or in [5460]other applicable
specifications that use the [5461]active function object as
their [5462]element interface.
2. If valid local names does not contain definition's [5463]local
name, then throw a [5464]TypeError.
This can occur when a custom element is defined to extend a
given local name but inherits from the wrong class:
customElements.define("bad-3", class Bad3 extends HTMLQuoteElement {}, { extends
: "p" });
In this case, during the (implicit) super() call that occurs
when constructing an instance of Bad3, valid local names is
the list containing [5465]q and [5466]blockquote, but
definition's [5467]local name is [5468]p, which is not in that
list.
3. Set isValue to definition's [5469]name.
9. If definition's [5470]construction stack is empty:
1. Let element be the result of [5471]internally creating a new
object implementing the interface to which the [5472]active
function object corresponds, given the [5473]current realm and
[5474]NewTarget.
2. Set element's [5475]node document to the [5476]current global
object's [5477]associated Document.
3. Set element's [5478]namespace to the [5479]HTML namespace.
4. Set element's [5480]namespace prefix to null.
5. Set element's [5481]local name to definition's [5482]local
name.
6. Set element's [5483]custom element state to "custom".
7. Set element's [5484]custom element definition to definition.
8. Set element's [5485]is value to isValue.
9. Return element.
This occurs when author script constructs a new custom element
directly, e.g. via new MyCustomElement().
10. Let prototype be ? [5486]Get([5487]NewTarget, "prototype").
11. If prototype [5488]is not an Object, then:
1. Let realm be ? [5489]GetFunctionRealm([5490]NewTarget).
2. Set prototype to the [5491]interface prototype object of realm
whose interface is the same as the interface of the
[5492]active function object.
The realm of the [5493]active function object might not be realm,
so we are using the more general concept of "the same interface"
across realms; we are not looking for equality of [5494]interface
objects. This fallback behavior, including using the realm of
[5495]NewTarget and looking up the appropriate prototype there, is
designed to match analogous behavior for the JavaScript built-ins
and Web IDL's [5496]internally create a new object implementing the
interface algorithm.
12. Let element be the last entry in definition's [5497]construction
stack.
13. If element is an [5498]already constructed marker, then throw a
[5499]TypeError.
This can occur when the author code inside the [5500]custom element
constructor [5501]non-conformantly creates another instance of the
class being constructed, before calling super():
let doSillyThing = true;
class DontDoThis extends HTMLElement {
constructor() {
if (doSillyThing) {
doSillyThing = false;
new DontDoThis();
// Now the construction stack will contain an already constructed marker.
}
// This will then fail with a TypeError:
super();
}
}
This can also occur when author code inside the [5502]custom
element constructor [5503]non-conformantly calls super() twice,
since per the JavaScript specification, this actually executes the
superclass constructor (i.e. this algorithm) twice, before throwing
an error:
class DontDoThisEither extends HTMLElement {
constructor() {
super();
// This will throw, but not until it has already called into the HTMLElement
constructor
super();
}
}
14. Perform ? element.[[SetPrototypeOf]](prototype).
15. Replace the last entry in definition's [5504]construction stack
with an [5505]already constructed marker.
16. Return element.
This step is normally reached when [5506]upgrading a custom
element; the existing element is returned, so that the super() call
inside the [5507]custom element constructor assigns that existing
element to this.
__________________________________________________________________
In addition to the constructor behavior implied by
[5508][HTMLConstructor], some elements also have [5509]named
constructors (which are really factory functions with a modified
prototype property).
Named constructors for HTML elements can also be used in an
[5510]extends clause when defining a [5511]custom element constructor:
class AutoEmbiggenedImage extends Image {
constructor(width, height) {
super(width * 10, height * 10);
}
}
Each element in this specification has a definition that includes the
following information:
Categories
A list of [5512]categories to which the element belongs. These
are used when defining the [5513]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, all [5514]phrasing content is [5515]flow content.
Thus, elements that are [5516]phrasing content will only be
listed as "where [5517]phrasing content is expected", since this
is the more-specific expectation. Anywhere that expects
[5518]flow content also expects [5519]phrasing content, and thus
also meets this expectation.
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 [5520]text/html
syntax, the [5521]start and [5522]end tags can be omitted. This
information is redundant with the normative requirements given
in the [5523]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.)
Accessibility considerations
For authors: Conformance requirements for use of ARIA [5524]role
and [5525]aria-* attributes are defined in ARIA in HTML.
[5526][ARIA] [5527][ARIAHTML]
For implementers: User agent requirements for implementing
accessibility API semantics are defined in HTML Accessibility
API Mappings. [5528][HTMLAAM]
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
[5529]represents, along with any additional normative conformance
criteria that may apply to authors and implementations. Examples are
sometimes also included.
3.2.4.1 Attributes
An attribute value is a string. Except where otherwise specified,
attribute values on [5530]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.
3.2.5 Content models
Each element defined in this specification has a content model: a
description of the element's expected [5531]contents. An [5532]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.
[5533]ASCII whitespace is always allowed between elements. User agents
represent these characters between elements in the source markup as
[5534]Text nodes in the DOM. Empty [5535]Text nodes and [5536]Text
nodes consisting of just sequences of those characters are considered
inter-element whitespace.
[5537]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 [5538]Text nodes (other than [5539]inter-element
whitespace) between them. Similarly, a node is the only child of an
element if that element contains no other nodes other than
[5540]inter-element whitespace, comment nodes, and processing
instruction nodes.
Authors must not use [5541]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 [5542]div element. Thus, a [5543]div
element is allowed in that context, even though this is not explicitly
normatively stated by this specification. [5544][ATOM]
In addition, [5545]HTML elements may be orphan nodes (i.e. without a
parent node).
For example, creating a [5546]td element and storing it in a global
variable in a script is conforming, even though [5547]td elements are
otherwise only supposed to be used inside [5548]tr elements.
var data = {
name: "Banana",
cell: document.createElement(ʼtdʼ),
};
3.2.5.1 The "nothing" content model
When an element's content model is nothing, the element must contain no
[5549]Text nodes (other than [5550]inter-element whitespace) and no
element nodes.
Most HTML elements whose content model is "nothing" are also, for
convenience, [5551]void elements (elements that have no [5552]end tag
in the [5553]HTML syntax). However, these are entirely separate
concepts.
3.2.5.2 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:
* [5554]Metadata content
* [5555]Flow content
* [5556]Sectioning content
* [5557]Heading content
* [5558]Phrasing content
* [5559]Embedded content
* [5560]Interactive content
Some elements also fall into other categories, which are defined in
other parts of this specification.
These categories are related as follows:
IFRAME: [5561]/images/content-venn.svg
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.
3.2.5.2.1 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.
* [5562]base
* [5563]link
* [5564]meta
* [5565]noscript
* [5566]script
* [5567]style
* [5568]template
* [5569]title
Elements from other namespaces whose semantics are primarily
metadata-related (e.g. RDF) are also [5570]metadata content.
Thus, in the XML serialization, one can use RDF, like this:
Hedralʼs Home PageCat HedralSir
My home page
I like playing with string, I guess. Sister says squirrels are fun
too so sometimes I follow her to play with them.
This isn't possible in the HTML serialization, however.
3.2.5.2.2 Flow content
Most elements that are used in the body of documents and applications
are categorized as flow content.
* [5571]a
* [5572]abbr
* [5573]address
* [5574]area (if it is a descendant of a [5575]map element)
* [5576]article
* [5577]aside
* [5578]audio
* [5579]b
* [5580]bdi
* [5581]bdo
* [5582]blockquote
* [5583]br
* [5584]button
* [5585]canvas
* [5586]cite
* [5587]code
* [5588]data
* [5589]datalist
* [5590]del
* [5591]details
* [5592]dfn
* [5593]dialog
* [5594]div
* [5595]dl
* [5596]em
* [5597]embed
* [5598]fieldset
* [5599]figure
* [5600]footer
* [5601]form
* [5602]h1
* [5603]h2
* [5604]h3
* [5605]h4
* [5606]h5
* [5607]h6
* [5608]header
* [5609]hgroup
* [5610]hr
* [5611]i
* [5612]iframe
* [5613]img
* [5614]input
* [5615]ins
* [5616]kbd
* [5617]label
* [5618]link (if it is [5619]allowed in the body)
* [5620]main (if it is a [5621]hierarchically correct main element)
* [5622]map
* [5623]mark
* [5624]MathML math
* [5625]menu
* [5626]meta (if the [5627]itemprop attribute is present)
* [5628]meter
* [5629]nav
* [5630]noscript
* [5631]object
* [5632]ol
* [5633]output
* [5634]p
* [5635]picture
* [5636]pre
* [5637]progress
* [5638]q
* [5639]ruby
* [5640]s
* [5641]samp
* [5642]script
* [5643]search
* [5644]section
* [5645]select
* [5646]slot
* [5647]small
* [5648]span
* [5649]strong
* [5650]sub
* [5651]sup
* [5652]SVG svg
* [5653]table
* [5654]template
* [5655]textarea
* [5656]time
* [5657]u
* [5658]ul
* [5659]var
* [5660]video
* [5661]wbr
* [5662]autonomous custom elements
* [5663]text
3.2.5.2.3 Sectioning content
Sectioning content is content that defines the scope of [5664]header
and [5665]footer elements.
* [5666]article
* [5667]aside
* [5668]nav
* [5669]section
3.2.5.2.4 Heading content
Heading content defines the heading of a section (whether explicitly
marked up using [5670]sectioning content elements, or implied by the
heading content itself).
* [5671]h1
* [5672]h2
* [5673]h3
* [5674]h4
* [5675]h5
* [5676]h6
* [5677]hgroup (if it has a descendant [5678]h1 to [5679]h6 element)
3.2.5.2.5 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 [5680]phrasing
content form [5681]paragraphs.
* [5682]a
* [5683]abbr
* [5684]area (if it is a descendant of a [5685]map element)
* [5686]audio
* [5687]b
* [5688]bdi
* [5689]bdo
* [5690]br
* [5691]button
* [5692]canvas
* [5693]cite
* [5694]code
* [5695]data
* [5696]datalist
* [5697]del
* [5698]dfn
* [5699]em
* [5700]embed
* [5701]i
* [5702]iframe
* [5703]img
* [5704]input
* [5705]ins
* [5706]kbd
* [5707]label
* [5708]link (if it is [5709]allowed in the body)
* [5710]map
* [5711]mark
* [5712]MathML math
* [5713]meta (if the [5714]itemprop attribute is present)
* [5715]meter
* [5716]noscript
* [5717]object
* [5718]output
* [5719]picture
* [5720]progress
* [5721]q
* [5722]ruby
* [5723]s
* [5724]samp
* [5725]script
* [5726]select
* [5727]slot
* [5728]small
* [5729]span
* [5730]strong
* [5731]sub
* [5732]sup
* [5733]SVG svg
* [5734]template
* [5735]textarea
* [5736]time
* [5737]u
* [5738]var
* [5739]video
* [5740]wbr
* [5741]autonomous custom elements
* [5742]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
[5743]Text nodes. [5744]Text is sometimes used as a content model on
its own, but is also [5745]phrasing content, and can be
[5746]inter-element whitespace (if the [5747]Text nodes are empty or
contain just [5748]ASCII whitespace).
[5749]Text nodes and attribute values must consist of [5750]scalar
values, excluding [5751]noncharacters, and [5752]controls other than
[5753]ASCII whitespace. This specification includes extra constraints
on the exact value of [5754]Text nodes and attribute values depending
on their precise context.
3.2.5.2.6 Embedded content
Embedded content is content that imports another resource into the
document, or content from another vocabulary that is inserted into the
document.
* [5755]audio
* [5756]canvas
* [5757]embed
* [5758]iframe
* [5759]img
* [5760]MathML math
* [5761]object
* [5762]picture
* [5763]SVG svg
* [5764]video
Elements that are from namespaces other than the [5765]HTML namespace
and that convey content but not metadata, are [5766]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.
3.2.5.2.7 Interactive content
Interactive content is content that is specifically intended for user
interaction.
* [5767]a (if the [5768]href attribute is present)
* [5769]audio (if the [5770]controls attribute is present)
* [5771]button
* [5772]details
* [5773]embed
* [5774]iframe
* [5775]img (if the [5776]usemap attribute is present)
* [5777]input (if the [5778]type attribute is not in the [5779]Hidden
state)
* [5780]label
* [5781]select
* [5782]textarea
* [5783]video (if the [5784]controls attribute is present)
3.2.5.2.8 Palpable content
As a general rule, elements whose content model allows any [5785]flow
content or [5786]phrasing content should have at least one node in its
[5787]contents that is palpable content and that does not have the
[5788]hidden attribute specified.
[5789]Palpable content makes an element non-empty by providing either
some descendant non-empty [5790]text, or else something users can hear
([5791]audio elements) or view ([5792]video, [5793]img, or [5794]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:
* [5795]a
* [5796]abbr
* [5797]address
* [5798]article
* [5799]aside
* [5800]audio (if the [5801]controls attribute is present)
* [5802]b
* [5803]bdi
* [5804]bdo
* [5805]blockquote
* [5806]button
* [5807]canvas
* [5808]cite
* [5809]code
* [5810]data
* [5811]del
* [5812]details
* [5813]dfn
* [5814]div
* [5815]dl (if the element's children include at least one name-value
group)
* [5816]em
* [5817]embed
* [5818]fieldset
* [5819]figure
* [5820]footer
* [5821]form
* [5822]h1
* [5823]h2
* [5824]h3
* [5825]h4
* [5826]h5
* [5827]h6
* [5828]header
* [5829]hgroup
* [5830]i
* [5831]iframe
* [5832]img
* [5833]input (if the [5834]type attribute is not in the [5835]Hidden
state)
* [5836]ins
* [5837]kbd
* [5838]label
* [5839]main
* [5840]map
* [5841]mark
* [5842]MathML math
* [5843]menu (if the element's children include at least one [5844]li
element)
* [5845]meter
* [5846]nav
* [5847]object
* [5848]ol (if the element's children include at least one [5849]li
element)
* [5850]output
* [5851]p
* [5852]picture
* [5853]pre
* [5854]progress
* [5855]q
* [5856]ruby
* [5857]s
* [5858]samp
* [5859]search
* [5860]section
* [5861]select
* [5862]small
* [5863]span
* [5864]strong
* [5865]sub
* [5866]sup
* [5867]SVG svg
* [5868]table
* [5869]textarea
* [5870]time
* [5871]u
* [5872]ul (if the element's children include at least one [5873]li
element)
* [5874]var
* [5875]video
* [5876]autonomous custom elements
* [5877]text that is not [5878]inter-element whitespace
3.2.5.2.9 Script-supporting elements
Script-supporting elements are those that do not [5879]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:
* [5880]script
* [5881]template
3.2.5.3 Transparent content models
Some elements are described as transparent; they have "transparent" in
the description of their content model. The content model of a
[5882]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 [5883]ins element inside a [5884]ruby element cannot
contain an [5885]rt element, because the part of the [5886]ruby
element's content model that allows [5887]ins elements is the part that
allows [5888]phrasing content, and the [5889]rt element is not
[5890]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:
To check whether "Apples" is allowed inside the [5891]a element, the
content models are examined. The [5892]a element's content model is
transparent, as is the [5893]map element's, as is the [5894]ins
element's, as is the [5895]object element's. The [5896]object element
is found in the [5897]p element, whose content model is [5898]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
[5899]flow content.
3.2.5.4 Paragraphs
The term [5900]paragraph as defined in this section is used for more
than just the definition of the [5901]p element. The [5902]paragraph
concept defined here is used to describe how to interpret documents.
The [5903]p element is merely one of several ways of marking up a
[5904]paragraph.
A paragraph is typically a run of [5905]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 [5906]inter-element whitespace do
not form paragraphs.
Example of paragraphs
This is the first paragraph in this example.
This is the second.
Paragraphs in [5907]flow content are defined relative to what the
document looks like without the [5908]a, [5909]ins, [5910]del, and
[5911]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 [5912]ins and [5913]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 [5914]ins and [5915]del
elements — the [5916]ins element straddles the heading and the first
paragraph, and the [5917]del element straddles the boundary between the
two paragraphs.
Example of paragraphs
This is the first paragraph in this example.
This is the second.
Let view be a view of the DOM that replaces all [5918]a, [5919]ins,
[5920]del, and [5921]map elements in the document with their
[5922]contents. Then, in view, for each run of sibling [5923]phrasing
content nodes uninterrupted by other types of content, in an element
that accepts content other than [5924]phrasing content as well as
[5925]phrasing content, let first be the first node of the run, and let
last be the last node of the run. For each such run that consists of at
least one node that is neither [5926]embedded content nor
[5927]inter-element whitespace, a paragraph exists in the original DOM
from immediately before first to immediately after last. (Paragraphs
can thus span across [5928]a, [5929]ins, [5930]del, and [5931]map
elements.)
Conformance checkers may warn authors of cases where they have
paragraphs that overlap each other (this can happen with [5932]object,
[5933]video, [5934]audio, and [5935]canvas elements, and indirectly
through elements in other namespaces that allow HTML to be further
embedded therein, like [5936]SVG svg or [5937]MathML math).
A [5938]paragraph is also formed explicitly by [5939]p elements.
The [5940]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.
Welcome!
This is home of...
It is possible for paragraphs to overlap when using certain elements
that define fallback content. For example, in the following section:
My Cats
You can play with my cat simulator.
Iʼm quite proud of it.
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 the [5941]object element.
2. The paragraph that says "To see the cat simulator, use one of the
following links:".
3. The paragraph that says "Download simulator file".
4. The paragraph that says "Use online simulator".
5. 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 [5942]p elements can be used. For
example:
My Cats
You can play with my cat simulator.
Iʼm quite proud of it.
3.2.6 Global attributes
(BUTTON) MDN
[5943]Global_attributes
The following attributes are common to and may be specified on all
[5944]HTML elements (even those not defined in this specification):
* [5945]accesskey
* [5946]autocapitalize
* [5947]autocorrect
* [5948]autofocus
* [5949]contenteditable
* [5950]dir
* [5951]draggable
* [5952]enterkeyhint
* [5953]hidden
* [5954]inert
* [5955]inputmode
* [5956]is
* [5957]itemid
* [5958]itemprop
* [5959]itemref
* [5960]itemscope
* [5961]itemtype
* [5962]lang
* [5963]nonce
* [5964]popover
* [5965]spellcheck
* [5966]style
* [5967]tabindex
* [5968]title
* [5969]translate
* [5970]writingsuggestions
These attributes are only defined by this specification as attributes
for [5971]HTML elements. When this specification refers to elements
having these attributes, elements from namespaces that are not defined
as having these attributes must not be considered as being elements
with these attributes.
For example, in the following XML fragment, the "bogus" element does
not have a [5972]dir attribute as defined in this specification,
despite having an attribute with the literal name "dir". Thus,
[5973]the directionality of the inner-most [5974]span element is
'[5975]rtl', inherited from the [5976]div element indirectly through
the "bogus" element.
DOM defines the user agent requirements for the class, id, and slot
attributes for any element in any namespace. [5978][DOM]
The [5979]class, [5980]id, and [5981]slot attributes may be specified
on all [5982]HTML elements.
When specified on [5983]HTML elements, the [5984]class attribute must
have a value that is a [5985]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 [5986]getElementsByClassName() method in the DOM, and other
such features.
There are no additional restrictions on the tokens authors can use in
the [5987]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 [5988]HTML elements, the [5989]id attribute value
must be unique amongst all the [5990]IDs in the element's [5991]tree
and must contain at least one character. The value must not contain any
[5992]ASCII whitespace.
The [5993]id attribute specifies its element's [5994]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 [5995]unique identifier can be used for a variety of
purposes, most notably as a way to link to specific parts of a document
using [5996]fragments, as a way to target an element when scripting,
and as a way to style a specific element from CSS.
Identifiers are opaque strings. Particular meanings should not be
derived from the value of the [5997]id attribute.
There are no conformance requirements for the [5998]slot attribute
specific to [5999]HTML elements.
The [6000]slot attribute is used to [6001]assign a slot to an element:
an element with a [6002]slot attribute is [6003]assigned to the
[6004]slot created by the [6005]slot element whose [6006]name
attribute's value matches that [6007]slot attribute's value — but only
if that [6008]slot element finds itself in the [6009]shadow tree whose
[6010]root's [6011]host has the corresponding [6012]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 [6013]annotations for assistive technology products can be
specified (the ARIA [6014]role and [6015]aria-* attributes).
[6016][ARIA]
__________________________________________________________________
The attributes marked with an asterisk have a different meaning when
specified on [6090]body elements as those elements expose [6091]event
handlers of the [6092]Window object with the same names.
While these attributes apply to all elements, they are not useful on
all elements. For example, only [6093]media elements will ever receive
a [6094]volumechange event fired by the user agent.
__________________________________________________________________
[6095]Custom data attributes (e.g. data-foldername or data-msgid) can
be specified on any [6096]HTML element, to store custom data, state,
annotations, and similar, specific to the page.
__________________________________________________________________
In [6097]HTML documents, elements in the [6098]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 [6099]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 [6100]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 [6101]xml:space attribute in the
[6102]XML namespace on any element in an [6103]XML document. This
attribute has no effect on [6104]HTML elements, as the default behavior
in HTML is to preserve whitespace. [6105][XML]
There is no way to serialize the [6106]xml:space attribute on
[6107]HTML elements in the [6108]text/html syntax.
3.2.6.1 The [6109]title attribute
(BUTTON) ✔MDN
[6110]Global_attributes/title
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
The title attribute [6111]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
[6112]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 [6113]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
[6114]title attribute of the nearest ancestor [6115]HTML element with a
[6116]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 [6117]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 [6118]title
attributes.
For instance, the following snippet actually defines an abbreviation's
expansion with a line break in it:
My logs show that there was some interest in HTTP today.
Some elements, such as [6119]link, [6120]abbr, and [6121]input, define
additional semantics for the [6122]title attribute beyond the semantics
described above.
The advisory information of an element is the value that the following
algorithm returns, with the algorithm being aborted once a value is
returned. When the algorithm returns the empty string, then there is no
advisory information.
1. If the element has a [6123]title attribute, then return the result
of running [6124]normalize newlines on its value.
2. If the element has a parent element, then return the parent
element's [6125]advisory information.
3. Return the empty string.
User agents should inform the user when elements have [6126]advisory
information, otherwise the information would not be discoverable.
__________________________________________________________________
(BUTTON) ✔MDN
[6127]HTMLElement/title
Support in all current engines.
Firefox1+Safari3+Chrome1+
__________________________________________________________________
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. [6133][BCP47]
The [6134]lang attribute in the [6135]XML namespace is defined in XML.
[6136][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 [6137]slot elements in a [6138]shadow tree).
The [6139]lang attribute in no namespace may be used on any [6140]HTML
element.
The [6141]lang attribute in the XML namespace may be used on [6142]HTML
elements in [6143]XML documents, as well as elements in other
namespaces if the relevant specifications allow it (in particular,
MathML and SVG allow [6144]lang attributes in the XML namespace to be
specified on their elements). If both the [6145]lang attribute in no
namespace and the [6146]lang attribute in the XML namespace are
specified on the same element, they must have exactly the same value
when compared in an [6147]ASCII case-insensitive manner.
Authors must not use the [6148]lang attribute in the XML namespace on
[6149]HTML elements in [6150]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 [6151]HTML elements
in [6152]HTML documents, but such attributes must only be specified if
a [6153]lang attribute in no namespace is also specified, and both
attributes must have the same value when compared in an [6154]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.
__________________________________________________________________
To determine the language of a node, user agents must use the first
appropriate step in the following list:
If the node is an element that has a [6155]lang attribute in the XML
namespace set
Use the value of that attribute.
If the node is an [6156]HTML element or an element in the [6157]SVG
namespace, and it has a [6158]lang in no namespace attribute set
Use the value of that attribute.
If the node's parent is a [6159]shadow root
Use the [6160]language of that [6161]shadow root's [6162]host.
If the node's [6163]parent element is not null
Use the [6164]language of that [6165]parent element.
Otherwise
If there is a [6166]pragma-set default language set, then that
is the language of the node. If there is no [6167]pragma-set
default language set, then language information from a
higher-level protocol (such as HTTP), if any, must be used as
the final fallback language instead. In the absence of any such
language information, and in cases where the higher-level
protocol reports multiple languages, the language of the node is
unknown, and the corresponding language tag is the empty string.
If the resulting value is not a recognized language tag, then it must
be treated as an unknown language having the given language tag,
distinct from all other languages. For the purposes of round-tripping
or communicating with other services that expect language tags, user
agents should pass unknown language tags through unmodified, and tagged
as being BCP 47 language tags, so that subsequent services do not
interpret the data as another type of language description.
[6168][BCP47]
Thus, for instance, an element with lang="xyzzy" would be matched by
the selector :lang(xyzzy) (e.g. in CSS), but it would not be matched by
:lang(abcde), even though both are equally invalid. Similarly, if a web
browser and screen reader working in unison communicated about the
language of the element, the browser would tell the screen reader that
the language was "xyzzy", even if it knew it was invalid, just in case
the screen reader actually supported a language with that tag after
all. Even if the screen reader supported both BCP 47 and another syntax
for encoding language names, and in that other syntax the string
"xyzzy" was a way to denote the Belarusian language, it would be
incorrect for the screen reader to then start treating text as
Belarusian, because "xyzzy" is not how Belarusian is described in BCP
47 codes (BCP 47 uses the code "be" for Belarusian).
If the resulting value is the empty string, then it must be interpreted
as meaning that the language of the node is explicitly unknown.
__________________________________________________________________
User agents may use the element's language to determine proper
processing or rendering (e.g. in the selection of appropriate fonts or
pronunciations, for dictionary selection, or for the user interfaces of
form controls such as date pickers).
__________________________________________________________________
(BUTTON) ✔MDN
[6169]HTMLElement/lang
Support in all current engines.
Firefox1+Safari3+Chrome1+
__________________________________________________________________
The translate attribute is used to specify whether an element's
attribute values and the values of its [6174]Text node children are to
be translated when the page is localized, or whether to leave them
unchanged. It is an attribute is an [6175]enumerated attribute with the
following keywords and states:
Keyword State Brief description
yes yes Sets [6176]translation mode to [6177]translate-enabled.
(the empty string)
no no Sets [6178]translation mode to [6179]no-translate.
The attribute's [6180]missing value default and [6181]invalid value
default are both the inherit state.
Each element (even non-HTML elements) has a translation mode, which is
in either the [6182]translate-enabled state or the [6183]no-translate
state. If an [6184]HTML element's [6185]translate attribute is in the
[6186]yes state, then the element's [6187]translation mode is in the
[6188]translate-enabled state; otherwise, if the element's
[6189]translate attribute is in the [6190]no state, then the element's
[6191]translation mode is in the [6192]no-translate state. Otherwise,
either the element's [6193]translate attribute is in the [6194]inherit
state, or the element is not an [6195]HTML element and thus does not
have a [6196]translate attribute; in either case, the element's
[6197]translation mode is in the same state as its [6198]parent
element's, if any, or in the [6199]translate-enabled state, if the
element's [6200]parent element is null.
When an element is in the translate-enabled state, the element's
[6201]translatable attributes and the values of its [6202]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 [6203]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:
* [6204]abbr on [6205]th elements
* alt on [6206]area, [6207]img, and [6208]input elements
* [6209]content on [6210]meta elements, if the [6211]name attribute
specifies a metadata name whose value is known to be translatable
* [6212]download on [6213]a and [6214]area elements
* label on [6215]optgroup, [6216]option, and [6217]track elements
* [6218]lang on [6219]HTML elements; must be "translated" to match
the language used in the translation
* placeholder on [6220]input and [6221]textarea elements
* [6222]srcdoc on [6223]iframe elements; must be parsed and
recursively processed
* [6224]style on [6225]HTML elements; must be parsed and recursively
processed (e.g. for the values of [6226]'content' properties)
* [6227]title on all [6228]HTML elements
* [6229]value on [6230]input elements with a [6231]type attribute in
the [6232]Button state or the [6233]Reset Button state
Other specifications may define other attributes that are also
[6234]translatable attributes. For example, ARIA would define the
[6235]aria-label attribute as translatable.
__________________________________________________________________
The translate IDL attribute must, on getting, return true if the
element's [6236]translation mode is [6237]translate-enabled, and false
otherwise. On setting, it must set the content attribute's value to
"yes" if the new value is true, and set the content attribute's value
to "no" otherwise.
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:
The Bee Game
The Bee Game is a text adventure game in English.
When the game launches, the first thing you should do is type
eat honey. The game will respond with:
Yum yum! That was some good honey!
3.2.6.4 The [6238]dir attribute
(BUTTON) ✔MDN
[6239]Global_attributes/dir
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
The dir attribute is an [6240]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 [6241]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. [6242][BIDI]
For [6243]textarea and [6244]pre elements, the heuristic is applied on
a per-paragraph level.
The attribute's [6245]missing value default and [6246]invalid value
default are both the undefined state.
__________________________________________________________________
The directionality of an element (any element, not just an [6247]HTML
element) is either 'ltr' or 'rtl'. To compute the [6248]directionality
given an element element, switch on element's [6249]dir attribute
state:
[6250]ltr
Return '[6251]ltr'.
[6252]rtl
Return '[6253]rtl'.
[6254]auto
1. Let result be the [6255]auto directionality of element.
2. If result is null, then return '[6256]ltr'.
3. Return result.
[6257]undefined
If element is a [6258]bdi element
1. Let result be the [6259]auto directionality of element.
2. If result is null, then return '[6260]ltr'.
3. Return result.
If element is an [6261]input element whose [6262]type attribute is
in the [6263]Telephone state
Return '[6264]ltr'.
Otherwise
Return the [6265]parent directionality of element.
Since the [6266]dir attribute is only defined for [6267]HTML elements,
it cannot be present on elements from other namespaces. Thus, elements
from other namespaces always end up using the [6268]parent
directionality.
The auto-directionality form-associated elements are:
* [6269]input elements whose [6270]type attribute is in the
[6271]Hidden, [6272]Text, [6273]Search, [6274]Telephone, [6275]URL,
[6276]Email, [6277]Password, [6278]Submit Button, [6279]Reset
Button, or [6280]Button state, and
* [6281]textarea elements.
To compute the auto directionality given an element element:
1. If element is an [6282]auto-directionality form-associated element:
1. If element's [6283]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 [6284]value, then return '[6285]rtl'. [6286][BIDI]
2. If element's [6287]value is not the empty string, then return
'[6288]ltr'.
3. Return null.
2. If element is a [6289]slot element whose [6290]root is a
[6291]shadow root and element's [6292]assigned nodes are not empty:
1. [6293]For each node child of element's [6294]assigned nodes:
1. Let childDirection be null.
2. If child is a [6295]Text node, then set childDirection to
the [6296]text node directionality of child.
3. Otherwise:
1. [6297]Assert: child is an [6298]Element node.
2. Set childDirection to the [6299]contained text auto
directionality of child with [6300]canExcludeRoot
set to true.
4. If childDirection is not null, then return
childDirection.
2. Return null.
3. Return the [6301]contained text auto directionality of element with
[6302]canExcludeRoot set to false.
To compute the contained text auto directionality of an element element
with a boolean canExcludeRoot:
1. [6303]For each node descendant of element's [6304]descendants, in
[6305]tree order:
1. If any of
o descendant
o any ancestor element of descendant that is a descendant
of element
o if canExcludeRoot is true, element
is one of
o a [6306]bdi element
o a [6307]script element
o a [6308]style element
o a [6309]textarea element
o an element whose [6310]dir attribute is not in the
[6311]undefined state
then [6312]continue.
2. If descendant is a [6313]slot element whose [6314]root is a
[6315]shadow root, then return the [6316]directionality of
that [6317]shadow root's [6318]host.
3. If descendant is not a [6319]Text node, then [6320]continue.
4. Let result be the [6321]text node directionality of
descendant.
5. If result is not null, then return result.
2. Return null.
To compute the text node directionality given a [6322]Text node text:
1. If text's [6323]data does not contain a code point whose
bidirectional character type is L, AL, or R, then return null.
[6324][BIDI]
2. Let codePoint be the first code point in text's [6325]data whose
bidirectional character type is L, AL, or R.
3. If codePoint is of bidirectional character type AL or R, then
return '[6326]rtl'.
4. If codePoint is of bidirectional character type L, then return
'[6327]ltr'.
To compute the parent directionality given an element element:
1. Let parentNode be element's parent node.
2. If parentNode is a [6328]shadow root, then return the
[6329]directionality of parentNode's [6330]host.
3. If parentNode is an element, then return the [6331]directionality
of parentNode.
4. Return '[6332]ltr'.
This attribute [6333]has rendering requirements involving the
bidirectional algorithm.
__________________________________________________________________
The directionality of an attribute of an [6334]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 [6335]directionality-capable attribute and the
element's [6336]dir attribute is in the [6337]auto state
Find the first character (in logical order) of the attribute's
value that is of bidirectional character type L, AL, or R.
[6338][BIDI]
If such a character is found and it is of bidirectional
character type AL or R, the [6339]directionality of the
attribute is '[6340]rtl'.
Otherwise, the [6341]directionality of the attribute is
'[6342]ltr'.
Otherwise
The [6343]directionality of the attribute is the same as
[6344]the element's directionality.
The following attributes are directionality-capable attributes:
* [6345]abbr on [6346]th elements
* alt on [6347]area, [6348]img, and [6349]input elements
* [6350]content on [6351]meta elements, if the [6352]name attribute
specifies a metadata name whose value is primarily intended to be
human-readable rather than machine-readable
* label on [6353]optgroup, [6354]option, and [6355]track elements
* placeholder on [6356]input and [6357]textarea elements
* [6358]title on all [6359]HTML elements
__________________________________________________________________
document.[6360]dir [ = value ]
Returns [6361]the html element's [6362]dir attribute's value, if
any.
Can be set, to either "ltr", "rtl", or "auto" to replace
[6363]the html element's [6364]dir attribute's value.
If there is no [6365]html element, returns the empty string and
ignores new values.
(BUTTON) ✔MDN
[6366]HTMLElement/dir
Support in all current engines.
Firefox1+Safari3+Chrome1+
__________________________________________________________________
The dir IDL attribute on [6371]Document objects must [6372]reflect the
[6373]dir content attribute of [6374]the html element, if any,
[6375]limited to only known values. If there is no such element, then
the attribute must return the empty string and do nothing on setting.
Authors are strongly encouraged to use the [6376]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.
Student: How do you write "Whatʼs your
name?" in Arabic?
Teacher: ما اسمك؟
Student: Thanks.
Teacher: Thatʼs written "شكرًا".
Teacher: Do you know how to write "Plea
se"?
Student: "من فضلك", right?
Given a suitable style sheet and the default alignment styles for the
[6377]p element, namely to align the text to the start edge of the
paragraph, the resulting rendering could be as follows:
Each paragraph rendered as a separate block, with the paragraphs
left-aligned except the second paragraph and the last one, which would
be right aligned, with the usernames ('Student' and 'Teacher' in this
example) flush right, with a colon to their left, and the text first to
the left of that.
As noted earlier, the [6378]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.
3.2.6.5 The [6379]style attribute
(BUTTON) ✔MDN
[6380]Global_attributes/style
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
All [6381]HTML elements may have the style content attribute set. This
is a [6382]style attribute as defined by CSS Style Attributes.
[6383][CSSATTR]
In user agents that support CSS, the attribute's value must be parsed
when the attribute is added or has its value changed, according to the
rules given for [6384]style attributes. [6385][CSSATTR]
However, if the [6386]Should element's inline behavior be blocked by
Content Security Policy? algorithm returns "Blocked" when executed upon
the attribute's [6387]element, "style attribute", and the attribute's
value, then the style rules defined in the attribute's value must not
be applied to the [6388]element. [6389][CSP]
Documents that use [6390]style attributes on any of their elements must
still be comprehensible and usable if those attributes were removed.
In particular, using the [6391]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
[6392]hidden attribute.)
__________________________________________________________________
element.[6393]style
Returns a [6394]CSSStyleDeclaration object for the element's
[6395]style attribute.
The [6396]style IDL attribute is defined in CSS Object Model.
[6397][CSSOM]
In the following example, the words that refer to colors are marked up
using the [6398]span element and the [6399]style attribute to make
those words show up in the relevant colors in visual media.
My sweat suit is green and my eyes are blue.
3.2.6.6 Embedding custom non-visible data with the [6400]data-*
attributes
(BUTTON) ✔MDN
[6401]Global_attributes/data-*
Support in all current engines.
Firefox6+Safari5.1+Chrome7+
__________________________________________________________________
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 [6402]XML-compatible, and contains no [6403]ASCII upper
alphas.
All attribute names on [6404]HTML elements in [6405]HTML documents get
ASCII-lowercased automatically, so the restriction on ASCII uppercase
letters doesn't affect such documents.
[6406]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 [6407]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.
Beyond The Sea
...
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:
The third claim covers the case of HTML markup.
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 [6408]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 [6409]custom
data attribute to be used.
In this example, custom data attributes are used to store the result of
a feature detection for [6410]PaymentRequest, which could be used in
CSS to style a checkout page differently.
Here, the data-has-payment-request attribute is effectively being used
as a [6411]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 [6412]HTML element may have any number of [6413]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.
User agents must not derive any implementation behavior from these
attributes or values. Specifications intended for user agents must not
define these attributes to have any meaningful values.
JavaScript libraries may use the [6414]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).
__________________________________________________________________
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android41+
Returns a [6418]DOMStringMap object for the element's
[6419]data-* attributes.
Hyphenated names become camel-cased. For example,
data-foo-bar="" becomes element.dataset.fooBar.
The dataset IDL attribute provides convenient accessors for all the
[6420]data-* attributes on an element. On getting, the [6421]dataset
IDL attribute must return a [6422]DOMStringMap whose associated element
is this element.
The [6423]DOMStringMap interface is used for the [6424]dataset
attribute. Each [6425]DOMStringMap has an associated element.
[Exposed=Window,
[6426]LegacyOverrideBuiltIns]
interface DOMStringMap {
[6427]getter DOMString (DOMString name);
[[6428]CEReactions] [6429]setter undefined (DOMString name, DOMString value);
[[6430]CEReactions] [6431]deleter undefined (DOMString name);
};
To get a DOMStringMap's name-value pairs, run the following algorithm:
1. Let list be an empty list of name-value pairs.
2. For each content attribute on the [6432]DOMStringMap's
[6433]associated element whose first five characters are the string
"data-" and whose remaining characters (if any) do not include any
[6434]ASCII upper alphas, in the order that those attributes are
listed in the element's [6435]attribute list, add a name-value pair
to list whose name is the attribute's name with the first five
characters removed and whose value is the attribute's value.
3. For each name in list, for each U+002D HYPHEN-MINUS character (-)
in the name that is followed by an [6436]ASCII lower alpha, remove
the U+002D HYPHEN-MINUS character (-) and replace the character
that followed it by the same character [6437]converted to ASCII
uppercase.
4. Return list.
The [6438]supported property names on a [6439]DOMStringMap object at
any instant are the names of each pair returned from [6440]getting the
DOMStringMap's name-value pairs at that instant, in the order returned.
To [6441]determine the value of a named property name for a
[6442]DOMStringMap, return the value component of the name-value pair
whose name component is name in the list returned from [6443]getting
the DOMStringMap's name-value pairs.
To [6444]set the value of a new named property or [6445]set the value
of an existing named property for a [6446]DOMStringMap, given a
property name name and a new value value, run the following steps:
1. If name contains a U+002D HYPHEN-MINUS character (-) followed by an
[6447]ASCII lower alpha, then throw a [6448]"SyntaxError"
[6449]DOMException.
2. For each [6450]ASCII upper alpha in name, insert a U+002D
HYPHEN-MINUS character (-) before the character and replace the
character with the same character [6451]converted to ASCII
lowercase.
3. Insert the string data- at the front of name.
4. If name does not match the XML [6452]Name production, throw an
[6453]"InvalidCharacterError" [6454]DOMException.
5. [6455]Set an attribute value for the [6456]DOMStringMap's
[6457]associated element using name and value.
To [6458]delete an existing named property name for a
[6459]DOMStringMap, run the following steps:
1. For each [6460]ASCII upper alpha in name, insert a U+002D
HYPHEN-MINUS character (-) before the character and replace the
character with the same character [6461]converted to ASCII
lowercase.
2. Insert the string data- at the front of name.
3. [6462]Remove an attribute by name given name and the
[6463]DOMStringMap's [6464]associated element.
This algorithm will only get invoked by Web IDL for names that are
given by the earlier algorithm for [6465]getting the DOMStringMap's
name-value pairs. [6466][WEBIDL]
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 [6467]class attribute along with
[6468]data-* attributes:
Notice how the hyphenated attribute name becomes camel-cased in the
API.
Given the following fragment and elements with similar constructions:
...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
}
}
3.2.7 The [6469]innerText and [6470]outerText properties
(BUTTON) ✔MDN
[6471]HTMLElement/innerText
Support in all current engines.
Firefox45+Safari1+Chrome1+
__________________________________________________________________
element.[6472]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 [6473]br elements.
element.[6474]outerText [ = value ]
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 [6475]br elements.
The get the text steps, given an [6476]HTMLElement element, are:
1. If element is not [6477]being rendered or if the user agent is a
non-CSS user agent, then return element's [6478]descendant text
content.
This step can produce surprising results, as when the
[6479]innerText getter is invoked on an element not [6480]being
rendered, its text contents are returned, but when accessed on an
element that is [6481]being rendered, all of its children that are
not [6482]being rendered have their text contents ignored.
2. Let results be a new empty [6483]list.
3. For each child node node of element:
1. Let current be the [6484]list resulting in running the
[6485]rendered text collection steps with node. Each item in
results will either be a [6486]string or a positive integer (a
required line break count).
Intuitively, a required line break count item means that a
certain number of line breaks appear at that point, but they
can be collapsed with the line breaks induced by adjacent
required line break count items, reminiscent to CSS
margin-collapsing.
2. For each item item in current, append item to results.
4. [6487]Remove any items from results that are the empty string.
5. [6488]Remove any runs of consecutive required line break count
items at the start or end of results.
6. [6489]Replace each remaining run of consecutive required line break
count items with a string consisting of as many U+000A LF code
points as the maximum of the values in the required line break
count items.
7. Return the concatenation of the string items in results.
(BUTTON) ✔MDN
[6490]HTMLElement/outerText
Support in all current engines.
Firefox98+Safari1.3+Chrome1+
__________________________________________________________________
The innerText and outerText getter steps are to return the result of
running [6491]get the text steps with [6492]this.
The rendered text collection steps, given a [6493]node node, are as
follows:
1. Let items be the result of running the [6494]rendered text
collection steps with each child node of node in [6495]tree order,
and then concatenating the results to a single [6496]list.
2. If node's [6497]computed value of [6498]'visibility' is not
'visible', then return items.
3. If node is not [6499]being rendered, then return items. For the
purpose of this step, the following elements must act as described
if the [6500]computed value of the [6501]'display' property is not
'none':
+ [6502]select elements have an associated non-replaced inline
[6503]CSS box whose child boxes include only those of
[6504]optgroup and [6505]option element child nodes;
+ [6506]optgroup elements have an associated non-replaced
block-level [6507]CSS box whose child boxes include only those
of [6508]option element child nodes; and
+ [6509]option element have an associated non-replaced
block-level [6510]CSS box whose child boxes are as normal for
non-replaced block-level [6511]CSS boxes.
items can be non-empty due to 'display:contents'.
4. If node is a [6512]Text node, then for each CSS text box produced
by node, in content order, compute the text of the box after
application of the CSS [6513]'white-space' processing rules and
[6514]'text-transform' rules, set items to the [6515]list of the
resulting strings, and return items. The CSS [6516]'white-space'
processing rules are slightly modified: collapsible spaces at the
end of lines are always collapsed, but they are only removed if the
line is the last line of the block, or it ends with a [6517]br
element. Soft hyphens should be preserved. [6518][CSSTEXT]
5. If node is a [6519]br element, then [6520]append a string
containing a single U+000A LF code point to items.
6. If node's [6521]computed value of [6522]'display' is
[6523]'table-cell', and node's [6524]CSS box is not the last
[6525]'table-cell' box of its enclosing [6526]'table-row' box, then
[6527]append a string containing a single U+0009 TAB code point to
items.
7. If node's [6528]computed value of [6529]'display' is
[6530]'table-row', and node's [6531]CSS box is not the last
[6532]'table-row' box of the nearest ancestor [6533]'table' box,
then [6534]append a string containing a single U+000A LF code point
to items.
8. If node is a [6535]p element, then [6536]append 2 (a required line
break count) at the beginning and end of items.
9. If node's [6537]used value of [6538]'display' is [6539]block-level
or [6540]'table-caption', then [6541]append 1 (a required line
break count) at the beginning and end of items. [6542][CSSDISPLAY]
Floats and absolutely-positioned elements fall into this category.
10. Return items.
Note that descendant nodes of most replaced elements (e.g.,
[6543]textarea, [6544]input, and [6545]video — but not [6546]button)
are not rendered by CSS, strictly speaking, and therefore have no
[6547]CSS boxes for the purposes of this algorithm.
This algorithm is amenable to being generalized to work on
[6548]ranges. Then we can use it as the basis for [6549]Selection's
stringifier and maybe expose it directly on [6550]ranges. See
[6551]Bugzilla bug 10583.
__________________________________________________________________
The set the inner text steps, given an [6552]HTMLElement element, and a
string value are:
1. Let fragment be the [6553]rendered text fragment for value given
element's [6554]node document.
2. [6555]Replace all with fragment within element.
The [6556]innerText setter steps are to run [6557]set the inner text
steps.
The [6558]outerText setter steps are:
1. If [6559]this's parent is null, then throw a
[6560]"NoModificationAllowedError" [6561]DOMException.
2. Let next be [6562]this's [6563]next sibling.
3. Let previous be [6564]this's [6565]previous sibling.
4. Let fragment be the [6566]rendered text fragment for the given
value given [6567]this's [6568]node document.
5. If fragment has no [6569]children, then [6570]append a new
[6571]Text node whose [6572]data is the empty string and [6573]node
document is [6574]this's [6575]node document to fragment.
6. [6576]Replace [6577]this with fragment within [6578]this's parent.
7. If next is non-null and next's [6579]previous sibling is a
[6580]Text node, then [6581]merge with the next text node given
next's [6582]previous sibling.
8. If previous is a [6583]Text node, then [6584]merge with the next
text node given previous.
The rendered text fragment for a string input given a [6585]Document
document is the result of running the following steps:
1. Let fragment be a new [6586]DocumentFragment whose [6587]node
document is document.
2. Let position be a [6588]position variable for input, initially
pointing at the start of input.
3. Let text be the empty string.
4. While position is not past the end of input:
1. [6589]Collect a sequence of code points that are not U+000A LF
or U+000D CR from input given position, and set text to the
result.
2. If text is not the empty string, then [6590]append a new
[6591]Text node whose [6592]data is text and [6593]node
document is document to fragment.
3. While position is not past the end of input, and the code
point at position is either U+000A LF or U+000D CR:
1. If the code point at position is U+000D CR and the next
code point is U+000A LF, then advance position to the
next code point in input.
2. Advance position to the next code point in input.
3. [6594]Append the result of [6595]creating an element
given document, "br", and the [6596]HTML namespace to
fragment.
5. Return fragment.
To merge with the next text node given a [6597]Text node node:
1. Let next be node's [6598]next sibling.
2. If next is not a [6599]Text node, then return.
3. [6600]Replace data with node, node's [6601]data's [6602]length, 0,
and next's [6603]data.
4. [6604]Remove next.
3.2.8 Requirements relating to the bidirectional algorithm
3.2.8.1 Authoring conformance criteria for bidirectional-algorithm
formatting characters
[6605]Text content in [6606]HTML elements with [6607]Text nodes in
their [6608]contents, and text in attributes of [6609]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). [6610][BIDI]
Authors are encouraged to use the [6611]dir attribute, the [6612]bdo
element, and the [6613]bdi element, rather than maintaining the
bidirectional-algorithm formatting characters manually. The
bidirectional-algorithm formatting characters interact poorly with CSS.
3.2.8.2 User agent conformance criteria
User agents must implement the Unicode bidirectional algorithm to
determine the proper ordering of characters when rendering documents
and parts of documents. [6614][BIDI]
The mapping of HTML to the Unicode bidirectional algorithm must be done
in one of three ways. Either the user agent must implement CSS,
including in particular the CSS [6615]'unicode-bidi',
[6616]'direction', and [6617]'content' properties, and must have, in
its user agent style sheet, the rules using those properties given in
this specification's [6618]rendering section, or, alternatively, the
user agent must act as if it implemented just the aforementioned
properties and had a user agent style sheet that included all the
aforementioned rules, but without letting style sheets specified in
documents override them, or, alternatively, the user agent must
implement another styling language with equivalent semantics.
[6619][CSSGC]
The following elements and attributes have requirements defined by the
[6620]rendering section that, due to the requirements in this section,
are requirements on all user agents (not just those that [6621]support
the suggested default rendering):
* [6622]dir attribute
* [6623]bdi element
* [6624]bdo element
* [6625]br element
* [6626]pre element
* [6627]textarea element
* [6628]wbr element
3.2.9 Requirements related to ARIA and to platform accessibility APIs
User agent requirements for implementing Accessibility API semantics on
[6629]HTML elements are defined in HTML Accessibility API Mappings. In
addition to the rules there, for a [6630]custom element element, the
default ARIA role semantics are determined as follows: [6631][HTMLAAM]
1. Let map be element's [6632]internal content attribute map.
2. If map["role"] [6633]exists, then return it.
3. Return no role.
Similarly, for a [6634]custom element element, the default ARIA state
and property semantics, for a state or property named stateOrProperty,
are determined as follows:
1. If element's [6635]attached internals is non-null:
1. If element's [6636]attached internals's [6637]get the
stateOrProperty-associated element exists, then return the
result of running it.
2. If element's [6638]attached internals's [6639]get the
stateOrProperty-associated elements exists, then return the
result of running it.
2. If element's [6640]internal content attribute map[stateOrProperty]
[6641]exists, then return it.
3. Return the default value for stateOrProperty.
The "default semantics" referred to here are sometimes also called
"native", "implicit", or "host language" semantics in ARIA.
[6642][ARIA]
One implication of these definitions is that the default semantics can
change over time. This allows custom elements the same expressivity as
built-in elements; e.g., compare to how the default ARIA role semantics
of an [6643]a element change as the [6644]href attribute is added or
removed.
For an example of this in action, see [6645]the custom elements
section.
__________________________________________________________________
Conformance checker requirements for checking use of ARIA [6646]role
and [6647]aria-* attributes on [6648]HTML elements are defined in ARIA
in HTML. [6649][ARIAHTML]
4 The elements of HTML
4.1 The document element
4.1.1 The html element
(BUTTON) ✔MDN
[6650]Element/html
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
[6653]Contexts in which this element can be used:
As document's [6654]document element.
Wherever a subdocument fragment is allowed in a compound
document.
[6655]Content model:
A [6656]head element followed by a [6657]body element.
[6658]Tag omission in text/html:
An [6659]html element's [6660]start tag can be omitted if the
first thing inside the [6661]html element is not a
[6662]comment.
An [6663]html element's [6664]end tag can be omitted if the
[6665]html element is not immediately followed by a
[6666]comment.
The [6676]html element [6677]represents the root of an HTML document.
Authors are encouraged to specify a [6678]lang attribute on the root
[6679]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 [6680]html element in the following example declares that the
document's language is English.
Swapping Songs
Swapping Songs
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.
4.2 Document metadata
4.2.1 The head element
(BUTTON) ✔MDN
[6681]Element/head
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
[6684]Contexts in which this element can be used:
As the first element in an [6685]html element.
[6686]Content model:
If the document is [6687]an iframe srcdoc document or if title
information is available from a higher-level protocol: Zero or
more elements of [6688]metadata content, of which no more than
one is a [6689]title element and no more than one is a
[6690]base element.
Otherwise: One or more elements of [6691]metadata content, of
which exactly one is a [6692]title element and no more than one
is a [6693]base element.
[6694]Tag omission in text/html:
A [6695]head element's [6696]start tag can be omitted if the
element is empty, or if the first thing inside the [6697]head
element is an element.
A [6698]head element's [6699]end tag can be omitted if the
[6700]head element is not immediately followed by [6701]ASCII
whitespace or a [6702]comment.
The [6711]head element [6712]represents a collection of metadata for
the [6713]Document.
The collection of metadata in a [6714]head element can be large or
small. Here is an example of a very short one:
A document with a short head
...
Here is an example of a longer one:
An application with a long head
...
The [6715]title element is a required child in most situations, but
when a higher-level protocol provides title information, e.g., in the
subject line of an email when HTML is used as an email authoring
format, the [6716]title element can be omitted.
4.2.2 The title element
(BUTTON) ✔MDN
[6717]Element/title
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
The [6738]title element [6739]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 [6740]title element per document.
If it's reasonable for the [6741]Document to have no title, then the
[6742]title element is probably not required. See the [6743]head
element's content model for a description of when the element is
required.
title.[6744]text [ = value ]
Returns the [6745]child text content of the element.
Can be set, to replace the element's children with the given
value.
The text attribute's getter must return this [6746]title element's
[6747]child text content.
The [6748]text attribute's setter must [6749]string replace all with
the given value within this [6750]title element.
Here are some examples of appropriate titles, contrasted with the
top-level headings that might be used on those same pages.
Introduction to The Mating Rituals of Bees
...
Introduction
This companion guide to the highly successful
Introduction to Medieval Bee-Keeping 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:
Dances used during bee mating rituals
...
The Dances
The string to use as the document's title is given by the
[6751]document.title IDL attribute.
User agents should use the document's title when referring to the
document in their user interface. When the contents of a [6752]title
element are used in this way, [6753]the directionality of that
[6754]title element should be used to set the directionality of the
document's title in the user interface.
4.2.3 The base element
(BUTTON) ✔MDN
[6755]Element/base
Support in all current engines.
Firefox1+Safari3+Chrome1+
__________________________________________________________________
The [6785]base element allows authors to specify the [6786]document
base URL for the purposes of parsing [6787]URLs, and the name of the
default [6788]navigable for the purposes of [6789]following hyperlinks.
The element does not [6790]represent any content beyond this
information.
There must be no more than one [6791]base element per document.
A [6792]base element must have either an [6793]href attribute, a
[6794]target attribute, or both.
The href content attribute, if specified, must contain a [6795]valid
URL potentially surrounded by spaces.
A [6796]base element, if it has an [6797]href attribute, must come
before any other elements in the tree that have attributes defined as
taking [6798]URLs.
If there are multiple [6799]base elements with [6800]href attributes,
all but the first are ignored.
The target attribute, if specified, must contain a [6801]valid
navigable target name or keyword, which specifies which [6802]navigable
is to be used as the default when [6803]hyperlinks and [6804]forms in
the [6805]Document cause [6806]navigation.
A [6807]base element, if it has a [6808]target attribute, must come
before any elements in the tree that represent [6809]hyperlinks.
If there are multiple [6810]base elements with [6811]target attributes,
all but the first are ignored.
To get an element's target, given an [6812]a, [6813]area, or [6814]form
element element, and an optional string-or-null target (default null),
run these steps:
1. If target is null, then:
1. If element has a target attribute, then set target to that
attribute's value.
2. Otherwise, if element's [6815]node document contains a
[6816]base element with a [6817]target attribute, set target
to the value of the [6818]target attribute of the first such
[6819]base element.
2. If target is not null, and contains an [6820]ASCII tab or newline
and a U+003C (<), then set target to "_blank".
3. Return target.
__________________________________________________________________
A [6821]base element that is the first [6822]base element with an
[6823]href content attribute [6824]in a document tree has a frozen base
URL. The [6825]frozen base URL must be [6826]immediately [6827]set for
an element whenever any of the following situations occur:
* The [6828]base element becomes the first [6829]base element in
[6830]tree order with an [6831]href content attribute in its
[6832]Document.
* The [6833]base element is the first [6834]base element in
[6835]tree order with an [6836]href content attribute in its
[6837]Document, and its [6838]href content attribute is changed.
To set the frozen base URL for an element element:
1. Let document be element's [6839]node document.
2. Let urlRecord be the result of [6840]parsing the value of element's
[6841]href content attribute with document's [6842]fallback base
URL, and document's [6843]character encoding. (Thus, the [6844]base
element isn't affected by itself.)
3. If any of the following are true:
+ urlRecord is failure;
+ urlRecord's [6845]scheme is "data" or "javascript"; or
+ running [6846]Is base allowed for Document? on urlRecord and
document returns "Blocked",
then set element's [6847]frozen base URL to document's
[6848]fallback base URL and return.
4. Set element's [6849]frozen base URL to urlRecord.
The href IDL attribute, on getting, must return the result of running
the following algorithm:
1. Let document be element's [6850]node document.
2. Let url be the value of the [6851]href attribute of this element,
if it has one, and the empty string otherwise.
3. Let urlRecord be the result of [6852]parsing url with document's
[6853]fallback base URL, and document's [6854]character encoding.
(Thus, the [6855]base element isn't affected by other [6856]base
elements or itself.)
4. If urlRecord is failure, return url.
5. Return the [6857]serialization of urlRecord.
The [6858]href IDL attribute, on setting, must set the [6859]href
content attribute to the given new value.
The target IDL attribute must [6860]reflect the content attribute of
the same name.
In this example, a [6861]base element is used to set the [6862]document
base URL:
[6865]Categories:
[6866]Metadata content.
If the element is [6867]allowed in the body: [6868]flow content.
If the element is [6869]allowed in the body: [6870]phrasing
content.
[6871]Contexts in which this element can be used:
Where [6872]metadata content is expected.
In a [6873]noscript element that is a child of a [6874]head
element.
If the element is [6875]allowed in the body: where
[6876]phrasing content is expected.
[6877]Content model:
[6878]Nothing.
[6879]Tag omission in text/html:
No [6880]end tag.
[6881]Content attributes:
[6882]Global attributes
[6883]href — Address of the [6884]hyperlink
[6885]crossorigin — How the element handles crossorigin requests
[6886]rel — Relationship between the document containing the
[6887]hyperlink and the destination resource
[6888]media — Applicable media
[6889]integrity — Integrity metadata used in Subresource
Integrity checks [6890][SRI]
[6891]hreflang — Language of the linked resource
[6892]type — Hint for the type of the referenced resource
[6893]referrerpolicy — [6894]Referrer policy for [6895]fetches
initiated by the element
[6896]sizes — Sizes of the icons (for [6897]rel="[6898]icon")
[6899]imagesrcset — Images to use in different situations, e.g.,
high-resolution displays, small monitors, etc. (for
[6900]rel="[6901]preload")
[6902]imagesizes — Image sizes for different page layouts (for
[6903]rel="[6904]preload")
[6905]as — [6906]Potential destination for a preload request
(for [6907]rel="[6908]preload" and
[6909]rel="[6910]modulepreload")
[6911]blocking — Whether the element is [6912]potentially
render-blocking
[6913]color — Color to use when customizing a site's icon (for
[6914]rel="mask-icon")
[6915]disabled — Whether the link is disabled
[6916]fetchpriority — Sets the [6917]priority for [6918]fetches
initiated by the element
Also, the [6919]title attribute [6920]has special semantics on
this element: Title of the link; [6921]CSS style sheet set name
// [6963]also has obsolete members
};
[6964]HTMLLinkElement includes [6965]LinkStyle;
The [6966]link element allows authors to link their document to other
resources.
The address of the link(s) is given by the href attribute. If the
[6967]href attribute is present, then its value must be a [6968]valid
non-empty URL potentially surrounded by spaces. One or both of the
[6969]href or [6970]imagesrcset attributes must be present.
If both the [6971]href and [6972]imagesrcset attributes are absent,
then the element does not define a link.
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
[6973]unordered set of unique space-separated tokens. The [6974]allowed
keywords and their meanings are defined in a later section. If the
[6975]rel attribute is absent, has no keywords, or if none of the
keywords used are allowed according to the definitions in this
specification, then the element does not create any links.
[6976]rel's [6977]supported tokens are the keywords defined in
[6978]HTML link types which are allowed on [6979]link elements, impact
the processing model, and are supported by the user agent. The possible
[6980]supported tokens are [6981]alternate, [6982]dns-prefetch,
[6983]expect, [6984]icon, [6985]manifest, [6986]modulepreload,
[6987]next, [6988]pingback, [6989]preconnect, [6990]prefetch,
[6991]preload, [6992]search, and [6993]stylesheet. [6994]rel's
[6995]supported tokens must only include the tokens from this list that
the user agent implements the processing model for.
Theoretically a user agent could support the processing model for the
[6996]canonical keyword — if it were a search engine that executed
JavaScript. But in practice that's quite unlikely. So in most cases,
[6997]canonical ought not be included in [6998]rel's [6999]supported
tokens.
A [7000]link element must have either a [7001]rel attribute or an
[7002]itemprop attribute, but not both.
If a [7003]link element has an [7004]itemprop attribute, or has a
[7005]rel attribute that contains only keywords that are [7006]body-ok,
then the element is said to be allowed in the body. This means that the
element can be used where [7007]phrasing content is expected.
If the [7008]rel attribute is used, the element can only sometimes be
used in the [7009]body of the page. When used with the [7010]itemprop
attribute, the element can be used both in the [7011]head element and
in the [7012]body of the page, subject to the constraints of the
microdata model.
__________________________________________________________________
Two categories of links can be created using the [7013]link element:
[7014]links to external resources and [7015]hyperlinks. The [7016]link
types section defines whether a particular link type is an external
resource or a hyperlink. One [7017]link element can create multiple
links (of which some might be [7018]external resource links and some
might be [7019]hyperlinks); exactly which and how many links are
created depends on the keywords given in the [7020]rel attribute. User
agents must process the links on a per-link basis, not a per-element
basis.
Each link created for a [7021]link element is handled separately. For
instance, if there are two [7022]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 [7023]link
element has a [7024]rel attribute with the value next stylesheet, it
creates both a [7025]hyperlink (for the [7026]next keyword) and an
[7027]external resource link (for the [7028]stylesheet keyword), and
they are affected by other attributes (such as [7029]media or
[7030]title) differently.
For example, the following [7031]link element creates two
[7032]hyperlinks (to the same page):
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.
[7033]Hyperlinks created with the [7034]link element and its [7035]rel
attribute apply to the whole document. This contrasts with the
[7036]rel attribute of [7037]a and [7038]area elements, which indicates
the type of a link whose context is given by the link's location within
the document.
Unlike those created by [7039]a and [7040]area elements,
[7041]hyperlinks created by [7042]link elements are not displayed as
part of the document by default, in user agents that [7043]support the
suggested default rendering. And even if they are force-displayed using
CSS, they have no [7044]activation behavior. Instead, they primarily
provide semantic information which might be used by the page or by
other software that consumes the page's contents. Additionally, the
user agent can [7045]provide its own UI for following such hyperlinks.
The exact behavior for [7046]links to external resources depends on the
exact relationship, as defined for the relevant [7047]link type.
__________________________________________________________________
The crossorigin attribute is a [7048]CORS settings attribute. It is
intended for use with [7049]external resource links.
The media attribute says which media the resource applies to. The value
must be a [7050]valid media query list.
(BUTTON) ✔MDN
[7051]Subresource_Integrity
Support in all current engines.
Firefox43+Safari11.1+Chrome45+
__________________________________________________________________
The integrity attribute represents the [7052]integrity metadata for
requests which this element is responsible for. The value is text. The
attribute must only be specified on [7053]link elements that have a
[7054]rel attribute that contains the [7055]stylesheet, [7056]preload,
or [7057]modulepreload keyword. [7058][SRI]
The hreflang attribute on the [7059]link element has the same semantics
as the [7060]hreflang attribute on the a element.
The type attribute gives the [7061]MIME type of the linked resource. It
is purely advisory. The value must be a [7062]valid MIME type string.
For [7063]external resource links, the [7064]type attribute is used as
a hint to user agents so that they can avoid fetching resources they do
not support.
The referrerpolicy attribute is a [7065]referrer policy attribute. It
is intended for use with [7066]external resource links, where it helps
set the [7067]referrer policy used when [7068]fetching and processing
the linked resource. [7069][REFERRERPOLICY]
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 that are [7070]in a document tree, for which the [7071]title
attribute defines [7072]CSS style sheet sets.
The [7073]title attribute on [7074]link elements differs from the
global [7075]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 imagesrcset attribute may be present, and is a [7076]srcset
attribute.
The [7077]imagesrcset and [7078]href attributes (if [7079]width
descriptors are not used) together contribute the [7080]image sources
to the [7081]source set.
If the [7082]imagesrcset attribute is present and has any [7083]image
candidate strings using a [7084]width descriptor, the imagesizes
attribute must also be present, and is a [7085]sizes attribute. The
[7086]imagesizes attribute contributes the [7087]source size to the
[7088]source set.
The [7089]imagesrcset and [7090]imagesizes attributes must only be
specified on [7091]link elements that have both a [7092]rel attribute
that specifies the [7093]preload keyword, as well as an [7094]as
attribute in the "image" state.
These attributes allow preloading the appropriate resource that is
later used by an [7095]img element that has the corresponding values
for its [7096]srcset and [7097]sizes attributes:
Note how we omit the [7098]href attribute, as it would only be relevant
for browsers that do not support [7099]imagesrcset, and in those cases
it would likely cause the incorrect image to be preloaded.
The [7100]imagesrcset attribute can be combined with the [7101]media
attribute to preload the appropriate resource selected from a
[7102]picture element's sources, for [7103]art direction:
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 [7104]unordered
set of unique space-separated tokens which are [7105]ASCII
case-insensitive. Each value must be either an [7106]ASCII
case-insensitive match for the string "[7107]any", or a value that
consists of two [7108]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 attribute must only be specified on [7109]link elements
that have a [7110]rel attribute that specifies the [7111]icon keyword
or the apple-touch-icon keyword.
The apple-touch-icon keyword is a registered [7112]extension to the
predefined set of link types, but user agents are not required to
support it in any way.
__________________________________________________________________
The as attribute specifies the [7113]potential destination for a
preload request for the resource given by the [7114]href attribute. It
is an [7115]enumerated attribute. Each [7116]potential destination is a
keyword for this attribute, mapping to a state of the same name. The
attribute must be specified on [7117]link elements that have a
[7118]rel attribute that contains the [7119]preload keyword. It may be
specified on [7120]link elements that have a [7121]rel attribute that
contains the [7122]modulepreload keyword; in such cases it must have a
value which is a [7123]script-like destination. For other [7124]link
elements, it must not be specified.
The processing model for how the [7125]as attribute is used is given in
an individual link type's [7126]fetch and process the linked resource
algorithm.
The attribute does not have a [7127]missing value default or
[7128]invalid value default, meaning that invalid or missing values for
the attribute map to no state. This is accounted for in the processing
model. For [7129]preload links, both conditions are an error; for
[7130]modulepreload links, a missing value will be treated as "script".
__________________________________________________________________
The blocking attribute is a [7131]blocking attribute. It is used by
link types [7132]stylesheet and [7133]expect, and it must only be
specified on link elements that have a [7134]rel attribute containing
those keywords.
__________________________________________________________________
The color attribute is used with the mask-icon link type. The attribute
must only be specified on [7135]link elements that have a [7136]rel
attribute that contains the mask-icon keyword. The value must be a
string that matches the CSS [7137] production, defining a
suggested color that user agents can use to customize the display of
the icon that the user sees when they pin your site.
This specification does not have any user agent requirements for the
[7138]color attribute.
The mask-icon keyword is a registered [7139]extension to the predefined
set of link types, but user agents are not required to support it in
any way.
__________________________________________________________________
[7140]link elements have an associated explicitly enabled boolean. It
is initially false.
The disabled attribute is a [7141]boolean attribute that is used with
the [7142]stylesheet link type. The attribute must only be specified on
[7143]link elements that have a [7144]rel attribute that contains the
[7145]stylesheet keyword.
Whenever the [7146]disabled attribute is removed, set the [7147]link
element's [7148]explicitly enabled attribute to true.
Removing the [7149]disabled attribute dynamically, e.g., using
document.querySelector("link").removeAttribute("disabled"), will fetch
and apply the style sheet:
The fetchpriority attribute is a [7151]fetch priority attribute that is
intended for use with [7152]external resource links, where it is used
to set the [7153]priority used when [7154]fetching and processing the
linked resource.
__________________________________________________________________
(BUTTON) ✔MDN
[7155]HTMLLinkElement/rel
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
The IDL attributes href, hreflang, integrity, media, rel, sizes, type,
blocking, and disabled each must [7156]reflect the respective content
attributes of the same name.
There is no reflecting IDL attribute for the [7157]color attribute, but
this might be added later.
(BUTTON) ✔MDN
[7158]HTMLLinkElement/as
Support in all current engines.
Firefox56+Safari10+Chrome50+
__________________________________________________________________
The relList IDL attribute must [7177]reflect the [7178]rel content
attribute.
The [7179]relList attribute can be used for feature detection, by
calling its [7180]supports() method to check which [7181]types of links
are supported.
4.2.4.1 Processing the [7182]media attribute
If the link is a [7183]hyperlink then the [7184]media attribute is
purely advisory, and describes for which media the document in question
was designed.
However, if the link is an [7185]external resource link, then the
[7186]media attribute is prescriptive. The user agent must apply the
external resource when the [7187]media attribute's value [7188]matches
the environment and the other relevant conditions apply, and must not
apply it otherwise.
The default, if the [7189]media attribute is omitted, is "all", meaning
that by default links apply to all media.
The external resource might have further restrictions defined within
that limit its applicability. For example, a CSS style sheet might have
some @media blocks. This specification does not override such further
restrictions or requirements.
4.2.4.2 Processing the [7190]type attribute
If the [7191]type attribute is present, then the user agent must assume
that the resource is of the given type (even if that is not a
[7192]valid MIME type string, e.g. the empty string). If the attribute
is omitted, but the [7193]external resource link type has a default
type defined, then the user agent must assume that the resource is of
that type. If the UA does not support the given [7194]MIME type for the
given link relationship, then the UA should not [7195]fetch and process
the linked resource; if the UA does support the given [7196]MIME type
for the given link relationship, then the UA should [7197]fetch and
process the linked resource at the appropriate time as specified for
the [7198]external resource link's particular type. If the attribute is
omitted, and the [7199]external resource link type does not have a
default type defined, but the user agent would [7200]fetch and process
the linked resource if the type was known and supported, then the user
agent should [7201]fetch and process the linked resource under the
assumption that it will be supported.
User agents must not consider the [7202]type attribute authoritative —
upon fetching the resource, user agents must not use the [7203]type
attribute to determine its actual type. Only the actual type (as
defined in the next paragraph) is used to determine whether to apply
the resource, not the aforementioned assumed type.
If the [7204]external resource link type defines rules for processing
the resource's [7205]Content-Type metadata, then those rules apply.
Otherwise, if the resource is expected to be an image, user agents may
apply the [7206]image sniffing rules, with the official type being the
type determined from the resource's [7207]Content-Type metadata, and
use the resulting [7208]computed type of the resource as if it was the
actual type. Otherwise, if neither of these conditions apply or if the
user agent opts not to apply the image sniffing rules, then the user
agent must use the resource's [7209]Content-Type metadata to determine
the type of the resource. If there is no type metadata, but the
[7210]external resource link type has a default type defined, then the
user agent must assume that the resource is of that type.
The [7211]stylesheet link type defines rules for processing the
resource's [7212]Content-Type metadata.
Once the user agent has established the type of the resource, the user
agent must apply the resource if it is of a supported type and the
other relevant conditions apply, and must ignore the resource
otherwise.
If a document contains style sheet links labeled as follows:
...then a compliant UA that supported only CSS style sheets would fetch
the B and C files, and skip the A file (since [7213]text/plain is not
the [7214]MIME type for CSS style sheets).
For files B and C, it would then check the actual types returned by the
server. For those that are sent as [7215]text/css, it would apply the
styles, but for those labeled as [7216]text/plain, or any other type,
it would not.
If one of the two files was returned without a [7217]Content-Type
metadata, or with a syntactically incorrect type like
Content-Type: "null", then the default type for [7218]stylesheet links
would kick in. Since that default type is [7219]text/css, the style
sheet would nonetheless be applied.
4.2.4.3 Fetching and processing a resource from a [7220]link element
All [7221]external resource links have a fetch and process the linked
resource algorithm, which takes a [7222]link element el. They also have
linked resource fetch setup steps which take a [7223]link element el
and [7224]request request. Individual link types may provide their own
[7225]fetch and process the linked resource algorithm, but unless
explicitly stated, they use the [7226]default fetch and process the
linked resource algorithm. Similarly, individual link types may provide
their own [7227]linked resource fetch setup steps, but unless
explicitly stated, these steps just return true.
The default fetch and process the linked resource, given a [7228]link
element el, is as follows:
1. Let options be the result of [7229]creating link options from el.
2. Let request be the result of [7230]creating a link request given
options.
3. If request is null, then return.
4. Set request's [7231]synchronous flag.
5. Run the [7232]linked resource fetch setup steps, given el and
request. If the result is false, then return.
6. Set request's [7233]initiator type to "css" if el's [7234]rel
attribute contains the keyword [7235]stylesheet; "link" otherwise.
7. [7236]Fetch request with [7237]processResponseConsumeBody set to
the following steps given [7238]response response and null,
failure, or a [7239]byte sequence bodyBytes:
1. Let success be true.
2. If any of the following are true:
o bodyBytes is null or failure; or
o response's [7240]status is not an [7241]ok status,
then set success to false.
Note that content-specific errors, e.g., CSS parse errors or
PNG decoding errors, do not affect success.
3. Otherwise, wait for the [7242]link resource's [7243]critical
subresources to finish loading.
The specification that defines a link type's [7244]critical
subresources (e.g., CSS) is expected to describe how these
subresources are fetched and processed. However, since this is
not currently explicit, this specification describes waiting
for a [7245]link resource's [7246]critical subresources to be
fetched and processed, with the expectation that this will be
done correctly.
4. [7247]Process the linked resource given el, success, response,
and bodyBytes.
To create a link request given a [7248]link processing options options:
1. [7249]Assert: options's [7250]href is not the empty string.
2. If options's [7251]destination is null, then return null.
3. Let url be the result of [7252]encoding-parsing a URL given
options's [7253]href, relative to options's [7254]base URL.
Passing the base URL instead of a document or environment is
tracked by [7255]issue #9715.
4. If url is failure, then return null.
5. Let request be the result of [7256]creating a potential-CORS
request given url, options's [7257]destination, and options's
[7258]crossorigin.
6. Set request's [7259]policy container to options's [7260]policy
container.
7. Set request's [7261]integrity metadata to options's
[7262]integrity.
8. Set request's [7263]cryptographic nonce metadata to options's
[7264]cryptographic nonce metadata.
9. Set request's [7265]referrer policy to options's [7266]referrer
policy.
10. Set request's [7267]client to options's [7268]environment.
11. Set request's [7269]priority to options's [7270]fetch priority.
12. Return request.
User agents may opt to only try to [7271]fetch and process such
resources when they are needed, instead of pro-actively fetching all
the [7272]external resources that are not applied.
Similar to the [7273]fetch and process the linked resource algorithm,
all [7274]external resource links have a process the linked resource
algorithm which takes a [7275]link element el, boolean success, a
[7276]response response, and a [7277]byte sequence bodyBytes.
Individual link types may provide their own [7278]process the linked
resource algorithm, but unless explicitly stated, that algorithm does
nothing.
Unless otherwise specified for a given [7279]rel keyword, the element
must [7280]delay the load event of the element's [7281]node document
until all the attempts to [7282]fetch and process the linked resource
and its [7283]critical subresources are complete. (Resources that the
user agent has not yet attempted to fetch and process, e.g., because it
is waiting for the resource to be needed, do not [7284]delay the load
event.)
4.2.4.4 Processing `[7285]Link` headers
All link types that can be [7286]external resource links define a
process a link header algorithm, which takes a [7287]link processing
options. This algorithm defines whether and how they react to appearing
in an HTTP `[7288]Link` response header.
For most link types, this algorithm does nothing. The [7289]summary
table is a good reference to quickly know whether a link type has
defined [7290]process a link header steps.
A link processing options is a [7291]struct. It has the following
[7292]items:
href (default the empty string)
destination (default the empty string)
initiator (default "link")
integrity (default the empty string)
type (default the empty string)
cryptographic nonce metadata (default the empty string)
A string
crossorigin (default [7293]No CORS)
A [7294]CORS settings attribute state
referrer policy (default the empty string)
A [7295]referrer policy
source set (default null)
Null or a [7296]source set
base URL
A [7297]URL
origin
An [7298]origin
environment
An [7299]environment
policy container
A [7300]policy container
document (default null)
Null or a [7301]Document
on document ready (default null)
Null or an algorithm accepting a [7302]Document
fetch priority (default [7303]auto)
A [7304]fetch priority attribute state
A [7305]link processing options has a [7306]base URL and an [7307]href
rather than a parsed URL because the URL could be a result of the
options's [7308]source set.
To create link options from element given a [7309]link element el:
1. Let document be el's [7310]node document.
2. Let options be a new [7311]link processing options with
[7312]destination
the result of [7313]translating the state of el's [7314]as
attribute
[7315]crossorigin
the state of el's [7316]crossorigin content attribute
[7317]referrer policy
the state of el's [7318]referrerpolicy content attribute
[7330]cryptographic nonce metadata
the current value of el's [7331][[CryptographicNonce]]
internal slot
[7332]fetch priority
the state of el's [7333]fetchpriority content attribute
3. If el has an [7334]href attribute, then set options's [7335]href to
the value of el's [7336]href attribute.
4. If el has an [7337]integrity attribute, then set options's
[7338]integrity to the value of el's [7339]integrity content
attribute.
5. If el has a [7340]type attribute, then set options's [7341]type to
the value of el's [7342]type attribute.
6. [7343]Assert: options's [7344]href is not the empty string, or
options's [7345]source set is not null.
A [7346]link element with neither an [7347]href or an
[7348]imagesrcset does not represent a link.
7. Return options.
To extract links from headers given a [7349]header list headers:
1. Let links be a new [7350]list.
2. Let rawLinkHeaders be the result of [7351]getting, decoding, and
splitting `[7352]Link` from headers.
3. [7353]For each linkHeader of rawLinkHeaders:
1. Let linkObject be the result of [7354]parsing linkHeader.
[7355][WEBLINK]
2. If linkObject["target_uri"] does not [7356]exist, then
[7357]continue.
3. [7358]Append linkObject to links.
4. Return links.
To process link headers given a [7359]Document doc, a [7360]response
response, and a "pre-media" or "media" phase:
1. Let links be the result of [7361]extracting links from response's
[7362]header list.
2. [7363]For each linkObject in links:
1. Let rel be linkObject["relation_type"].
2. Let attribs be linkObject["target_attributes"].
3. Let expectedPhase be "media" if either "[7364]srcset",
"[7365]imagesrcset", or "[7366]media" [7367]exist in attribs;
otherwise "pre-media".
4. If expectedPhase is not phase, then [7368]continue.
5. If attribs["[7369]media"] [7370]exists and
attribs["[7371]media"] does not [7372]match the environment,
then [7373]continue.
6. Let options be a new [7374]link processing options with
7. [7385]Apply link options from parsed header attributes to
options given attribs.
8. If attribs["[7386]imagesrcset"] [7387]exists and
attribs["[7388]imagesizes"] [7389]exists, then set options's
[7390]source set to the result of [7391]creating a source set
given linkObject["target_uri"], attribs["[7392]imagesrcset"],
attribs["[7393]imagesizes"], and null.
9. Run the [7394]process a link header steps for rel given
options.
To apply link options from parsed header attributes to a [7395]link
processing options options given attribs:
1. If attribs["[7396]as"] [7397]exists, then set options's
[7398]destination to the result of [7399]translating
attribs["[7400]as"].
2. If attribs["[7401]crossorigin"] [7402]exists and is an [7403]ASCII
case-insensitive match for one of the [7404]CORS settings attribute
[7405]keywords, then set options's [7406]crossorigin to the
[7407]CORS settings attribute state corresponding to that keyword.
3. If attribs["[7408]integrity"] [7409]exists, then set options's
[7410]integrity to attribs["[7411]integrity"].
4. If attribs["[7412]referrerpolicy"] [7413]exists and is an
[7414]ASCII case-insensitive match for some [7415]referrer policy,
then set options's [7416]referrer policy to that [7417]referrer
policy.
5. If attribs["[7418]nonce"] [7419]exists, then set options's
[7420]nonce to attribs["[7421]nonce"].
6. If attribs["[7422]type"] [7423]exists, then set options's
[7424]type to attribs["[7425]type"].
7. If attribs["[7426]fetchpriority"] [7427]exists and is an
[7428]ASCII case-insensitive match for a [7429]fetch priority
attribute keyword, then set options's [7430]fetch priority to that
[7431]fetch priority attribute keyword.
Early hints allow user-agents to perform some operations, such as to
speculatively load resources that are likely to be used by the
document, before the navigation request is fully handled by the server
and a response code is served. Servers can indicate early hints by
serving a [7433]response with a 103 status code before serving the
final [7434]response.[7435][RFC8297]
For compatibility reasons [7436]early hints are typically delivered
over HTTP/2 or above, but for readability we use HTTP/1.1-style
notation below.
For example, given the following sequence of responses:
103 Early Hint
Link: ; [7437]rel=[7438]preload; [7439]as=image
200 OK
Content-Type: text/html
...
the image will start loading before the HTML content arrives.
Only the first early hint response served during the navigation is
handled, and it is discarded if it is succeeded by a cross-origin
redirect.
In addition to the `[7440]Link` headers, it is possible that the 103
response contains a [7441]Content Security Policy header, which is
enforced when processing the early hint.
For example, given the following sequence of responses:
103 Early Hint
Content-Security-Policy: style-src: self;
Link: ; [7442]rel=[7443]preload; [7444]as=style
103 Early Hint
Link: ; [7445]rel=[7446]preload; [7447]as=image
302 Redirect
Location: /alternate.html
200 OK
Content-Security-Policy: style-src: none;
Link: ; [7448]rel=[7449]preload; [7450]as=font
The font and style would be loaded, and the image will be discarded, as
only the first early hint response in the final redirect chain is
respected. The late [7451]Content Security Policy header comes after
the request to fetch the style has already been performed, but the
style will not be accessible to the document.
To process early hint headers given a [7452]response response and an
[7453]environment reservedEnvironment:
Early-hint `[7454]Link` headers are always processed before
`[7455]Link` headers from the final [7456]response, followed by
[7457]link elements. This is equivalent to prepending the contents of
the early and final `[7458]Link` headers to the [7459]Document's
[7460]head element, in respective order.
1. Let earlyPolicyContainer be the result of [7461]creating a policy
container from a fetch response given response and
reservedEnvironment.
This allows the early hint [7462]response to include a
[7463]Content Security Policy which would be [7464]enforced when
fetching the early hint [7465]request.
2. Let links be the result of [7466]extracting links from response's
[7467]header list.
3. Let earlyHints be an empty [7468]list.
4. [7469]For each linkObject in links:
The moment we receive the early hint link header, we begin
[7470]fetching earlyRequest. If it comes back before the
[7471]Document is created, we set earlyResponse to the
[7472]response of that [7473]fetch and once the [7474]Document is
created we commit it (by making it available in the [7475]map of
preloaded resources as if it was a [7476]link element). If the
[7477]Document is created first, the [7478]response is committed as
soon as it becomes available.
1. Let rel be linkObject["relation_type"].
2. Let options be a new [7479]link processing options with
[7480]href
linkObject["target_uri"]
[7481]initiator
"early-hint"
[7482]base URL
response's [7483]URL
[7484]origin
response's [7485]URL's [7486]origin
[7487]environment
reservedEnvironment
[7488]policy container
earlyPolicyContainer
3. Let attribs be linkObject["target_attributes"].
Only the [7489]as, [7490]crossorigin, [7491]integrity, and
[7492]type attributes are handled as part of early hint
processing. The other ones, in particular [7493]blocking,
[7494]imagesrcset, [7495]imagesizes, and [7496]media are only
applicable once a [7497]Document is created.
4. [7498]Apply link options from parsed header attributes to
options given attribs.
5. Run the [7499]process a link header steps for rel given
options.
6. [7500]Append options to earlyHints.
5. Return the following substeps given [7501]Document doc: [7502]for
each options in earlyHints:
1. If options's [7503]on document ready is null, then set
options's [7504]document to doc.
2. Otherwise, call options's [7505]on document ready with doc.
4.2.4.6 Providing users with a means to follow hyperlinks created using
the [7506]link element
Interactive user agents may provide users with a means to [7507]follow
the hyperlinks created using the [7508]link element, somewhere within
their user interface. Such invocations of the [7509]follow the
hyperlink algorithm must set the [7510]userInvolvement argument to
"[7511]browser UI". The exact interface is not defined by this
specification, but it could include the following information (obtained
from the element's attributes, again as defined below), in some form or
another (possibly simplified), for each [7512]hyperlink created with
each [7513]link element in the document:
* The relationship between this document and the resource (given by
the [7514]rel attribute)
* The title of the resource (given by the [7515]title attribute).
* The address of the resource (given by the [7516]href attribute).
* The language of the resource (given by the [7517]hreflang
attribute).
* The optimum media for the resource (given by the [7518]media
attribute).
User agents could also include other information, such as the type of
the resource (as given by the [7519]type attribute).
4.2.5 The meta element
(BUTTON) ✔MDN
[7520]Element/meta
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
[7522]Categories:
[7523]Metadata content.
If the [7524]itemprop attribute is present: [7525]flow content.
If the [7526]itemprop attribute is present: [7527]phrasing
content.
[7528]Contexts in which this element can be used:
If the [7529]charset attribute is present, or if the element's
[7530]http-equiv attribute is in the [7531]Encoding declaration
state: in a [7532]head element.
If the [7533]http-equiv attribute is present but not in the
[7534]Encoding declaration state: in a [7535]head element.
If the [7536]http-equiv attribute is present but not in the
[7537]Encoding declaration state: in a [7538]noscript element
that is a child of a [7539]head element.
If the [7540]name attribute is present: where [7541]metadata
content is expected.
If the [7542]itemprop attribute is present: where [7543]metadata
content is expected.
If the [7544]itemprop attribute is present: where [7545]phrasing
content is expected.
[7546]Content model:
[7547]Nothing.
[7548]Tag omission in text/html:
No [7549]end tag.
[7550]Content attributes:
[7551]Global attributes
[7552]name — Metadata name
[7553]http-equiv — Pragma directive
[7554]content — Value of the element
[7555]charset — [7556]Character encoding declaration
[7557]media — Applicable media
The [7573]meta element [7574]represents various kinds of metadata that
cannot be expressed using the [7575]title, [7576]base, [7577]link,
[7578]style, and [7579]script elements.
The [7580]meta element can represent document-level metadata with the
[7581]name attribute, pragma directives with the [7582]http-equiv
attribute, and the file's [7583]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 [7584]charset attribute.
Exactly one of the [7585]name, [7586]http-equiv, [7587]charset, and
[7588]itemprop attributes must be specified.
If either [7589]name, [7590]http-equiv, or [7591]itemprop is specified,
then the [7592]content attribute must also be specified. Otherwise, it
must be omitted.
The charset attribute specifies the [7593]character encoding used by
the document. This is a [7594]character encoding declaration. If the
attribute is present, its value must be an [7595]ASCII case-insensitive
match for the string "utf-8".
The [7596]charset attribute on the [7597]meta element has no effect in
XML documents, but is allowed in XML documents in order to facilitate
migration to and from XML.
There must not be more than one [7598]meta element with a [7599]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 [7600]meta element has a name attribute, it sets document
metadata. Document metadata is expressed in terms of name-value pairs,
the [7601]name attribute on the [7602]meta element giving the name, and
the [7603]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 [7604]meta element has no [7605]content attribute, then the value
part of the metadata name-value pair is the empty string.
The media attribute says which media the metadata applies to. The value
must be a [7606]valid media query list. Unless the [7607]name is
[7608]theme-color, the [7609]media attribute has no effect on the
processing model and must not be used by authors.
The name, content, and media IDL attributes must [7610]reflect the
respective content attributes of the same name. The IDL attribute
httpEquiv must [7611]reflect the content attribute [7612]http-equiv.
4.2.5.1 Standard metadata names
(BUTTON) ✔MDN
[7613]Element/meta/name
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
This specification defines a few names for the [7614]name attribute of
the [7615]meta element.
Names are case-insensitive, and must be compared in an [7616]ASCII
case-insensitive manner.
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 [7617]application-name metadata name must
not be used. Translations of the web application's name may be
given, using the [7618]lang attribute to specify the language of
each name.
There must not be more than one [7619]meta element with a given
[7620]language and where the [7621]name attribute value is an
[7622]ASCII case-insensitive match for [7623]application-name
per document.
User agents may use the application name in UI in preference to
the page's [7624]title, since the title might include status
messages and the like relevant to the status of the page at a
particular moment in time instead of just being the name of the
application.
To find the application name to use given an ordered list of
languages (e.g. British English, American English, and English),
user agents must run the following steps:
1. Let languages be the list of languages.
2. Let default language be the [7625]language of the
[7626]Document's [7627]document element, if any, and if that
language is not unknown.
3. If there is a default language, and if it is not the same
language as any of the languages in languages, append it to
languages.
4. Let winning language be the first language in languages for
which there is a [7628]meta element in the [7629]Document
where the [7630]name attribute value is an [7631]ASCII
case-insensitive match for [7632]application-name and whose
[7633]language is the language in question.
If none of the languages have such a [7634]meta element, then
return; there's no given application name.
5. Return the value of the [7635]content attribute of the first
[7636]meta element in the [7637]Document in [7638]tree order
where the [7639]name attribute value is an [7640]ASCII
case-insensitive match for [7641]application-name and whose
[7642]language is winning language.
This algorithm would be used by a browser when it needs a name
for the page, for instance, to label a bookmark. The languages
it would provide to the algorithm would be the user's preferred
languages.
author
The value must be a free-form string giving the name of one of
the page's authors.
description
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
[7643]meta element where the [7644]name attribute value is an
[7645]ASCII case-insensitive match for [7646]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 [7647]head element, to identify itself as
the tool used to generate the page:
keywords
The value must be a [7648]set of comma-separated tokens, each of
which is a keyword relevant to the page.
This page about typefaces on British motorways uses a [7649]meta
element to specify some keywords that users might use to look
for the page:
Typefaces on UK motorways
...
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.
To obtain the list of keywords that the author has specified as
applicable to the page, the user agent must run the following
steps:
1. Let keywords be an empty list.
2. For each [7650]meta element with a [7651]name attribute and a
[7652]content attribute and where the [7653]name attribute
value is an [7654]ASCII case-insensitive match for
[7655]keywords:
1. [7656]Split the value of the element's content attribute
on commas.
2. Add the resulting tokens, if any, to keywords.
3. Remove any duplicates from keywords.
4. Return keywords. This is the list of keywords that the author
has specified as applicable to the page.
User agents should not use this information when there is
insufficient confidence in the reliability of the value.
For instance, it would be reasonable for a content management
system to use the keyword information of pages within the system
to populate the index of a site-specific search engine, but a
large-scale content aggregator that used this information would
likely find that certain users would try to game its ranking
mechanism through the use of inappropriate keywords.
referrer
The value must be a [7657]referrer policy, which defines the
default [7658]referrer policy for the [7659]Document.
[7660][REFERRERPOLICY]
If any [7661]meta element element is [7662]inserted into the
document, or has its [7663]name or [7664]content attributes
changed, user agents must run the following algorithm:
1. If element is not [7665]in a document tree, then return.
2. If element does not have a [7666]name attribute whose value is
an [7667]ASCII case-insensitive match for "[7668]referrer",
then return.
3. If element does not have a [7669]content attribute, or that
attribute's value is the empty string, then return.
4. Let value be the value of element's [7670]content attribute,
[7671]converted to ASCII lowercase.
5. If value is one of the values given in the first column of the
following table, then set value to the value given in the
second column:
Legacy value Referrer policy
never [7672]no-referrer
default the [7673]default referrer policy
always [7674]unsafe-url
origin-when-crossorigin [7675]origin-when-cross-origin
6. If value is a [7676]referrer policy, then set element's
[7677]node document's [7678]policy container's [7679]referrer
policy to policy.
For historical reasons, unlike other standard metadata names,
the processing model for [7680]referrer is not responsive to
element removals, and does not use [7681]tree order. Only the
most-recently-inserted or most-recently-modified [7682]meta
element in this state has an effect.
Firefox Android?Safari iOS?Chrome Android80+WebView
AndroidNoSamsung Internet6.2+Opera AndroidNo
The value must be a string that matches the CSS [7684]
production, defining a suggested color that user agents should
use to customize the display of the page or of the surrounding
user interface. For example, a browser might color the page's
title bar with the specified value, or use it as a color
highlight in a tab bar or task switcher.
Within an HTML document, the [7685]media attribute value must be
unique amongst all the [7686]meta elements with their [7687]name
attribute value set to an [7688]ASCII case-insensitive match for
[7689]theme-color.
This standard itself uses "WHATWG green" as its theme color:
HTML Standard
...
The [7690]media attribute may be used to describe the context in
which the provided color should be used.
If we only wanted to use "WHATWG green" as this standard's theme
color in dark mode, we could use the prefers-color-scheme media
feature:
HTML Standard
...
To obtain a page's theme color, user agents must run the
following steps:
1. Let candidate elements be the list of all [7691]meta elements
that meet the following criteria, in [7692]tree order:
o the element is [7693]in a document tree;
o the element has a [7694]name attribute, whose value is an
[7695]ASCII case-insensitive match for [7696]theme-color;
and
o the element has a [7697]content attribute.
2. For each element in candidate elements:
1. If element has a [7698]media attribute and the value of
element's [7699]media attribute does not [7700]match the
environment, then [7701]continue.
2. Let value be the result of [7702]stripping leading and
trailing ASCII whitespace from the value of element's
[7703]content attribute.
3. Let color be the result of [7704]parsing value.
4. If color is not failure, then return color.
3. Return nothing (the page has no theme color).
If any [7705]meta elements are [7706]inserted into the document
or [7707]removed from the document, or existing [7708]meta
elements have their [7709]name, [7710]content, or [7711]media
attributes changed, or if the environment changes such that any
[7712]meta element's [7713]media attribute's value may now or
may no longer [7714]match the environment, user agents must
re-run the above algorithm and apply the result to any affected
UI.
When using the theme color in UI, user agents may adjust it in
implementation-specific ways to make it more suitable for the UI
in question. For example, if a user agent intends to use the
theme color as a background and display white text over it, it
might use a darker variant of the theme color in that part of
the UI, to ensure adequate contrast.
color-scheme
To aid user agents in rendering the page background with the
desired color scheme immediately (rather than waiting for all
CSS in the page to load), a [7715]'color-scheme' value can be
provided in a [7716]meta element.
The value must be a string that matches the syntax for the CSS
[7717]'color-scheme' property value. It determines the
[7718]page's supported color-schemes.
There must not be more than one [7719]meta element with its
[7720]name attribute value set to an [7721]ASCII
case-insensitive match for [7722]color-scheme per document.
The following declaration indicates that the page is aware of
and can handle a color scheme with dark background colors and
light foreground colors:
To obtain a [7723]page's supported color-schemes, user agents
must run the following steps:
1. Let candidate elements be the list of all [7724]meta elements
that meet the following criteria, in [7725]tree order:
o the element is [7726]in a document tree;
o the element has a [7727]name attribute, whose value is an
[7728]ASCII case-insensitive match for
[7729]color-scheme; and
o the element has a [7730]content attribute.
2. For each element in candidate elements:
1. Let parsed be the result of [7731]parsing a list of
component values given the value of element's
[7732]content attribute.
2. If parsed is a valid CSS [7733]'color-scheme' property
value, then return parsed.
3. Return null.
If any [7734]meta elements are [7735]inserted into the document
or [7736]removed from the document, or existing [7737]meta
elements have their [7738]name or [7739]content attributes
changed, user agents must re-run the above algorithm.
Because these rules check successive elements until they find a
match, an author can provide multiple such values to handle
fallback for legacy user agents. Opposite to how CSS fallback
works for properties, the multiple meta elements needs to be
arranged with the legacy values after the newer values.
4.2.5.2 Other metadata names
Anyone can create and use their own extensions to the predefined set of
metadata names. There is no requirement to register such extensions.
However, a new metadata name should not be created in any of the
following cases:
* If either the name is a [7740]URL, or the value of its accompanying
[7741]content attribute is a [7742]URL; in those cases, registering
it as an [7743]extension to the predefined set of link types is
encouraged (rather than creating a new metadata name).
* If the name is for something expected to have processing
requirements in user agents; in that case it ought to be
standardized.
Also, before creating and using a new metadata name, consulting the
[7744]WHATWG Wiki MetaExtensions page is encouraged — to avoid choosing
a metadata name that's already in use, and to avoid duplicating the
purpose of any metadata names that are already in use, and to avoid new
standardized names clashing with your chosen name. [7745][WHATWGWIKI]
Anyone is free to edit the WHATWG Wiki MetaExtensions page at any time
to add a metadata name. New metadata names can 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.
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 added in the "proposed" state for a period
of a month or more without being used or specified, then it may
be removed from the WHATWG Wiki MetaExtensions page.
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.
4.2.5.3 Pragma directives
When the http-equiv attribute is specified on a [7746]meta element, the
element is a pragma directive.
The [7747]http-equiv attribute is an [7748]enumerated attribute with
the following keywords and states:
Keyword Conforming State Brief description
content-language No [7749]Content language Sets the [7750]pragma-set
default language.
content-type [7751]Encoding declaration An alternative form of setting
the [7752]charset.
default-style [7753]Default style Sets the [7754]name of the default
[7755]CSS style sheet set.
refresh [7756]Refresh Acts as a timed redirect.
set-cookie No [7757]Set-Cookie Has no effect.
x-ua-compatible [7758]X-UA-Compatible In practice, encourages Internet
Explorer to more closely follow the specifications.
content-security-policy [7759]Content security policy [7760]Enforces a
[7761]Content Security Policy on a [7762]Document.
When a [7763]meta element is [7764]inserted into the document, if its
[7765]http-equiv attribute is present and represents one of the above
states, then the user agent must run the algorithm appropriate for that
state, as described in the following list:
Content language state (http-equiv="[7766]content-language")
This feature is non-conforming. Authors are encouraged to use
the [7767]lang attribute instead.
This pragma sets the pragma-set default language. Until such a
pragma is successfully processed, there is no [7768]pragma-set
default language.
1. If the [7769]meta element has no [7770]content attribute, then
return.
2. If the element's [7771]content attribute contains a U+002C
COMMA character (,) then return.
3. Let input be the value of the element's [7772]content
attribute.
4. Let position point at the first character of input.
5. [7773]Skip ASCII whitespace within input given position.
6. [7774]Collect a sequence of code points that are not
[7775]ASCII whitespace from input given position.
7. Let candidate be the string that resulted from the previous
step.
8. If candidate is the empty string, return.
9. Set the [7776]pragma-set default language to candidate.
If the value consists of multiple space-separated tokens,
tokens after the first are ignored.
This pragma is almost, but not quite, entirely unlike the HTTP
`[7777]Content-Language` header of the same name. [7778][HTTP]
Encoding declaration state (http-equiv="[7779]content-type")
The [7780]Encoding declaration state is just an alternative form
of setting the [7781]charset attribute: it is a [7782]character
encoding declaration. This state's user agent requirements are
all handled by the parsing section of the specification.
For [7783]meta elements with an [7784]http-equiv attribute in
the [7785]Encoding declaration state, the [7786]content
attribute must have a value that is an [7787]ASCII
case-insensitive match for a string that consists of:
"text/html;", optionally followed by any number of [7788]ASCII
whitespace, followed by "charset=utf-8".
A document must not contain both a [7789]meta element with an
[7790]http-equiv attribute in the [7791]Encoding declaration
state and a [7792]meta element with the [7793]charset attribute
present.
The [7794]Encoding declaration state may be used in [7795]HTML
documents, but elements with an [7796]http-equiv attribute in
that state must not be used in [7797]XML documents.
Default style state (http-equiv="[7798]default-style")
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
This pragma sets the [7800]name of the default [7801]CSS style
sheet set.
1. If the [7802]meta element has no [7803]content attribute, or
if that attribute's value is the empty string, then return.
2. [7804]Change the preferred CSS style sheet set name with the
name being the value of the element's [7805]content attribute.
[7806][CSSOM]
Refresh state (http-equiv="[7807]refresh")
This pragma acts as a timed redirect.
A [7808]Document object has an associated will declaratively
refresh (a boolean). It is initially false.
1. If the [7809]meta element has no [7810]content attribute, or
if that attribute's value is the empty string, then return.
2. Let input be the value of the element's [7811]content
attribute.
3. Run the [7812]shared declarative refresh steps with the
[7813]meta element's [7814]node document, input, and the
[7815]meta element.
The shared declarative refresh steps, given a [7816]Document
object document, string input, and optionally a [7817]meta
element meta, are as follows:
1. If document's [7818]will declaratively refresh is true, then
return.
2. Let position point at the first [7819]code point of input.
3. [7820]Skip ASCII whitespace within input given position.
4. Let time be 0.
5. [7821]Collect a sequence of code points that are [7822]ASCII
digits from input given position, and let the result be
timeString.
6. If timeString is the empty string, then:
1. If the [7823]code point in input pointed to by position
is not U+002E (.), then return.
7. Otherwise, set time to the result of parsing timeString using
the [7824]rules for parsing non-negative integers.
8. [7825]Collect a sequence of code points that are [7826]ASCII
digits and U+002E FULL STOP characters (.) from input given
position. Ignore any collected characters.
9. Let urlRecord be document's [7827]URL.
10. If position is not past the end of input, then:
1. If the [7828]code point in input pointed to by position
is not U+003B (;), U+002C (,), or [7829]ASCII whitespace,
then return.
2. [7830]Skip ASCII whitespace within input given position.
3. If the [7831]code point in input pointed to by position
is U+003B (;) or U+002C (,), then advance position to the
next [7832]code point.
4. [7833]Skip ASCII whitespace within input given position.
11. If position is not past the end of input, then:
1. Let urlString be the substring of input from the
[7834]code point at position to the end of the string.
2. If the [7835]code point in input pointed to by position
is U+0055 (U) or U+0075 (u), then advance position to the
next [7836]code point. Otherwise, jump to the step
labeled skip quotes.
3. If the [7837]code point in input pointed to by position
is U+0052 (R) or U+0072 (r), then advance position to the
next [7838]code point. Otherwise, jump to the step
labeled parse.
4. If the [7839]code point in input pointed to by position
is U+004C (L) or U+006C (l), then advance position to the
next [7840]code point. Otherwise, jump to the step
labeled parse.
5. [7841]Skip ASCII whitespace within input given position.
6. If the [7842]code point in input pointed to by position
is U+003D (=), then advance position to the next
[7843]code point. Otherwise, jump to the step labeled
parse.
7. [7844]Skip ASCII whitespace within input given position.
8. Skip quotes: If the [7845]code point in input pointed to
by position is U+0027 (') or U+0022 ("), then let quote
be that [7846]code point, and advance position to the
next [7847]code point. Otherwise, let quote be the empty
string.
9. Set urlString to the substring of input from the
[7848]code point at position to the end of the string.
10. If quote is not the empty string, and there is a
[7849]code point in urlString equal to quote, then
truncate urlString at that [7850]code point, so that it
and all subsequent [7851]code points are removed.
11. Parse: Set urlRecord to the result of
[7852]encoding-parsing a URL given urlString, relative to
document.
12. If urlRecord is failure, then return.
12. Set document's [7853]will declaratively refresh to true.
13. Perform one or more of the following steps:
o After the refresh has come due (as defined below), if the
user has not canceled the redirect and, if meta is given,
document's [7854]active sandboxing flag set does not have
the [7855]sandboxed automatic features browsing context
flag set, then [7856]navigate document's [7857]node
navigable to urlRecord using document, with
[7858]historyHandling set to "[7859]replace".
For the purposes of the previous paragraph, a refresh is
said to have come due as soon as the later of the
following two conditions occurs:
# At least time seconds have elapsed since document's
[7860]completely loaded time, adjusted to take into
account user or user agent preferences.
# If meta is given, at least time seconds have elapsed
since meta was [7861]inserted into the document
document, adjusted to take into account user or user
agent preferences.
It is important to use document here, and not meta's
[7862]node document, as that might have changed between
the initial set of steps and the refresh coming due and
meta is not always given (in case of the HTTP
`[7863]Refresh` header).
o Provide the user with an interface that, when selected,
[7864]navigates document's [7865]node navigable to
urlRecord using document.
o Do nothing.
In addition, the user agent may, as with anything, inform the
user of any and all aspects of its operation, including the
state of any timers, the destinations of any timed redirects,
and so forth.
For [7866]meta elements with an [7867]http-equiv attribute in
the [7868]Refresh state, the [7869]content attribute must have a
value consisting either of:
+ just a [7870]valid non-negative integer, or
+ a [7871]valid non-negative integer, followed by a U+003B
SEMICOLON character (;), followed by one or more [7872]ASCII
whitespace, followed by a substring that is an [7873]ASCII
case-insensitive match for the string "URL", followed by a
U+003D EQUALS SIGN character (=), followed by a [7874]valid
URL string 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 [7875]URL.
A news organization's front page could include the following
markup in the page's [7876]head element, to ensure that the page
automatically reloads from the server every five minutes:
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:
Set-Cookie state (http-equiv="[7877]set-cookie")
This pragma is non-conforming and has no effect.
User agents are required to ignore this pragma.
X-UA-Compatible state (http-equiv="[7878]x-ua-compatible")
In practice, this pragma encourages Internet Explorer to more
closely follow the specifications.
For [7879]meta elements with an [7880]http-equiv attribute in
the [7881]X-UA-Compatible state, the [7882]content attribute
must have a value that is an [7883]ASCII case-insensitive match
for the string "IE=edge".
User agents are required to ignore this pragma.
Content security policy state
(http-equiv="[7884]content-security-policy")
This pragma [7885]enforces a [7886]Content Security Policy on a
[7887]Document. [7888][CSP]
1. If the [7889]meta element is not a child of a [7890]head
element, return.
2. If the [7891]meta element has no [7892]content attribute, or
if that attribute's value is the empty string, then return.
3. Let policy be the result of executing Content Security
Policy's [7893]parse a serialized Content Security Policy
algorithm on the [7894]meta element's [7895]content
attribute's value, with a source of "meta", and a disposition
of "enforce".
4. Remove all occurrences of the [7896]report-uri,
[7897]frame-ancestors, and [7898]sandbox [7899]directives from
policy.
5. [7900]Enforce the policy policy.
For [7901]meta elements with an [7902]http-equiv attribute in
the [7903]Content security policy state, the [7904]content
attribute must have a value consisting of a [7905]valid Content
Security Policy, but must not contain any [7906]report-uri,
[7907]frame-ancestors, or [7908]sandbox [7909]directives. The
[7910]Content Security Policy given in the [7911]content
attribute will be [7912]enforced upon the current document.
[7913][CSP]
At the time of inserting the [7914]meta element to the document,
it is possible that some resources have already been fetched.
For example, images might be stored in the [7915]list of
available images prior to dynamically inserting a [7916]meta
element with an [7917]http-equiv attribute in the [7918]Content
security policy state. Resources that have already been fetched
are not guaranteed to be blocked by a [7919]Content Security
Policy that's [7920]enforced late.
A page might choose to mitigate the risk of cross-site scripting
attacks by preventing the execution of inline JavaScript, as
well as blocking all plugin content, using a policy such as the
following:
There must not be more than one [7921]meta element with any particular
state in the document at a time.
4.2.5.4 Specifying the document's character encoding
A character encoding declaration is a mechanism by which the
[7922]character encoding used to store or transmit a document is
specified.
The Encoding standard requires use of the [7923]UTF-8 [7924]character
encoding and requires use of the "utf-8" [7925]encoding label to
identify it. Those requirements necessitate that the document's
[7926]character encoding declaration, if it exists, specifies an
[7927]encoding label using an [7928]ASCII case-insensitive match for
"utf-8". Regardless of whether a [7929]character encoding declaration
is present or not, the actual [7930]character encoding used to encode
the document must be [7931]UTF-8. [7932][ENCODING]
To enforce the above rules, authoring tools must default to using
[7933]UTF-8 for newly-created documents.
The following restrictions also apply:
* The character encoding declaration must be serialized without the
use of [7934]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 [7935]meta elements,
there can only be one [7936]meta-based character encoding declaration
per document.
If an [7937]HTML document does not start with a BOM, and its
[7938]encoding is not explicitly given by [7939]Content-Type metadata,
and the document is not [7940]an iframe srcdoc document, then the
encoding must be specified using a [7941]meta element with a
[7942]charset attribute or a [7943]meta element with an
[7944]http-equiv attribute in the [7945]Encoding declaration state.
A character encoding declaration is required (either in the
[7946]Content-Type metadata or explicitly in the file) even when all
characters are in the ASCII range, 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.
Using non-UTF-8 encodings can have unexpected results on form
submission and URL encodings, which use the [7947]document's character
encoding by default.
If the document is [7948]an iframe srcdoc document, the document must
not have a [7949]character encoding declaration. (In this case, the
source is already decoded, since it is part of the document that
contained the [7950]iframe.)
In XML, the XML declaration should be used for inline character
encoding information, if necessary.
In HTML, to declare that the character encoding is [7951]UTF-8, the
author could include the following markup near the top of the document
(in the [7952]head element):
In XML, the XML declaration would be used instead, at the very top of
the markup:
4.2.6 The style element
(BUTTON) ✔MDN
[7953]Element/style
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
[7957]Contexts in which this element can be used:
Where [7958]metadata content is expected.
In a [7959]noscript element that is a child of a [7960]head
element.
[7961]Content model:
[7962]Text that gives a [7963]conformant style sheet.
[7964]Tag omission in text/html:
Neither tag is omissible.
[7965]Content attributes:
[7966]Global attributes
[7967]media — Applicable media
[7968]blocking — Whether the element is [7969]potentially
render-blocking
Also, the [7970]title attribute [7971]has special semantics on
this element: [7972]CSS style sheet set name
// [7985]also has obsolete members
};
[7986]HTMLStyleElement includes [7987]LinkStyle;
The [7988]style element allows authors to embed CSS style sheets in
their documents. The [7989]style element is one of several inputs to
the styling processing model. The element does not [7990]represent
content for the user.
(BUTTON) ✔MDN
[7991]HTMLStyleElement/disabled
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
The disabled getter steps are:
1. If [7992]this does not have an [7993]associated CSS style sheet,
return false.
2. If [7994]this's [7995]associated CSS style sheet's [7996]disabled
flag is set, return true.
3. Return false.
The [7997]disabled setter steps are:
1. If [7998]this does not have an [7999]associated CSS style sheet,
return.
2. If the given value is true, set [8000]this's [8001]associated CSS
style sheet's [8002]disabled flag. Otherwise, unset [8003]this's
[8004]associated CSS style sheet's [8005]disabled flag.
Importantly, [8006]disabled attribute assignments only take effect when
the [8007]style element has an [8008]associated CSS style sheet:
const style = document.createElement(ʼstyleʼ);
style.disabled = true;
style.textContent = ʼbody { background-color: red; }ʼ;
document.body.append(style);
console.log(style.disabled); // false
The media attribute says which media the styles apply to. The value
must be a [8009]valid media query list. The user agent must apply the
styles when the [8010]media attribute's value [8011]matches the
environment and the other relevant conditions apply, and must not apply
them otherwise.
The styles might be further limited in scope, e.g. in CSS with the use
of @media blocks. This specification does not override such further
restrictions or requirements.
The default, if the [8012]media attribute is omitted, is "all", meaning
that by default styles apply to all media.
The blocking attribute is a [8013]blocking attribute.
(BUTTON) ⚠MDN
[8014]Alternative_style_sheets
Support in one engine only.
Firefox3+Safari?Chrome1–48
__________________________________________________________________
The title attribute on [8015]style elements defines [8016]CSS style
sheet sets. If the [8017]style element has no [8018]title attribute,
then it has no title; the [8019]title attribute of ancestors does not
apply to the [8020]style element. If the [8021]style element is not
[8022]in a document tree, then the [8023]title attribute is ignored.
[8024][CSSOM]
The [8025]title attribute on [8026]style elements, like the [8027]title
attribute on [8028]link elements, differs from the global [8029]title
attribute in that a [8030]style block without a title does not inherit
the title of the parent element: it merely has no title.
The [8031]child text content of a [8032]style element must be that of a
[8033]conformant style sheet.
A [8034]style element is [8035]implicitly potentially render-blocking
if the element was created by its [8036]node document's parser.
__________________________________________________________________
The user agent must run the [8037]update a style block algorithm
whenever any of the following conditions occur:
* The element is popped off the [8038]stack of open elements of an
[8039]HTML parser or [8040]XML parser.
* The element is not on the [8041]stack of open elements of an
[8042]HTML parser or [8043]XML parser, and it [8044]becomes
connected or [8045]disconnected.
* The element's [8046]children changed steps run.
The update a style block algorithm is as follows:
1. Let element be the [8047]style element.
2. If element has an [8048]associated CSS style sheet, [8049]remove
the CSS style sheet in question.
3. If element is not [8050]connected, then return.
4. If element's [8051]type attribute is present and its value is
neither the empty string nor an [8052]ASCII case-insensitive match
for "[8053]text/css", then return.
In particular, a [8054]type value with parameters, such as
"text/css; charset=utf-8", will cause this algorithm to return
early.
5. If the [8055]Should element's inline behavior be blocked by Content
Security Policy? algorithm returns "Blocked" when executed upon the
[8056]style element, "style", and the [8057]style element's
[8058]child text content, then return. [8059][CSP]
6. [8060]Create a CSS style sheet with the following properties:
[8061]type
[8062]text/css
[8063]owner node
element
[8064]media
The [8065]media attribute of element.
This is a reference to the (possibly absent at this time)
attribute, rather than a copy of the attribute's current
value. CSSOM defines what happens when the attribute is
dynamically set, changed, or removed.
[8066]title
The [8067]title attribute of element, if element is
[8068]in a document tree, or the empty string otherwise.
This doesn't seem right. Presumably we should be using the
element's [8076]child text content? Tracked as [8077]issue
#2997.
7. If element [8078]contributes a script-blocking style sheet,
[8079]append element to its [8080]node document's
[8081]script-blocking style sheet set.
8. If element's [8082]media attribute's value [8083]matches the
environment and element is [8084]potentially render-blocking, then
[8085]block rendering on element.
Once the attempts to obtain the style sheet's [8086]critical
subresources, if any, are complete, or, if the style sheet has no
[8087]critical subresources, once the style sheet has been parsed and
processed, the user agent must run these steps:
Fetching the [8088]critical subresources is not well-defined; probably
[8089]issue #968 is the best resolution for that. In the meantime, any
[8090]critical subresource [8091]request should have its
[8092]render-blocking set to whether or not the [8093]style element is
currently [8094]render-blocking.
1. Let element be the [8095]style element associated with the style
sheet in question.
2. Let success be true.
3. If the attempts to obtain any of the style sheet's [8096]critical
subresources failed for any reason (e.g., DNS error, HTTP 404
response, a connection being prematurely closed, unsupported
Content-Type), set success to false.
Note that content-specific errors, e.g., CSS parse errors or PNG
decoding errors, do not affect success.
4. [8097]Queue an element task on the [8098]networking task source
given element and the following steps:
1. If success is true, [8099]fire an event named [8100]load at
element.
2. Otherwise, [8101]fire an event named [8102]error at element.
3. If element [8103]contributes a script-blocking style sheet:
1. [8104]Assert: element's [8105]node document's
[8106]script-blocking style sheet set [8107]contains
element.
2. [8108]Remove element from its [8109]node document's
[8110]script-blocking style sheet set.
4. [8111]Unblock rendering on element.
The element must [8112]delay the load event of the element's [8113]node
document until all the attempts to obtain the style sheet's
[8114]critical subresources, if any, are complete.
This specification does not specify a style system, but CSS is expected
to be supported by most web browsers. [8115][CSS]
(BUTTON) ✔MDN
[8116]HTMLStyleElement/media
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
The media and blocking IDL attributes must each [8117]reflect the
respective content attributes of the same name.
The [8118]LinkStyle interface is also implemented by this element.
[8119][CSSOM]
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.
My favorite book
My favorite book of all time has got to be
A Catʼs Life. It is a book by P. Rahmel that talks
about the Felis catus in modern human society.
4.2.7 Interactions of styling and scripting
If the style sheet referenced no other resources (e.g., it was an
internal style sheet given by a [8120]style element with no @import
rules), then the style rules must be [8121]immediately made available
to script; otherwise, the style rules must only be made available to
script once the [8122]event loop reaches its [8123]update the rendering
step.
An element el in the context of a [8124]Document of an [8125]HTML
parser or [8126]XML parser contributes a script-blocking style sheet if
all of the following are true:
* el was created by that [8127]Document's parser.
* el is either a [8128]style element or a [8129]link element that was
an [8130]external resource link that contributes to the styling
processing model when the el was created by the parser.
* el's media attribute's value [8131]matches the environment.
* el's style sheet was enabled when the element was created by the
parser.
* The last time the [8132]event loop reached [8133]step 1, el's
[8134]root was that [8135]Document.
* The user agent hasn't given up on loading that particular style
sheet yet. A user agent may give up on loading a style sheet at any
time.
Giving up on a style sheet before the style sheet loads, if the
style sheet eventually does still load, means that the script might
end up operating with incorrect information. For example, if a
style sheet sets the color of an element to green, but a script
that inspects the resulting style is executed before the sheet is
loaded, the script will find that the element is black (or whatever
the default color is), and might thus make poor choices (e.g.,
deciding to use black as the color elsewhere on the page, instead
of green). Implementers have to balance the likelihood of a script
using incorrect information with the performance impact of doing
nothing while waiting for a slow network request to finish.
It is expected that counterparts to the above rules also apply to
[8136] PIs. However, this has not yet been thoroughly
investigated.
A [8137]Document has a script-blocking style sheet set, which is an
[8138]ordered set, initially empty.
A [8139]Document document has a style sheet that is blocking scripts if
the following steps return true:
1. If document's [8140]script-blocking style sheet set is not
[8141]empty, then return true.
2. If document's [8142]node navigable is null, then return false.
3. Let containerDocument be document's [8143]node navigable's
[8144]container document.
4. If containerDocument is non-null and containerDocument's
[8145]script-blocking style sheet set is not [8146]empty, then
return true.
5. Return false.
A [8147]Document has no style sheet that is blocking scripts if it does
not [8148]have a style sheet that is blocking scripts.
[8153]Contexts in which this element can be used:
As the second element in an [8154]html element.
[8155]Content model:
[8156]Flow content.
[8157]Tag omission in text/html:
A [8158]body element's [8159]start tag can be omitted if the
element is empty, or if the first thing inside the [8160]body
element is not [8161]ASCII whitespace or a [8162]comment, except
if the first thing inside the [8163]body element is a
[8164]meta, [8165]noscript, [8166]link, [8167]script,
[8168]style, or [8169]template element.
A [8170]body element's [8171]end tag can be omitted if the
[8172]body element is not immediately followed by a
[8173]comment.
[8201]HTMLBodyElement includes [8202]WindowEventHandlers;
The [8203]body element [8204]represents the contents of the document.
In conforming documents, there is only one [8205]body element. The
[8206]document.body IDL attribute provides scripts with easy access to
a document's [8207]body element.
Some DOM operations (for example, parts of the [8208]drag and drop
model) are defined in terms of "[8209]the body element". This refers to
a particular element in the DOM, as per the definition of the term, and
not any arbitrary [8210]body element.
The [8211]body element exposes as [8212]event handler content
attributes a number of the [8213]event handlers of the [8214]Window
object. It also mirrors their [8215]event handler IDL attributes.
The [8216]event handlers of the [8217]Window object named by the
[8218]Window-reflecting body element event handler set, exposed on the
[8219]body element, replace the generic [8220]event handlers with the
same names normally supported by [8221]HTML elements.
Thus, for example, a bubbling [8222]error event dispatched on a child
of [8223]the body element of a [8224]Document would first trigger the
[8225]onerror [8226]event handler content attributes of that element,
then that of the root [8227]html element, and only then would it
trigger the [8228]onerror [8229]event handler content attribute on the
[8230]body element. This is because the event would bubble from the
target, to the [8231]body, to the [8232]html, to the [8233]Document, to
the [8234]Window, and the [8235]event handler on the [8236]body is
watching the [8237]Window not the [8238]body. A regular event listener
attached to the [8239]body using addEventListener(), however, would be
run when the event bubbled through the [8240]body and not when it
reaches the [8241]Window object.
This page updates an indicator to show whether or not the user is
online:
Online or offline?
You are: (Unknown)
4.3.2 The article element
(BUTTON) ✔MDN
[8242]Element/article
Support in all current engines.
Firefox4+Safari5+Chrome5+
__________________________________________________________________
The [8259]article element [8260]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 [8261]article elements are nested, the inner [8262]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
[8263]article elements nested within the [8264]article element for the
blog entry.
Author information associated with an [8265]article element (q.v. the
[8266]address element) does not apply to nested [8267]article elements.
When used specifically with content to be redistributed in syndication,
the [8268]article element is similar in purpose to the entry element in
Atom. [8269][ATOM]
The schema.org microdata vocabulary can be used to provide the
publication date for an [8270]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 [8271]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 [8272]article element, with
some schema.org annotations:
The Very First Rule of Life
If thereʼs a microphone anywhere near you, assume itʼs hot and
sending whatever youʼre saying to the world. Seriously.
...
Here is that same blog post, but showing some of the comments:
The Very First Rule of Life
If thereʼs a microphone anywhere near you, assume itʼs hot and
sending whatever youʼre saying to the world. Seriously.
...
Comments
Yeah! Especially when talking about your lobbyist friends!
Hey, you have the same first name as me.
Notice the use of [8273]footer to give the information for each comment
(such as who wrote it and when): the [8274]footer element can appear at
the start of its section when appropriate, such as in this case. (Using
[8275]header in this case wouldn't be wrong either; it's mostly a
matter of authoring preference.)
In this example, [8276]article elements are used to host widgets on a
portal page. The widgets are implemented as [8277]customized built-in
elements in order to get specific styling and scripted behavior.
eHome Portal
Stocks
Stock
Value
Delta
News
4.3.3 The section element
(BUTTON) ✔MDN
[8278]Element/section
Support in all current engines.
Firefox4+Safari5+Chrome5+
__________________________________________________________________
The [8295]section element [8296]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 [8297]article element instead of the
[8298]section element when it would make sense to syndicate the
contents of the element.
The [8299]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 [8300]div element instead.
A general rule is that the [8301]section element is appropriate only if
the element's contents would be listed explicitly in the document's
[8302]outline.
In the following example, we see an article (part of a larger web page)
about apples, containing two short sections.
Apples
Tasty, delicious fruit!
The apple is the pomaceous fruit of the apple tree.
Red Delicious
These bright red apples are the most common found in many
supermarkets.
Granny Smith
These juicy, green apples make a great filling for
apple pies.
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 [8303]inter-element whitespace.)
Graduation Ceremony Summer 2022
Graduation
Ceremony
Opening Procession
Speech by Valedictorian
Speech by Class President
Presentation of Diplomas
Closing Speech by Headmaster
Graduates
Molly Carpenter
Anastasia Luccio
Ebenezar McCoy
Karrin Murphy
Thomas Raith
Susan Rodriguez
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.
My Book
A sample with not much content
Published by Dummy Publicorp Ltd.
My First Chapter
This is the first of my chapters. It doesnʼt say much.
But it has two paragraphs!
It Continues: The Second Chapter
Bla dee bla, dee bla dee bla. Boom.
Chapter Three: A Further Example
Itʼs not like a battle between brightness and earthtones would go
unnoticed.
But it might ruin my story.
Appendix A: Overview of Examples
These are demonstrations.
Appendix B: Some Closing Remarks
Hopefully this long example shows that you can style
sections, so long as they are used to indicate actual sections.
4.3.4 The nav element
(BUTTON) ✔MDN
[8304]Element/nav
Support in all current engines.
Firefox4+Safari5+Chrome5+
__________________________________________________________________
The [8321]nav element [8322]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 [8323]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 [8324]footer element
alone is sufficient for such cases; while a [8325]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, there are two [8326]nav elements, one for
primary navigation around the site, and one for secondary navigation
around the page itself.
The Wiki Center Of Exampland
Demos in Exampland
Written by A. N. Other.
Public demonstrations
...more...
Demolitions
...more...
...more...
In the following example, the page has several places where links are
present, but only one of those places is considered a navigation
section.
You can also see microdata annotations in the above example that use
the schema.org vocabulary to provide the publication date and other
metadata about the blog post.
A [8327]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:
In this example, [8328]nav is used in an email application, to let the
user switch folders:
4.3.5 The aside element
(BUTTON) ✔MDN
[8329]Element/aside
Support in all current engines.
Firefox4+Safari5+Chrome5+
__________________________________________________________________
The [8346]aside element [8347]represents a section of a page that
consists of content that is tangentially related to the content around
the [8348]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 [8349]nav elements, and for
other content that is considered separate from the main content of the
page.
It's not appropriate to use the [8350]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.
The following example shows how an aside is used to mark up a pull
quote in a longer article.
...
He later joined a large company, continuing on the same work.
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.
Of course his work — or should that be hobby? —
isnʼt his only passion. He also enjoys other pleasures.
...
The following extract shows how [8351]aside can be used for blogrolls
and other side content on a blog:
My wonderful blog
My tagline
My last post
This is my last post.
My first post
This is my first post.
4.3.6 The h1, h2, h3, h4, h5, and h6 elements
(BUTTON) ✔MDN
[8352]Element/Heading_Elements
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
These elements [8378]represent headings for their sections.
The semantics and meaning of these elements are defined in the section
on [8379]headings and outlines.
These elements have a [8380]heading level given by the number in their
name. The [8381]heading level corresponds to the levels of nested
sections. The [8382]h1 element is for a top-level section, [8383]h2 for
a subsection, [8384]h3 for a sub-subsection, and so on.
As far as their respective document outlines (their heading and section
structures) are concerned, these two snippets are semantically
equivalent:
Letʼs call it a draw(ing surface)
Diving in
Simple shapes
Canvas coordinates
Canvas coordinates diagram
Paths
Letʼs call it a draw(ing surface)
Diving in
Simple shapes
Canvas coordinates
Canvas coordinates diagram
Paths
Authors might prefer the former style for its terseness, or the latter
style for its additional styling hooks. Which is best is purely an
issue of preferred authoring style.
4.3.7 The hgroup element
(BUTTON) ✔MDN
[8385]Element/hgroup
Support in all current engines.
Firefox4+Safari5+Chrome5+
__________________________________________________________________
[8390]Contexts in which this element can be used:
Where [8391]heading content is expected.
[8392]Content model:
Zero or more [8393]p elements, followed by one [8394]h1,
[8395]h2, [8396]h3, [8397]h4, [8398]h5, or [8399]h6 element,
followed by zero or more [8400]p elements, optionally intermixed
with [8401]script-supporting elements.
[8402]Tag omission in text/html:
Neither tag is omissible.
The [8410]hgroup element [8411]represents a heading and related
content. The element may be used to group an [8412]h1–[8413]h6 element
with one or more [8414]p elements containing content representing a
subheading, alternative title, or tagline.
Here are some examples of valid headings contained within an
[8415]hgroup element.
The reality dysfunction
Space is not the only void
Dr. Strangelove
Or: How I Learned to Stop Worrying and Love the Bomb
4.3.8 The header element
(BUTTON) ✔MDN
[8416]Element/header
Support in all current engines.
Firefox4+Safari5+Chrome5+
__________________________________________________________________
[8420]Contexts in which this element can be used:
Where [8421]flow content is expected.
[8422]Content model:
[8423]Flow content, but with no [8424]header or [8425]footer
element descendants.
[8426]Tag omission in text/html:
Neither tag is omissible.
[8427]Content attributes:
[8428]Global attributes
[8429]Accessibility considerations:
If there is an ancestor [8430]sectioning content element:
[8431]for authors; [8432]for implementers.
Otherwise: [8433]for authors; [8434]for implementers.
[8435]DOM interface:
Uses [8436]HTMLElement.
The [8437]header element [8438]represents a group of introductory or
navigational aids.
A [8439]header element is intended to usually contain a heading (an
[8440]h1–[8441]h6 element or an [8442]hgroup element), but this is not
required. The [8443]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:
Welcome to...
Voidwars!
The following snippet shows how the element can be used to mark up a
specification's header:
The [8444]header element is not [8445]sectioning content; it doesn't
introduce a new section.
In this example, the page has a page heading given by the [8446]h1
element, and two subsections whose headings are given by [8447]h2
elements. The content after the [8448]header element is still part of
the last subsection started in the [8449]header element, because the
[8450]header element doesn't take part in the [8451]outline algorithm.
Little Green Guys With Guns
Important News
To play todayʼs games you will need to update your client.
Games
You have three active games:
...
4.3.9 The footer element
(BUTTON) ✔MDN
[8452]Element/footer
Support in all current engines.
Firefox4+Safari5+Chrome5+
__________________________________________________________________
[8456]Contexts in which this element can be used:
Where [8457]flow content is expected.
[8458]Content model:
[8459]Flow content, but with no [8460]header or [8461]footer
element descendants.
[8462]Tag omission in text/html:
Neither tag is omissible.
[8463]Content attributes:
[8464]Global attributes
[8465]Accessibility considerations:
If there is an ancestor [8466]sectioning content element:
[8467]for authors; [8468]for implementers.
Otherwise: [8469]for authors; [8470]for implementers.
[8471]DOM interface:
Uses [8472]HTMLElement.
The [8473]footer element [8474]represents a footer for its nearest
ancestor [8475]sectioning content element, or for [8476]the body
element if there is no such ancestor. A footer typically contains
information about its section such as who wrote it, links to related
documents, copyright data, and the like.
When the [8477]footer element contains entire sections, they
[8478]represent appendices, indices, long colophons, verbose license
agreements, and other such content.
Contact information for the author or editor of a section belongs in an
[8479]address element, possibly itself inside a [8480]footer. Bylines
and other information that could be suitable for both a [8481]header or
a [8482]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 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 there is no ancestor [8483]sectioning content element, then it
applies to the whole page.
The [8484]footer element is not itself [8485]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:
Lorem ipsum
The ipsum of all lorems
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.
Here is an example which shows the [8486]footer element being used both
for a site-wide footer and for a section footer.
The Ramblings of a Scientist
The Ramblings of a Scientist
Episode 15
My Favorite Trains
I love my trains. My favorite train of all time is a Köf.
It is fun to see them pull some coal cars because they look so
dwarfed in comparison.
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":
...
4.3.10 The address element
(BUTTON) ✔MDN
[8487]Element/address
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
[8491]Contexts in which this element can be used:
Where [8492]flow content is expected.
[8493]Content model:
[8494]Flow content, but with no [8495]heading content
descendants, no [8496]sectioning content descendants, and no
[8497]header, [8498]footer, or [8499]address element
descendants.
[8500]Tag omission in text/html:
Neither tag is omissible.
The [8508]address element [8509]represents the contact information for
its nearest [8510]article or [8511]body element ancestor. If that is
[8512]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:
The [8513]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 [8514]p element is the
appropriate element for marking up postal addresses in general.)
The [8515]address element must not contain information other than
contact information.
For example, the following is non-conforming use of the [8516]address
element:
Last Modified: 1999/12/24 23:37:50
Typically, the [8517]address element would be included along with other
information in a [8518]footer element.
The contact information for a node node is a collection of
[8519]address elements defined by the first applicable entry from the
following list:
If node is an [8520]article element
If node is a [8521]body element
The contact information consists of all the [8522]address
elements that have node as an ancestor and do not have another
[8523]body or [8524]article element ancestor that is a
descendant of node.
If node has an ancestor element that is an [8525]article element
If node has an ancestor element that is a [8526]body element
The contact information of node is the same as the contact
information of the nearest [8527]article or [8528]body element
ancestor, whichever is nearest.
If node's [8529]node document has [8530]a body element
The contact information of node is the same as the contact
information of [8531]the body element of the [8532]Document.
Otherwise
There is no contact information for node.
User agents may expose the contact information of a node to the user,
or use it for other purposes, such as indexing sections based on the
sections' contact information.
In this example the footer contains contact information and a copyright
notice.
4.3.11 Headings and outlines
[8533]h1–[8534]h6 elements have a heading level, which is given by the
number in the element's name.
These elements [8535]represent headings. The lower a [8536]heading's
[8537]heading level is, the fewer ancestor sections the [8538]heading
has.
The outline is all [8539]headings in a document, in [8540]tree order.
The [8541]outline should be used for generating document outlines, for
example when generating tables of contents. When creating an
interactive table of contents, entries should jump the user to the
relevant [8542]heading.
If a document has one or more [8543]headings, at least a single
[8544]heading within the [8545]outline should have a [8546]heading
level of 1.
Each [8547]heading following another [8548]heading lead in the
[8549]outline must have a [8550]heading level that is less than, equal
to, or 1 greater than lead's [8551]heading level.
The following example is non-conforming:
Apples
Apples are fruit.
Taste
They taste lovely.
It could be written as follows and then it would be conforming:
Apples
Apples are fruit.
Taste
They taste lovely.
4.3.11.1 Sample outlines
The following markup fragment:
HTML: Living Standard
Last Updated 12 August 2016
Some intro to the document.
Table of contents
...
First section
Some intro to the first section.
...results in 3 document headings:
1.
HTML: Living Standard
2.
Table of contents
.
3.
First section
.
A rendered view of the [8552]outline might look like:
Top-level section with the heading "HTML: Living Standard" and two
subsections; "Table of contents" and "First section".
First, here is a document, which is a book with very short chapters and
subsections:
The Tax Book (all in one page)
The Tax Book
Earning money
Earning money is good.
Getting a job
To earn money you typically need a job.
Spending money
Spending is what money is mainly used for.
Cheap things
Buying cheap things often not cost-effective.
Expensive things
The most expensive thing is often not the most cost-effective either.
Investing money
You can lend your money to other people.
Losing money
If you spend money or invest money, sooner or later you will lose money.
Poor judgement
Usually if you lose money itʼs because you made a mistake.
Its [8553]outline could be presented as follows:
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 [8554]title element is not a [8555]heading.
A document can contain multiple top-level headings:
Alphabetic Fruit
Apples
Pomaceous.
Bananas
Edible.
Carambola
Star.
The document's [8556]outline could be presented as follows:
1. Apples
2. Bananas
3. Carambola
[8557]header elements do not influence the [8558]outline of a document:
Weʼre adopting a child! — Rayʼs blog
Rayʼs blog
Weʼre adopting a child!
As of today, Janine and I have signed the papers to become
the proud parents of baby Diane! Weʼve been looking forward to
this day for weeks.
The document's [8559]outline could be presented as follows:
1. Ray's blog
1. We're adopting a child!
__________________________________________________________________
The following example is conforming, but not encouraged as it has no
[8560]heading whose [8561]heading level is 1:
Alphabetic Fruit
Apples
Pomaceous.
Bananas
Edible.
Carambola
Star.
The document's [8562]outline could be presented as follows:
1.
1. Apples
2. Bananas
3. Carambola
The following example is conforming, but not encouraged as the first
[8563]heading's [8564]heading level is not 1:
Feathers on The Site of Encyclopedic Knowledge
A plea from our caretakers
Please, we beg of you, send help! Weʼre stuck in the server room!
Feathers
Epidermal growths.
The document's [8565]outline could be presented as follows:
1.
1. A plea from our caretakers
2. Feathers
4.3.11.2 Exposing outlines to users
User agents are encouraged to expose page [8566]outlines to users to
aid in navigation. This is especially true for non-visual media, e.g.
screen readers.
For instance, a user agent could map the arrow keys as follows:
Shift + ← Left
Go to previous heading
Shift + → Right
Go to next heading
Shift + ↑ Up
Go to next heading whose [8567]level is one less than the
current heading's level
Shift + ↓ Down
Go to next heading whose [8568]level is the same as the current
heading's level
4.3.12 Usage summary
This section is non-normative.
Element Purpose
Example
[8569]body The contents of the document.
Steve Hillʼs Home Page
Hard Trance is My Life.
[8570]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.
My fave Masif tee so far!
Happy 2nd birthday Masif Saturdays!!!
[8571]section A generic section of a document or application. A
section, in this context, is a thematic grouping of content, typically
with a heading.
Biography
The facts
1500+ shows, 14+ countries
2010/2011 figures per year
100+ shows, 8+ countries
[8572]nav A section of a page that links to other pages or to parts
within the page: a section with navigation links.
[8573]aside A section of a page that consists of content that is
tangentially related to the content around the [8574]aside element, and
which could be considered separate from that content. Such sections are
often represented as sidebars in printed typography.
Music
As any burner can tell you, the event has a lot of trance.
This year we played a kind of trance that originated in Belgium, Germany, and
the Netherlands in the mid-90s.
[8575]h1–[8576]h6 A heading
The Guide To Music On The Playa
The Main Stage
If you want to play on a stage, you should bring one.
Amplified Music
Amplifiers up to 300W or 90dB are welcome.
[8577]hgroup A heading and related content. The element may be used to
group an [8578]h1–[8579]h6 element with one or more [8580]p elements
containing content representing a subheading, alternative title, or
tagline.
Burning Music
The Guide To Music On The Playa
Main Stage
The Fiction Of A Music Festival
If you want to play on a stage, you should bring one.
Loudness!
Questions About Amplified Music
Amplifiers up to 300W or 90dB are welcome.
[8581]header A group of introductory or navigational aids.
Hard Trance is My Life
By DJ Steve Hill and Technikal
The album with the amusing punctuation has red artwork.
[8582]footer A footer for its nearest ancestor [8583]sectioning content
element, or for [8584]the body element if there is no such ancestor. A
footer typically contains information about its section such as who
wrote it, links to related documents, copyright data, and the like.
Hard Trance is My Life
The album with the amusing punctuation has red artwork.
4.3.12.1 Article or section?
This section is non-normative.
A [8585]section forms part of something else. An [8586]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 [8587]section because there'd be lots of
other chapters on (maybe) 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 [8588]articles because that was the whole thing.
A comment on an article is not part of the [8589]article on which it is
commenting, therefore it is its own [8590]article.
4.4 Grouping content
4.4.1 The p element
(BUTTON) ✔MDN
[8591]Element/p
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
[8596]Contexts in which this element can be used:
Where [8597]flow content is expected.
[8598]Content model:
[8599]Phrasing content.
[8600]Tag omission in text/html:
A [8601]p element's [8602]end tag can be omitted if the [8603]p
element is immediately followed by an [8604]address,
[8605]article, [8606]aside, [8607]blockquote, [8608]details,
[8609]dialog, [8610]div, [8611]dl, [8612]fieldset,
[8613]figcaption, [8614]figure, [8615]footer, [8616]form,
[8617]h1, [8618]h2, [8619]h3, [8620]h4, [8621]h5, [8622]h6,
[8623]header, [8624]hgroup, [8625]hr, [8626]main, [8627]menu,
[8628]nav, [8629]ol, [8630]p, [8631]pre, [8632]search,
[8633]section, [8634]table, or [8635]ul element, or if there is
no more content in the parent element and the parent element is
an [8636]HTML element that is not an [8637]a, [8638]audio,
[8639]del, [8640]ins, [8641]map, [8642]noscript, or [8643]video
element, or an [8644]autonomous custom element.
The [8654]p element [8655]represents a [8656]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:
The little kitten gently seated herself on a piece of
carpet. Later in her life, this would be referred to as the time the
cat sat on the mat.
There was once an example from Femley,
Whose markup was of dubious quality.
The validator complained,
So the author was pained,
To move the error from the markup to the rhyming.
The [8657]p element should not be used when a more specific element is
more appropriate.
The following example is technically correct:
Last modified: 2001-04-23
Author: fred@example.com
However, it would be better marked-up as:
Author: fred@example.com
Or:
List elements (in particular, [8658]ol and [8659]ul elements) cannot be
children of [8660]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 realize that a [8661]paragraph, in HTML terms, is
not a logical concept, but a structural one. In the fantastic example
above, there are actually five [8662]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:
For instance, this fantastic sentence has bullets relating to
wizards,
faster-than-light travel, and
telepathy,
and is further discussed below.
Authors wishing to conveniently style such "logical" paragraphs
consisting of multiple "structural" paragraphs can use the [8663]div
element instead of the [8664]p element.
Thus for instance the above example could become the following:
For instance, this fantastic sentence has bullets relating to
wizards,
faster-than-light travel, and
telepathy,
and is further discussed below.
This example still has five structural paragraphs, but now the author
can style just the [8665]div instead of having to consider each part of
the example separately.
4.4.2 The hr element
(BUTTON) ✔MDN
[8666]Element/hr
Support in all current engines.
Firefox1+Safari3+Chrome1+
__________________________________________________________________
The [8686]hr element [8687]represents a [8688]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; alternatively, it
represents a separator between a set of options of a [8689]select
element.
The following fictional extract from a project manual shows two
sections that use the [8690]hr element to separate topics within the
section.
Communication
There are various methods of communication. This section
covers a few of the important ones used by the project.
Communication stones seem to come in pairs and have mysterious
properties:
They can transfer thoughts in two directions once activated
if used alone.
If used with another device, they can transfer oneʼs
consciousness to another body.
If both stones are used with another device, the
consciousnesses switch bodies.
Radios use the electromagnetic spectrum in the meter range and
longer.
Signal flares use the electromagnetic spectrum in the
nanometer range.
Food
All food at the project is rationed:
Potatoes
Two per day
Soup
One bowl per day
Cooking is done by the chefs on a set rotation.
There is no need for an [8691]hr element between the sections
themselves, since the [8692]section elements and the [8693]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 [8694]hr element.
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
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.
Maybe it wonʼt be that bad, he told himself. The lie was
comforting enough to get him through the rest of the nightʼs
shift.
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 metre-deep snow
of Gralmondʼs winters.
The [8695]hr element does not affect the document's [8696]outline.
4.4.3 The pre element
(BUTTON) ✔MDN
[8697]Element/pre
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
The [8716]pre element [8717]represents a block of preformatted text, in
which structure is represented by typographic conventions rather than
by elements.
In [8718]the HTML syntax, a leading newline character immediately
following the [8719]pre element start tag is stripped.
Some examples of cases where the [8720]pre element could be used:
* Including an email, 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 [8721]pre element can be
used with a [8722]code element; to represent a block of computer output
the [8723]pre element can be used with a [8724]samp element. Similarly,
the [8725]kbd element can be used within a [8726]pre element to
indicate text that the user is to enter.
This element [8727]has rendering requirements involving the
bidirectional algorithm.
In the following snippet, a sample of computer code is presented.
This is the Panel constructor:
function Panel(element, canClose, closeHandler) {
this.element = element;
this.canClose = canClose;
this.closeHandler = function () { if (closeHandler) closeHandler() };
}
In the following snippet, [8728]samp and [8729]kbd elements are mixed
in the contents of a [8730]pre element to show a session of Zork I.
You are in an open field west of a big white house with a boarded
front door.
There is a small mailbox here.
>
open mailbox
Opening the mailbox reveals:
A leaflet.
>
The following shows a contemporary poem that uses the [8731]pre element
to preserve its unusual formatting, which forms an intrinsic part of
the poem itself.
maxling
it is with a heart
heavy
that i admit loss of a feline
so loved
a friend lost to the
unknown
(night)
~cdr 11dec07
4.4.4 The blockquote element
(BUTTON) ✔MDN
[8732]Element/blockquote
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
The [8753]HTMLQuoteElement interface is also used by the [8754]q
element.
The [8755]blockquote element [8756]represents a section that is quoted
from another source.
Content inside a [8757]blockquote must be quoted from another source,
whose address, if it has one, may be cited in the cite attribute.
If the [8758]cite attribute is present, it must be a [8759]valid URL
potentially surrounded by spaces. To obtain the corresponding citation
link, the value of the attribute must be [8760]parsed relative to the
element's [8761]node document. 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 [8762]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 "Jane ate the cracker. She
then said she liked apples and fish."; it could be quoted as follows:
[Jane] then said she liked [...] fish.
Attribution for the quotation, if any, must be placed outside the
[8763]blockquote element.
For example, here the attribution is given in a paragraph after the
quote:
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.
— Stephen Roberts
The other examples below show other ways of showing attribution.
The cite IDL attribute must [8764]reflect the element's cite content
attribute.
Here a [8765]blockquote element is used in conjunction with a
[8766]figure element and its [8767]figcaption to clearly relate a quote
to its attribution (which is not part of the quote and therefore
doesn't belong inside the [8768]blockquote itself):
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
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.
Carl Sagan, in "Wonder and Skepticism", from
the Skeptical Inquirer Volume 19, Issue 1 (January-February
1995)
This next example shows the use of [8769]cite alongside
[8770]blockquote:
His next piece was the aptly named Sonnet 130:
My mistressʼ eyes are nothing like the sun,
Coral is far more red, than her lips red,
...
This example shows how a forum post could use [8771]blockquote to show
what post a user is replying to. The [8772]article element is used for
each post, to mark up the threading.
Next thing youʼll be saying they donʼt get capes and wizard
hats either!
boing -5 points 1 hour ago
narwhals are worse than ceiling cat
fred 1 points 23 minutes ago
I bet a narwhal would love that.
I bet theyʼd love to peel a banana too.
This example shows the use of a [8773]blockquote for short snippets,
demonstrating that one does not have to use [8774]p elements inside
[8775]blockquote elements:
He began his list of "lessons" with the following:
One should never assume that his side of
the issue will be recognized, let alone that it will
be conceded to have merits.
He continued with a number of similar points, ending with:
Finally, one should be prepared for the threat
of breakdown in negotiations at any given moment and not
be cowed by the possibility.
We shall now discuss these points...
[8776]Examples of how to represent a conversation are shown in a later
section; it is not appropriate to use the [8777]cite and
[8778]blockquote elements for this purpose.
4.4.5 The ol element
(BUTTON) ✔MDN
[8779]Element/ol
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
[8781]Categories:
[8782]Flow content.
If the element's children include at least one [8783]li element:
[8784]Palpable content.
[8785]Contexts in which this element can be used:
Where [8786]flow content is expected.
[8787]Content model:
Zero or more [8788]li and [8789]script-supporting elements.
[8790]Tag omission in text/html:
Neither tag is omissible.
[8791]Content attributes:
[8792]Global attributes
[8793]reversed — Number the list backwards
[8794]start — [8795]Starting value of the list
[8796]type — Kind of list marker
The [8810]ol element [8811]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 [8812]li element child nodes of the
[8813]ol element, in [8814]tree order.
(BUTTON) ✔MDN
[8815]Element/ol#attr-reversed
Support in all current engines.
Firefox18+Safari6+Chrome18+
__________________________________________________________________
The reversed attribute is a [8816]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 [8817]valid integer. It is
used to determine the [8818]starting value of the list.
An [8819]ol element has a starting value, which is an integer
determined as follows:
1. If the [8820]ol element has a [8821]start attribute, then:
1. Let parsed be the result of [8822]parsing the value of the
attribute as an integer.
2. If parsed is not an error, then return parsed.
2. If the [8823]ol element has a [8824]reversed attribute, then return
the number of [8825]owned li elements.
3. Return 1.
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
[8826]referenced by their number/letter). The attribute, if specified,
must have a value that is [8827]identical to one of the characters
given in the first cell of one of the rows of the following table. The
[8828]type attribute represents the state given in the cell in the
second column of the row whose first cell matches the attribute's
value; if none of the cells match, or if the attribute is omitted, then
the attribute represents the [8829]decimal state.
Keyword State Description Examples for values 1-3 and 3999-4001
1 (U+0031) decimal Decimal numbers 1. 2. 3. ... 3999. 4000. 4001. ...
a (U+0061) lower-alpha Lowercase latin alphabet a. b. c. ... ewu. ewv.
eww. ...
A (U+0041) upper-alpha Uppercase latin alphabet A. B. C. ... EWU. EWV.
EWW. ...
i (U+0069) lower-roman Lowercase roman numerals i. ii. iii. ...
mmmcmxcix. i̅v̅. i̅v̅i. ...
I (U+0049) upper-roman Uppercase roman numerals I. II. III. ...
MMMCMXCIX. I̅V̅. I̅V̅I. ...
User agents should render the items of the list in a manner consistent
with the state of the [8830]type attribute of the [8831]ol element.
Numbers less than or equal to zero should always use the decimal system
regardless of the [8832]type attribute.
For CSS user agents, a mapping for this attribute to the
[8833]'list-style-type' CSS property is given [8834]in the Rendering
section (the mapping is straightforward: the states above have the same
names as their corresponding CSS values).
It is possible to redefine the default CSS list styles used to
implement this attribute in CSS user agents; doing so will affect how
list items are rendered.
The reversed and type IDL attributes must [8835]reflect the respective
content attributes of the same name.
The start IDL attribute must [8836]reflect the content attribute of the
same name, with a [8837]default value of 1.
This means that the [8838]start IDL attribute does not necessarily
match the list's [8839]starting value, in cases where the [8840]start
content attribute is omitted and the [8841]reversed content attribute
is specified.
The following markup shows a list where the order matters, and where
the [8842]ol element is therefore appropriate. Compare this list to the
equivalent list in the [8843]ul section to see an example of the same
items using the [8844]ul element.
I have lived in the following countries (given in the order of when
I first lived there):
Switzerland
United Kingdom
United States
Norway
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:
I have lived in the following countries (given in the order of when
I first lived there):
United Kingdom
Switzerland
United States
Norway
4.4.6 The ul element
(BUTTON) ✔MDN
[8845]Element/ul
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
The [8866]ul element [8867]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 [8868]li element child nodes of the
[8869]ul element.
The following markup shows a list where the order does not matter, and
where the [8870]ul element is therefore appropriate. Compare this list
to the equivalent list in the [8871]ol section to see an example of the
same items using the [8872]ol element.
I have lived in the following countries:
Norway
Switzerland
United Kingdom
United States
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:
I have lived in the following countries:
Switzerland
Norway
United Kingdom
United States
4.4.7 The menu element
(BUTTON) ✔MDN
[8873]Element/menu
Support in all current engines.
Firefox1+Safari3+Chrome1+
__________________________________________________________________
The [8894]menu element [8895]represents a toolbar consisting of its
contents, in the form of an unordered list of items (represented by
[8896]li elements), each of which represents a command that the user
can perform or activate.
The [8897]menu element is simply a semantic alternative to [8898]ul to
express an unordered list of commands (a "toolbar").
In this example, a text-editing application uses a [8899]menu element
to provide a series of editing commands:
Note that the styling to make this look like a conventional toolbar
menu is up to the application.
4.4.8 The li element
(BUTTON) ✔MDN
[8900]Element/li
Support in all current engines.
Firefox1+Safari3+Chrome1+
__________________________________________________________________
[8903]Contexts in which this element can be used:
Inside [8904]ol elements.
Inside [8905]ul elements.
Inside [8906]menu elements.
[8907]Content model:
[8908]Flow content.
[8909]Tag omission in text/html:
An [8910]li element's [8911]end tag can be omitted if the
[8912]li element is immediately followed by another [8913]li
element or if there is no more content in the parent element.
[8914]Content attributes:
[8915]Global attributes
If the element is not a child of an [8916]ul or [8917]menu
element: [8918]value — [8919]Ordinal value of the list item
The [8929]li element [8930]represents a list item. If its parent
element is an [8931]ol, [8932]ul, or [8933]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 [8934]li element.
The value attribute, if present, must be a [8935]valid integer. It is
used to determine the [8936]ordinal value of the list item, when the
[8937]li's [8938]list owner is an [8939]ol element.
__________________________________________________________________
Any element whose [8940]computed value of [8941]'display' is
'list-item' has a list owner, which is determined as follows:
1. If the element is not [8942]being rendered, return null; the
element has no [8943]list owner.
2. Let ancestor be the element's parent.
3. If the element has an [8944]ol, [8945]ul, or [8946]menu ancestor,
set ancestor to the closest such ancestor element.
4. Return the closest inclusive ancestor of ancestor that produces a
[8947]CSS box.
Such an element will always exist, as at the very least the
[8948]document element will always produce a [8949]CSS box.
To determine the ordinal value of each element owned by a given
[8950]list owner owner, perform the following steps:
1. Let i be 1.
2. If owner is an [8951]ol element, let numbering be owner's
[8952]starting value. Otherwise, let numbering be 1.
3. Loop: If i is greater than the number of [8953]list items that
owner owns, then return; all of owner's [8954]owned list items have
been assigned [8955]ordinal values.
4. Let item be the ith of owner's [8956]owned list items, in
[8957]tree order.
5. If item is an [8958]li element that has a [8959]value attribute,
then:
1. Let parsed be the result of [8960]parsing the value of the
attribute as an integer.
2. If parsed is not an error, then set numbering to parsed.
6. The [8961]ordinal value of item is numbering.
7. If owner is an [8962]ol element, and owner has a [8963]reversed
attribute, decrement numbering by 1; otherwise, increment numbering
by 1.
8. Increment i by 1.
9. Go to the step labeled loop.
__________________________________________________________________
The value IDL attribute must [8964]reflect the value of the [8965]value
content attribute.
The element's [8966]value IDL attribute does not directly correspond to
its [8967]ordinal value; it simply [8968]reflects the content
attribute. For example, given this list:
Item 1
Item 3
Item 4
The [8969]ordinal values are 1, 3, and 4, whereas the [8970]value IDL
attributes return 0, 3, 0 on getting.
The following example, the top ten movies are listed (in reverse
order). Note the way the list is given a title by using a [8971]figure
element and its [8972]figcaption element.
The top 10 movies of all time
Josie and the Pussycats, 2001
Црна мачка, бели мачор, 1998
A Bugʼs Life, 1998
Toy Story, 1995
Monsters, Inc, 2001
Cars, 2006
Toy Story 2, 1999
Finding Nemo, 2003
The Incredibles, 2004
Ratatouille, 2007
The markup could also be written as follows, using the [8973]reversed
attribute on the [8974]ol element:
The top 10 movies of all time
Josie and the Pussycats, 2001
Црна мачка, бели мачор, 1998
A Bugʼs Life, 1998
Toy Story, 1995
Monsters, Inc, 2001
Cars, 2006
Toy Story 2, 1999
Finding Nemo, 2003
The Incredibles, 2004
Ratatouille, 2007
While it is conforming to include heading elements (e.g. [8975]h1)
inside [8976]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.
4.4.9 The dl element
(BUTTON) ✔MDN
[8977]Element/dl
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
[8979]Categories:
[8980]Flow content.
If the element's children include at least one name-value group:
[8981]Palpable content.
[8982]Contexts in which this element can be used:
Where [8983]flow content is expected.
[8984]Content model:
Either: Zero or more groups each consisting of one or more
[8985]dt elements followed by one or more [8986]dd elements,
optionally intermixed with [8987]script-supporting elements.
Or: One or more [8988]div elements, optionally intermixed with
[8989]script-supporting elements.
[8990]Tag omission in text/html:
Neither tag is omissible.
The [9000]dl element [9001]represents an association list consisting of
zero or more name-value groups (a description list). A name-value group
consists of one or more names ([9002]dt elements, possibly as children
of a [9003]div element child) followed by one or more values ([9004]dd
elements, possibly as children of a [9005]div element child), ignoring
any nodes other than [9006]dt and [9007]dd element children, and
[9008]dt and [9009]dd elements that are children of [9010]div element
children. Within a single [9011]dl element, there should not be more
than one [9012]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 [9013]dd
element.
The order of the list of groups, and of the names and values within
each group, may be significant.
In order to annotate groups with [9014]microdata attributes, or other
[9015]global attributes that apply to whole groups, or just for styling
purposes, each group in a [9016]dl element can be wrapped in a
[9017]div element. This does not change the semantics of the [9018]dl
element.
The name-value groups of a [9019]dl element dl are determined using the
following algorithm. A name-value group has a name (a list of [9020]dt
elements, initially empty) and a value (a list of [9021]dd elements,
initially empty).
1. Let groups be an empty list of name-value groups.
2. Let current be a new name-value group.
3. Let seenDd be false.
4. Let child be dl's [9022]first child.
5. Let grandchild be null.
6. While child is not null:
1. If child is a [9023]div element, then:
1. Let grandchild be child's [9024]first child.
2. While grandchild is not null:
1. [9025]Process dt or dd for grandchild.
2. Set grandchild to grandchild's [9026]next sibling.
2. Otherwise, [9027]process dt or dd for child.
3. Set child to child's [9028]next sibling.
7. If current is not empty, then append current to groups.
8. Return groups.
To process dt or dd for a node node means to follow these steps:
1. Let groups, current, and seenDd be the same variables as those of
the same name in the algorithm that invoked these steps.
2. If node is a [9029]dt element, then:
1. If seenDd is true, then append current to groups, set current
to a new name-value group, and set seenDd to false.
2. Append node to current's name.
3. Otherwise, if node is a [9030]dd element, then append node to
current's value and set seenDd to true.
When a name-value group has an empty list as name or value, it is often
due to accidentally using [9031]dd elements in the place of [9032]dt
elements and vice versa. Conformance checkers can spot such mistakes
and might be able to advise authors how to correctly use the markup.
In the following example, one entry ("Authors") is linked to two values
("John" and "Luke").
Authors
John
Luke
Editor
Frank
In the following example, one definition is linked to two terms.
color
colour
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.
The following example illustrates the use of the [9033]dl element to
mark up 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"). This example also uses the [9034]div
element around the groups of [9035]dt and [9036]dd element, to aid with
styling.
Last modified time
2004-12-23T23:33Z
Recommended update interval
60s
Authors
Editors
Robert Rothman
Daniel Jackson
The following example shows the [9037]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).
Determine the victory points as follows (use the
first matching case):
If you have exactly five gold coins
You get five victory points
If you have one or more gold coins, and you have one or more silver coins
You get two victory points
If you have one or more silver coins
You get one victory point
Otherwise
You get no victory points
The following snippet shows a [9038]dl element being used as a
glossary. Note the use of [9039]dfn to indicate the word being defined.
Apartment, n.
An execution context grouping one or more threads with one or
more COM objects.
Flat, n.
A deflated tire.
Home, n.
The userʼs login directory.
This example uses [9040]microdata attributes in a [9041]dl element,
together with the [9042]div element, to annotate the ice cream desserts
at a French restaurant.
Café ou Chocolat Liégeois
3.50
€
2 boules Café ou Chocolat, 1 boule Vanille, sauce café ou chocolat, chantilly
Without the [9043]div element the markup would need to use the
[9044]itemref attribute to link the data in the [9045]dd elements with
the item, as follows.
Café ou Chocolat Liégeois
3.50
€
2 boules Café ou Chocolat, 1 boule Vanille, sauce café ou chocolat, chantilly
[9050]Contexts in which this element can be used:
Before [9051]dd or [9052]dt elements inside [9053]dl elements.
Before [9054]dd or [9055]dt elements inside [9056]div elements
that are children of a [9057]dl element.
[9058]Content model:
[9059]Flow content, but with no [9060]header, [9061]footer,
[9062]sectioning content, or [9063]heading content descendants.
[9064]Tag omission in text/html:
A [9065]dt element's [9066]end tag can be omitted if the
[9067]dt element is immediately followed by another [9068]dt
element or a [9069]dd element.
The [9077]dt element [9078]represents the term, or name, part of a
term-description group in a description list ([9079]dl element).
The [9080]dt element itself, when used in a [9081]dl element, does not
indicate that its contents are a term being defined, but this can be
indicated using the [9082]dfn element.
This example shows a list of frequently asked questions (a FAQ) marked
up using the [9083]dt element for questions and the [9084]dd element
for answers.
FAQ
What do we want?
Our data.
When do we want it?
Now.
Where is it?
We are not sure.
4.4.11 The dd element
(BUTTON) ✔MDN
[9085]Element/dd
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
[9087]Contexts in which this element can be used:
After [9088]dt or [9089]dd elements inside [9090]dl elements.
After [9091]dt or [9092]dd elements inside [9093]div elements
that are children of a [9094]dl element.
[9095]Content model:
[9096]Flow content.
[9097]Tag omission in text/html:
A [9098]dd element's [9099]end tag can be omitted if the
[9100]dd element is immediately followed by another [9101]dd
element or a [9102]dt element, or if there is no more content in
the parent element.
The [9110]dd element [9111]represents the description, definition, or
value, part of a term-description group in a description list ([9112]dl
element).
A [9113]dl can be used to define a vocabulary list, like in a
dictionary. In the following example, each entry, given by a [9114]dt
with a [9115]dfn, has several [9116]dds, showing the various parts of
the definition.
happiness
/ˈhæpinəs/
n.
The state of being happy.
Good fortune; success. Oh happiness! It worked!
rejoice
/rɪˈdʒɔɪs/
v.intr. To be delighted oneself.
v.tr. To cause one to be delight
ed.
4.4.12 The figure element
(BUTTON) ✔MDN
[9117]Element/figure
Support in all current engines.
Firefox4+Safari5.1+Chrome8+
__________________________________________________________________
[9121]Contexts in which this element can be used:
Where [9122]flow content is expected.
[9123]Content model:
Either: one [9124]figcaption element followed by [9125]flow
content.
Or: [9126]flow content followed by one [9127]figcaption element.
Or: [9128]flow content.
[9129]Tag omission in text/html:
Neither tag is omissible.
The [9137]figure element [9138]represents some [9139]flow content,
optionally with a caption, that is self-contained (like a complete
sentence) and is typically [9140]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 [9141]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 [9142]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 [9143]figure element is [9144]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 first [9145]figcaption element child of the element, if any,
represents the caption of the [9146]figure element's contents. If there
is no child [9147]figcaption element, then there is no caption.
A [9148]figure element's contents are part of the surrounding flow. If
the purpose of the page is to display the figure, for example a
photograph on an image sharing site, the [9149]figure and
[9150]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 [9151]aside
element should be used (and can itself wrap a [9152]figure). For
example, a pull quote that repeats content from an [9153]article would
be more appropriate in an [9154]aside than in a [9155]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 [9156]figure element to mark up a code listing.
In listing 4 we see the primary core interface
API declaration.
Listing 4. The primary core interface API declaration.
Here we see a [9157]figure element to mark up a photo that is the main
content of the page (as in a gallery).
Bubbles at work — My Gallery™Bubbles at work
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
[9158]figure would be inappropriate.
Malinkoʼs comics
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:
...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.
Exhibit A. The alleged rough copy comic.
Exhibit B. The Rough Copy trailer.
The case was resolved out of court.
Here, a part of a poem is marked up using [9159]figure.
ʼTwas brillig, and the slithy toves
Did gyre and gimble in the wabe;
All mimsy were the borogoves,
And the mome raths outgrabe.
Jabberwocky (first verse). Lewis Carroll, 1832-98
In this example, which could be part of a much larger work discussing a
castle, nested [9160]figure elements are used to provide both a group
caption and individual captions for each figure in the group:
The castle through the ages: 1423, 1858, and 1999 respectively.
Etching. Anonymous, ca. 1423.Oil-based paint on canvas. Maria Towle, 1858.Film photograph. Peter Jankle, 1999.
The previous example could also be more succinctly written as follows
(using [9161]title attributes in place of the nested
[9162]figure/[9163]figcaption pairs):
The castle through the ages: 1423, 1858, and 1999 respectively.
The figure is sometimes [9164]referenced only implicitly from the
content:
Fiscal negotiations stumble in Congress as deadline nears
Barack Obama and Harry Reid. White House press photograph.
Negotiations in Congress to end the fiscal impasse sputtered on Tuesday, lea
ving both chambers
grasping for a way to reopen the government and raise the countryʼs borrowing a
uthority with a
Thursday deadline drawing near.
...
4.4.13 The figcaption element
(BUTTON) ✔MDN
[9165]Element/figcaption
Support in all current engines.
Firefox4+Safari5.1+Chrome8+
__________________________________________________________________
The [9179]figcaption element [9180]represents a caption or legend for
the rest of the contents of the [9181]figcaption element's parent
[9182]figure element, if any.
The element can contain additional information about the source:
A duck.
Photograph courtesy of 🌟 News.
Average rent for 3-room apartments, excluding non-profit apartments
Zürich’s Statistics Office —
4.4.14 The main element
(BUTTON) ✔MDN
[9183]Element/main
Support in all current engines.
Firefox21+Safari7+Chrome26+
__________________________________________________________________
The [9200]main element [9201]represents the dominant contents of the
document.
A document must not have more than one [9202]main element that does not
have the [9203]hidden attribute specified.
A hierarchically correct main element is one whose ancestor elements
are limited to [9204]html, [9205]body, [9206]div, [9207]form without an
[9208]accessible name, and [9209]autonomous custom elements. Each
[9210]main element must be a [9211]hierarchically correct main element.
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 [9212]main element is used.
RPG System 17
System Eighteen
Character creation
Attributes (magic, strength, agility) are purchased at the cost of one point
per level.
Rolls
Each encounter, roll the dice for all your skills. If you roll more than the
opponent, you win.
In the following example, multiple [9213]main elements are used and
script is used to make navigation work without a server roundtrip and
to set the [9214]hidden attribute on those that are not current:
…
Home
…
About
…
Contact
…
4.4.15 The search element
(BUTTON) ⚠MDN
[9215]Element/search
No support in current engines.
FirefoxNoSafariNoChromeNo
__________________________________________________________________
The [9231]search element [9232]represents a part of a document or
application that contains a set of form controls or other content
related to performing a search or filtering operation. This could be a
search of the web site or application; a way of searching or filtering
search results on the current web page; or a global or Internet-wide
search function.
It's not appropriate to use the [9233]search element just for
presenting search results, though suggestions and links as part of
"quick search" results can be included as part of a search feature.
Rather, a returned web page of search results would instead be expected
to be presented as part of the main content of that web page.
In the following example, the author is including a search form within
the [9234]header of the web page:
In this example, the author has implemented their web application's
search functionality entirely with JavaScript. There is no use of the
[9235]form element to perform server-side submission, but the
containing [9236]search element semantically identifies the purpose of
the descendant content as representing search capabilities.
Find out how can we help you improve your business with our integrated
consultants, Bob and Bob.
...
In the following example, the page has two search features. The first
is located in the web page's [9237]header and serves as a global
mechanism to search the web site's content. Its purpose is indicated by
its specified [9238]title attribute. The second is included as part of
the main content of the page, as it represents a mechanism to search
and filter the content of the current page. It contains a heading to
indicate its purpose.
...
...
Hotels near your location
Filter results
...
4.4.16 The div element
(BUTTON) ✔MDN
[9239]Element/div
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
[9244]Contexts in which this element can be used:
Where [9245]flow content is expected.
As a child of a [9246]dl element.
[9247]Content model:
If the element is a child of a [9248]dl element: one or more
[9249]dt elements followed by one or more [9250]dd elements,
optionally intermixed with [9251]script-supporting elements.
If the element is not a child of a [9252]dl element: [9253]flow
content.
[9254]Tag omission in text/html:
Neither tag is omissible.
The [9264]div element has no special meaning at all. It
[9265]represents its children. It can be used with the [9266]class,
[9267]lang, and [9268]title attributes to mark up semantics common to a
group of consecutive elements. It can also be used in a [9269]dl
element, wrapping groups of [9270]dt and [9271]dd elements.
Authors are strongly encouraged to view the [9272]div element as an
element of last resort, for when no other element is suitable. Use of
more appropriate elements instead of the [9273]div element leads to
better accessibility for readers and easier maintainability for
authors.
For example, a blog post would be marked up using [9274]article, a
chapter using [9275]section, a page's navigation aids using [9276]nav,
and a group of form controls using [9277]fieldset.
On the other hand, [9278]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
[9279]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:
My use of language and my cats
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.
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.
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"...
I should say "sidewalk" and "apartment" and "color"!
4.5 Text-level semantics
4.5.1 The a element
(BUTTON) ✔MDN
[9280]Element/a
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
[9282]Categories:
[9283]Flow content.
[9284]Phrasing content.
If the element has an [9285]href attribute: [9286]Interactive
content.
[9287]Palpable content.
[9288]Contexts in which this element can be used:
Where [9289]phrasing content is expected.
[9290]Content model:
[9291]Transparent, but there must be no [9292]interactive
content descendant, [9293]a element descendant, or descendant
with the [9294]tabindex attribute specified.
[9295]Tag omission in text/html:
Neither tag is omissible.
[9296]Content attributes:
[9297]Global attributes
[9298]href — Address of the [9299]hyperlink
[9300]target — [9301]Navigable for [9302]hyperlink
[9303]navigation
[9304]download — Whether to download the resource instead of
navigating to it, and its filename if so
[9305]ping — [9306]URLs to ping
[9307]rel — Relationship between the location in the document
containing the [9308]hyperlink and the destination resource
[9309]hreflang — Language of the linked resource
[9310]type — Hint for the type of the referenced resource
[9311]referrerpolicy — [9312]Referrer policy for [9313]fetches
initiated by the element
[9314]Accessibility considerations:
If the element has an [9315]href attribute: [9316]for authors;
[9317]for implementers.
Otherwise: [9318]for authors; [9319]for implementers.
// [9342]also has obsolete members
};
[9343]HTMLAnchorElement includes [9344]HTMLHyperlinkElementUtils;
If the [9345]a element has an [9346]href attribute, then it
[9347]represents a [9348]hyperlink (a hypertext anchor) labeled by its
contents.
If the [9349]a element has no [9350]href attribute, then the element
[9351]represents a placeholder for where a link might otherwise have
been placed, if it had been relevant, consisting of just the element's
contents.
The [9352]target, [9353]download, [9354]ping, [9355]rel,
[9356]hreflang, [9357]type, and [9358]referrerpolicy attributes must be
omitted if the [9359]href attribute is not present.
If the [9360]itemprop attribute is specified on an [9361]a element,
then the [9362]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 [9363]a element:
The [9364]href, [9365]target, [9366]download, [9367]ping, and
[9368]referrerpolicy attributes affect what happens when users
[9369]follow hyperlinks or [9370]download hyperlinks created using the
[9371]a element. The [9372]rel, [9373]hreflang, and [9374]type
attributes may be used to indicate to the user the likely nature of the
target resource before the user follows the link.
a.[9375]text
Same as [9376]textContent.
(BUTTON) ✔MDN
[9377]HTMLAnchorElement/download
Support in all current engines.
Firefox20+Safari10.1+Chrome15+
__________________________________________________________________
The IDL attribute referrerPolicy must [9384]reflect the
[9385]referrerpolicy content attribute, [9386]limited to only known
values.
The text attribute's getter must return this element's [9387]descendant
text content.
The [9388]text attribute's setter must [9389]string replace all with
the given value within this element.
The [9390]a element can 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:
The following example shows how a bit of script can be used to
effectively make an entire row in a job listing table a hyperlink:
The [9408]em element [9409]represents stress emphasis of its contents.
The level of stress that a particular piece of content has is given by
its number of ancestor [9410]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:
Cats are cute animals.
By emphasizing the first word, the statement implies that the kind of
animal under discussion is in question (maybe someone is asserting that
dogs are cute):
Cats are cute animals.
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):
Cats are cute animals.
By moving it to the adjective, the exact nature of the cats is
reasserted (maybe someone suggested cats were mean animals):
Cats are cute animals.
Similarly, if someone asserted that cats were vegetables, someone
correcting this might emphasize the last word:
Cats are cute animals.
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.
Cats are cute animals!
Anger mixed with emphasizing the cuteness could lead to markup such as:
Cats are cute animals!
The [9411]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 [9412]i element is more
appropriate.
The [9413]em element also isn't intended to convey importance; for that
purpose, the [9414]strong element is more appropriate.
4.5.3 The strong element
(BUTTON) ✔MDN
[9415]Element/strong
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
The [9432]strong element [9433]represents strong importance,
seriousness, or urgency for its contents.
Importance: the [9434]strong element can be used in a heading, caption,
or paragraph to distinguish the part that really matters from other
parts that might be more detailed, more jovial, or merely boilerplate.
(This is distinct from marking up subheadings, for which the
[9435]hgroup element is appropriate.)
For example, the first word of the previous paragraph is marked up with
[9436]strong to distinguish it from the more detailed text in the rest
of the paragraph.
Seriousness: the [9437]strong element can be used to mark up a warning
or caution notice.
Urgency: the [9438]strong element can be used to denote contents that
the user needs to see sooner than other parts of the document.
The relative level of importance of a piece of content is given by its
number of ancestor [9439]strong elements; each [9440]strong element
increases the importance of its contents.
Changing the importance of a piece of text with the [9441]strong
element does not change the meaning of the sentence.
Here, the word "chapter" and the actual chapter number are mere
boilerplate, and the actual name of the chapter is marked up with
[9442]strong:
Chapter 1: The Praxis
In the following example, the name of the diagram in the caption is
marked up with [9443]strong, to distinguish it from boilerplate text
(before) and the description (after):
Figure 1. Ant colony dynamics. The ants in this col
ony are
affected by the heat source (upper left) and the food source (lower right).
In this example, the heading is really "Flowers, Bees, and Honey", but
the author has added a light-hearted addition to the heading. The
[9444]strong element is thus used to mark up the first part to
distinguish it from the latter part.
Flowers, Bees, and Honey and other things I donʼt understan
d
Here is an example of a warning notice in a game, with the various
parts marked up according to how important they are:
Warning. This dungeon is dangerous.
Avoid the ducks. Take any gold you find.
Do not take any of the diamonds,
they are explosive and will destroy anything within
ten meters. You have been warned.
In this example, the [9445]strong element is used to denote the part of
the text that the user is intended to read first.
Welcome to Remy, the reminder system.
Your tasks for today:
Turn off the oven.
Put out the trash.
Do the laundry.
4.5.4 The small element
(BUTTON) ✔MDN
[9446]Element/small
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
The [9463]small element [9464]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 [9465]small element does not "de-emphasize" or lower the importance
of text emphasized by the [9466]em element or marked as important with
the [9467]strong element. To mark text as not emphasized or important,
simply do not mark it up with the [9468]em or [9469]strong elements
respectively.
The [9470]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
[9471]small element: in such a case, the text is not a side comment, it
is the main content of the page.
The [9472]small element must not be used for subheadings; for that
purpose, use the [9473]hgroup element.
In this example, the [9474]small element is used to indicate that
value-added tax is not included in a price of a hotel room:
Single room
199 € breakfast included, VAT not included
Double room
239 € breakfast included, VAT not included
In this second example, the [9475]small element is used for a side
comment in an article.
Example Corp today announced record profits for the
second quarter (Full Disclosure: Foo News is a subsidiary of
Example Corp), leading to speculation about a third quarter
merger with Demo Group.
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.
In this last example, the [9476]small element is marked as being
important small print.
Continued use of this service will result in a kiss.
strong>
4.5.5 The s element
(BUTTON) ✔MDN
[9477]Element/s
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
The [9494]s element [9495]represents contents that are no longer
accurate or no longer relevant.
The [9496]s element is not appropriate when indicating document edits;
to mark a span of text as having been removed from a document, use the
[9497]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.
Buy our Iced Tea and Lemonade!
Recommended retail price: $3.99 per bottle
Now selling for just $2.99 a bottle!
4.5.6 The cite element
(BUTTON) ✔MDN
[9498]Element/cite
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
The [9515]cite element [9516]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, a computer
program, etc.). This can be a work that is being quoted or
[9517]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 [9518]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
[9519]span element can be used.)
This next example shows a typical use of the [9520]cite element:
My favorite book is The Reality Dysfunction by
Peter F. Hamilton. My favorite comic is Pearls Before
Swine by Stephan Pastis. My favorite track is Jive
Samba by the Cannonball Adderley Sextet.
This is correct usage:
According to the Wikipedia article HTML, as it
stood in mid-February 2008, leaving attribute values unquoted is
unsafe. This is obviously an over-simplification.
The following, however, is incorrect usage, as the [9521]cite element
here is containing far more than the title of the work:
According to the Wikipedia article on HTML, as it
stood in mid-February 2008, leaving attribute values unquoted is
unsafe. This is obviously an over-simplification.
The [9522]cite element is a key part of any citation in a bibliography,
but it is only used to mark the title:
Universal Declaration of Human Rights, United Nations,
December 1948. Adopted by General Assembly resolution 217 A (III).
A citation is not a quote (for which the [9523]q element is
appropriate).
This is incorrect usage, because [9524]cite is not for quotes:
This is wrong!, said Ian.
This is also incorrect usage, because a person is not a work:
This is still wrong!, said Ian.
The correct usage does not use a [9525]cite element:
This is correct, said Ian.
As mentioned above, the [9526]b element might be relevant for marking
names as being keywords in certain kinds of documents:
And then Ian said this might be right, in a
gossip column, maybe!.
4.5.7 The q element
(BUTTON) ✔MDN
[9527]Element/q
Support in all current engines.
Firefox1+Safari3+Chrome1+
__________________________________________________________________
The [9545]q element [9546]represents some [9547]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 [9548]q elements; they will be inserted into the rendering by
the user agent.
Content inside a [9549]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 [9550]cite attribute is present, it must be a [9551]valid URL
potentially surrounded by spaces. To obtain the corresponding citation
link, the value of the attribute must be [9552]parsed relative to the
element's [9553]node document. 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 [9554]q element must not be used in place of quotation marks that
do not represent quotes; for example, it is inappropriate to use the
[9555]q element for marking up sarcastic statements.
The use of [9556]q elements to mark up quotations is entirely optional;
using explicit quotation punctuation without [9557]q elements is just
as correct.
Here is a simple example of the use of the [9558]q element:
The man said Things that are impossible just take
longer. I disagreed with him.
Here is an example with both an explicit citation link in the [9559]q
element, and an explicit citation outside:
The W3C page About W3C says the W3Cʼs
mission is To lead the
World Wide Web to its full potential by developing protocols and
guidelines that ensure long-term growth for the Web. I
disagree with this mission.
In the following example, the quotation itself contains a quotation:
In Example One, he writes The man
said Things that are impossible just take longer. I
disagreed with him. Well, I disagree even more!
In the following example, quotation marks are used instead of the
[9560]q element:
His best argument was ❝I disagree❞, which
I thought was laughable.
In the following example, there is no quote — the quotation marks are
used to name a word. Use of the [9561]q element in this case would be
inappropriate.
The word "ineffable" could have been used to describe the disaster
resulting from the campaignʼs mismanagement.
4.5.8 The dfn element
(BUTTON) ✔MDN
[9562]Element/dfn
Support in all current engines.
Firefox1+Safari6+Chrome15+
__________________________________________________________________
[9567]Contexts in which this element can be used:
Where [9568]phrasing content is expected.
[9569]Content model:
[9570]Phrasing content, but there must be no [9571]dfn element
descendants.
[9572]Tag omission in text/html:
Neither tag is omissible.
[9573]Content attributes:
[9574]Global attributes
Also, the [9575]title attribute [9576]has special semantics on
this element: Full term or expansion of abbreviation
The [9582]dfn element [9583]represents the defining instance of a term.
The [9584]paragraph, [9585]description list group, or [9586]section
that is the nearest ancestor of the [9587]dfn element must also contain
the definition(s) for the [9588]term given by the [9589]dfn element.
Defining term: if the [9590]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 [9591]Text
nodes, and that child element is an [9592]abbr element with a
[9593]title attribute, then the exact value of that attribute is the
term being defined. Otherwise, it is the [9594]descendant text content
of the [9595]dfn element that gives the term being defined.
If the [9596]title attribute of the [9597]dfn element is present, then
it must contain only the term being defined.
The [9598]title attribute of ancestor elements does not affect
[9599]dfn elements.
An [9600]a element that links to a [9601]dfn element represents an
instance of the term defined by the [9602]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.
The GDO
is a device that allows off-world teams to open the iris.
Tealʼc activated his GDO
and so Hammond ordered the iris to be opened.
With the addition of an [9603]a element, the [9604]reference can be
made explicit:
The GDO
is a device that allows off-world teams to open the iris.
Tealʼc activated his GDO
and so Hammond ordered the iris to be opened.
4.5.9 The abbr element
(BUTTON) ✔MDN
[9605]Element/abbr
Support in all current engines.
Firefox1+Safari4+Chrome2+
__________________________________________________________________
[9610]Contexts in which this element can be used:
Where [9611]phrasing content is expected.
[9612]Content model:
[9613]Phrasing content.
[9614]Tag omission in text/html:
Neither tag is omissible.
[9615]Content attributes:
[9616]Global attributes
Also, the [9617]title attribute [9618]has special semantics on
this element: Full term or expansion of abbreviation
The [9624]abbr element [9625]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
[9626]abbr element. This paragraph [9627]defines the term "Web
Hypertext Application Technology Working Group".
The WHATWG
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.
An alternative way to write this would be:
The Web Hypertext Application Technology
Working Group (WHATWG)
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.
This paragraph has two abbreviations. Notice how only one is defined;
the other, with no expansion associated with it, does not use the
[9628]abbr element.
The
WHATWG
started working on HTML5 in 2004.
This paragraph links an abbreviation to its definition.
The WHATWG
community does not have much representation from Asia.
This paragraph marks up an abbreviation without giving an expansion,
possibly as a hook to apply styles for abbreviations (e.g. smallcaps).
Philip` and Dashiva both denied that they were going to
get the issue counts from past revisions of the specification to
backfill the WHATWG issue graph.
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:
Two WGs worked on
this specification: the WHATWG and the
HTMLWG.
Here the plural is inside the element, so the expansion is in the
plural:
Two WGs worked on
this specification: the WHATWG and the
HTMLWG.
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 [9629]abbr element with a [9630]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 [9631]abbr element with a [9632]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 [9633]abbr element can be used
without a [9634]title attribute.
Providing an expansion in a [9635]title attribute once will not
necessarily cause other [9636]abbr elements in the same document with
the same contents but without a [9637]title attribute to behave as if
they had the same expansion. Every [9638]abbr element is independent.
4.5.10 The ruby element
(BUTTON) ✔MDN
[9639]Element/ruby
Support in all current engines.
Firefox38+Safari5+Chrome5+
__________________________________________________________________
The [9655]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 pronunciation or to include other
annotations. In Japanese, this form of typography is also known as
furigana.
The content model of [9656]ruby elements consists of one or more of the
following sequences:
1. One or the other of the following:
+ [9657]Phrasing content, but with no [9658]ruby elements and
with no [9659]ruby element descendants
+ A single [9660]ruby element that itself has no [9661]ruby
element descendants
2. One or the other of the following:
+ One or more [9662]rt elements
+ An [9663]rp element followed by one or more [9664]rt elements,
each of which is itself followed by an [9665]rp element
The [9666]ruby and [9667]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. [9668][JLREQ]
At the time of writing, CSS does not yet provide a way to fully control
the rendering of the HTML [9669]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.
B
In this example, notice how each annotation corresponds to a
single base character.
君子は和して同ぜず。
君くん子しは和わして同どうぜず。
This example can also be written as follows, using one
[9670]ruby element with two segments of base text and two
annotations (one for each) rather than two back-to-back
[9671]ruby elements each with one base text segment and
annotation (as in the markup above):
君子は和して同ぜず。
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.
BB
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 [9672]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.
鬼門の方角を凝視する
鬼き門もんの方ほう角がくを凝ぎょう視しする
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.
鬼門の方角を凝視する
For more details on [9673]Jukugo Ruby rendering, see Appendix F
in the Requirements for Japanese Text Layout. [9674][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.
BASE
Here a compound ideographic word has its corresponding katakana
given as an annotation.
境界面
境界面インターフェース
Here a compound ideographic word has its translation in English
provided as an annotation.
編集者
編集者editor
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:
紫陽花
紫陽花あじさい
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.
BASE
BaaAaaSaaE<
rt>aa
In this contrived example, some symbols are given names in
English and French.
♥ Heart Cœur
☘ Shamrock Trèfle
✶ Star Étoile
In more complicated situations such as the following examples, a
nested [9675]ruby element is used to give the inner annotations,
and then that whole [9676]ruby is then given an annotation at
the "outer" level.
BaAnStEnannotation
Here both a phonetic reading and the meaning are given in ruby
annotations. The annotation on the nested [9677]ruby element
gives a mono-ruby phonetic annotation for each base character,
while the annotation in the [9678]rt element that is a child of
the outer [9679]ruby element gives the meaning using hiragana.
東とう南なんたつみの方角
東とう南なんたつみの方角
This is the same example, but the meaning is given in English
instead of Japanese:
Within a [9680]ruby element that does not have a [9681]ruby element
ancestor, content is 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 [9682]inter-element whitespace and [9683]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 [9684]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 [9685]ruby element [9686]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. [9687][DOM]
At any particular time, the segmentation and categorization of content
of a [9688]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 [9689]ruby element for which the algorithm is being
run.
4. If root has a [9690]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 saved start index be null.
9. Let current base text be null.
10. Start mode: If index is greater than or equal to the number of
child nodes in current parent, then jump to the step labeled end
mode.
11. If the indexth node in current parent is an [9691]rt or [9692]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 [9693]ruby
element, and if current parent is the same element as root, then
[9694]push a ruby level and then jump to the step labeled start
mode.
14. If the indexth node in current parent is an [9695]rt or [9696]rp
element, then [9697]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 greater than or equal to 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
[9698]rt element, then [9699]push a ruby annotation and jump to the
step labeled annotation mode increment.
19. If the indexth node in current parent is an [9700]rp element, jump
to the step labeled annotation mode increment.
20. If the indexth node in current parent is not a [9701]Text node, or
is a [9702]Text node that is not [9703]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 [9704]rt
element or an [9705]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 [9706]Text
node, or is a [9707]Text node that is not [9708]inter-element
whitespace, then jump to the step labeled base mode (without
further incrementing index, so the [9709]inter-element 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
[9710]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 [9711]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 [9712]start is the
[9713]boundary point (current parent, start index) and whose
[9714]end is the [9715]boundary point (current parent, index).
2. Let new text segment be a base text segment described by the range
text 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.
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 [9716]rt element that is the indexth node of current
parent.
2. Let annotation range be a DOM range whose [9717]start is the
[9718]boundary point (current parent, index) and whose [9719]end is
the [9720]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:
The two main ideographs, each with its annotation in hiragana rendered
in a smaller font above it.
In this example, each ideograph in the traditional Chinese text 漢字 is
annotated with its bopomofo reading.
漢ㄏㄢˋ字ㄗˋ
This might be rendered as:
The two main ideographs, each with its bopomofo annotation rendered in
a smaller font next to it.
In this example, each ideograph in the simplified Chinese text 汉字 is
annotated with its pinyin reading.
...汉hàn字zì...
This might be rendered as:
The two main ideographs, each with its pinyin annotation rendered in a
smaller font above it.
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".
HTHypertextMMarkupLLanguageAn abstract language for describing documents and applications
4.5.11 The rt element
(BUTTON) ✔MDN
[9721]Element/rt
Support in all current engines.
Firefox38+Safari5+Chrome5+
__________________________________________________________________
[9723]Contexts in which this element can be used:
As a child of a [9724]ruby element.
[9725]Content model:
[9726]Phrasing content.
[9727]Tag omission in text/html:
An [9728]rt element's [9729]end tag can be omitted if the
[9730]rt element is immediately followed by an [9731]rt or
[9732]rp element, or if there is no more content in the parent
element.
The [9740]rt element marks the ruby text component of a ruby
annotation. When it is the child of a [9741]ruby element, it doesn't
[9742]represent anything itself, but the [9743]ruby element uses it as
part of determining what it [9744]represents.
An [9745]rt element that is not a child of a [9746]ruby element
[9747]represents the same thing as its children.
4.5.12 The rp element
(BUTTON) ✔MDN
[9748]Element/rp
Support in all current engines.
Firefox38+Safari5+Chrome5+
__________________________________________________________________
[9750]Contexts in which this element can be used:
As a child of a [9751]ruby element, either immediately before or
immediately after an [9752]rt element.
[9753]Content model:
[9754]Text.
[9755]Tag omission in text/html:
An [9756]rp element's [9757]end tag can be omitted if the
[9758]rp element is immediately followed by an [9759]rt or
[9760]rp element, or if there is no more content in the parent
element.
The [9768]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 [9769]rp element that is a child of a [9770]ruby element
[9771]represents nothing. An [9772]rp element whose parent element is
not a [9773]ruby element [9774]represents its children.
The example above, in which each ideograph in the text 漢字 is annotated
with its phonetic reading, could be expanded to use [9775]rp so that in
legacy user agents the readings are in parentheses:
...
漢かん字じ
...
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, [9776]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 [9777]rp elements as well:
♥HeartCœur
☘ShamrockTrèfle
✶StarÉtoile
This would make the example render as follows in non-ruby-capable user
agents:
♥: Heart, Cœur. ☘: Shamrock, Trèfle. ✶: Star, Étoile.
4.5.13 The data element
(BUTTON) ✔MDN
[9778]Element/data
Support in all current engines.
Firefox22+Safari10+Chrome62+
__________________________________________________________________
The [9800]data element [9801]represents its contents, along with a
machine-readable form of those contents in the [9802]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 [9803]time
element can be used instead.
The element can be used for several purposes.
When combined with microformats or the [9804]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 [9805]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 value. In such cases, the format to be used depends only
on the needs of the script. (The [9806]data-* attributes can also be
useful in such situations.)
(BUTTON) ✔MDN
[9807]HTMLDataElement/value
Support in all current engines.
Firefox22+Safari10+Chrome62+
__________________________________________________________________
The value IDL attribute must [9808]reflect the content attribute of the
same name.
Here, a short table has its numeric values encoded using the [9809]data
element so that the table sorting JavaScript library 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.
Game
Corporations
Map Size
1830
Eight
19+74 h
exes (93 total)
1856
Eleven
12+87
hexes (99 total)
1870
Ten
4+145 h
exes (149 total)
4.5.14 The time element
(BUTTON) ✔MDN
[9810]Element/time
Support in all current engines.
Firefox22+Safari7+Chrome62+
__________________________________________________________________
[9816]Contexts in which this element can be used:
Where [9817]phrasing content is expected.
[9818]Content model:
If the element has a [9819]datetime attribute: [9820]Phrasing
content.
Otherwise: [9821]Text, but must match requirements described in
prose below.
[9822]Tag omission in text/html:
Neither tag is omissible.
[9823]Content attributes:
[9824]Global attributes
[9825]datetime — Machine-readable value
The [9834]time element [9835]represents its contents, along with a
machine-readable form of those contents in the [9836]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 [9837]time element that does not have a [9838]datetime content
attribute must not have any element descendants.
The datetime value of a [9839]time element is the value of the
element's [9840]datetime content attribute, if it has one, otherwise
the [9841]child text content of the [9842]time element.
The [9843]datetime value of a [9844]time element must match one of the
following syntaxes.
A [9845]valid month string
A [9846]valid date string
A [9847]valid yearless date string
A [9848]valid time string
A [9849]valid local date and time string
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-01-01 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 [9850]valid global date and time
string is likely more useful.
A [9851]valid time-zone offset string
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 saving 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. [9852][TZDATABASE]
A [9853]valid global date and time string
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 saving time or not. For events where the
precise time varies by the local time zone offset of a specific
geographic location, a [9854]valid local date and time string
combined with that geographic location is likely more useful.
A [9855]valid week string
Four or more [9856]ASCII digits, at least one of which is not U+0030
DIGIT ZERO (0)
A [9857]valid duration string
The machine-readable equivalent of the element's contents must be
obtained from the element's [9858]datetime value by using the following
algorithm:
1. If [9859]parsing a month string from the element's [9860]datetime
value returns a [9861]month, that is the machine-readable
equivalent; return.
2. If [9862]parsing a date string from the element's [9863]datetime
value returns a [9864]date, that is the machine-readable
equivalent; return.
3. If [9865]parsing a yearless date string from the element's
[9866]datetime value returns a [9867]yearless date, that is the
machine-readable equivalent; return.
4. If [9868]parsing a time string from the element's [9869]datetime
value returns a [9870]time, that is the machine-readable
equivalent; return.
5. If [9871]parsing a local date and time string from the element's
[9872]datetime value returns a [9873]local date and time, that is
the machine-readable equivalent; return.
6. If [9874]parsing a time-zone offset string from the element's
[9875]datetime value returns a [9876]time-zone offset, that is the
machine-readable equivalent; return.
7. If [9877]parsing a global date and time string from the element's
[9878]datetime value returns a [9879]global date and time, that is
the machine-readable equivalent; return.
8. If [9880]parsing a week string from the element's [9881]datetime
value returns a [9882]week, that is the machine-readable
equivalent; return.
9. If the element's [9883]datetime value consists of only [9884]ASCII
digits, at least one of which is not U+0030 DIGIT ZERO (0), then
the machine-readable equivalent is the base-ten interpretation of
those digits, representing a year; return.
10. If [9885]parsing a duration string from the element's
[9886]datetime value returns a [9887]duration, that is the
machine-readable equivalent; return.
11. There is no machine-readable equivalent.
The algorithms referenced above are intended to be designed such that
for any arbitrary string s, only one of the algorithms returns a value.
A more efficient approach might be to create a single algorithm that
parses all these data types in one pass; developing such an algorithm
is left as an exercise to the reader.
(BUTTON) ✔MDN
[9888]HTMLTimeElement/dateTime
Support in all current engines.
Firefox22+Safari10+Chrome62+
__________________________________________________________________
The dateTime IDL attribute must [9889]reflect the element's
[9890]datetime content attribute.
The [9891]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 [9892]time element:
Here, a fictional microdata vocabulary based on the Atom vocabulary is
used with the [9893]time element to mark up a blog post's publication
date.
Big tasks
Today, I went out and bought a bike for my kid.
In this example, another article's publication date is marked up using
[9894]time, this time using the schema.org microdata vocabulary:
Small tasks
I put a bike bell on her bike.
In the following snippet, the [9895]time element is used to encode a
date in the ISO8601 format, for later processing by a script:
Our first date was .
In this second snippet, the value includes a time:
We stopped talking at .
A script loaded by the page (and thus privy to the page's internal
convention of marking up dates and times using the [9896]time element)
could scan through the page and look at all the [9897]time elements
therein to create an index of dates and times.
For example, this element conveys the string "Friday" with the
additional semantic that the 18th of November 2011 is the meaning that
corresponds to "Friday":
Today is .
In this example, a specific time in the Pacific Standard Time timezone
is specified:
Your next meeting is at .
4.5.15 The code element
(BUTTON) ✔MDN
[9898]Element/code
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
The [9915]code element [9916]represents a fragment of computer code.
This could be an XML element name, a filename, 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 [9917]code elements with the
language used, e.g. so that syntax highlighting scripts can use the
right rules, can use the [9918]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.
The code element represents a fragment of computer
code.
When you call the activate() method on the
robotSnowman object, the eyes glow.
The example below uses the begin keyword to indicate
the start of a statement block. It is paired with an end
keyword, which is followed by the . punctuation character
(full stop) to indicate the end of the program.
The following example shows how a block of code could be marked up
using the [9919]pre and [9920]code elements.
var i: Integer;
begin
i := 1;
end.
A class is used in that example to indicate the language used.
See the [9921]pre element for more details.
4.5.16 The var element
(BUTTON) ✔MDN
[9922]Element/var
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
The [9939]var element [9940]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:
If there are n pipes leading to the ice
cream factory then I expect at leastn
flavors of ice cream to be available for purchase!
For mathematics, in particular for anything beyond the simplest of
expressions, MathML is more appropriate. However, the [9941]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
[9942]var.
Using Pythagorasʼ theorem to solve for the hypotenuse a of
a triangle with sides b and c
Here, the equation describing mass-energy equivalence is used in a
sentence, and the [9943]var element is used to mark the variables and
constants in that equation:
Then she turned to the blackboard and picked up the chalk. After a few moment
ʼs
thought, she wrote E = mc2. The tea
cher
looked pleased.
4.5.17 The samp element
(BUTTON) ✔MDN
[9944]Element/samp
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
The [9961]samp element [9962]represents sample or quoted output from
another program or computing system.
See the [9963]pre and [9964]kbd elements for more details.
This element can be contrasted with the [9965]output element, which can
be used to provide immediate output in a web application.
This example shows the [9966]samp element being used inline:
The computer said Too much cheese in tray
two but I didnʼt know what that meant.
This second example shows a block of sample output from a console
program. Nested [9967]samp and [9968]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 [9969]samp that are annotated with even more
detailed markup, to enable very precise styling. To achieve this,
[9970]span elements are used.
jdoe@mowmow:~$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+gr2b-reslog-v6.189 #1 SM
P Tue Feb 1 11:22:36 PST 2005 i686 unknown
jdoe@demo:~$_
This third example shows a block of input and its respective output.
The example uses both [9971]code and [9972]samp elements.
console.log(2.3 + 2.4)4.699999999999999
4.5.18 The kbd element
(BUTTON) ✔MDN
[9973]Element/kbd
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
The [9990]kbd element [9991]represents user input (typically keyboard
input, although it may also be used to represent other input, such as
voice commands).
When the [9992]kbd element is nested inside a [9993]samp element, it
represents the input as it was echoed by the system.
When the [9994]kbd element contains a [9995]samp element, it represents
input based on system output, for example invoking a menu item.
When the [9996]kbd element is nested inside another [9997]kbd element,
it represents an actual key or other single unit of input as
appropriate for the input mechanism.
Here the [9998]kbd element is used to indicate keys to press:
To make George eat an apple, press Shift + F3
In this second example, the user is told to pick a particular menu
item. The outer [9999]kbd element marks up a block of input, with the
inner [10000]kbd elements representing each individual step of the
input, and the [10001]samp elements inside them indicating that the
steps are input based on something being displayed by the system, in
this case menu labels:
To make George eat an apple, select
File|Eat Apple...
Such precision isn't necessary; the following is equally fine:
To make George eat an apple, select File | Eat Apple...
4.5.19 The sub and sup elements
(BUTTON) ✔MDN
[10002]Element/sub
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
[10015]Accessibility considerations:
The [10016]sub element: [10017]for authors; [10018]for
implementers.
The [10019]sup element: [10020]for authors; [10021]for
implementers.
[10022]DOM interface:
Use [10023]HTMLElement.
The [10024]sup element [10025]represents a superscript and the
[10026]sub element [10027]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
[10028]sub and [10029]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.
Their names are
Mlle Gwendoline and
Mme Denise.
The [10030]sub element can be used inside a [10031]var element, for
variables that have subscripts.
Here, the [10032]sub element is used to represent the subscript that
identifies the variable in a family of variables:
The coordinate of the ith point is
(xi, yi).
For example, the 10th point has coordinate
(x10, y10).
Mathematical expressions often use subscripts and superscripts. Authors
are encouraged to use MathML for marking up mathematics, but authors
may opt to use [10033]sub and [10034]sup if detailed mathematical
markup is not desired. [10035][MATHML]
E=mc2
f(x, n) = log4xn
4.5.20 The i element
(BUTTON) ✔MDN
[10036]Element/i
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
The [10053]i element [10054]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 [10055]lang attributes (or, in XML, [10056]lang attributes in the
XML namespace).
The examples below show uses of the [10057]i element:
The Felis silvestris catus is cute.
The term prose content is defined above.
There is a certain je ne sais quoi in the air.
In the following example, a dream sequence is marked up using [10058]i
elements.
Raymond tried to sleep.
The ship sailed away on Thursday, he
dreamt. 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.
Finally one night he picked up the courage to speak with
her—
Raymond woke with a start as the fire alarm rang out.
Authors can use the [10059]class attribute on the [10060]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
applicable than the [10061]i element, for instance the [10062]em
element for marking up stress emphasis, or the [10063]dfn element to
mark up the defining instance of a term.
Style sheets can be used to format [10064]i elements, just like any
other element can be restyled. Thus, it is not the case that content in
[10065]i elements will necessarily be italicized.
4.5.21 The b element
(BUTTON) ✔MDN
[10066]Element/b
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
The [10083]b element [10084]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 text-driven software, or an article
lede.
The following example shows a use of the [10085]b element to highlight
key words without marking them up as important:
The frobonitor and barbinator components are fried.
In the following example, objects in a text adventure are highlighted
as being special by use of the [10086]b element.
You enter a small room. Your sword glows
brighter. A rat scurries past the corner wall.
Another case where the [10087]b element is appropriate is in marking up
the lede (or lead) sentence or paragraph. The following example shows
how a [10088]BBC article about kittens adopting a rabbit as their own
could be marked up:
Kittens ʼadoptedʼ by pet rabbit
Six abandoned kittens have found an
unexpected new mother figure — a pet rabbit.
Veterinary nurse Melanie Humble took the three-week-old
kittens to her Aberdeen home.
[...]
As with the [10089]i element, authors can use the [10090]class
attribute on the [10091]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 [10092]b element should be used as a last resort when no other
element is more appropriate. In particular, headings should use the
[10093]h1 to [10094]h6 elements, stress emphasis should use the
[10095]em element, importance should be denoted with the [10096]strong
element, and text marked or highlighted should use the [10097]mark
element.
The following would be incorrect usage:
WARNING! Do not frob the barbinator!
In the previous example, the correct element to use would have been
[10098]strong, not [10099]b.
Style sheets can be used to format [10100]b elements, just like any
other element can be restyled. Thus, it is not the case that content in
[10101]b elements will necessarily be boldened.
4.5.22 The u element
(BUTTON) ✔MDN
[10102]Element/u
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
The [10119]u element [10120]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 [10121]em element should be used; for
marking key words or phrases either the [10122]b element or the
[10123]mark element should be used, depending on the context; for
marking book titles, the [10124]cite element should be used; for
labeling text with explicit textual annotations, the [10125]ruby
element should be used; for technical terms, taxonomic designation,
transliteration, a thought, or for labeling ship names in Western
texts, the [10126]i element should be used.
The default rendering of the [10127]u element in visual presentations
clashes with the conventional rendering of hyperlinks (underlining).
Authors are encouraged to avoid using the [10128]u element where it
could be confused for a hyperlink.
In this example, a [10129]u element is used to mark a word as misspelt:
The see is full of fish.
4.5.23 The mark element
(BUTTON) ✔MDN
[10130]Element/mark
Support in all current engines.
Firefox4+Safari5.1+Chrome7+
__________________________________________________________________
The [10147]mark element [10148]represents a run of text in one document
marked or highlighted for [10149]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 [10150]mark element can be used to bring
attention to a particular part of a quotation:
Consider the following quote:
Look around and you will find, no-oneʼs really
colour blind.
As we can tell from the spelling of the word,
the person writing this quote is clearly not American.
(If the goal was to mark the element as misspelt, however, the [10151]u
element, possibly with a class, would be more appropriate.)
Another example of the [10152]mark element is highlighting parts of a
document that 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:
I also have some kittens who are visiting me
these days. Theyʼre really cute. I think they like my garden! Maybe I
should adopt a kitten.
In the following snippet, a paragraph of text refers to a specific part
of a code fragment.
The highlighted part below is where the error lies:
var i: Integer;
begin
i := 1.1;
end.
This is separate from syntax highlighting, for which [10153]span is
more appropriate. Combining both, one would get:
The highlighted part below is where the error lies:
vari: Integer;
begini := 1.1;
end.
This is another example showing the use of [10154]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 [10155]mark elements in quotes to render in italics.
She knew
Did you notice the subtle joke in the joke on panel 4?
I didnʼt want to believe. Of course
on some level I realized it was a known-plaintext attack. But I
couldnʼt admit it until I saw for myself.
(Emphasis mine.) I thought that was great. Itʼs so pedantic, yet it
explains everything neatly.
Note, incidentally, the distinction between the [10156]em element in
this example, which is part of the original text being quoted, and the
[10157]mark element, which is highlighting a part for comment.
The following example shows the difference between denoting the
importance of a span of text ([10158]strong) as opposed to denoting the
relevance of a span of text ([10159]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.
Wormhole Physics Introduction
A wormhole in normal conditions can be held open for a
maximum of just under 39 minutes. 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).
Momentum is preserved across the wormhole. Electromagnetic
radiation can travel in both directions through a wormhole,
but matter cannot.
When a wormhole is created, a vortex normally forms.
Warning: The vortex caused by the wormhole opening will
annihilate anything in its path. Vortexes can be avoided when
using sufficiently advanced dialing technology.
An obstruction in a gate will prevent it from accepting a
wormhole connection.
4.5.24 The bdi element
(BUTTON) ✔MDN
[10160]Element/bdi
Support in all current engines.
Firefox10+Safari6+Chrome16+
__________________________________________________________________
The [10178]bdi element [10179]represents a span of text that is to be
isolated from its surroundings for the purposes of bidirectional text
formatting. [10180][BIDI]
The [10181]dir global attribute defaults to [10182]auto on this element
(it never inherits from the parent element like with other elements).
This element [10183]has rendering requirements involving the
bidirectional algorithm.
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 [10184]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").
User jcranmer: 12 posts.
User hober: 5 posts.
User إيان: 3 posts.
When using the [10185]bdi element, the username acts as expected. If
the [10186]bdi element were to be replaced by a [10187]b element, the
username would confuse the bidirectional algorithm and the third bullet
would end up saying "User 3 :", followed by the Arabic name
(right-to-left), followed by "posts" and a period.
4.5.25 The bdo element
(BUTTON) ✔MDN
[10188]Element/bdo
Support in all current engines.
Firefox10+Safari4+Chrome15+
__________________________________________________________________
The [10206]bdo element [10207]represents explicit text directionality
formatting control for its children. It allows authors to override the
Unicode bidirectional algorithm by explicitly specifying a direction
override. [10208][BIDI]
Authors must specify the [10209]dir attribute on this element, with the
value [10210]ltr to specify a left-to-right override and with the value
[10211]rtl to specify a right-to-left override. The [10212]auto value
must not be specified.
This element [10213]has rendering requirements involving the
bidirectional algorithm.
4.5.26 The span element
(BUTTON) ✔MDN
[10214]Element/span
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
The [10233]span element doesn't mean anything on its own, but can be
useful when used together with the [10234]global attributes, e.g.
[10235]class, [10236]lang, or [10237]dir. It [10238]represents its
children.
In this example, a code fragment is marked up using [10239]span
elements and [10240]class attributes so that its keywords and
identifiers can be color-coded from CSS:
The [10261]br element [10262]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.
[10263]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 [10264]br element:
P. Sherman
42 Wallaby Way
Sydney
[10265]br elements must not be used for separating thematic groups in a
paragraph.
The following examples are non-conforming, as they abuse the [10266]br
element:
If a [10267]paragraph consists of nothing but a single [10268]br
element, it represents a placeholder blank line (e.g. as in a
template). Such blank lines must not be used for presentation purposes.
Any content inside [10269]br elements must not be considered part of
the surrounding text.
This element [10270]has rendering requirements involving the
bidirectional algorithm.
4.5.28 The wbr element
(BUTTON) ✔MDN
[10271]Element/wbr
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
The [10288]wbr element [10289]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 [10290]wbr element.
So then she pointed at the tiger and screamed
"thereisnowayyouareevergoingtocatch
me"!
Any content inside [10291]wbr elements must not be considered part of
the surrounding text.
var wbr = document.createElement("wbr");
wbr.textContent = "This is wrong";
document.body.appendChild(wbr);
This element [10292]has rendering requirements involving the
bidirectional algorithm.
4.5.29 Usage summary
This section is non-normative.
Element Purpose Example
[10293]a Hyperlinks
Visit my drinks page.
[10294]em Stress emphasis
I must say I adore lemonade.
[10295]strong Importance
This tea is very hot.
[10296]small Side comments
These grapes are made into wine. Alcohol is addictive.
[10297]s Inaccurate text
Price: £4.50 £2.00!
[10298]cite Titles of works
The case Hugo v. Danielle is relevant here.
[10299]q Quotations
The judge said You can drink water from the fish tank but advised against
it.
[10300]dfn Defining instance
The term organic food refers to food produced without synthetic chemi
cals.
[10301]abbr Abbreviations
Organic food in Ireland is certified by the IOFGA.
[10305]data Machine-readable equivalent
Available starting today! North Coast Organic App
le Cider
[10306]time Machine-readable equivalent of date- or time-related data
Available starting on !
[10307]code Computer code
The fruitdb program can be used for tracking fruit production.
[10308]var Variables
If there are n fruit in the bowl, at least n÷2 will be rip
e.
[10309]samp Computer output
The computer said Unknown error -3.
[10310]kbd User input
Hit F1 to continue.
[10311]sub Subscripts
Water is H2O.
[10312]sup Superscripts
The Hydrogen in heavy water is usually 2H.
[10313]i Alternative voice
Lemonade consists primarily of Citrus limon.
[10314]b Keywords
Take a lemon and squeeze it with a juicer.
[10315]u Annotations
The mixture of apple juice and eldeflower juice is very
pleasant.
[10316]mark Highlight
Elderflower cordial, with one part cordial to ten part
s water, stands apart from the rest.
[10317]bdi Text directionality isolation
The recommended restaurant is My Juice Café (At The Beach).
[10318]bdo Text directionality formatting
The proposal is to write English, but in reverse order. "Juice" would become "Juice">
[10319]span Other
In French we call it sirop de sureau.
[10320]br Line break
Simply Orange Juice Company Apopka, FL 32703 U.S.A.
[10321]wbr Line breaking opportunity
www.simplyorangejuice.com
4.6 Links
4.6.1 Introduction
Links are a conceptual construct, created by [10322]a, [10323]area,
[10324]form, and [10325]link elements, that [10326]represent a
connection between two resources, one of which is the current
[10327]Document. There are three 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. All [10328]external resource links have a [10329]fetch
and process the linked resource algorithm which describes how
the resource is obtained.
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 [10330]navigate to those resources, e.g. to visit them
in a browser or download them.
Internal resource links
These are links to resources within the current document, used
to give those resources special meaning or behavior.
For [10331]link elements with an [10332]href attribute and a [10333]rel
attribute, links must be created for the keywords of the [10334]rel
attribute, as defined for those keywords in the [10335]link types
section.
Similarly, for [10336]a and [10337]area elements with an [10338]href
attribute and a [10339]rel attribute, links must be created for the
keywords of the [10340]rel attribute as defined for those keywords in
the [10341]link types section. Unlike [10342]link elements, however,
[10343]a and [10344]area elements with an [10345]href attribute that
either do not have a [10346]rel attribute, or whose [10347]rel
attribute has no keywords that are defined as specifying
[10348]hyperlinks, must also create a [10349]hyperlink. This implied
hyperlink has no special meaning (it has no [10350]link type) beyond
linking the element's [10351]node document to the resource given by the
element's [10352]href attribute.
Similarly, for [10353]form elements with a [10354]rel attribute, links
must be created for the keywords of the [10355]rel attribute as defined
for those keywords in the [10356]link types section. [10357]form
elements that do not have a [10358]rel attribute, or whose [10359]rel
attribute has no keywords that are defined as specifying
[10360]hyperlinks, must also create a [10361]hyperlink.
A [10362]hyperlink can have one or more hyperlink annotations that
modify the processing semantics of that hyperlink.
4.6.2 Links created by [10363]a and [10364]area elements
The href attribute on [10365]a and [10366]area elements must have a
value that is a [10367]valid URL potentially surrounded by spaces.
The [10368]href attribute on [10369]a and [10370]area elements is not
required; when those elements do not have [10371]href attributes they
do not create hyperlinks.
The target attribute, if present, must be a [10372]valid navigable
target name or keyword. It gives the name of the [10373]navigable that
will be used. User agents use this name when [10374]following
hyperlinks.
The download attribute, if present, indicates that the author intends
the hyperlink to be used for [10375]downloading a resource. The
attribute may have a value; the value, if any, specifies the default
filename 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 filenames, and user agents
are likely to adjust filenames accordingly.
(BUTTON) ✔MDN
[10376]Element/a#attr-ping
Support in all current engines.
Firefox🔰 1+Safari6+Chrome12+
__________________________________________________________________
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 [10377]set of space-separated tokens, each of which
must be a [10378]valid non-empty URL whose [10379]scheme is an
[10380]HTTP(S) scheme. The value is used by the user agent for
[10381]hyperlink auditing.
The rel attribute on [10382]a and [10383]area elements controls what
kinds of links the elements create. The attribute's value must be an
[10384]unordered set of unique space-separated tokens. The
[10385]allowed keywords and their meanings are defined below.
[10386]rel's [10387]supported tokens are the keywords defined in
[10388]HTML link types which are allowed on [10389]a and [10390]area
elements, impact the processing model, and are supported by the user
agent. The possible [10391]supported tokens are [10392]noreferrer,
[10393]noopener, and [10394]opener. [10395]rel's [10396]supported
tokens must only include the tokens from this list that the user agent
implements the processing model for.
The [10397]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 [10398]a elements that create
[10399]hyperlinks, if present, gives the language of the linked
resource. It is purely advisory. The value must be a valid BCP 47
language tag. [10400][BCP47] User agents must not consider this
attribute authoritative — upon fetching the resource, user agents must
use only language information associated with the resource to determine
its language, not metadata included in the link to the resource.
The type attribute, if present, gives the [10401]MIME type of the
linked resource. It is purely advisory. The value must be a
[10402]valid MIME type string. User agents must not consider the
[10403]type attribute authoritative — upon fetching the resource, user
agents must not use metadata included in the link to the resource to
determine its type.
The referrerpolicy attribute is a [10404]referrer policy attribute. Its
purpose is to set the [10405]referrer policy used when [10406]following
hyperlinks. [10407][REFERRERPOLICY]
__________________________________________________________________
When an [10408]a or [10409]area element's [10410]activation behavior is
invoked, the user agent may allow the user to indicate a preference
regarding whether the hyperlink is to be used for [10411]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 [10412]download attribute, and should be to
download the specified resource if it does.
The [10413]activation behavior of an [10414]a or [10415]area element
element given an event event is:
1. If element has no [10416]href attribute, then return.
2. Let hyperlinkSuffix be null.
3. If element is an [10417]a element, and event's [10418]target is an
[10419]img with an [10420]ismap attribute specified, then:
1. Let x and y be 0.
2. If event's [10421]isTrusted attribute is initialized to true,
then set x to the distance in [10422]CSS pixels from the left
edge of the image to the location of the click, and set y to
the distance in [10423]CSS pixels from the top edge of the
image to the location of the click.
3. If x is negative, set x to 0.
4. If y is negative, set y to 0.
5. Set hyperlinkSuffix to the concatenation of U+003F (?), the
value of x expressed as a base-ten integer using [10424]ASCII
digits, U+002C (,), and the value of y expressed as a base-ten
integer using [10425]ASCII digits.
4. Let userInvolvement be event's [10426]user navigation involvement.
5. If the user has expressed a preference to download the hyperlink,
then set userInvolvement to "[10427]browser UI".
That is, if the user has expressed a specific preference for
downloading, this no longer counts as merely "[10428]activation".
6. If element has a [10429]download attribute, or if the user has
expressed a preference to download the hyperlink, then
[10430]download the hyperlink created by element with
[10431]hyperlinkSuffix set to hyperlinkSuffix and
[10432]userInvolvement set to userInvolvement.
7. Otherwise, [10433]follow the hyperlink created by element with
[10434]hyperlinkSuffix set to hyperlinkSuffix and
[10435]userInvolvement set to userInvolvement.
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
Returns the hyperlink's URL's host and port (if different from
the default port for the scheme).
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
Returns the hyperlink's URL's fragment (includes leading "#" if
non-empty).
Can be set, to change the URL's fragment (ignores leading "#").
An element implementing the [10494]HTMLHyperlinkElementUtils mixin has
an associated url (null or a [10495]URL). It is initially null.
An element implementing the [10496]HTMLHyperlinkElementUtils mixin has
an associated set the url algorithm, which runs these steps:
1. Set this element's [10497]url to null.
2. If this element's [10498]href content attribute is absent, then
return.
3. Let url be the result of [10499]encoding-parsing a URL given this
element's [10500]href content attribute's value, relative to this
element's [10501]node document.
4. If url is not failure, then set this element's [10502]url to url.
When elements implementing the [10503]HTMLHyperlinkElementUtils mixin
are created, and whenever those elements have their [10504]href content
attribute set, changed, or removed, the user agent must [10505]set the
url.
This is only observable for [10506]blob: URLs as [10507]parsing them
involves a [10508]Blob URL Store lookup.
An element implementing the [10509]HTMLHyperlinkElementUtils mixin has
an associated reinitialize url algorithm, which runs these steps:
1. If the element's [10510]url is non-null, its [10511]scheme is
"blob", and it has an [10512]opaque path, then terminate these
steps.
2. [10513]Set the url.
To update href, set the element's [10514]href content attribute's value
to the element's [10515]url, [10516]serialized.
__________________________________________________________________
The href getter steps are:
1. [10517]Reinitialize url.
2. Let url be [10518]this's [10519]url.
3. If url is null and [10520]this has no [10521]href content
attribute, return the empty string.
4. Otherwise, if url is null, return [10522]this's [10523]href content
attribute's value.
5. Return url, [10524]serialized.
The [10525]href setter steps are to set [10526]this's [10527]href
content attribute's value to the given value.
The origin getter steps are:
1. [10528]Reinitialize url.
2. If [10529]this's [10530]url is null, return the empty string.
3. Return the [10531]serialization of [10532]this's [10533]url's
[10534]origin.
The protocol getter steps are:
1. [10535]Reinitialize url.
2. If [10536]this's [10537]url is null, return ":".
3. Return [10538]this's [10539]url's [10540]scheme, followed by ":".
The [10541]protocol setter steps are:
1. [10542]Reinitialize url.
2. If [10543]this's [10544]url is null, then return.
3. [10545]Basic URL parse the given value, followed by ":", with
[10546]this's [10547]url as [10548]url and [10549]scheme start
state as [10550]state override.
Because the URL parser ignores multiple consecutive colons,
providing a value of "https:" (or even "https::::") is the same as
providing a value of "https".
4. [10551]Update href.
The username getter steps are:
1. [10552]Reinitialize url.
2. If [10553]this's [10554]url is null, return the empty string.
3. Return [10555]this's [10556]url's [10557]username.
The [10558]username setter steps are:
1. [10559]Reinitialize url.
2. Let url be [10560]this's [10561]url.
3. If url is null or url [10562]cannot have a username/password/port,
then return.
4. [10563]Set the username, given url and the given value.
5. [10564]Update href.
The password getter steps are:
1. [10565]Reinitialize url.
2. Let url be [10566]this's [10567]url.
3. If url is null, then return the empty string.
4. Return url's [10568]password.
The [10569]password setter steps are:
1. [10570]Reinitialize url.
2. Let url be [10571]this's [10572]url.
3. If url is null or url [10573]cannot have a username/password/port,
then return.
4. [10574]Set the password, given url and the given value.
5. [10575]Update href.
The host getter steps are:
1. [10576]Reinitialize url.
2. Let url be [10577]this's [10578]url.
3. If url or url's [10579]host is null, return the empty string.
4. If url's [10580]port is null, return url's [10581]host,
[10582]serialized.
5. Return url's [10583]host, [10584]serialized, followed by ":" and
url's [10585]port, [10586]serialized.
The [10587]host setter steps are:
1. [10588]Reinitialize url.
2. Let url be [10589]this's [10590]url.
3. If url is null or url has an [10591]opaque path, then return.
4. [10592]Basic URL parse the given value, with url as [10593]url and
[10594]host state as [10595]state override.
5. [10596]Update href.
The hostname getter steps are:
1. [10597]Reinitialize url.
2. Let url be [10598]this's [10599]url.
3. If url or url's [10600]host is null, return the empty string.
4. Return url's [10601]host, [10602]serialized.
The [10603]hostname setter steps are:
1. [10604]Reinitialize url.
2. Let url be [10605]this's [10606]url.
3. If url is null or url has an [10607]opaque path, then return.
4. [10608]Basic URL parse the given value, with url as [10609]url and
[10610]hostname state as [10611]state override.
5. [10612]Update href.
The port getter steps are:
1. [10613]Reinitialize url.
2. Let url be [10614]this's [10615]url.
3. If url or url's [10616]port is null, return the empty string.
4. Return url's [10617]port, [10618]serialized.
The [10619]port setter steps are:
1. [10620]Reinitialize url.
2. Let url be [10621]this's [10622]url.
3. If url is null or url [10623]cannot have a username/password/port,
then return.
4. If the given value is the empty string, then set url's [10624]port
to null.
5. Otherwise, [10625]basic URL parse the given value, with url as
[10626]url and [10627]port state as [10628]state override.
6. [10629]Update href.
The pathname getter steps are:
1. [10630]Reinitialize url.
2. Let url be [10631]this's [10632]url.
3. If url is null, then return the empty string.
4. Return the result of [10633]URL path serializing url.
The [10634]pathname setter steps are:
1. [10635]Reinitialize url.
2. Let url be [10636]this's [10637]url.
3. If url is null or url has an [10638]opaque path, then return.
4. Set url's [10639]path to the empty list.
5. [10640]Basic URL parse the given value, with url as [10641]url and
[10642]path start state as [10643]state override.
6. [10644]Update href.
The search getter steps are:
1. [10645]Reinitialize url.
2. Let url be [10646]this's [10647]url.
3. If url is null, or url's [10648]query is either null or the empty
string, return the empty string.
4. Return "?", followed by url's [10649]query.
The [10650]search setter steps are:
1. [10651]Reinitialize url.
2. Let url be [10652]this's [10653]url.
3. If url is null, terminate these steps.
4. If the given value is the empty string, set url's [10654]query to
null.
5. Otherwise:
1. Let input be the given value with a single leading "?"
removed, if any.
2. Set url's [10655]query to the empty string.
3. [10656]Basic URL parse input, with url as [10657]url and
[10658]query state as [10659]state override.
6. [10660]Update href.
The hash getter steps are:
1. [10661]Reinitialize url.
2. Let url be [10662]this's [10663]url.
3. If url is null, or url's [10664]fragment is either null or the
empty string, return the empty string.
4. Return "#", followed by url's [10665]fragment.
The [10666]hash setter steps are:
1. [10667]Reinitialize url.
2. Let url be [10668]this's [10669]url.
3. If url is null, then return.
4. If the given value is the empty string, set url's [10670]fragment
to null.
5. Otherwise:
1. Let input be the given value with a single leading "#"
removed, if any.
2. Set url's [10671]fragment to the empty string.
3. [10672]Basic URL parse input, with url as [10673]url and
[10674]fragment state as [10675]state override.
6. [10676]Update href.
4.6.4 Following hyperlinks
An element element cannot navigate if any of the following are true:
* element's [10677]node document is not [10678]fully active; or
* element is not an [10679]a element and is not [10680]connected.
This is also used by [10681]form submission for the [10682]form
element. The exception for [10683]a elements is for compatibility with
web content.
To get an element's noopener, given an [10684]a, [10685]area, or
[10686]form element element, a [10687]URL record url, and a string
target, perform the following steps. They return a boolean.
1. If element's [10688]link types include the [10689]noopener or
[10690]noreferrer keyword, then return true.
2. If element's [10691]link types do not include the [10692]opener
keyword and target is an [10693]ASCII case-insensitive match for
"_blank", then return true.
3. If url's [10694]blob URL entry is not null:
1. Let blobOrigin be url's [10695]blob URL entry's
[10696]environment's [10697]origin.
2. Let topLevelOrigin be element's [10698]relevant settings
object's [10699]top-level origin.
3. If blobOrigin is not [10700]same site with topLevelOrigin,
then return true.
4. Return false.
To follow the hyperlink created by an element subject, given an
optional hyperlinkSuffix (default null) and an optional userInvolvement
(default "[10701]none"):
1. If subject [10702]cannot navigate, then return.
2. Let targetAttributeValue be the empty string.
3. If subject is an [10703]a or [10704]area element, then set
targetAttributeValue to the result of [10705]getting an element's
target given subject.
4. Let urlRecord be the result of [10706]encoding-parsing a URL given
subject's [10707]href attribute value, relative to subject's
[10708]node document.
5. If urlRecord is failure, then return.
6. Let noopener be the result of [10709]getting an element's noopener
with subject, urlRecord, and targetAttributeValue.
7. Let targetNavigable be the first return value of applying
[10710]the rules for choosing a navigable given
targetAttributeValue, subject's [10711]node navigable, and
noopener.
8. If targetNavigable is null, then return.
9. Let urlString be the result of applying the [10712]URL serializer
to urlRecord.
10. If hyperlinkSuffix is non-null, then append it to urlString.
11. Let referrerPolicy be the current state of subject's referrerpolicy
content attribute.
12. If subject's [10713]link types includes the [10714]noreferrer
keyword, then set referrerPolicy to "no-referrer".
13. [10715]Navigate targetNavigable to urlString using subject's
[10716]node document, with [10717]referrerPolicy set to
referrerPolicy, [10718]userInvolvement set to userInvolvement, and
[10719]sourceElement set to subject.
Unlike many other types of navigations, following hyperlinks does
not have special "[10720]replace" behavior for when documents are
not [10721]completely loaded. This is true for both user-initiated
instances of following hyperlinks, as well as script-triggered ones
via, e.g., aElement.click().
4.6.5 Downloading resources
(BUTTON) ✔MDN
[10722]HTMLAnchorElement/download
Support in all current engines.
Firefox20+Safari10.1+Chrome15+
__________________________________________________________________
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
[10723]download attribute can be specified on the [10724]a or
[10725]area element that creates the [10726]hyperlink to that resource.
The attribute can furthermore be given a value, to specify the filename
that user agents are to use when storing the resource in a file system.
This value can be overridden by the `[10727]Content-Disposition` HTTP
header's filename parameters. [10728][RFC6266]
In cross-origin situations, the [10729]download attribute has to be
combined with the `[10730]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.)
__________________________________________________________________
To download the hyperlink created by an element subject, given an
optional hyperlinkSuffix (default null) and an optional userInvolvement
(default "[10731]none"):
1. If subject [10732]cannot navigate, then return.
2. If subject's [10733]node document's [10734]active sandboxing flag
set has the [10735]sandboxed downloads browsing context flag set,
then return.
3. Let urlString be the result of
[10736]encoding-parsing-and-serializing a URL given subject's
[10737]href attribute value, relative to subject's [10738]node
document.
4. If urlString is failure, then return.
5. If hyperlinkSuffix is non-null, then append it to urlString.
6. If userInvolvement is not "[10739]browser UI", then:
1. [10740]Assert: subject has a [10741]download attribute.
2. Let navigation be subject's [10742]relevant global object's
[10743]navigation API.
3. Let filename be the value of subject's [10744]download
attribute.
4. Let continue be the result of [10745]firing a download request
navigate event at navigation with [10746]destinationURL set to
urlString, [10747]userInvolvement set to userInvolvement,
[10748]sourceElement set to subject, and [10749]filename set
to filename.
5. If continue is false, then return.
7. Run these steps [10750]in parallel:
1. Optionally, the user agent may abort these steps, if it
believes doing so would safeguard the user from a potentially
hostile download.
2. Let request be a new [10751]request whose [10752]URL is
urlString, [10753]client is [10754]entry settings object,
[10755]initiator is "download", [10756]destination is the
empty string, and whose [10757]synchronous flag and
[10758]use-URL-credentials flag are set.
3. [10759]Handle as a download the result of [10760]fetching
request.
To handle as a download a [10761]response response:
1. Let suggestedFilename be the result of [10762]getting the suggested
filename for response.
2. Provide the user with a way to save response for later use. If the
user agent needs a filename, it should use suggestedFilename.
Report any problems downloading the file to the user.
3. Return suggestedFilename.
To get the suggested filename for a [10763]response response:
This algorithm is intended to mitigate security dangers involved in
downloading files from untrusted sites, and user agents are strongly
urged to follow it.
1. Let filename be the undefined value.
2. If response has a `[10764]Content-Disposition` header, that header
specifies the attachment disposition type, and the header includes
filename information, then let filename have the value specified by
the header, and jump to the step labeled sanitize below.
[10765][RFC6266]
3. Let interface origin be the [10766]origin of the [10767]Document in
which the [10768]download or [10769]navigate action resulting in
the download was initiated, if any.
4. Let response origin be the [10770]origin of the URL of response,
unless that URL's [10771]scheme component is data, in which case
let response origin be the same as the interface origin, if any.
5. If there is no interface origin, then let trusted operation be
true. Otherwise, let trusted operation be true if response origin
is the [10772]same origin as interface origin, and false otherwise.
6. If trusted operation is true and response has a
`[10773]Content-Disposition` header and that header includes
filename information, then let filename have the value specified by
the header, and jump to the step labeled sanitize below.
[10774][RFC6266]
7. If the download was not initiated from a [10775]hyperlink created
by an [10776]a or [10777]area element, or if the element of the
[10778]hyperlink from which it was initiated did not have a
[10779]download attribute when the download was initiated, or if
there was such an attribute but its value when the download was
initiated was the empty string, then jump to the step labeled no
proposed filename.
8. Let proposed filename have the value of the [10780]download
attribute of the element of the [10781]hyperlink that initiated the
download at the time the download was initiated.
9. If trusted operation is true, let filename have the value of
proposed filename, and jump to the step labeled sanitize below.
10. If response has a `[10782]Content-Disposition` header and that
header specifies the attachment disposition type, let filename have
the value of proposed filename, and jump to the step labeled
sanitize below. [10783][RFC6266]
11. No proposed filename: If trusted operation is true, or if the user
indicated a preference for having the response in question
downloaded, let filename have a value derived from the [10784]URL
of response in an [10785]implementation-defined manner, and jump to
the step labeled sanitize below.
12. Let filename be set to the user's preferred filename or to a
filename selected by the user agent, and jump to the step labeled
sanitize below.
If the algorithm reaches this step, then a download was begun from
a different origin than response, and the origin did not mark the
file as suitable for downloading, and the download was not
initiated by the user. This could be because a [10786]download
attribute was used to trigger the download, or because response is
not of a type that the user agent supports.
This could be dangerous, because, for instance, a hostile server
could be trying to get a user to unknowingly download private
information and then re-upload it to the hostile server, by
tricking the user into thinking the data is from the hostile
server.
Thus, it is in the user's interests that the user be somehow
notified that response comes from quite a different source, and to
prevent confusion, any suggested filename from the potentially
hostile interface origin should be ignored.
13. Sanitize: Optionally, allow the user to influence filename. For
example, a user agent could prompt the user for a filename,
potentially providing the value of filename as determined above as
a default value.
14. Adjust filename to be suitable for the local file system.
For example, this could involve removing characters that are not
legal in filenames, or trimming leading and trailing whitespace.
15. If the platform conventions do not in any way use [10787]extensions
to determine the types of file on the file system, then return
filename as the filename.
16. Let claimed type be the type given by response's
[10788]Content-Type metadata, if any is known. Let named type be
the type given by filename's [10789]extension, if any is known. For
the purposes of this step, a type is a mapping of a [10790]MIME
type to an [10791]extension.
17. If named type is consistent with the user's preferences (e.g.,
because the value of filename was determined by prompting the
user), then return filename as the filename.
18. If claimed type and named type are the same type (i.e., the type
given by response's [10792]Content-Type metadata is consistent with
the type given by filename's [10793]extension), then return
filename as the filename.
19. If the claimed type is known, then alter filename to add an
[10794]extension corresponding to claimed type.
Otherwise, if named type is known to be potentially dangerous (e.g.
it will be treated by the platform conventions as a native
executable, shell script, HTML application, or
executable-macro-capable document) then optionally alter filename
to add a known-safe [10795]extension (e.g. ".txt").
This last step would make it impossible to download executables,
which might not be desirable. As always, implementers are forced to
balance security and usability in this matter.
20. Return filename as the filename.
For the purposes of this algorithm, a file extension consists of any
part of the filename that platform conventions dictate will be used for
identifying the type of the file. For example, many operating systems
use the part of the filename following the last dot (".") in the
filename to determine the type of the file, and from that the manner in
which the file is to be opened or executed.
User agents should ignore any directory or path information provided by
the response itself, its [10796]URL, and any [10797]download attribute,
in deciding where to store the resulting file in the user's file
system.
4.6.6 Hyperlink auditing
If a [10798]hyperlink created by an [10799]a or [10800]area element has
a [10801]ping attribute, and the user follows the hyperlink, and the
value of the element's [10802]href attribute can be [10803]parsed,
relative to the element's [10804]node document, without failure, then
the user agent must take the [10805]ping attribute's value,
[10806]split that string on ASCII whitespace, [10807]parse each
resulting token, relative to the element's [10808]node document, and
then run these steps for each resulting [10809]URL ping URL, ignoring
when parsing returns failure:
1. If ping URL's [10810]scheme is not an [10811]HTTP(S) scheme, then
return.
2. Optionally, return. (For example, the user agent might wish to
ignore any or all ping URLs in accordance with the user's expressed
preferences.)
3. Let settingsObject be the element's [10812]node document's
[10813]relevant settings object.
4. Let request be a new [10814]request whose [10815]URL is ping URL,
[10816]method is `POST`, [10817]header list is «
(`[10818]Content-Type`, `[10819]text/ping`) », [10820]body is
`PING`, [10821]client is settingsObject, [10822]destination is the
empty string, [10823]credentials mode is "include", [10824]referrer
is "no-referrer", and whose [10825]use-URL-credentials flag is set,
and whose [10826]initiator type is "ping".
5. Let target URL be the result of
[10827]encoding-parsing-and-serializing a URL given the element's
[10828]href attribute's value, relative to the element's
[10829]node document, and then:
If the [10830]URL of the [10831]Document object containing the
hyperlink being audited and ping URL have the [10832]same
origin
If the origins are different, but the [10833]scheme of the
[10834]URL of the [10835]Document containing the hyperlink
being audited is not "https"
request must include a `[10836]Ping-From` header with, as
its value, the [10837]URL of the document containing the
hyperlink, and a `[10838]Ping-To` HTTP header with, as its
value, the target URL.
Otherwise
request must include a `[10839]Ping-To` HTTP header with,
as its value, target URL. request does not include a
`[10840]Ping-From` header.
6. [10841]Fetch request.
This may be done [10842]in parallel with the primary fetch, and is
independent of the result of that fetch.
User agents should allow the user to adjust this behavior, for example
in conjunction with a setting that disables the sending of HTTP
`[10843]Referer` (sic) headers. Based on the user's preferences, UAs
may either [10844]ignore the [10845]ping attribute altogether, or
selectively ignore URLs in the list (e.g. ignoring any third-party
URLs); this is explicitly accounted for in the steps above.
User agents must ignore any entity bodies returned in the responses.
User agents may close the connection prematurely once they start
receiving a response body.
When the [10846]ping attribute is present, user agents should clearly
indicate to the user that following the hyperlink will also cause
secondary requests to be sent in the background, possibly including
listing the actual target URLs.
For example, a visual user agent could include the hostnames of the
target ping URLs along with the hyperlink's actual URL in a status bar
or tooltip.
The [10847]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 [10848]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 [10849]ping attribute so that the user agent
can make the user experience more transparent.
4.6.6.1 The `[10850]Ping-From` and `[10851]Ping-To` headers
The `Ping-From` and `Ping-To` HTTP request headers are included in
[10852]hyperlink auditing requests. Their value is a [10853]URL,
[10854]serialized.
4.6.7 Link types
(BUTTON) ✔MDN
[10855]Link_types
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
The following table summarizes the link types that are defined by this
specification, by their corresponding keywords. 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.
To determine which link types apply to a [10857]link, [10858]a,
[10859]area, or [10860]form element, the element's rel attribute must
be [10861]split on ASCII whitespace. The resulting tokens are the
keywords for the link types that apply to that element.
Except where otherwise specified, a keyword must not be specified more
than once per [10862]rel attribute.
Some of the sections that follow the table below list synonyms for
certain keywords. The indicated synonyms are to be handled as specified
by user agents, but must not be used in documents (for example, the
keyword "copyright").
Keywords are always [10863]ASCII case-insensitive, and must be compared
as such.
Thus, rel="next" is the same as rel="NEXT".
Keywords that are body-ok affect whether [10864]link elements are
[10865]allowed in the body. The [10866]body-ok keywords are
[10867]dns-prefetch, [10868]modulepreload, [10869]pingback,
[10870]preconnect, [10871]prefetch, [10872]preload, and
[10873]stylesheet.
New link types that are to be implemented by web browsers are to be
added to this standard. The remainder can be [10874]registered as
extensions.
Link type Effect on... [10875]body-ok Has `[10876]Link` processing
Brief description
[10877]link [10878]a and [10879]area [10880]form
[10881]alternate [10882]Hyperlink not allowed · · Gives alternate
representations of the current document.
[10883]canonical [10884]Hyperlink not allowed · · Gives the preferred
URL for the current document.
[10885]author [10886]Hyperlink not allowed · · Gives a link to the
author of the current document or article.
[10887]bookmark not allowed [10888]Hyperlink not allowed · · Gives the
permalink for the nearest ancestor section.
[10889]dns-prefetch [10890]External Resource not allowed Yes ·
Specifies that the user agent should preemptively perform DNS
resolution for the target resource's [10891]origin.
[10892]expect [10893]Internal Resource not allowed · · Expect an
element with the target ID to appear in the current document.
[10894]external not allowed [10895]Annotation · · Indicates that the
referenced document is not part of the same site as the current
document.
[10896]help [10897]Hyperlink · · Provides a link to context-sensitive
help.
[10898]icon [10899]External Resource not allowed · · Imports an icon to
represent the current document.
[10900]manifest [10901]External Resource not allowed · · Imports or
links to an [10902]application manifest. [10903][MANIFEST]
[10904]modulepreload [10905]External Resource not allowed Yes ·
Specifies that the user agent must preemptively [10906]fetch the module
script and store it in the document's [10907]module map for later
evaluation. Optionally, the module's dependencies can be fetched as
well.
[10908]license [10909]Hyperlink · · Indicates that the main content of
the current document is covered by the copyright license described by
the referenced document.
[10910]next [10911]Hyperlink · · Indicates that the current document is
a part of a series, and that the next document in the series is the
referenced document.
[10912]nofollow not allowed [10913]Annotation · · Indicates that the
current document's original author or publisher does not endorse the
referenced document.
[10914]noopener not allowed [10915]Annotation · · Creates a
[10916]top-level traversable with a non-[10917]auxiliary browsing
context if the hyperlink would otherwise create one that was auxiliary
(i.e., has an appropriate [10918]target attribute value).
[10919]noreferrer not allowed [10920]Annotation · · No `[10921]Referer`
(sic) header will be included. Additionally, has the same effect as
[10922]noopener.
[10923]opener not allowed [10924]Annotation · · Creates an
[10925]auxiliary browsing context if the hyperlink would otherwise
create a [10926]top-level traversable with a non-[10927]auxiliary
browsing context (i.e., has "_blank" as [10928]target attribute value).
[10929]pingback [10930]External Resource not allowed Yes · Gives the
address of the pingback server that handles pingbacks to the current
document.
[10931]preconnect [10932]External Resource not allowed Yes Yes
Specifies that the user agent should preemptively connect to the target
resource's [10933]origin.
[10934]prefetch [10935]External Resource not allowed Yes · Specifies
that the user agent should preemptively [10936]fetch and cache the
target resource as it is likely to be required for a followup
[10937]navigation.
[10938]preload [10939]External Resource not allowed Yes Yes Specifies
that the user agent must preemptively [10940]fetch and cache the target
resource for current [10941]navigation according to the
[10942]potential destination given by the [10943]as attribute (and the
[10944]priority associated with the [10945]corresponding
[10946]destination).
[10947]prev [10948]Hyperlink · · Indicates that the current document is
a part of a series, and that the previous document in the series is the
referenced document.
[10949]privacy-policy [10950]Hyperlink not allowed · · Gives a link to
information about the data collection and usage practices that apply to
the current document.
[10951]search [10952]Hyperlink · · Gives a link to a resource that can
be used to search through the current document and its related pages.
[10953]stylesheet [10954]External Resource not allowed Yes · Imports a
style sheet.
[10955]tag not allowed [10956]Hyperlink not allowed · · Gives a tag
(identified by the given address) that applies to the current document.
[10957]terms-of-service [10958]Hyperlink not allowed · · Gives a link
to information about the agreements between the current document's
provider and users who wish to use the current document.
4.6.7.1 Link type "alternate"
(BUTTON) ⚠MDN
[10959]Alternative_style_sheets
Support in one engine only.
Firefox3+Safari?Chrome1–48
__________________________________________________________________
The [10960]alternate keyword may be used with [10961]link, [10962]a,
and [10963]area elements.
The meaning of this keyword depends on the values of the other
attributes.
If the element is a [10964]link element and the [10965]rel attribute
also contains the keyword [10966]stylesheet
The [10967]alternate keyword modifies the meaning of the
[10968]stylesheet keyword in the way described for that keyword.
The [10969]alternate keyword does not create a link of its own.
Here, a set of [10970]link elements provide some style sheets:
If the [10971]alternate keyword is used with the [10972]type attribute
set to the value application/rss+xml or the value
application/atom+xml
The keyword creates a [10973]hyperlink referencing a syndication
feed (though not necessarily syndicating exactly the same
content as the current page).
For the purposes of feed autodiscovery, user agents should
consider all [10974]link elements in the document with the
[10975]alternate keyword used and with their [10976]type
attribute set to the value application/rss+xml or the value
application/atom+xml. If the user agent has the concept of a
default syndication feed, the first such element (in [10977]tree
order) should be used as the default.
The following [10978]link elements give syndication feeds for a
blog:
Such [10979]link elements would be used by user agents engaged
in feed autodiscovery, with the first being the default (where
applicable).
The following example offers various different syndication feeds
to the user, using [10980]a elements:
You can access the planets database using Atom feeds:
These links would not be used in feed autodiscovery.
Otherwise
The keyword creates a [10981]hyperlink referencing an alternate
representation of the current document.
The nature of the referenced document is given by the
[10982]hreflang, and [10983]type attributes.
If the [10984]alternate keyword is used with the [10985]hreflang
attribute, and that attribute's value differs from the
[10986]document element's [10987]language, it indicates that the
referenced document is a translation.
If the [10988]alternate keyword is used with the [10989]type
attribute, it indicates that the referenced document is a
reformulation of the current document in the specified format.
The [10990]hreflang and [10991]type attributes can be combined
when specified with the [10992]alternate keyword.
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:
This relationship is transitive — that is, if a document links
to two other documents with the link type "[10993]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.
4.6.7.2 Link type "author"
The [10994]author keyword may be used with [10995]link, [10996]a, and
[10997]area elements. This keyword creates a [10998]hyperlink.
For [10999]a and [11000]area elements, the [11001]author keyword
indicates that the referenced document provides further information
about the author of the nearest [11002]article element ancestor of the
element defining the hyperlink, if there is one, or of the page as a
whole, otherwise.
For [11003]link elements, the [11004]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 [11005]mailto: URL
giving the email address of the author. [11006][MAILTO]
Synonyms: For historical reasons, user agents must also treat
[11007]link, [11008]a, and [11009]area elements that have a rev
attribute with the value "made" as having the [11010]author keyword
specified as a link relationship.
4.6.7.3 Link type "bookmark"
The [11011]bookmark keyword may be used with [11012]a and [11013]area
elements. This keyword creates a [11014]hyperlink.
The [11015]bookmark keyword gives a permalink for the nearest ancestor
[11016]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 [11017]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.
...
The [11018]canonical keyword may be used with [11019]link element. This
keyword creates a [11020]hyperlink.
The [11021]canonical keyword indicates that URL given by the
[11022]href attribute is the preferred URL for the current document.
That helps search engines reduce duplicate content, as described in
more detail in The Canonical Link Relation. [11023][RFC6596]
The [11025]dns-prefetch keyword may be used with [11026]link elements.
This keyword creates an [11027]external resource link. This keyword is
[11028]body-ok.
The [11029]dns-prefetch keyword indicates that preemptively performing
DNS resolution for the [11030]origin of the specified resource is
likely to be beneficial, as it is highly likely that the user will
require resources located at that [11031]origin, and the user
experience would be improved by preempting the latency costs associated
with DNS resolution.
There is no default type for resources given by the [11032]dns-prefetch
keyword.
The appropriate times to [11033]fetch and process this type of link
are:
* When the [11034]external resource link is created on a [11035]link
element that is already [11036]browsing-context connected.
* When the [11037]external resource link's [11038]link element
[11039]becomes browsing-context connected.
* When the [11040]href attribute of the [11041]link element of an
[11042]external resource link that is already
[11043]browsing-context connected is changed.
The [11044]fetch and process the linked resource steps for this type of
linked resource, given a [11045]link element el, are:
1. Let url be the result of [11046]encoding-parsing a URL given el's
[11047]href attribute's value, relative to el's [11048]node
document.
2. If url is failure, then return.
3. Let partitionKey be the result of [11049]determining the network
partition key given el's [11050]node document's [11051]relevant
settings object.
4. The user agent should [11052]resolve an origin given partitionKey
and url's [11053]origin.
As the results of this algorithm can be cached, future fetches
could be faster.
4.6.7.6 Link type "expect"
The [11054]expect keyword may be used with [11055]link elements. This
keyword creates an [11056]internal resource link.
An [11057]internal resource link created by the [11058]expect keyword
can be used to [11059]block rendering until the element that it
[11060]indicates is connected to the document and fully parsed.
There is no default type for resources given by the [11061]expect
keyword.
Whenever any of the following conditions occur for a [11062]link
element el:
* the [11063]expect [11064]internal resource link is created on el
that is already [11065]browsing-context connected;
* an [11066]expect [11067]internal resource link has been created on
el and el becomes [11068]browsing-context connected;
* an [11069]expect[11070]internal resource link has been created on
el, el is already [11071]browsing-context connected, and el's
[11072]href attribute is set, changed, or removed; or
* an [11073]expect [11074]internal resource link has been created on
el, el is already [11075]browsing-context connected, and el's
[11076]media attribute is set, changed, or removed,
then [11077]process el.
To process internal resource link given a [11078]link element el, run
these steps:
1. Let doc be el's [11079]node document.
2. Let url be the result of [11080]encoding-parsing a URL given el's
[11081]href attribute's value, relative to doc.
3. If this fails, or if url does not [11082]equal doc's [11083]URL
with [11084]exclude fragments set to false, then [11085]unblock
rendering on el and return.
4. Let indicatedElement be the result of [11086]selecting the
indicated part given doc and url.
5. If all of the following are true:
+ doc's [11087]current document readiness is "loading";
+ el creates an [11088]internal resource link;
+ el is [11089]browsing-context connected;
+ el's [11090]rel attribute contains [11091]expect;
+ el is [11092]potentially render-blocking;
+ el's [11093]media attribute [11094]matches the environment;
and
+ indicatedElement is not an element, or is on a [11095]stack of
open elements of an [11096]HTML parser whose associated
[11097]Document is doc,
then [11098]block rendering on el.
6. Otherwise, [11099]unblock rendering on el.
To process internal resource links given a [11100]Document doc:
1. [11101]For each [11102]expect [11103]link element link in doc's
[11104]render-blocking element set, [11105]process link.
The following [11106]attribute change steps, given element, localName,
value, and namespace, are used to ensure [11107]expect [11108]link
elements respond to dynamic [11109]id and [11110]name changes:
1. If namespace is not null, then return.
2. If element is in a [11111]stack of open elements of an [11112]HTML
parser, then return.
3. If any of the following is true:
+ localName is [11113]id; or
+ localName is [11114]name and element is an [11115]a element,
then [11116]process internal resource links given element's
[11117]node document.
4.6.7.7 Link type "external"
The [11118]external keyword may be used with [11119]a, [11120]area, and
[11121]form elements. This keyword does not create a [11122]hyperlink,
but [11123]annotates any other hyperlinks created by the element (the
implied hyperlink, if no other keywords create one).
The [11124]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.
4.6.7.8 Link type "help"
The [11125]help keyword may be used with [11126]link, [11127]a,
[11128]area, and [11129]form elements. This keyword creates a
[11130]hyperlink.
For [11131]a, [11132]area, and [11133]form elements, the [11134]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.
For [11135]link elements, the [11136]help keyword indicates that the
referenced document provides help for the page as a whole.
For [11137]a and [11138]area elements, on some browsers, the
[11139]help keyword causes the link to use a different cursor.
4.6.7.9 Link type "icon"
(BUTTON) ✔MDN
[11140]Link_types#icon
Support in all current engines.
Firefox2+Safari3.1+Chrome4+
__________________________________________________________________
The [11142]icon keyword may be used with [11143]link elements. This
keyword creates an [11144]external resource link.
The specified resource is an icon representing the page or site, and
should be used by the user agent when representing the page in the user
interface.
Icons could be auditory icons, visual icons, or other kinds of icons.
If multiple icons are provided, the user agent must select the most
appropriate icon according to the [11145]type, [11146]media, and
[11147]sizes attributes. If there are multiple equally appropriate
icons, user agents must use the last one declared in [11148]tree order
at the time that the user agent collected the list of icons. If the
user agent tries to use an icon but that icon is determined, upon
closer examination, to in fact be inappropriate (e.g. because it uses
an unsupported format), then the user agent must try the
next-most-appropriate icon as determined by the attributes.
User agents are not required to update icons when the list of icons
changes, but are encouraged to do so.
There is no default type for resources given by the [11149]icon
keyword. However, for the purposes of [11150]determining the type of
the resource, user agents must expect the resource to be an image.
The [11151]sizes keywords represent icon sizes in raw pixels (as
opposed to [11152]CSS pixels).
An icon that is 50 [11153]CSS pixels wide intended for displays with a
device pixel density of two device pixels per [11154]CSS pixel (2x,
192dpi) would have a width of 100 raw pixels. This feature does not
support indicating that a different resource is to be used for small
high-resolution icons vs large low-resolution icons (e.g. 50×50 2x vs
100×100 1x).
To parse and process the attribute's value, the user agent must first
[11155]split the attribute's value on ASCII whitespace, and must then
parse each resulting keyword to determine what it represents.
The any keyword represents that the resource contains a scalable icon,
e.g. as provided by an SVG image.
Other keywords must be further parsed as follows to determine what they
represent:
1. If the keyword doesn't contain exactly one U+0078 LATIN SMALL
LETTER X or U+0058 LATIN CAPITAL LETTER X character, then this
keyword doesn't represent anything. Return for that keyword.
2. Let width string be the string before the "x" or "X".
3. Let height string be the string after the "x" or "X".
4. If either width string or height string start with a U+0030 DIGIT
ZERO (0) character or contain any characters other than
[11156]ASCII digits, then this keyword doesn't represent anything.
Return for that keyword.
5. Apply the [11157]rules for parsing non-negative integers to width
string to obtain width.
6. Apply the [11158]rules for parsing non-negative integers to height
string to obtain height.
7. The keyword represents that the resource contains a bitmap icon
with a width of width device pixels and a height of height device
pixels.
The keywords specified on the [11159]sizes attribute must not represent
icon sizes that are not actually available in the linked resource.
The [11160]linked resource fetch setup steps for this type of linked
resource, given a [11161]link element el and [11162]request request,
are:
1. Set request's [11163]destination to "image".
2. Return true.
The [11164]process a link header steps for this type of linked resource
are to do nothing.
In the absence of a [11165]link with the [11166]icon keyword, for
[11167]Document objects whose [11168]URL's [11169]scheme is an
[11170]HTTP(S) scheme, user agents may instead run these steps
[11171]in parallel:
1. Let request be a new [11172]request whose [11173]URL is the
[11174]URL record obtained by resolving the [11175]URL
"/favicon.ico" against the [11176]Document object's [11177]URL,
[11178]client is the [11179]Document object's [11180]relevant
settings object, [11181]destination is "image", [11182]synchronous
flag is set, [11183]credentials mode is "include", and whose
[11184]use-URL-credentials flag is set.
2. Let response be the result of [11185]fetching request.
3. Use response's [11186]unsafe response as an icon as if it had been
declared using the [11187]icon keyword.
The following snippet shows the top part of an application with several
icons.
lsForums — Inbox
...
For historical reasons, the [11188]icon keyword may be preceded by the
keyword "shortcut". If the "shortcut" keyword is present, the
[11189]rel attribute's entire value must be an [11190]ASCII
case-insensitive match for the string "shortcut icon" (with a single
U+0020 SPACE character between the tokens and no other [11191]ASCII
whitespace).
4.6.7.10 Link type "license"
The [11192]license keyword may be used with [11193]link, [11194]a,
[11195]area, and [11196]form elements. This keyword creates a
[11197]hyperlink.
The [11198]license keyword indicates that the referenced document
provides the copyright license terms under which the main content of
the current document is provided.
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:
In this case the [11199]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).
Synonyms: For historical reasons, user agents must also treat the
keyword "copyright" like the [11200]license keyword.
4.6.7.11 Link type "manifest"
(BUTTON) ⚠MDN
[11201]Link_types/manifest
Support in one engine only.
Firefox?Safari?ChromeNo
__________________________________________________________________
The [11202]manifest keyword may be used with [11203]link elements. This
keyword creates an [11204]external resource link.
The [11205]manifest keyword indicates the manifest file that provides
metadata associated with the current document.
There is no default type for resources given by the [11206]manifest
keyword.
When a web application is not [11207]installed, the appropriate time to
[11208]fetch and process the linked resource for this link type is when
the user agent deems it necessary. For example, when the user chooses
to [11209]install the web application.
For an [11210]installed web application, the appropriate times to
[11211]fetch and process the linked resource for this link type are:
* When the [11212]external resource link is created on a [11213]link
element that is already [11214]browsing-context connected.
* When the [11215]external resource link's [11216]link element
[11217]becomes browsing-context connected.
* When the [11218]href attribute of the [11219]link element of an
[11220]external resource link that is already
[11221]browsing-context connected is changed.
In any case, only the first [11222]link element in [11223]tree order
whose [11224]rel attribute contains the token [11225]manifest may be
used.
A user agent must not [11226]delay the load event for this link type.
The [11227]linked resource fetch setup steps for this type of linked
resource, given a [11228]link element el and [11229]request request,
are:
1. Let navigable be el's [11230]node document's [11231]node navigable.
2. If navigable is null, then return false.
3. If navigable is not a [11232]top-level traversable, then return
false.
4. Set request's [11233]initiator to "manifest".
5. Set request's [11234]destination to "manifest".
6. Set request's [11235]mode to "cors".
7. Set request's [11236]credentials mode to the [11237]CORS settings
attribute credentials mode for el's [11238]crossorigin content
attribute.
8. Return true.
To [11239]process this type of linked resource given a [11240]link
element el, boolean success, [11241]response response, and [11242]byte
sequence bodyBytes:
1. If response's [11243]Content-Type metadata is not a [11244]JSON
MIME type, then set success to false.
2. If success is true:
1. Let document URL be el's [11245]node document's [11246]URL.
2. Let manifest URL be response's [11247]URL.
3. [11248]Process the manifest given document URL, manifest URL,
and bodyBytes. [11249][MANIFEST]
The [11250]process a link header steps for this type of linked resource
are to do nothing.
The [11252]modulepreload keyword may be used with [11253]link elements.
This keyword creates an [11254]external resource link. This keyword is
[11255]body-ok.
The [11256]modulepreload keyword is a specialized alternative to the
[11257]preload keyword, with a processing model geared toward
preloading [11258]module scripts. In particular, it uses the specific
fetch behavior for module scripts (including, e.g., a different
interpretation of the [11259]crossorigin attribute), and places the
result into the appropriate [11260]module map for later evaluation. In
contrast, a similar [11261]external resource link using the
[11262]preload keyword would place the result in the preload cache,
without affecting the document's [11263]module map.
Additionally, implementations can take advantage of the fact that
[11264]module scripts declare their dependencies in order to fetch the
specified module's dependency as well. This is intended as an
optimization opportunity, since the user agent knows that, in all
likelihood, those dependencies will also be needed later. It will not
generally be observable without using technology such as service
workers, or monitoring on the server side. Notably, the appropriate
[11265]load or [11266]error events will occur after the specified
module is fetched, and will not wait for any dependencies.
A user agent must not [11267]delay the load event for this link type.
The appropriate times to [11268]fetch and process the linked resource
for such a link are:
* When the [11269]external resource link is created on a [11270]link
element that is already [11271]browsing-context connected.
* When the [11272]external resource link's [11273]link element
[11274]becomes browsing-context connected.
* When the [11275]href attribute of the [11276]link element of an
[11277]external resource link that is already
[11278]browsing-context connected is changed.
Unlike some other link relations, changing the relevant attributes
(such as [11279]as, [11280]crossorigin, and [11281]referrerpolicy) of
such a [11282]link does not trigger a new fetch. This is because the
document's [11283]module map has already been populated by a previous
fetch, and so re-fetching would be pointless.
The [11284]fetch and process the linked resource algorithm for
[11285]modulepreload links, given a [11286]link element el, is as
follows:
1. If el's [11287]href attribute's value is the empty string, then
return.
2. Let destination be the current state of el's [11288]as attribute (a
[11289]destination), or "script" if it is in no state.
3. If destination is not [11290]script-like, then [11291]queue an
element task on the [11292]networking task source given el to
[11293]fire an event named [11294]error at el, and return.
4. Let url be the result of [11295]encoding-parsing a URL given el's
[11296]href attribute's value, relative to el's [11297]node
document.
5. If url is failure, then return.
6. Let settings object be el's [11298]node document's [11299]relevant
settings object.
7. Let credentials mode be the [11300]CORS settings attribute
credentials mode for el's [11301]crossorigin attribute.
8. Let cryptographic nonce be el.[11302][[CryptographicNonce]].
9. Let integrity metadata be the value of el's [11303]integrity
attribute, if it is specified, or the empty string otherwise.
10. If el does not have an [11304]integrity attribute, then set
integrity metadata to the result of [11305]resolving a module
integrity metadata with url and settings object.
11. Let referrer policy be the current state of el's
[11306]referrerpolicy attribute.
12. Let fetch priority be the current state of el's
[11307]fetchpriority attribute.
13. Let options be a [11308]script fetch options whose
[11309]cryptographic nonce is cryptographic nonce, [11310]integrity
metadata is integrity metadata, [11311]parser metadata is
"not-parser-inserted", [11312]credentials mode is credentials mode,
[11313]referrer policy is referrer policy, and [11314]fetch
priority is fetch priority.
14. [11315]Fetch a modulepreload module script graph given url,
destination, settings object, options, and with the following steps
given result:
1. If result is null, then [11316]fire an event named
[11317]error at el, and return.
2. [11318]Fire an event named [11319]load at el.
The [11320]process a link header steps for this type of linked resource
are to do nothing.
The following snippet shows the top part of an application with several
modules preloaded:
IRCFog
4.8.3 The img element
(BUTTON) ✔MDN
[12172]Element/img
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
[12174]Categories:
[12175]Flow content.
[12176]Phrasing content.
[12177]Embedded content.
[12178]Form-associated element.
If the element has a [12179]usemap attribute: [12180]Interactive
content.
[12181]Palpable content.
[12182]Contexts in which this element can be used:
Where [12183]embedded content is expected.
As a child of a [12184]picture element, after all [12185]source
elements.
[12186]Content model:
[12187]Nothing.
[12188]Tag omission in text/html:
No [12189]end tag.
[12190]Content attributes:
[12191]Global attributes
[12192]alt — Replacement text for use when images are not
available
[12193]src — Address of the resource
[12194]srcset — Images to use in different situations, e.g.,
high-resolution displays, small monitors, etc.
[12195]sizes — Image sizes for different page layouts
[12196]crossorigin — How the element handles crossorigin
requests
[12197]usemap — Name of [12198]image map to use
[12199]ismap — Whether the image is a server-side image map
[12200]width — Horizontal dimension
[12201]height — Vertical dimension
[12202]referrerpolicy — [12203]Referrer policy for
[12204]fetches initiated by the element
[12205]decoding — Decoding hint to use when processing this
image for presentation
[12206]loading — Used when determining loading deferral
[12207]fetchpriority — Sets the [12208]priority for
[12209]fetches initiated by the element
[12210]Accessibility considerations:
If the element has a non-empty [12211]alt attribute: [12212]for
authors; [12213]for implementers.
Otherwise: [12214]for authors; [12215]for implementers.
[12216]DOM interface:
[Exposed=Window,
[12217]LegacyFactoryFunction=[12218]Image(optional unsigned long width, optiona
l unsigned long height)]
interface HTMLImageElement : [12219]HTMLElement {
[[12220]HTMLConstructor] constructor();
The image given by the src and srcset attributes, and any previous
sibling [12258]source elements' [12259]srcset attributes if the parent
is a [12260]picture element, 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 [12261]img
element's [12262]fallback content).
The requirements on the [12263]alt attribute's value are described
[12264]in a separate section.
The [12265]src attribute must be present, and must contain a
[12266]valid non-empty URL potentially surrounded by spaces referencing
a non-interactive, optionally animated, image resource that is neither
paged nor scripted.
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 document element), animated bitmaps (APNGs, animated
GIFs), animated vector graphics (XML files with an SVG [12267]document
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 the
like. [12268][PNG] [12269][GIF] [12270][JPEG] [12271][PDF] [12272][XML]
[12273][APNG] [12274][SVG] [12275][MNG]
The [12276]srcset attribute may also be present, and is a [12277]srcset
attribute.
The [12278]srcset attribute and the [12279]src attribute (if
[12280]width descriptors are not used) contribute the [12281]image
sources to the [12282]source set (if no [12283]source element was
selected).
If the [12284]srcset attribute is present and has any [12285]image
candidate strings using a [12286]width descriptor, the [12287]sizes
attribute must also be present. If the [12288]srcset attribute is not
specified, and the [12289]loading attribute is in the [12290]Lazy
state, the [12291]sizes attribute may be specified with the value
"auto" ([12292]ASCII case-insensitive). The sizes attribute is a
[12293]sizes attribute, which contributes the [12294]source size to the
[12295]source set (if no [12296]source element was selected).
An [12297]img element allows auto-sizes if:
* its [12298]loading attribute is in the [12299]Lazy state, and
* its [12300]sizes attribute's value is "auto" ([12301]ASCII
case-insensitive), or starts with "auto," ([12302]ASCII
case-insensitive).
(BUTTON) ✔MDN
[12303]Attributes/crossorigin
Support in all current engines.
Firefox8+Safari6+Chrome13+
__________________________________________________________________
The crossorigin attribute is a [12304]CORS settings attribute. Its
purpose is to allow images from third-party sites that allow
cross-origin access to be used with [12305]canvas.
The referrerpolicy attribute is a [12306]referrer policy attribute. Its
purpose is to set the [12307]referrer policy used when [12308]fetching
the image. [12309][REFERRERPOLICY]
The decoding attribute indicates the preferred method to [12310]decode
this image. The attribute, if present, must be an [12311]image decoding
hint. This attribute's [12312]missing value default and [12313]invalid
value default are both the [12314]auto state.
The fetchpriority attribute is a [12316]fetch priority attribute. Its
purpose is to set the [12317]priority used when [12318]fetching the
image.
The loading attribute is a [12319]lazy loading attribute. Its purpose
is to indicate the policy for loading images that are outside the
viewport.
When the [12320]loading attribute's state is changed to the
[12321]Eager state, the user agent must run these steps:
1. Let resumptionSteps be the [12322]img element's [12323]lazy load
resumption steps.
2. If resumptionSteps is null, then return.
3. Set the [12324]img's [12325]lazy load resumption steps to null.
4. Invoke resumptionSteps.
You are standing in an open field west of a house.
There is a small mailbox here.
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.
You are standing in an open field west of a house.
There is a small mailbox here.
Text such as "Photo of white house with boarded door" would be equally
bad alternative text (though it could be suitable for the [13397]title
attribute or in the [13398]figcaption element of a [13399]figure with
this image).
4.8.4.4.4 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 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 [13400]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 [13401]alt attribute:
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 [13402]alt attribute.
Here, posts on a news site are labeled with an icon indicating their
topic.
Ratatouille wins Best Movie of the Year award
Pixar has won yet another Best Movie of the Year award,
making this its 8th win in the last 12 years.
Latest TWiT episode is online
The latest TWiT episode has been posted, in which we hear
several tech news stories as well as learning much more about the
iPhone. This week, the panelists compare how reflective their
iPhonesʼ Apple logos are.
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 [13403]alt attribute must contain the name of the entity
being represented by the logo. The [13404]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 [13405]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:
Next, we see a paragraph which uses a logo right next to the company
name, and so doesn't have any alternative text:
News
We have recently been looking at buying the ΑΒΓ company, a small Greek company
specializing in our type of product.
In this third snippet, we have a logo being used in an aside, as part
of the larger article discussing the acquisition:
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.
Finally, we have an opinion piece talking about a logo, and the logo is
therefore described in detail in the alternative text.
Consider for a moment their logo:
How unoriginal can you get? I mean, oooooh, a question mark, how
revolutionary, how utterly ground-breaking, 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.
This example shows how the alternative text should be written such that
if the image isn't [13406]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.
4.8.4.4.5 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.
In such cases, the [13407]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:
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.
nce upon a time and a long long time ago, l
ate 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
pronunciation.
Only 5.99!
An image should not be used if characters would serve an identical
purpose. Only when the text cannot be directly represented using text,
e.g., because of decorations or because there is no appropriate
character (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.
4.8.4.4.6 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
[13408]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:
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.
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 [13409]title attribute can be used, or the [13410]figure and
[13411]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.
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.
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.
Flowchart representation of the parsing model.
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.
A graph that repeats the previous paragraph in graphical form:
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.
4.8.4.4.7 Ancillary images
Sometimes, an image is not critical to the content, but is nonetheless
neither purely decorative nor entirely redundant with the text. In
these cases, the [13412]alt attribute must be present, and its value
should either be the empty string, or a textual representation of the
information that the image conveys. If the image has a caption giving
the image's title, then the [13413]alt attribute's value must not be
empty (as that would be quite confusing for non-visual readers).
Consider a news article about a political figure, in which the
individual's face was shown in an image. The image is not purely
decorative, as it is relevant to the story. The image is not entirely
redundant with the story either, as it shows what the politician looks
like. Whether any alternative text need be provided is an authoring
decision, decided by whether the image influences the interpretation of
the prose.
In this first variant, the image is shown without context, and no
alternative text is provided:
Ahead of todayʼs referendum,
the President wrote an open letter to all registered voters. In it, she admitted
that the country was
divided.
If the picture is just a face, there might be no value in describing
it. It's of no interest to the reader whether the individual has red
hair or blond hair, whether the individual has white skin or black
skin, whether the individual has one eye or two eyes.
However, if the picture is more dynamic, for instance showing the
politician as angry, or particularly happy, or devastated, some
alternative text would be useful in setting the tone of the article, a
tone that might otherwise be missed:
Ahead of todayʼs referendum, the President wrote an open letter to all
registered voters. In it, she admitted that the country was divided.
Ahead of todayʼs referendum, the President wrote an open letter to all
registered voters. In it, she admitted that the country was divided.
Whether the individual was "sad" or "happy" makes a difference to how
the rest of the paragraph is to be interpreted: is she likely saying
that she is unhappy with the country being divided, or is she saying
that the prospect of a divided country is good for her political
career? The interpretation varies based on the image.
If the image has a caption, then including alternative text avoids
leaving the non-visual user confused as to what the caption refers to.
Ahead of todayʼs referendum, the President wrote an open letter to
all registered voters. In it, she admitted that the country was divided.
4.8.4.4.8 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
[13414]img element. Such images are decorative, but still form part of
the content. In these cases, the [13415]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):
The Lady of Shalott
On either side the river lie
Long fields of barley and of rye,
That clothe the wold and meet the sky;
And through the field the road run by
To many-towerʼd Camelot;
And up and down the people go,
Gazing where the lilies blow
Round an island there below,
The island of Shalott.
4.8.4.4.9 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 [13416]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 [13417]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.
In the following example, a rating is shown as three filled stars and
two empty stars. While the alternative text could have been "★★★☆☆",
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.
Rating:
4.8.4.4.10 A group of images that form a single larger picture with
links
Generally, [13418]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 alternative text in its [13419]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.
The Church
You come across a flying spaghetti monster. Which side of His
Noodliness do you wish to reach out for?
4.8.4.4.11 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 [13420]alt attribute.
A screenshot in a gallery of screenshots for a new OS, with some
alternative text:
Screenshot of a KDE desktop.
A graph in a financial report:
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 [13421]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:
A black outline of the first of the ten cards
in the Rorschach inkblot test.
Note that the following would be a very bad use of alternative
text:
A black outline of the first of the ten cards
in the Rorschach inkblot test.
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.
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:
A Biography of Isaac Asimov
Born Isaak Yudovich Ozimov in 1920, Isaac was a prolific author.
Asimov was born in Russia, and moved to the US when he was three years old.<
/p>
...
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 themself know what the
images represent (e.g. a blind photographer sharing an image on
their blog).
In such cases, the [13422]alt attribute may be omitted, but one
of the following conditions must be met as well:
+ The [13423]img element is in a [13424]figure element that
contains a [13425]figcaption element that contains content
other than [13426]inter-element whitespace, and, ignoring the
[13427]figcaption element and its descendants, the
[13428]figure element has no [13429]flow content descendants
other than [13430]inter-element whitespace and the [13431]img
element.
+ The [13432]title attribute is present and has a non-empty
value.
Relying on the [13433]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 [13434]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:
Bubbles traveled everywhere with us.
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 they
took shows:
I took a photo
I went out today and took a photo!
A photograph taken blindly from my front porch.
Eventually though, the user might obtain a description of the
image from their friends and could then include alternative
text:
I took a photo
I went out today and took a photo!
A photograph taken blindly from my front porch.
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 [13435]title attribute):
(If you cannot see the image, you can use an audio test instead.)
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:
Image
Description
Notice that even in this example, as much useful information as
possible is still included in the [13436]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 [13437]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 [13438]alt attribute.
4.8.4.4.12 An image not intended for the user
Generally authors should avoid using [13439]img elements for purposes
other than showing images.
If an [13440]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
[13441]alt attribute must be the empty string.
In such cases, the [13442]width and [13443]height attributes should
both be set to zero.
4.8.4.4.13 An image in an email 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, emails sent to public mailing
lists, or 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 [13444]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 email 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.
4.8.4.4.14 Guidance for markup generators
Markup generators (such as WYSIWYG authoring tools) should, wherever
possible, obtain alternative text from their users. However, it is
recognized that in many cases, this will not be possible.
For images that are the sole contents of links, markup generators
should examine the link target to determine the title of the target, or
the URL of the target, and use information obtained in this manner as
the alternative text.
For images that have captions, markup generators should use the
[13445]figure and [13446]figcaption elements, or the [13447]title
attribute, to provide the image's caption.
As a last resort, implementers should either set the [13448]alt
attribute to the empty string, under the assumption that the image is a
purely decorative image that doesn't add any information but is still
specific to the surrounding content, or omit the [13449]alt attribute
altogether, under the assumption that the image is a key part of the
content.
Markup generators may specify a
generator-unable-to-provide-required-alt attribute on [13450]img
elements for which they have been unable to obtain alternative text and
for which they have therefore omitted the [13451]alt attribute. The
value of this attribute must be the empty string. Documents containing
such attributes are not conforming, but conformance checkers will
[13452]silently ignore this error.
This is intended to avoid markup generators from being pressured into
replacing the error of omitting the [13453]alt attribute with the even
more egregious error of providing phony alternative text, because
state-of-the-art automated conformance checkers cannot distinguish
phony alternative text from correct alternative text.
Markup generators should generally avoid using the image's own filename
as the alternative text. Similarly, markup generators should avoid
generating alternative text from any content that will be equally
available to presentation user agents (e.g., web browsers).
This is because once a page is generated, it will typically not be
updated, whereas the browsers that later read the page can be updated
by the user, therefore the browser is likely to have more up-to-date
and finely-tuned heuristics than the markup generator did when
generating the page.
4.8.4.4.15 Guidance for conformance checkers
A conformance checker must report the lack of an [13454]alt attribute
as an error unless one of the conditions listed below applies:
* The [13455]img element is in a [13456]figure element that satisfies
[13457]the conditions described above.
* The [13458]img element has a [13459]title attribute with a value
that is not the empty string (also as [13460]described above).
* The conformance checker has been configured to assume that the
document is an email or document intended for a specific person who
is known to be able to view images.
* The [13461]img element has a (non-conforming)
[13462]generator-unable-to-provide-required-alt attribute whose
value is the empty string. A conformance checker that is not
reporting the lack of an [13463]alt attribute as an error must also
not report the presence of the empty
[13464]generator-unable-to-provide-required-alt attribute as an
error. (This case does not represent a case where the document is
conforming, only that the generator could not determine appropriate
alternative text — validators are not required to show an error in
this case, because such an error might encourage markup generators
to include bogus alternative text purely in an attempt to silence
validators. Naturally, conformance checkers may report the lack of
an [13465]alt attribute as an error even in the presence of the
[13466]generator-unable-to-provide-required-alt attribute; for
example, there could be a user option to report all conformance
errors even those that might be the more or less inevitable result
of using a markup generator.)
4.8.5 The iframe element
(BUTTON) ✔MDN
[13467]Element/iframe
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
[13475]Contexts in which this element can be used:
Where [13476]embedded content is expected.
[13477]Content model:
[13478]Nothing.
[13479]Tag omission in text/html:
Neither tag is omissible.
[13480]Content attributes:
[13481]Global attributes
[13482]src — Address of the resource
[13483]srcdoc — A document to render in the [13484]iframe
[13485]name — Name of [13486]content navigable
[13487]sandbox — Security rules for nested content
[13488]allow — [13489]Permissions policy to be applied to the
[13490]iframe's contents
[13491]allowfullscreen — Whether to allow the [13492]iframe's
contents to use [13493]requestFullscreen()
[13494]width — Horizontal dimension
[13495]height — Vertical dimension
[13496]referrerpolicy — [13497]Referrer policy for
[13498]fetches initiated by the element
[13499]loading — Used when determining loading deferral
The [13535]iframe element [13536]represents its [13537]content
navigable.
The src attribute gives the [13538]URL of a page that the element's
[13539]content navigable is to contain. The attribute, if present, must
be a [13540]valid non-empty URL potentially surrounded by spaces. If
the [13541]itemprop attribute is specified on an [13542]iframe element,
then the [13543]src attribute must also be specified.
(BUTTON) ✔MDN
[13544]Element/iframe#attr-srcdoc
Support in all current engines.
Firefox25+Safari6+Chrome20+
__________________________________________________________________
The srcdoc attribute gives the content of the page that the element's
[13545]content navigable is to contain. The value of the attribute is
used to [13546]construct an iframe srcdoc document, which is a
[13547]Document whose [13548]URL [13549]matches about:srcdoc.
The [13550]srcdoc attribute, if present, must have a value using
[13551]the HTML syntax that consists of the following syntactic
components, in the given order:
1. Any number of [13552]comments and [13553]ASCII whitespace.
2. Optionally, a [13554]DOCTYPE.
3. Any number of [13555]comments and [13556]ASCII whitespace.
4. The [13557]document element, in the form of an [13558]html
[13559]element.
5. Any number of [13560]comments and [13561]ASCII whitespace.
The above requirements apply in [13562]XML documents as well.
Here a blog uses the [13563]srcdoc attribute in conjunction with the
[13564]sandbox attribute 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:
I got my own magazine!
After much effort, Iʼve finally found a publisher, and so now I
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!
Notice the way that quotes have to be escaped (otherwise the
[13565]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 [13566]srcdoc attribute, and once
more to prevent the ampersand from being misinterpreted when parsing
the sandboxed content.
Furthermore, notice that since the [13567]DOCTYPE is optional in
[13568]iframe srcdoc documents, and the [13569]html, [13570]head, and
[13571]body elements have [13572]optional start and end tags, and the
[13573]title element is also optional in [13574]iframe srcdoc
documents, the markup in a [13575]srcdoc attribute can be relatively
succinct despite representing an entire document, since only the
contents of the [13576]body element need appear literally in the
syntax. The other elements are still present, but only by implication.
In [13577]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+0026 AMPERSAND (&) and U+0022 QUOTATION MARK (")
characters, and to specify the [13578]sandbox attribute, to ensure safe
embedding of content. (And remember to escape ampersands before
quotation marks, to ensure quotation marks become " and not
".)
In XML the U+003C LESS-THAN SIGN character (<) needs to be escaped as
well. In order to prevent [13579]attribute-value 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. [13580][XML]
If the [13581]src attribute and the [13582]srcdoc attribute are both
specified together, the [13583]srcdoc attribute takes priority. This
allows authors to provide a fallback [13584]URL for legacy user agents
that do not support the [13585]srcdoc attribute.
__________________________________________________________________
The [13586]iframe [13587]HTML element post-connection steps, given
insertedNode, are:
1. [13588]Create a new child navigable for insertedNode.
2. If insertedNode has a [13589]sandbox attribute, then [13590]parse
the sandboxing directive given the attribute's value and
insertedNode's [13591]iframe sandboxing flag set.
3. [13592]Process the iframe attributes for insertedNode, with
[13593]initialInsertion set to true.
The [13594]iframe [13595]HTML element removing steps, given
removedNode, are to [13596]destroy a child navigable given removedNode.
This happens without any [13597]unload events firing (the element's
[13598]content document is [13599]destroyed, not [13600]unloaded).
Although [13601]iframes are processed while in a [13602]shadow tree,
per the above, several other aspects of their behavior are not
well-defined with regards to shadow trees. See [13603]issue #763 for
more detail.
Whenever an [13604]iframe element with a non-null [13605]content
navigable has its [13606]srcdoc attribute set, changed, or removed, the
user agent must [13607]process the iframe attributes.
Similarly, whenever an [13608]iframe element with a non-null
[13609]content navigable but with no [13610]srcdoc attribute specified
has its [13611]src attribute set, changed, or removed, the user agent
must [13612]process the iframe attributes.
To process the iframe attributes for an element element, with an
optional boolean initialInsertion (default false):
1. If element's [13613]srcdoc attribute is specified, then:
1. Set element's [13614]current navigation was lazy loaded
boolean to false.
2. If the [13615]will lazy load element steps given element
return true, then:
1. Set element's [13616]lazy load resumption steps to the
rest of this algorithm starting with the step labeled
navigate to the srcdoc resource.
2. Set element's [13617]current navigation was lazy loaded
boolean to true.
3. [13618]Start intersection-observing a lazy loading
element for element.
4. Return.
3. Navigate to the srcdoc resource: [13619]Navigate an iframe or
frame given element, [13620]about:srcdoc, the empty string,
and the value of element's [13621]srcdoc attribute.
The resulting [13622]Document must be considered [13623]an
iframe srcdoc document.
2. Otherwise:
1. Let url be the result of running the [13624]shared attribute
processing steps for iframe and frame elements given element
and initialInsertion.
2. If url is null, then return.
3. If url [13625]matches about:blank and initialInsertion is
true, then:
1. Run the [13626]iframe load event steps given element.
2. Return.
4. Let referrerPolicy be the current state of element's
[13627]referrerpolicy content attribute.
5. Set element's [13628]current navigation was lazy loaded
boolean to false.
6. If the [13629]will lazy load element steps given element
return true, then:
1. Set element's [13630]lazy load resumption steps to the
rest of this algorithm starting with the step labeled
navigate.
2. Set element's [13631]current navigation was lazy loaded
boolean to true.
3. [13632]Start intersection-observing a lazy loading
element for element.
4. Return.
7. Navigate: [13633]Navigate an iframe or frame given element,
url, and referrerPolicy.
The shared attribute processing steps for iframe and frame elements,
given an element element and a boolean initialInsertion, are:
1. Let url be the [13634]URL record [13635]about:blank.
2. If element has a [13636]src attribute specified, and its value is
not the empty string, then:
1. Let maybeURL be the result of [13637]encoding-parsing a URL
given that attribute's value, relative to element's
[13638]node document.
2. If maybeURL is not failure, then set url to maybeURL.
3. If the [13639]inclusive ancestor navigables of element's
[13640]node navigable contains a [13641]navigable whose
[13642]active document's [13643]URL [13644]equals url with
[13645]exclude fragments set to true, then return null.
4. If url [13646]matches about:blank and initialInsertion is true,
then perform the [13647]URL and history update steps given
element's [13648]content navigable's [13649]active document and
url.
This is necessary in case url is something like about:blank?foo. If
url is just plain about:blank, this will do nothing.
5. Return url.
To navigate an iframe or frame given an element element, a [13650]URL
url, a [13651]referrer policy referrerPolicy, and an optional
string-or-null srcdocString (default null):
1. Let historyHandling be "[13652]auto".
2. If element's [13653]content navigable's [13654]active document is
not [13655]completely loaded, then set historyHandling to
"[13656]replace".
3. If element is an [13657]iframe, then set element's [13658]pending
resource-timing start time to the [13659]current high resolution
time given element's [13660]node document's [13661]relevant global
object.
4. [13662]Navigate element's [13663]content navigable to url using
element's [13664]node document, with [13665]historyHandling set to
historyHandling, [13666]referrerPolicy set to referrerPolicy, and
[13667]documentResource set to srcdocString.
Each [13668]Document has an iframe load in progress flag and a mute
iframe load flag. When a [13669]Document is created, these flags must
be unset for that [13670]Document.
To run the iframe load event steps, given an [13671]iframe element
element:
1. [13672]Assert: element's [13673]content navigable is not null.
2. Let childDocument be element's [13674]content navigable's
[13675]active document.
3. If childDocument has its [13676]mute iframe load flag set, then
return.
4. If element's [13677]pending resource-timing start time is not null,
then:
1. Let global be element's [13678]node document's [13679]relevant
global object.
2. Let fallbackTimingInfo be a new [13680]fetch timing info whose
[13681]start time is element's [13682]pending resource-timing
start time and whose [13683]response end time is the
[13684]current high resolution time given global.
3. [13685]Mark resource timing given fallbackTimingInfo, url,
"[13686]iframe", global, the empty string, a new
[13687]response body info, and 0.
4. Set element's [13688]pending resource-timing start time to
null.
5. Set childDocument's [13689]iframe load in progress flag.
6. [13690]Fire an event named [13691]load at element.
7. Unset childDocument's [13692]iframe load in progress flag.
This, in conjunction with scripting, can be used to probe the URL space
of the local network's HTTP servers. User agents may implement
[13693]cross-origin access control policies that are stricter than
those described above to mitigate this attack, but unfortunately such
policies are typically not compatible with existing web content.
If an element type potentially delays the load event, then for each
element element of that type, the user agent must [13694]delay the load
event of element's [13695]node document if element's [13696]content
navigable is non-null and any of the following are true:
* element's [13697]content navigable's [13698]active document is not
[13699]ready for post-load tasks;
* element's [13700]content navigable's [13701]is delaying load events
is true; or
* anything is [13702]delaying the load event of element's
[13703]content navigable's [13704]active document.
If, during the handling of the [13705]load event, element's
[13706]content navigable is again [13707]navigated, that will further
[13708]delay the load event.
Each [13709]iframe element has an associated current navigation was
lazy loaded boolean, initially false. It is set and unset in the
[13710]process the iframe attributes algorithm.
An [13711]iframe element whose [13712]current navigation was lazy
loaded boolean is false [13713]potentially delays the load event.
Each [13714]iframe element has an associated null or
[13715]DOMHighResTimeStamp pending resource-timing start time,
initially set to null.
If, when the element is created, the [13716]srcdoc attribute is not
set, and the [13717]src attribute is either also not set or set but its
value cannot be [13718]parsed, the element's [13719]content navigable
will remain at the [13720]initial about:blank [13721]Document.
If the user [13722]navigates away from this page, the [13723]iframe's
[13724]content navigable's [13725]active WindowProxy object will proxy
new [13726]Window objects for new [13727]Document objects, but the
[13728]src attribute will not change.
__________________________________________________________________
The name attribute, if present, must be a [13729]valid navigable target
name. The given value is used to name the element's [13730]content
navigable if present when that is [13731]created.
__________________________________________________________________
(BUTTON) ✔MDN
[13732]Element/iframe#attr-sandbox
Support in all current engines.
Firefox17+Safari5+Chrome4+
__________________________________________________________________
The sandbox attribute, when specified, enables a set of extra
restrictions on any content hosted by the [13733]iframe. Its value must
be an [13734]unordered set of unique space-separated tokens that are
[13735]ASCII case-insensitive. The allowed values are:
* [13736]allow-downloads
* [13737]allow-forms
* [13738]allow-modals
* [13739]allow-orientation-lock
* [13740]allow-pointer-lock
* [13741]allow-popups
* [13742]allow-popups-to-escape-sandbox
* [13743]allow-presentation
* [13744]allow-same-origin
* [13745]allow-scripts
* [13746]allow-top-navigation
* [13747]allow-top-navigation-by-user-activation
* [13748]allow-top-navigation-to-custom-protocols
When the attribute is set, the content is treated as being from a
unique [13749]opaque origin, forms, scripts, and various potentially
annoying APIs are disabled, and links are prevented from targeting
other [13750]navigables. The [13751]allow-same-origin keyword causes
the content to be treated as being from its real origin instead of
forcing it into an [13752]opaque origin; the
[13753]allow-top-navigation keyword allows the content to
[13754]navigate its [13755]traversable navigable; the
[13756]allow-top-navigation-by-user-activation keyword behaves
similarly but allows such [13757]navigation only when the browsing
context's [13758]active window has [13759]transient activation; the
[13760]allow-top-navigation-to-custom-protocols reenables navigations
toward non [13761]fetch scheme to be [13762]handed off to external
software; and the [13763]allow-forms, [13764]allow-modals,
[13765]allow-orientation-lock, [13766]allow-pointer-lock,
[13767]allow-popups, [13768]allow-presentation, [13769]allow-scripts,
and [13770]allow-popups-to-escape-sandbox keywords re-enable forms,
modal dialogs, screen orientation lock, the pointer lock API, popups,
the presentation API, scripts, and the creation of unsandboxed
[13771]auxiliary browsing contexts respectively. The
[13772]allow-downloads keyword allows content to perform downloads.
[13773][POINTERLOCK] [13774][SCREENORIENTATION] [13775][PRESENTATION]
The [13776]allow-top-navigation and
[13777]allow-top-navigation-by-user-activation keywords must not both
be specified, as doing so is redundant; only
[13778]allow-top-navigation will have an effect in such non-conformant
markup.
Similarly, the [13779]allow-top-navigation-to-custom-protocols keyword
must not be specified if either [13780]allow-top-navigation or
[13781]allow-popups are specified, as doing so is redundant.
To allow [13782]alert(), [13783]confirm(), and [13784]prompt() inside
sandboxed content, both the [13785]allow-modals and
[13786]allow-same-origin keywords need to be specified, and the loaded
URL needs to be [13787]same origin with the [13788]top-level origin.
Without the [13789]allow-same-origin keyword, the content is always
treated as cross-origin, and cross-origin content [13790]cannot show
simple dialogs.
Setting both the [13791]allow-scripts and [13792]allow-same-origin
keywords together when the embedded page has the [13793]same origin as
the page containing the [13794]iframe allows the embedded page to
simply remove the [13795]sandbox attribute and then reload itself,
effectively breaking out of the sandbox altogether.
These flags only take effect when the [13796]content navigable of the
[13797]iframe element is [13798]navigated. Removing them, or removing
the entire [13799]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 [13800]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 [13801]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 [13802]sandbox attribute.
When an [13803]iframe element's [13804]sandbox attribute is set or
changed while it has a non-null [13805]content navigable, the user
agent must [13806]parse the sandboxing directive given the attribute's
value and the [13807]iframe element's [13808]iframe sandboxing flag
set.
When an [13809]iframe element's [13810]sandbox attribute is removed
while it has a non-null [13811]content navigable, the user agent must
empty the [13812]iframe element's [13813]iframe sandboxing flag set.
In this example, some completely-unknown, potentially hostile,
user-provided 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).
Weʼre not scared of you! Here is your content, unedited:
It is important to use a separate domain so that if the attacker
convinces 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.
Suppose a file A contained the following fragment:
Suppose that file B contained an iframe also:
Further, suppose that file C contained a link:
Link
For this example, suppose all the files were served as
[13814]text/html.
Page C in this scenario has all the sandboxing flags set. Scripts are
disabled, because the [13815]iframe in A has scripts disabled, and this
overrides the [13816]allow-scripts keyword set on the [13817]iframe in
B. Forms are also disabled, because the inner [13818]iframe (in B) does
not have the [13819]allow-forms keyword set.
Suppose now that a script in A removes all the [13820]sandbox
attributes in A and B. This would change nothing immediately. If the
user clicked the link in C, loading page D into the [13821]iframe in B,
page D would now act as if the [13822]iframe in B had the
[13823]allow-same-origin and [13824]allow-forms keywords set, because
that was the state of the [13825]content navigable in the [13826]iframe
in A when page B was loaded.
Generally speaking, dynamically removing or changing the [13827]sandbox
attribute is ill-advised, because it can make it quite hard to reason
about what will be allowed and what will not.
__________________________________________________________________
The allow attribute, when specified, determines the [13828]container
policy that will be used when the [13829]permissions policy for a
[13830]Document in the [13831]iframe's [13832]content navigable is
initialized. Its value must be a [13833]serialized permissions policy.
[13834][PERMISSIONSPOLICY]
In this example, an [13835]iframe is used to embed a map from an online
navigation service. The [13836]allow attribute is used to enable the
Geolocation API within the nested context.
The allowfullscreen attribute is a [13837]boolean attribute. When
specified, it indicates that [13838]Document objects in the
[13839]iframe element's [13840]content navigable will be initialized
with a [13841]permissions policy which allows the "fullscreen" feature
to be used from any [13842]origin. This is enforced by the
[13843]process permissions policy attributes algorithm.
[13844][PERMISSIONSPOLICY]
Here, an [13845]iframe is used to embed a player from a video site. The
[13846]allowfullscreen attribute is needed to enable the player to show
its video fullscreen.
Neither [13847]allow nor [13848]allowfullscreen can grant access to a
feature in an [13849]iframe element's [13850]content navigable if the
element's [13851]node document is not already allowed to use that
feature.
To determine whether a [13852]Document object document is allowed to
use the policy-controlled-feature feature, run these steps:
1. If document's [13853]browsing context is null, then return false.
2. If document is not [13854]fully active, then return false.
3. If the result of running [13855]is feature enabled in document for
origin on feature, document, and document's [13856]origin is
"Enabled", then return true.
4. Return false.
Because they only influence the [13857]permissions policy of the
[13858]content navigable's [13859]active document, the [13860]allow and
[13861]allowfullscreen attributes only take effect when the
[13862]content navigable of the [13863]iframe is [13864]navigated.
Adding or removing them has no effect on an already-loaded document.
__________________________________________________________________
The [13865]iframe element supports [13866]dimension attributes for
cases where the embedded content has specific dimensions (e.g. ad units
have well-defined dimensions).
An [13867]iframe element never has [13868]fallback content, as it will
always [13869]create a new child navigable, regardless of whether the
specified initial contents are successfully used.
__________________________________________________________________
The referrerpolicy attribute is a [13870]referrer policy attribute. Its
purpose is to set the [13871]referrer policy used when
[13872]processing the iframe attributes. [13873][REFERRERPOLICY]
The loading attribute is a [13874]lazy loading attribute. Its purpose
is to indicate the policy for loading [13875]iframe elements that are
outside the viewport.
When the [13876]loading attribute's state is changed to the
[13877]Eager state, the user agent must run these steps:
1. Let resumptionSteps be the [13878]iframe element's [13879]lazy load
resumption steps.
2. If resumptionSteps is null, then return.
3. Set the [13880]iframe's [13881]lazy load resumption steps to null.
4. Invoke resumptionSteps.
__________________________________________________________________
Descendants of [13882]iframe elements represent nothing. (In legacy
user agents that do not support [13883]iframe elements, the contents
would be parsed as markup that could act as fallback content.)
The [13884]HTML parser treats markup inside [13885]iframe elements as
text.
__________________________________________________________________
(BUTTON) ✔MDN
[13886]HTMLIFrameElement/src
Support in all current engines.
Firefox1+Safari3+Chrome1+
__________________________________________________________________
The srcdoc getter steps are:
1. Let attribute be the result of running [13889]get an attribute by
namespace and local name given null, [13890]srcdoc's [13891]local
name, and [13892]this.
2. If attribute is null, then return the empty string.
3. Return attribute's [13893]value.
The [13894]srcdoc setter steps are:
1. Let compliantString be the result of invoking the [13895]Get
Trusted Type compliant string algorithm with [13896]TrustedHTML,
[13897]this's [13898]relevant global object, the given value,
"HTMLIFrameElement srcdoc", and "script".
2. [13899]Set an attribute value given [13900]this, [13901]srcdoc's
[13902]local name, and compliantString.
The [13903]supported tokens for [13904]sandbox's [13905]DOMTokenList
are the allowed values defined in the [13906]sandbox attribute and
supported by the user agent.
The allowFullscreen IDL attribute must [13907]reflect the
[13908]allowfullscreen content attribute.
(BUTTON) ✔MDN
[13909]HTMLIFrameElement/referrerPolicy
Support in all current engines.
Firefox50+Safari14+Chrome52+
__________________________________________________________________
[13931]Contexts in which this element can be used:
Where [13932]embedded content is expected.
[13933]Content model:
[13934]Nothing.
[13935]Tag omission in text/html:
No [13936]end tag.
[13937]Content attributes:
[13938]Global attributes
[13939]src — Address of the resource
[13940]type — Type of embedded resource
[13941]width — Horizontal dimension
[13942]height — Vertical dimension
Any other attribute that has no namespace (see prose).
The [13960]embed element provides an integration point for an external
application or interactive content.
The src attribute gives the [13961]URL of the resource being embedded.
The attribute, if present, must contain a [13962]valid non-empty URL
potentially surrounded by spaces.
If the [13963]itemprop attribute is specified on an [13964]embed
element, then the [13965]src attribute must also be specified.
The type attribute, if present, gives the [13966]MIME type by which the
plugin to instantiate is selected. The value must be a [13967]valid
MIME type string. If both the [13968]type attribute and the [13969]src
attribute are present, then the [13970]type attribute must specify the
same type as the [13971]explicit Content-Type metadata of the resource
given by the [13972]src attribute.
While any of the following conditions are occurring, any [13973]plugin
instantiated for the element must be removed, and the [13974]embed
element [13975]represents nothing:
* The element has neither a [13976]src attribute nor a [13977]type
attribute.
* The element has a [13978]media element ancestor.
* The element has an ancestor [13979]object element that is not
showing its [13980]fallback content.
An [13981]embed element is said to be potentially active when the
following conditions are all met simultaneously:
* The element is [13982]in a document or was [13983]in a document the
last time the [13984]event loop reached [13985]step 1.
* The element's [13986]node document is [13987]fully active.
* The element has either a [13988]src attribute set or a [13989]type
attribute set (or both).
* The element's [13990]src attribute is either absent or its value is
not the empty string.
* The element is not a descendant of a [13991]media element.
* The element is not a descendant of an [13992]object element that is
not showing its [13993]fallback content.
* The element is [13994]being rendered, or was [13995]being rendered
the last time the [13996]event loop reached [13997]step 1.
Whenever an [13998]embed element that was not [13999]potentially active
becomes [14000]potentially active, and whenever a [14001]potentially
active [14002]embed element that is remaining [14003]potentially active
and has its [14004]src attribute set, changed, or removed or its
[14005]type attribute set, changed, or removed, the user agent must
[14006]queue an element task on the embed task source given the element
to run [14007]the embed element setup steps for that element.
The embed element setup steps for a given [14008]embed element element
are as follows:
1. If another [14009]task has since been queued to run [14010]the
embed element setup steps for element, then return.
2. If element has a [14011]src attribute set, then:
1. Let url be the result of [14012]encoding-parsing a URL given
element's [14013]src attribute's value, relative to element's
[14014]node document.
2. If url is failure, then return.
3. Let request be a new [14015]request whose [14016]URL is url,
[14017]client is element's [14018]node document's
[14019]relevant settings object, [14020]destination is
"embed", [14021]credentials mode is "include", [14022]mode is
"navigate", [14023]initiator type is "embed", and whose
[14024]use-URL-credentials flag is set.
4. [14025]Fetch request, with [14026]processResponse set to the
following steps given [14027]response response:
1. If another [14028]task has since been queued to run
[14029]the embed element setup steps for element, then
return.
2. If response is a [14030]network error, then [14031]fire
an event named [14032]load at element, and return.
3. Let type be the result of determining the [14033]type of
content given element and response.
4. Switch on type:
null
1. [14034]Display no plugin for element.
Otherwise
1. If element's [14035]content navigable is null,
then [14036]create a new child navigable for
element.
2. [14037]Navigate element's [14038]content
navigable to response's [14039]URL using
element's [14040]node document, with
[14041]response set to response, and
[14042]historyHandling set to "[14043]replace".
element's [14044]src attribute does not get
updated if the [14045]content navigable gets
further navigated to other locations.
3. element now [14046]represents its
[14047]content navigable.
Fetching the resource must [14048]delay the load event of
element's [14049]node document.
3. Otherwise, [14050]display no plugin for element.
To determine the type of the content given an [14051]embed element
element and a [14052]response response, run the following steps:
1. If element has a [14053]type attribute, and that attribute's value
is a type that a [14054]plugin supports, then return the value of
the [14055]type attribute.
2. If the [14056]path component of response's [14057]url matches a
pattern that a [14058]plugin supports, then return the type that
that plugin can handle.
For example, a plugin might say that it can handle URLs with
[14059]path components that end with the four character string
".swf".
3. If response has [14060]explicit Content-Type metadata, and that
value is a type that a [14061]plugin supports, then return that
value.
4. Return null.
It is intentional that the above algorithm allows response to have a
non-[14062]ok status. This allows servers to return data for plugins
even with error responses (e.g., HTTP 500 Internal Server Error codes
can still contain plugin data).
To display no plugin for an [14063]embed element element:
1. [14064]Destroy a child navigable given element.
2. Display an indication that no [14065]plugin could be found for
element, as the contents of element.
3. element now [14066]represents nothing.
The [14067]embed element has no [14068]fallback content; its
descendants are ignored.
Whenever an [14069]embed element that was [14070]potentially active
stops being [14071]potentially active, any [14072]plugin that had been
instantiated for that element must be unloaded.
The [14073]embed element [14074]potentially delays the load event.
The [14075]embed element supports [14076]dimension attributes.
The IDL attributes src and type each must [14077]reflect the respective
content attributes of the same name.
4.8.7 The object element
(BUTTON) ✔MDN
[14078]Element/object
Support in all current engines.
Firefox1+Safari3+Chrome1+
__________________________________________________________________
[14087]Contexts in which this element can be used:
Where [14088]embedded content is expected.
[14089]Content model:
[14090]Transparent.
[14091]Tag omission in text/html:
Neither tag is omissible.
[14092]Content attributes:
[14093]Global attributes
[14094]data — Address of the resource
[14095]type — Type of embedded resource
[14096]name — Name of [14097]content navigable
[14098]form — Associates the element with a [14099]form element
[14100]width — Horizontal dimension
[14101]height — Vertical dimension
Depending on the type of content instantiated by the
[14134]object element, the node also supports other interfaces.
The [14135]object element can represent an external resource, which,
depending on the type of the resource, will either be treated as an
image or as a [14136]child navigable.
The data attribute specifies the [14137]URL of the resource. It must be
present, and must contain a [14138]valid non-empty URL potentially
surrounded by spaces.
The type attribute, if present, specifies the type of the resource. If
present, the attribute must be a [14139]valid MIME type string.
The name attribute, if present, must be a [14140]valid navigable target
name. The given value is used to name the element's [14141]content
navigable, if applicable, and if present when the element's
[14142]content navigable is [14143]created.
Whenever one of the following conditions occur:
* the element is created,
* the element is popped off the [14144]stack of open elements of an
[14145]HTML parser or [14146]XML parser,
* the element is not on the [14147]stack of open elements of an
[14148]HTML parser or [14149]XML parser, and it is either
[14150]inserted into a document or [14151]removed from a document,
* the element's [14152]node document changes whether it is
[14153]fully active,
* one of the element's ancestor [14154]object elements changes to or
from showing its [14155]fallback content,
* the element's [14156]classid attribute is set, changed, or removed,
* the element's [14157]classid attribute is not present, and its
[14158]data attribute is set, changed, or removed,
* neither the element's [14159]classid attribute nor its [14160]data
attribute are present, and its [14161]type attribute is set,
changed, or removed,
* the element changes from [14162]being rendered to not being
rendered, or vice versa,
...the user agent must [14163]queue an element task on the [14164]DOM
manipulation task source given the [14165]object element to run the
following steps to (re)determine what the [14166]object element
represents. This [14167]task being [14168]queued or actively running
must [14169]delay the load event of the element's [14170]node document.
1. If the user has indicated a preference that this [14171]object
element's [14172]fallback content be shown instead of the element's
usual behavior, then jump to the step below labeled fallback.
For example, a user could ask for the element's [14173]fallback
content to be shown because that content uses a format that the
user finds more accessible.
2. If the element has an ancestor [14174]media element, or has an
ancestor [14175]object element that is not showing its
[14176]fallback content, or if the element is not [14177]in a
document whose [14178]browsing context is non-null, or if the
element's [14179]node document is not [14180]fully active, or if
the element is still in the [14181]stack of open elements of an
[14182]HTML parser or [14183]XML parser, or if the element is not
[14184]being rendered, then jump to the step below labeled
fallback.
3. If the [14185]data attribute is present and its value is not the
empty string, then:
1. If the [14186]type attribute is present and its value is not a
type that the user agent supports, then the user agent may
jump to the step below labeled fallback without fetching the
content to examine its real type.
2. Let url be the result of [14187]encoding-parsing a URL given
the [14188]data attribute's value, relative to the element's
[14189]node document.
3. If url is failure, then [14190]fire an event named
[14191]error at the element and jump to the step below labeled
fallback.
4. Let request be a new [14192]request whose [14193]URL is url,
[14194]client is the element's [14195]node document's
[14196]relevant settings object, [14197]destination is
"object", [14198]credentials mode is "include", [14199]mode is
"navigate", [14200]initiator type is "object", and whose
[14201]use-URL-credentials flag is set.
5. [14202]Fetch request.
Fetching the resource must [14203]delay the load event of the
element's [14204]node document until the [14205]task that is
[14206]queued by the [14207]networking task source once the
resource has been fetched (defined next) has been run.
6. If the resource is not yet available (e.g. because the
resource was not available in the cache, so that loading the
resource required making a request over the network), then
jump to the step below labeled fallback. The [14208]task that
is [14209]queued by the [14210]networking task source once the
resource is available must restart this algorithm from this
step. Resources can load incrementally; user agents may opt to
consider a resource "available" whenever enough data has been
obtained to begin processing the resource.
7. If the load failed (e.g. there was an HTTP 404 error, there
was a DNS error), [14211]fire an event named [14212]error at
the element, then jump to the step below labeled fallback.
8. Determine the resource type, as follows:
1. Let the resource type be unknown.
2. If the user agent is configured to strictly obey
Content-Type headers for this resource, and the resource
has [14213]associated Content-Type metadata, then let the
resource type be the type specified in [14214]the
resource's Content-Type metadata, and jump to the step
below labeled handler.
This can introduce a vulnerability, wherein a site is
trying to embed a resource that uses a particular type,
but the remote site overrides that and instead furnishes
the user agent with a resource that triggers a different
type of content with different security characteristics.
3. Run the appropriate set of steps from the following list:
If the resource has [14215]associated Content-Type
metadata
1. Let binary be false.
2. If the type specified in [14216]the resource's
Content-Type metadata is "[14217]text/plain",
and the result of applying the [14218]rules for
distinguishing if a resource is text or binary
to the resource is that the resource is not
[14219]text/plain, then set binary to true.
3. If the type specified in [14220]the resource's
Content-Type metadata is
"[14221]application/octet-stream", then set
binary to true.
4. If binary is false, then let the resource type
be the type specified in [14222]the resource's
Content-Type metadata, and jump to the step
below labeled handler.
5. If there is a [14223]type attribute present on
the [14224]object element, and its value is not
[14225]application/octet-stream, then run the
following steps:
1. If the attribute's value is a type that
starts with "image/" that is not also an
[14226]XML MIME type, then let the
resource type be the type specified in
that [14227]type attribute.
2. Jump to the step below labeled handler.
Otherwise, if the resource does not have
[14228]associated Content-Type metadata
1. If there is a [14229]type attribute present on
the [14230]object element, then let the
tentative type be the type specified in that
[14231]type attribute.
Otherwise, let tentative type be the
[14232]computed type of the resource.
2. If tentative type is not
[14233]application/octet-stream, then let
resource type be tentative type and jump to the
step below labeled handler.
4. If applying the [14234]URL parser algorithm to the
[14235]URL of the specified resource (after any
redirects) results in a [14236]URL record whose
[14237]path component matches a pattern that a
[14238]plugin supports, then let resource type be the
type that that plugin can handle.
For example, a plugin might say that it can handle
resources with [14239]path components that end with the
four character string ".swf".
It is possible for this step to finish, or for one of the
substeps above to jump straight to the next step, with
resource type still being unknown. In both cases, the next
step will trigger fallback.
9. Handler: Handle the content as given by the first of the
following cases that matches:
If the resource type is an [14240]XML MIME type, or if the
resource type does not start with "image/"
If the [14241]object element's [14242]content
navigable is null, then [14243]create a new child
navigable for the element.
Let response be the [14244]response from
[14245]fetch.
If response's [14246]URL does not [14247]match
about:blank, then [14248]navigate the element's
[14249]content navigable to response's [14250]URL
using the element's [14251]node document, with
[14252]historyHandling set to "[14253]replace".
The [14254]data attribute of the [14255]object
element doesn't get updated if the [14256]content
navigable gets further [14257]navigated to other
locations.
The [14258]object element [14259]represents its
[14260]content navigable.
If the resource type starts with "image/", and support for
images has not been disabled
[14261]Destroy a child navigable given the
[14262]object element.
Apply the [14263]image sniffing rules to determine
the type of the image.
The [14264]object element [14265]represents the
specified image.
If the image cannot be rendered, e.g. because it is
malformed or in an unsupported format, jump to the
step below labeled fallback.
Otherwise
The given resource type is not supported. Jump to
the step below labeled fallback.
If the previous step ended with the resource type
being unknown, this is the case that is triggered.
10. The element's contents are not part of what the [14266]object
element represents.
11. If the [14267]object element does not represent its
[14268]content navigable, then once the resource is completely
loaded, [14269]queue an element task on the [14270]DOM
manipulation task source given the [14271]object element to
[14272]fire an event named [14273]load at the element.
If the element does represent its [14274]content navigable,
then an analogous task will be queued when the created
[14275]Document is [14276]completely finished loading.
12. Return.
4. Fallback: The [14277]object element [14278]represents the element's
children. This is the element's [14279]fallback content.
[14280]Destroy a child navigable given the element.
Due to the algorithm above, the contents of [14281]object elements act
as [14282]fallback content, used only when referenced resources can't
be shown (e.g. because it returned a 404 error). This allows multiple
[14283]object elements to be nested inside each other, targeting
multiple user agents with different capabilities, with the user agent
picking the first one it supports.
The [14284]object element [14285]potentially delays the load event.
The [14286]form attribute is used to explicitly associate the
[14287]object element with its [14288]form owner.
The [14289]object element supports [14290]dimension attributes.
(BUTTON) ✔MDN
[14291]HTMLObjectElement/data
Support in all current engines.
Firefox1+Safari3+Chrome1+
__________________________________________________________________
The contentWindow getter steps are to return [14299]this's
[14300]content window.
The [14301]willValidate, [14302]validity, and [14303]validationMessage
attributes, and the [14304]checkValidity(), [14305]reportValidity(),
and [14306]setCustomValidity() methods, are part of the
[14307]constraint validation API. The [14308]form IDL attribute is part
of the element's forms API.
In this example, an HTML page is embedded in another using the
[14309]object element.
My HTML Clock
4.8.8 The video element
(BUTTON) ✔MDN
[14310]Element/video
Support in all current engines.
Firefox3.5+Safari3.1+Chrome3+
__________________________________________________________________
[14312]Categories:
[14313]Flow content.
[14314]Phrasing content.
[14315]Embedded content.
If the element has a [14316]controls attribute:
[14317]Interactive content.
[14318]Palpable content.
[14319]Contexts in which this element can be used:
Where [14320]embedded content is expected.
[14321]Content model:
If the element has a [14322]src attribute: zero or more
[14323]track elements, then [14324]transparent, but with no
[14325]media element descendants.
If the element does not have a [14326]src attribute: zero or
more [14327]source elements, then zero or more [14328]track
elements, then [14329]transparent, but with no [14330]media
element descendants.
[14331]Tag omission in text/html:
Neither tag is omissible.
[14332]Content attributes:
[14333]Global attributes
[14334]src — Address of the resource
[14335]crossorigin — How the element handles crossorigin
requests
[14336]poster — Poster frame to show prior to video playback
[14337]preload — Hints how much buffering the [14338]media
resource will likely need
[14339]autoplay — Hint that the [14340]media resource can be
started automatically when the page is loaded
[14341]playsinline — Encourage the user agent to display video
content within the element's playback area
[14342]loop — Whether to loop the [14343]media resource
[14344]muted — Whether to mute the [14345]media resource by
default
[14346]controls — Show user agent controls
[14347]width — Horizontal dimension
[14348]height — Vertical dimension
[[14355]CEReactions] attribute unsigned long [14356]width;
[[14357]CEReactions] attribute unsigned long [14358]height;
readonly attribute unsigned long [14359]videoWidth;
readonly attribute unsigned long [14360]videoHeight;
[[14361]CEReactions] attribute USVString [14362]poster;
[[14363]CEReactions] attribute boolean [14364]playsInline;
};
A [14365]video element is used for playing videos or movies, and audio
files with captions.
Content may be provided inside the [14366]video element. User agents
should not show this content to the user; it is intended for older web
browsers which do not support [14367]video, so that text can be shown
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 hard-of-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 [14368]track element. Sign-language tracks can
be embedded in the video stream. Audio descriptions can be embedded in
the video stream or in text form using a [14369]WebVTT file referenced
using the [14370]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 [14371]video element. [14372][WEBVTT]
The [14373]video element is a [14374]media element whose [14375]media
data is ostensibly video data, possibly with associated audio data.
The [14376]src, [14377]crossorigin, [14378]preload, [14379]autoplay,
[14380]loop, [14381]muted, and [14382]controls attributes are
[14383]the attributes common to all media elements.
The poster attribute gives the [14384]URL of an image file that the
user agent can show while no video data is available. The attribute, if
present, must contain a [14385]valid non-empty URL potentially
surrounded by spaces.
If the specified resource is to be used, then, when the element is
created or when the [14386]poster attribute is set, changed, or
removed, the user agent must run the following steps to determine the
element's poster frame (regardless of the value of the element's
[14387]show poster flag):
1. If there is an existing instance of this algorithm running for this
[14388]video element, abort that instance of this algorithm without
changing the [14389]poster frame.
2. If the [14390]poster attribute's value is the empty string or if
the attribute is absent, then there is no [14391]poster frame;
return.
3. Let url be the result of [14392]encoding-parsing a URL given the
[14393]poster attribute's value, relative to the element's
[14394]node document.
4. If url is failure, then return. There is no [14395]poster frame.
5. Let request be a new [14396]request whose [14397]URL is url,
[14398]client is the element's [14399]node document's
[14400]relevant settings object, [14401]destination is "image",
[14402]initiator type is "video", [14403]credentials mode is
"include", and whose [14404]use-URL-credentials flag is set.
6. [14405]Fetch request. This must [14406]delay the load event of the
element's [14407]node document.
7. If an image is thus obtained, the [14408]poster frame is that
image. Otherwise, there is no [14409]poster frame.
The image given by the [14410]poster attribute, the [14411]poster
frame, is intended to be 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.
The playsinline attribute is a [14412]boolean attribute. If present, it
serves as a hint to the user agent that the video ought to be displayed
"inline" in the document by default, constrained to the element's
playback area, instead of being displayed fullscreen or in an
independent resizable window.
The absence of the [14413]playsinline attribute does not imply that the
video will display fullscreen by default. Indeed, most user agents have
chosen to play all videos inline by default, and in such user agents
the [14414]playsinline attribute has no effect.
__________________________________________________________________
A [14415]video element represents what is given for the first matching
condition in the list below:
When no video data is available (the element's [14416]readyState
attribute is either [14417]HAVE_NOTHING, or [14418]HAVE_METADATA
but no video data has yet been obtained at all, or the element's
[14419]readyState attribute is any subsequent value but the
[14420]media resource does not have a video channel)
The [14421]video element [14422]represents its [14423]poster
frame, if any, or else [14424]transparent black with no
[14425]natural dimensions.
When the [14426]video element is [14427]paused, the [14428]current
playback position is the first frame of video, and the element's
[14429]show poster flag is set
The [14430]video element [14431]represents its [14432]poster
frame, if any, or else the first frame of the video.
When the [14433]video element is [14434]paused, and the frame of video
corresponding to the [14435]current playback position is not
available (e.g. because the video is seeking or buffering)
When the [14436]video element is neither [14437]potentially playing nor
[14438]paused (e.g. when seeking or stalled)
The [14439]video element [14440]represents the last frame of the
video to have been rendered.
When the [14441]video element is [14442]paused
The [14443]video element [14444]represents the frame of video
corresponding to the [14445]current playback position.
Otherwise (the [14446]video element has a video channel and is
[14447]potentially playing)
The [14448]video element [14449]represents the frame of video at
the continuously increasing [14450]"current" position. When the
[14451]current playback position changes such that the last
frame rendered is no longer the frame corresponding to the
[14452]current playback position in the video, the new frame
must be rendered.
Frames of video must be obtained from the video track that was
[14453]selected when the [14454]event loop last reached [14455]step 1.
Which frame in a video stream corresponds to a particular playback
position is defined by the video stream's format.
The [14456]video element also [14457]represents any [14458]text track
cues whose [14459]text track cue active flag is set and whose
[14460]text track is in the [14461]showing mode, and any audio from the
[14462]media resource, at the [14463]current playback position.
Any audio associated with the [14464]media resource must, if played, be
played synchronized with the [14465]current playback position, at the
element's [14466]effective media volume. The user agent must play the
audio from audio tracks that were [14467]enabled when the [14468]event
loop last reached step 1.
In addition to the above, the user agent may provide messages to the
user (such as "buffering", "no video loaded", "error", or more detailed
information) by overlaying text or icons on the video or other areas of
the element's playback area, or in another appropriate manner.
User agents that cannot render the video may instead make the element
[14469]represent a link to an external video playback utility or to the
video data itself.
When a [14470]video element's [14471]media resource has a video
channel, the element provides a [14472]paint source whose width is the
[14473]media resource's [14474]natural width, whose height is the
[14475]media resource's [14476]natural height, and whose appearance is
the frame of video corresponding to the [14477]current playback
position, if that is available, or else (e.g. when the video is seeking
or buffering) its previous appearance, if any, or else (e.g. because
the video is still loading the first frame) blackness.
__________________________________________________________________
Firefox Android?Safari iOS3+Chrome Android?WebView
Android37+Samsung Internet?Opera Android11+
These attributes return the natural dimensions of the video, or
0 if the dimensions are not known.
The natural width and natural height of the [14482]media resource are
the dimensions of the resource in [14483]CSS pixels after taking into
account the resource's dimensions, aspect ratio, clean aperture,
resolution, and so forth, as defined for the format used by the
resource. If an anamorphic format does not define how to apply the
aspect ratio to the video data's dimensions to obtain the "correct"
dimensions, then the user agent must apply the ratio by increasing one
dimension and leaving the other unchanged.
The videoWidth IDL attribute must return the [14484]natural width of
the video in [14485]CSS pixels. The videoHeight IDL attribute must
return the [14486]natural height of the video in [14487]CSS pixels. If
the element's [14488]readyState attribute is [14489]HAVE_NOTHING, then
the attributes must return 0.
Whenever the [14490]natural width or [14491]natural height of the video
changes (including, for example, because the [14492]selected video
track was changed), if the element's [14493]readyState attribute is not
[14494]HAVE_NOTHING, the user agent must [14495]queue a media element
task given the [14496]media element to [14497]fire an event named
[14498]resize at the [14499]media element.
The [14500]video element supports [14501]dimension attributes.
In the absence of style rules to the contrary, video content should be
rendered inside the element's playback area such that the video content
is shown centered in the playback area at the largest possible size
that fits completely within it, with the video content's aspect ratio
being preserved. Thus, if the aspect ratio of the playback area does
not match the aspect ratio of the video, the video will be shown
letterboxed or pillarboxed. Areas of the element's playback area that
do not contain the video represent nothing.
In user agents that implement CSS, the above requirement can be
implemented by using the [14502]style rule suggested in the Rendering
section.
The [14503]natural width of a [14504]video element's playback area is
the [14505]natural width of the [14506]poster frame, if that is
available and the element currently [14507]represents its poster frame;
otherwise, it is the [14508]natural width of the video resource, if
that is available; otherwise the [14509]natural width is missing.
The [14510]natural height of a [14511]video element's playback area is
the [14512]natural height of the [14513]poster frame, if that is
available and the element currently [14514]represents its poster frame;
otherwise it is the [14515]natural height of the video resource, if
that is available; otherwise the [14516]natural height is missing.
The [14517]default object size is a width of 300 [14518]CSS pixels and
a height of 150 [14519]CSS pixels. [14520][CSSIMAGES]
__________________________________________________________________
User agents should provide controls to enable or disable the display of
closed captions, audio description tracks, and other additional data
associated with the video stream, though such features should, again,
not interfere with the page's normal rendering.
User agents may allow users to view the video content in manners more
suitable to the user, such as fullscreen or in an independent resizable
window. User agents may even trigger such a viewing mode by default
upon playing a video, although they should not do so when the
[14521]playsinline attribute is specified. As with the other user
interface features, controls to enable this should not interfere with
the page's normal rendering unless the user agent is [14522]exposing a
user interface. In such an independent viewing mode, however, user
agents may make full user interfaces visible, even if the
[14523]controls attribute is absent.
User agents may allow video playback to affect system features that
could interfere with the user's experience; for example, user agents
could disable screensavers while video playback is in progress.
__________________________________________________________________
The poster IDL attribute must [14524]reflect the [14525]poster content
attribute.
The playsInline IDL attribute must [14526]reflect the
[14527]playsinline content attribute.
This example shows how to detect when a video has failed to play
correctly:
[14530]Categories:
[14531]Flow content.
[14532]Phrasing content.
[14533]Embedded content.
If the element has a [14534]controls attribute:
[14535]Interactive content.
If the element has a [14536]controls attribute: [14537]Palpable
content.
[14538]Contexts in which this element can be used:
Where [14539]embedded content is expected.
[14540]Content model:
If the element has a [14541]src attribute: zero or more
[14542]track elements, then [14543]transparent, but with no
[14544]media element descendants.
If the element does not have a [14545]src attribute: zero or
more [14546]source elements, then zero or more [14547]track
elements, then [14548]transparent, but with no [14549]media
element descendants.
[14550]Tag omission in text/html:
Neither tag is omissible.
[14551]Content attributes:
[14552]Global attributes
[14553]src — Address of the resource
[14554]crossorigin — How the element handles crossorigin
requests
[14555]preload — Hints how much buffering the [14556]media
resource will likely need
[14557]autoplay — Hint that the [14558]media resource can be
started automatically when the page is loaded
[14559]loop — Whether to loop the [14560]media resource
[14561]muted — Whether to mute the [14562]media resource by
default
[14563]controls — Show user agent controls
An [14572]audio element [14573]represents a sound or audio stream.
Content may be provided inside the [14574]audio element. User agents
should not show this content to the user; it is intended for older web
browsers which do not support [14575]audio, so that text can be shown
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
[14576]video element can be used instead of the [14577]audio element to
play the audio, allowing users to enable the visual alternatives.
Chapter titles can be provided to aid navigation, using the
[14578]track element and a [14579]WebVTT file. And, naturally,
transcripts or other textual alternatives can be provided by simply
linking to them in the prose near the [14580]audio element.
[14581][WEBVTT]
The [14582]audio element is a [14583]media element whose [14584]media
data is ostensibly audio data.
The [14585]src, [14586]crossorigin, [14587]preload, [14588]autoplay,
[14589]loop, [14590]muted, and [14591]controls attributes are
[14592]the attributes common to all media elements.
Firefox Android?Safari iOS3+Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
Returns a new [14595]audio element, with the [14596]src
attribute set to the value passed in the argument, if
applicable.
A legacy factory function is provided for creating
[14597]HTMLAudioElement objects (in addition to the factory methods
from DOM such as [14598]createElement()): Audio(src). When invoked, the
legacy factory function must perform the following steps:
1. Let document be the [14599]current global object's
[14600]associated Document.
2. Let audio be the result of [14601]creating an element given
document, "audio", and the [14602]HTML namespace.
3. [14603]Set an attribute value for audio using "[14604]preload" and
"[14605]auto".
4. If src is given, then [14606]set an attribute value for audio using
"[14607]src" and src. (This will [14608]cause the user agent to
invoke the object's [14609]resource selection algorithm before
returning.)
5. Return audio.
4.8.10 The track element
(BUTTON) ✔MDN
[14610]Element/track
Support in all current engines.
Firefox31+Safari6+Chrome23+
__________________________________________________________________
[14613]Contexts in which this element can be used:
As a child of a [14614]media element, before any [14615]flow
content.
[14616]Content model:
[14617]Nothing.
[14618]Tag omission in text/html:
No [14619]end tag.
[14620]Content attributes:
[14621]Global attributes
[14622]kind — The type of text track
[14623]src — Address of the resource
[14624]srclang — Language of the text track
[14625]label — User-visible label
[14626]default — Enable the track if no other [14627]text track
is more suitable
The [14651]track element allows authors to specify explicit external
timed [14652]text tracks for [14653]media elements. It does not
[14654]represent anything on its own.
The kind attribute is an [14655]enumerated attribute with the following
keywords and states:
Keyword State Brief description
subtitles Subtitles 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 [14656]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 [14657]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 metadata Tracks intended for use from script. Not
displayed by the user agent.
metadata Metadata
The attribute's [14658]missing value default is the [14659]subtitles
state, and its [14660]invalid value default is the [14661]metadata
state.
The src attribute gives the [14662]URL of the text track data. The
value must be a [14663]valid non-empty URL potentially surrounded by
spaces. This attribute must be present.
The element has an associated track URL (a string), initially the empty
string.
When the element's [14664]src attribute is set, run these steps:
1. Let trackURL be failure.
2. Let value be the element's [14665]src attribute value.
3. If value is not the empty string, then set trackURL to the result
of [14666]encoding-parsing-and-serializing a URL given value,
relative to the element's [14667]node document.
4. Set the element's [14668]track URL to trackURL if it is not
failure; otherwise to the empty string.
If the element's [14669]track URL identifies a WebVTT resource, and the
element's [14670]kind attribute is not in the [14671]chapters metadata
or [14672]metadata state, then the WebVTT file must be a [14673]WebVTT
file using cue text. [14674][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 [14675]kind attribute is in the
[14676]subtitles state. [14677][BCP47]
If the element has a [14678]srclang attribute whose value is not the
empty string, then the element's track language is the value of the
attribute. Otherwise, the element has no [14679]track language.
The label attribute gives a user-readable title for the track. This
title is used by user agents when listing [14680]subtitle,
[14681]caption, and [14682]audio description tracks in their user
interface.
The value of the [14683]label attribute, if the attribute is present,
must not be the empty string. Furthermore, there must not be two
[14684]track element children of the same [14685]media element whose
[14686]kind attributes are in the same state, whose [14687]srclang
attributes are both missing or have values that represent the same
language, and whose [14688]label attributes are again both missing or
both have the same value.
If the element has a [14689]label attribute whose value is not the
empty string, then the element's track label is the value of the
attribute. Otherwise, the element's [14690]track label is an empty
string.
The default attribute is a [14691]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 [14692]media element must have no more than one [14693]track
element child whose [14694]kind attribute is in the [14695]subtitles or
[14696]captions state and whose [14697]default attribute is specified.
Each [14698]media element must have no more than one [14699]track
element child whose [14700]kind attribute is in the [14701]description
state and whose [14702]default attribute is specified.
Each [14703]media element must have no more than one [14704]track
element child whose [14705]kind attribute is in the [14706]chapters
metadata state and whose [14707]default attribute is specified.
There is no limit on the number of [14708]track elements whose
[14709]kind attribute is in the [14710]metadata state and whose
[14711]default attribute is specified.
track.[14712]readyState
Returns the [14713]text track readiness state, represented by a
number from the following list:
track.[14714]NONE (0)
The [14715]text track not loaded state.
track.[14716]LOADING (1)
The [14717]text track loading state.
track.[14718]LOADED (2)
The [14719]text track loaded state.
track.[14720]ERROR (3)
The [14721]text track failed to load state.
track.[14722]track
Returns the [14723]TextTrack object corresponding to the
[14724]text track of the [14725]track element.
The readyState attribute must return the numeric value corresponding to
the [14726]text track readiness state of the [14727]track element's
[14728]text track, as defined by the following list:
NONE (numeric value 0)
The [14729]text track not loaded state.
LOADING (numeric value 1)
The [14730]text track loading state.
LOADED (numeric value 2)
The [14731]text track loaded state.
ERROR (numeric value 3)
The [14732]text track failed to load state.
The track IDL attribute must, on getting, return the [14733]track
element's [14734]text track's corresponding [14735]TextTrack object.
(BUTTON) ✔MDN
[14736]HTMLTrackElement/src
Support in all current engines.
Firefox31+Safari6+Chrome23+
__________________________________________________________________
The src, srclang, label, and default IDL attributes must [14737]reflect
the respective content attributes of the same name. The kind IDL
attribute must [14738]reflect the content attribute of the same name,
[14739]limited to only known values.
This video has subtitles in several languages:
(The [14740]lang attributes on the last two describe the language of
the [14741]label attribute, not the language of the subtitles
themselves. The language of the subtitles is given by the
[14742]srclang attribute.)
4.8.11 Media elements
[14743]HTMLMediaElement objects ([14744]audio and [14745]video, in this
specification) are simply known as media elements.
(BUTTON) ✔MDN
[14746]HTMLMediaElement
Support in all current engines.
Firefox3.5+Safari3.1+Chrome3+
__________________________________________________________________
The media element attributes, [14818]src, [14819]crossorigin,
[14820]preload, [14821]autoplay, [14822]loop, [14823]muted, and
[14824]controls, apply to all [14825]media elements. They are defined
in this section.
[14826]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 [14827]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 [14828]media resource has an associated origin, which is either
"none", "multiple", "rewritten", or an [14829]origin. It is initially
set to "none".
A [14830]media resource can have multiple audio and video tracks. For
the purposes of a [14831]media element, the video data of the
[14832]media resource is only that of the currently selected track (if
any) as given by the element's [14833]videoTracks attribute when the
[14834]event loop last reached [14835]step 1, and the audio data of the
[14836]media resource is the result of mixing all the currently enabled
tracks (if any) given by the element's [14837]audioTracks attribute
when the [14838]event loop last reached [14839]step 1.
Both [14840]audio and [14841]video elements can be used for both audio
and video. The main difference between the two is simply that the
[14842]audio element has no playback area for visual content (such as
video or captions), whereas the [14843]video element does.
Each [14844]media element has a unique media element event task source.
To queue a media element task with a [14845]media element element and a
series of steps steps, [14846]queue an element task on the [14847]media
element's [14848]media element event task source given element and
steps.
4.8.11.1 Error codes
(BUTTON) ✔MDN
[14849]MediaError
Support in all current engines.
Firefox4+Safari3.1+Chrome3+
__________________________________________________________________
Firefox Android?Safari iOS3+Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
Returns a [14852]MediaError object representing the current
error state of the element.
Returns null if there is no error.
All [14853]media elements have an associated error status, which
records the last error the element encountered since its
[14854]resource selection algorithm was last invoked. The error
attribute, on getting, must return the [14855]MediaError object created
for this last error, or null if there has not been an error.
[Exposed=Window]
interface MediaError {
const unsigned short [14856]MEDIA_ERR_ABORTED = 1;
const unsigned short [14857]MEDIA_ERR_NETWORK = 2;
const unsigned short [14858]MEDIA_ERR_DECODE = 3;
const unsigned short [14859]MEDIA_ERR_SRC_NOT_SUPPORTED = 4;
readonly attribute unsigned short [14860]code;
readonly attribute DOMString [14861]message;
};
Firefox Android?Safari iOS?Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
Returns the current error's error code, from the list below.
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
Returns a specific informative diagnostic message about the
error condition encountered. The message and message format are
not generally uniform across different user agents. If no such
message is available, then the empty string is returned.
Every [14868]MediaError object has a message, which is a string, and a
code, which is one of the following:
MEDIA_ERR_ABORTED (numeric value 1)
The fetching process for the [14869]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 [14870]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
[14871]media resource, after the resource was established to be
usable.
MEDIA_ERR_SRC_NOT_SUPPORTED (numeric value 4)
The [14872]media resource indicated by the [14873]src attribute
or [14874]assigned media provider object was not suitable.
To create a MediaError, given an error code which is one of the above
values, return a new [14875]MediaError object whose [14876]code is the
given error code and whose [14877]message is a string containing any
details the user agent is able to supply about the cause of the error
condition, or the empty string if the user agent is unable to supply
such details. This message string must not contain only the information
already available via the supplied error code; for example, it must not
simply be a translation of the code into a string format. If no
additional information is available beyond that provided by the error
code, the [14878]message must be set to the empty string.
The code getter steps are to return [14879]this's [14880]code.
The message getter steps are to return [14881]this's [14882]message.
4.8.11.2 Location of the media resource
The src content attribute on [14883]media elements gives the [14884]URL
of the media resource (video, audio) to show. The attribute, if
present, must contain a [14885]valid non-empty URL potentially
surrounded by spaces.
If the [14886]itemprop attribute is specified on the [14887]media
element, then the [14888]src attribute must also be specified.
The crossorigin content attribute on [14889]media elements is a
[14890]CORS settings attribute.
If a [14891]media element is created with a [14892]src attribute, the
user agent must [14893]immediately invoke the [14894]media element's
[14895]resource selection algorithm.
If a [14896]src attribute of a [14897]media element is set or changed,
the user agent must invoke the [14898]media element's [14899]media
element load algorithm. (Removing the [14900]src attribute does not do
this, even if there are [14901]source elements present.)
(BUTTON) ✔MDN
[14902]HTMLMediaElement/src
Support in all current engines.
Firefox3.5+Safari3.1+Chrome3+
__________________________________________________________________
The crossOrigin IDL attribute must [14906]reflect the
[14907]crossorigin content attribute, [14908]limited to only known
values.
A media provider object is an object that can represent a [14909]media
resource, separate from a [14910]URL. [14911]MediaStream objects,
[14912]MediaSource objects, and [14913]Blob objects are all
[14914]media provider objects.
Each [14915]media element can have an assigned media provider object,
which is a [14916]media provider object. When a [14917]media element is
created, it has no [14918]assigned media provider object.
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
Allows the [14921]media element to be assigned a [14922]media
provider object.
Firefox Android?Safari iOS3+Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
Returns the [14925]URL of the current [14926]media resource, if
any.
Returns the empty string when there is no [14927]media resource,
or it doesn't have a [14928]URL.
The currentSrc IDL attribute must initially be set to the empty string.
Its value is changed by the [14929]resource selection algorithm defined
below.
The srcObject IDL attribute, on getting, must return the element's
[14930]assigned media provider object, if any, or null otherwise. On
setting, it must set the element's [14931]assigned media provider
object to the new value, and then invoke the element's [14932]media
element load algorithm.
There are three ways to specify a [14933]media resource: the
[14934]srcObject IDL attribute, the [14935]src content attribute, and
[14936]source elements. The IDL attribute takes priority, followed by
the content attribute, followed by the elements.
4.8.11.3 MIME types
A [14937]media resource can be described in terms of its type,
specifically a [14938]MIME type, in some cases with a codecs parameter.
(Whether the codecs parameter is allowed or not depends on the MIME
type.) [14939][RFC6381]
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 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 [14940]MIME type "[14941]application/octet-stream" with no
parameters is never [14942]a type that the user agent knows it cannot
render. User agents must treat that type as equivalent to the lack of
any explicit [14943]Content-Type metadata when it is used to label a
potential [14944]media resource.
Only the [14945]MIME type "[14946]application/octet-stream" with no
parameters is special-cased here; if any parameter appears with it, it
will be treated just like any other [14947]MIME type. This is a
deviation from the rule that unknown [14948]MIME type parameters should
be ignored.
Firefox Android?Safari iOS3+Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
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.
The canPlayType(type) method must return the empty string if type is
[14951]a type that the user agent knows it cannot render or is the type
"[14952]application/octet-stream"; it must return "probably" if the
user agent is confident that the type represents a [14953]media
resource that it can render if used in with this [14954]audio or
[14955]video element; and it must return "maybe" otherwise.
Implementers are encouraged to return "[14956]maybe" unless the type
can be confidently established as being supported or not. Generally, a
user agent should never return "[14957]probably" for a type that allows
the codecs parameter if that parameter is not present.
This script tests to see if the user agent supports a (fictional) new
format to dynamically decide whether to use a [14958]video element:
Firefox Android4+Safari iOS3+Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
Returns the current state of network activity for the element,
from the codes in the list below.
As [14963]media elements interact with the network, their current
network activity is represented by the networkState attribute. On
getting, it must return the current network state of the element, which
must be one of the following values:
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's [14964]resource selection algorithm is active and
has selected a [14965]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's [14966]resource selection algorithm is active, but
it has not yet found a [14967]resource to use.
The [14968]resource selection algorithm defined below describes exactly
when the [14969]networkState attribute changes value and what events
fire to indicate changes in this state.
Firefox Android?Safari iOS3+Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
Causes the element to reset and start selecting and loading a
new [14972]media resource from scratch.
All [14973]media elements have a can autoplay flag, which must begin in
the true state, and a delaying-the-load-event flag, which must begin in
the false state. While the [14974]delaying-the-load-event flag is true,
the element must [14975]delay the load event of its document.
When the load() method on a [14976]media element is invoked, the user
agent must run the [14977]media element load algorithm.
A [14978]media element has an associated boolean is currently stalled,
which is initially false.
The media element load algorithm consists of the following steps.
1. Set this element's [14979]is currently stalled to false.
2. Abort any already-running instance of the [14980]resource selection
algorithm for this element.
3. Let pending tasks be a list of all [14981]tasks from the
[14982]media element's [14983]media element event task source in
one of the [14984]task queues.
4. For each task in pending tasks that would [14985]resolve pending
play promises or [14986]reject pending play promises, immediately
resolve or reject those promises in the order the corresponding
tasks were queued.
5. Remove each [14987]task in pending tasks from its [14988]task
queue.
Basically, pending events and callbacks are discarded and promises
in-flight to be resolved/rejected are resolved/rejected immediately
when the media element starts loading a new resource.
6. If the [14989]media element's [14990]networkState is set to
[14991]NETWORK_LOADING or [14992]NETWORK_IDLE, [14993]queue a media
element task given the [14994]media element to [14995]fire an event
named [14996]abort at the [14997]media element.
7. If the [14998]media element's [14999]networkState is not set to
[15000]NETWORK_EMPTY, then:
1. [15001]Queue a media element task given the [15002]media
element to [15003]fire an event named [15004]emptied at the
[15005]media element.
2. If a fetching process is in progress for the [15006]media
element, the user agent should stop it.
3. If the [15007]media element's [15008]assigned media provider
object is a [15009]MediaSource object, then [15010]detach it.
4. [15011]Forget the media element's media-resource-specific
tracks.
5. If [15012]readyState is not set to [15013]HAVE_NOTHING, then
set it to that state.
6. If the [15014]paused attribute is false, then:
1. Set the [15015]paused attribute to true.
2. [15016]Take pending play promises and [15017]reject
pending play promises with the result and an
[15018]"AbortError" [15019]DOMException.
7. If [15020]seeking is true, set it to false.
8. Set the [15021]current playback position to 0.
Set the [15022]official playback position to 0.
If this changed the [15023]official playback position, then
[15024]queue a media element task given the [15025]media
element to [15026]fire an event named [15027]timeupdate at the
[15028]media element.
9. Set the [15029]timeline offset to Not-a-Number (NaN).
10. Update the [15030]duration attribute to Not-a-Number (NaN).
The user agent [15031]will not fire a [15032]durationchange
event for this particular change of the duration.
8. Set the [15033]playbackRate attribute to the value of the
[15034]defaultPlaybackRate attribute.
9. Set the [15035]error attribute to null and the [15036]can autoplay
flag to true.
10. Invoke the [15037]media element's [15038]resource selection
algorithm.
11. Playback of any previously playing [15039]media resource for this
element stops.
The resource selection algorithm for a [15040]media element is as
follows. This algorithm is always invoked as part of a [15041]task, but
one of the first steps in the algorithm is to return and continue
running the remaining steps [15042]in parallel. In addition, this
algorithm interacts closely with the [15043]event loop mechanism; in
particular, it has [15044]synchronous sections (which are triggered as
part of the [15045]event loop algorithm). Steps in such sections are
marked with ⌛.
1. Set the element's [15046]networkState attribute to the
[15047]NETWORK_NO_SOURCE value.
2. Set the element's [15048]show poster flag to true.
3. Set the [15049]media element's [15050]delaying-the-load-event flag
to true (this [15051]delays the load event).
4. [15052]Await a stable state, allowing the [15053]task that invoked
this algorithm to continue. The [15054]synchronous section consists
of all the remaining steps of this algorithm until the algorithm
says the [15055]synchronous section has ended. (Steps in
[15056]synchronous sections are marked with ⌛.)
5. ⌛ If the [15057]media element's [15058]blocked-on-parser flag is
false, then [15059]populate the list of pending text tracks.
6. ⌛ If the [15060]media element has an [15061]assigned media provider
object, then let mode be object.
⌛ Otherwise, if the [15062]media element has no [15063]assigned
media provider object but has a [15064]src attribute, then let mode
be attribute.
⌛ Otherwise, if the [15065]media element does not have an
[15066]assigned media provider object and does not have a
[15067]src attribute, but does have a [15068]source element child,
then let mode be children and let candidate be the first such
[15069]source element child in [15070]tree order.
⌛ Otherwise, the [15071]media element has no [15072]assigned media
provider object and has neither a [15073]src attribute nor a
[15074]source element child:
1. ⌛ Set the [15075]networkState to [15076]NETWORK_EMPTY.
2. ⌛ Set the element's [15077]delaying-the-load-event flag to
false. This stops [15078]delaying the load event.
3. End the [15079]synchronous section and return.
7. ⌛ Set the [15080]media element's [15081]networkState to
[15082]NETWORK_LOADING.
8. ⌛ [15083]Queue a media element task given the [15084]media element
to [15085]fire an event named [15086]loadstart at the [15087]media
element.
9. Run the appropriate steps from the following list:
If mode is object
1. ⌛ Set the [15088]currentSrc attribute to the empty
string.
2. End the [15089]synchronous section, continuing the
remaining steps [15090]in parallel.
3. Run the [15091]resource fetch algorithm with the
[15092]assigned media provider object. If that algorithm
returns without aborting this one, then the load failed.
4. Failed with media provider: Reaching this step indicates
that the media resource failed to load. [15093]Take
pending play promises and [15094]queue a media element
task given the [15095]media element to run the
[15096]dedicated media source failure steps with the
result.
5. Wait for the [15097]task queued by the previous step to
have executed.
6. Return. The element won't attempt to load another
resource until this algorithm is triggered again.
If mode is attribute
1. ⌛ If the [15098]src attribute's value is the empty
string, then end the [15099]synchronous section, and jump
down to the failed with attribute step below.
2. ⌛ Let urlRecord be the result of [15100]encoding-parsing
a URL given the [15101]src attribute's value, relative to
the [15102]media element's [15103]node document when the
[15104]src attribute was last changed.
3. ⌛ If urlRecord is not failure, then set the
[15105]currentSrc attribute to the result of applying the
[15106]URL serializer to urlRecord.
4. End the [15107]synchronous section, continuing the
remaining steps [15108]in parallel.
5. If urlRecord is not failure, then run the [15109]resource
fetch algorithm with urlRecord. If that algorithm returns
without aborting this one, then the load failed.
6. Failed with attribute: Reaching this step indicates that
the media resource failed to load or that urlRecord is
failure. [15110]Take pending play promises and
[15111]queue a media element task given the [15112]media
element to run the [15113]dedicated media source failure
steps with the result.
7. Wait for the [15114]task queued by the previous step to
have executed.
8. Return. The element won't attempt to load another
resource until this algorithm is triggered again.
Otherwise (mode is children)
1. ⌛ Let pointer be a position defined by two adjacent nodes
in the [15115]media element's child list, treating the
start of the list (before the first child in the list, if
any) and end of the list (after the last child in the
list, if any) as nodes in their own right. One node is
the node before pointer, and the other node is the node
after pointer. Initially, let pointer be the position
between the candidate node and the next node, if there
are any, or the end of the list, if it is the last node.
As nodes are [15116]inserted, [15117]removed, and
[15118]moved into the [15119]media element, pointer must
be updated as follows:
If a new node is [15120]inserted or [15121]moved
between the two nodes that define pointer
Let pointer be the point between the node
before pointer and the new node. In other
words, insertions at pointer go after pointer.
If the node before pointer is removed
Let pointer be the point between the node
after pointer and the node before the node
after pointer. In other words, pointer doesn't
move relative to the remaining nodes.
If the node after pointer is removed
Let pointer be the point between the node
before pointer and the node after the node
before pointer. Just as with the previous
case, pointer doesn't move relative to the
remaining nodes.
Other changes don't affect pointer.
2. ⌛ Process candidate: If candidate does not have a
[15122]src attribute, or if its [15123]src attribute's
value is the empty string, then end the
[15124]synchronous section, and jump down to the failed
with elements step below.
3. ⌛ If candidate has a [15125]media attribute whose value
does not [15126]match the environment, then end the
[15127]synchronous section, and jump down to the failed
with elements step below.
4. ⌛ Let urlRecord be the result of [15128]encoding-parsing
a URL given candidate's [15129]src attribute's value,
relative to candidate's [15130]node document when the
[15131]src attribute was last changed.
5. ⌛ If urlRecord is failure, then end the
[15132]synchronous section, and jump down to the failed
with elements step below.
6. ⌛ If candidate has a [15133]type attribute whose value,
when parsed as a [15134]MIME type (including any codecs
described by the codecs parameter, for types that define
that parameter), represents [15135]a type that the user
agent knows it cannot render, then end the
[15136]synchronous section, and jump down to the failed
with elements step below.
7. ⌛ Set the [15137]currentSrc attribute to the result of
applying the [15138]URL serializer to urlRecord.
8. End the [15139]synchronous section, continuing the
remaining steps [15140]in parallel.
9. Run the [15141]resource fetch algorithm with urlRecord.
If that algorithm returns without aborting this one, then
the load failed.
10. Failed with elements: [15142]Queue a media element task
given the [15143]media element to [15144]fire an event
named [15145]error at candidate.
11. [15146]Await a stable state. The [15147]synchronous
section consists of all the remaining steps of this
algorithm until the algorithm says the [15148]synchronous
section has ended. (Steps in [15149]synchronous sections
are marked with ⌛.)
12. ⌛ [15150]Forget the media element's
media-resource-specific tracks.
13. ⌛ Find next candidate: Let candidate be null.
14. ⌛ Search loop: If the node after pointer is the end of
the list, then jump to the waiting step below.
15. ⌛ If the node after pointer is a [15151]source element,
let candidate be that element.
16. ⌛ Advance pointer so that the node before pointer is now
the node that was after pointer, and the node after
pointer is the node after the node that used to be after
pointer, if any.
17. ⌛ If candidate is null, jump back to the search loop
step. Otherwise, jump back to the process candidate step.
18. ⌛ Waiting: Set the element's [15152]networkState
attribute to the [15153]NETWORK_NO_SOURCE value.
19. ⌛ Set the element's [15154]show poster flag to true.
20. ⌛ [15155]Queue a media element task given the
[15156]media element to set the element's
[15157]delaying-the-load-event flag to false. This stops
[15158]delaying the load event.
21. End the [15159]synchronous section, continuing the
remaining steps [15160]in parallel.
22. Wait until the node after pointer is a node other than
the end of the list. (This step might wait forever.)
23. [15161]Await a stable state. The [15162]synchronous
section consists of all the remaining steps of this
algorithm until the algorithm says the [15163]synchronous
section has ended. (Steps in [15164]synchronous sections
are marked with ⌛.)
24. ⌛ Set the element's [15165]delaying-the-load-event flag
back to true (this [15166]delays the load event again, in
case it hasn't been fired yet).
25. ⌛ Set the [15167]networkState back to
[15168]NETWORK_LOADING.
26. ⌛ Jump back to the find next candidate step above.
The dedicated media source failure steps with a list of promises
promises are the following steps:
1. Set the [15169]error attribute to the result of
[15170]creating a MediaError with
[15171]MEDIA_ERR_SRC_NOT_SUPPORTED.
2. [15172]Forget the media element's media-resource-specific
tracks.
3. Set the element's [15173]networkState attribute to the
[15174]NETWORK_NO_SOURCE value.
4. Set the element's [15175]show poster flag to true.
5. [15176]Fire an event named [15177]error at the [15178]media
element.
6. [15179]Reject pending play promises with promises and a
[15180]"NotSupportedError" [15181]DOMException.
7. Set the element's [15182]delaying-the-load-event flag to
false. This stops [15183]delaying the load event.
To verify a media response given a [15184]response response, a
[15185]media resource resource, and "entire resource" or a (number,
number or "until end") tuple byteRange:
1. If response is a [15186]network error, then return false.
2. If byteRange is "entire resource", then return true.
3. Let internalResponse be response's [15187]unsafe response.
4. If internalResponse's [15188]status is 200, then return true.
5. If internalResponse's [15189]status is not 206, then return false.
6. If the result of [15190]extracting content-range values from
internalResponse is failure, then return false.
Note that the extracted values are not used, and in particular are
not compared to byteRange. So this step serves as syntactic
validation of the `[15191]Content-Range` header, but if the
`[15192]Content-Range` values on the response mismatch the
`[15193]Range` values on the request, that is not considered a
failure.
7. Let origin be "rewritten" if internalResponse's [15194]URL is null;
otherwise internalResponse's [15195]URL's [15196]origin.
8. Let previousOrigin be resource's [15197]origin.
9. If any of the following are true:
+ previousOrigin is "none";
+ origin and previousOrigin are "rewritten"; or
+ origin and previousOrigin are [15198]origins, and origin is
[15199]same origin with previousOrigin,
then set resource's [15200]origin to origin.
Otherwise, if response is [15201]CORS-cross-origin, then return
false.
Otherwise, set resource's [15202]origin to "multiple".
This ensures that opaque responses with range headers do not leak
information by being patched together with other responses from
different origins.
10. Return true.
The resource fetch algorithm for a [15203]media element and a given
[15204]URL record or [15205]media provider object is as follows:
1. Let mode be remote.
2. If the algorithm was invoked with [15206]media provider object,
then set mode to local.
Otherwise:
1. Let object be the result of [15207]obtaining a blob object
using the [15208]URL record's [15209]blob URL entry and the
[15210]media element's [15211]node document's [15212]relevant
settings object.
2. If object is a [15213]media provider object, then set mode to
local.
3. If mode is remote, then let the current media resource be the
resource given by the [15214]URL record passed to this algorithm;
otherwise, let the current media resource be the resource given by
the [15215]media provider object. Either way, the current media
resource is now the element's [15216]media resource.
4. Remove all [15217]media-resource-specific text tracks from the
[15218]media element's [15219]list of pending text tracks, if any.
5. Run the appropriate steps from the following list:
If mode is remote
1. Optionally, run the following substeps. This is the
expected behavior if the user agent intends to not
attempt to fetch the resource until the user requests it
explicitly (e.g. as a way to implement the [15220]preload
attribute's [15221]none keyword).
1. Set the [15222]networkState to [15223]NETWORK_IDLE.
2. [15224]Queue a media element task given the
[15225]media element to [15226]fire an event named
[15227]suspend at the element.
3. [15228]Queue a media element task given the
[15229]media element to set the element's
[15230]delaying-the-load-event flag to false. This
stops [15231]delaying the load event.
4. Wait for the task to be run.
5. Wait for an [15232]implementation-defined event
(e.g., the user requesting that the media element
begin playback).
6. Set the element's [15233]delaying-the-load-event
flag back to true (this [15234]delays the load event
again, in case it hasn't been fired yet).
7. Set the [15235]networkState to
[15236]NETWORK_LOADING.
2. Let destination be "audio" if the [15237]media element is
an [15238]audio element, or "video" otherwise.
3. Let request be the result of [15239]creating a
potential-CORS request given current media resource's
[15240]URL record, destination, and the current state of
[15241]media element's [15242]crossorigin content
attribute.
4. Set request's [15243]client to the [15244]media element's
[15245]node document's [15246]relevant settings object.
5. Set request's [15247]initiator type to destination.
6. Let byteRange, which is "entire resource" or a (number,
number or "until end") tuple, be the byte range required
to satisfy missing data in [15248]media data. This value
is [15249]implementation-defined and may rely on codec,
network conditions or other heuristics. The user-agent
may determine to fetch the resource in full, in which
case byteRange would be "entire resource", to fetch from
a byte offset until the end, in which case byteRange
would be (number, "until end"), or to fetch a range
between two byte offsets, in which case byteRange would
be a (number, number) tuple representing the two offsets.
7. If byteRange is not "entire resource", then:
1. If byteRange[1] is "until end" then [15250]add a
range header to request given byteRange[0].
2. Otherwise, [15251]add a range header to request
given byteRange[0] and byteRange[1].
8. [15252]Fetch request, with [15253]processResponse set to
the following steps given [15254]response response:
1. Let global be the [15255]media element's [15256]node
document's [15257]relevant global object.
2. Let updateMedia be to [15258]queue a media element
task given the [15259]media element to run the first
appropriate steps from the [15260]media data
processing steps list below. (A new task is used for
this so that the work described below occurs
relative to the appropriate [15261]media element
event task source rather than using the
[15262]networking task source.)
3. Let processEndOfMedia be the following step: If the
fetching process has completed without errors,
including decoding the media data, and if all of the
data is available to the user agent without network
access, then, the user agent must move on to the
final step below. This might never happen, e.g. when
streaming an infinite resource such as web radio, or
if the resource is longer than the user agent's
ability to cache data.
4. If the result of [15263]verifying response given the
current media resource and byteRange is false, then
abort these steps.
5. Otherwise, [15264]incrementally read response's
[15265]body given updateMedia, processEndOfMedia, an
empty algorithm, and global.
6. Update the [15266]media data with the contents of
response's [15267]unsafe response obtained in this
fashion. response can be [15268]CORS-same-origin or
[15269]CORS-cross-origin; this affects whether
subtitles referenced in the [15270]media data are
exposed in the API and, for [15271]video elements,
whether a [15272]canvas gets tainted when the video
is drawn on it.
The media element stall timeout is an
[15273]implementation-defined length of time, which
should be about three seconds. When a [15274]media
element that is actively attempting to obtain
[15275]media data has failed to receive any data for a
duration equal to the [15276]media element stall timeout,
the user agent must [15277]queue a media element task
given the [15278]media element to:
1. [15279]Fire an event named [15280]stalled at the
element.
2. Set the element's [15281]is currently stalled to
true.
User agents may allow users to selectively block or slow
[15282]media data downloads. When a [15283]media
element's download has been blocked altogether, the user
agent must act as if it was stalled (as opposed to acting
as if the connection was closed). The rate of the
download may also be throttled automatically by the user
agent, e.g. to balance the download with other
connections sharing the same bandwidth.
User agents may decide to not download more content at
any time, e.g. after buffering five minutes of a one hour
media resource, while waiting for the user to decide
whether to play the resource or not, while waiting for
user input in an interactive resource, or when the user
navigates away from the page. When a [15284]media
element's download has been suspended, the user agent
must [15285]queue a media element task given the
[15286]media element to set the [15287]networkState to
[15288]NETWORK_IDLE and [15289]fire an event named
[15290]suspend at the element. If and when downloading of
the resource resumes, the user agent must [15291]queue a
media element task given the [15292]media element to set
the [15293]networkState to [15294]NETWORK_LOADING.
Between the queuing of these tasks, the load is suspended
(so [15295]progress events don't fire, as described
above).
The [15296]preload attribute provides a hint regarding
how much buffering the author thinks is advisable, even
in the absence of the [15297]autoplay attribute.
When a user agent decides to completely suspend a
download, e.g., if it is waiting until the user starts
playback before downloading any further content, the user
agent must [15298]queue a media element task given the
[15299]media element to set the element's
[15300]delaying-the-load-event flag to false. This stops
[15301]delaying the load event.
Although the above steps give an algorithm for issuing
requests, the user agent may use other means besides
those exact ones, especially in the face of error
conditions. For example, the user agent may reconnect to
the server or switch to a streaming protocol. The user
agent must only consider the resource erroneous, and
proceed into the error branches of the above steps, if
the user agent has given up trying to fetch the resource.
To determine the format of the [15302]media resource, the
user agent must use the [15303]rules for sniffing audio
and video specifically.
While the load is not suspended (see below), every 350ms
(±200ms) or for every byte received, whichever is least
frequent, [15304]queue a media element task given the
[15305]media element to:
1. [15306]Fire an event named [15307]progress at the
element.
2. Set the element's [15308]is currently stalled to
false.
While the user agent might still need network access to
obtain parts of the [15309]media resource, the user agent
must remain on this step.
For example, if the user agent has discarded the first
half of a video, the user agent will remain at this step
even once the [15310]playback has ended, because there is
always the chance the user will seek back to the start.
In fact, in this situation, once [15311]playback has
ended, the user agent will end up firing a [15312]suspend
event, as described earlier.
Otherwise (mode is local)
The resource described by the current media resource, if
any, contains the [15313]media data. It is
[15314]CORS-same-origin.
If the current media resource is a raw data stream (e.g.
from a [15315]File object), then to determine the format
of the [15316]media resource, the user agent must use the
[15317]rules for sniffing audio and video specifically.
Otherwise, if the data stream is pre-decoded, then the
format is the format given by the relevant specification.
Whenever new data for the current media resource becomes
available, [15318]queue a media element task given the
[15319]media element to run the first appropriate steps
from the [15320]media data processing steps list below.
When the current media resource is permanently exhausted
(e.g. all the bytes of a [15321]Blob have been processed),
if there were no decoding errors, then the user agent must
move on to the final step below. This might never happen,
e.g. if the current media resource is a
[15322]MediaStream.
The media data processing steps list is as follows:
If the [15323]media data cannot be fetched at all, due to network
errors, causing the user agent to give up trying to fetch
the resource
If the [15324]media data can be fetched but is found by inspection
to be in an unsupported format, or can otherwise not be
rendered at all
DNS errors, HTTP 4xx and 5xx errors (and equivalents in
other protocols), and other fatal network errors that
occur before the user agent has established whether the
current media resource is usable, as well as the file
using an unsupported container format, or using
unsupported codecs for all the data, must cause the user
agent to execute the following steps:
1. The user agent should cancel the fetching process.
2. Abort this subalgorithm, returning to the [15325]resource
selection algorithm.
If the [15326]media resource is found to have an audio track
1. Create an [15327]AudioTrack object to represent the audio
track.
2. Update the [15328]media element's [15329]audioTracks
attribute's [15330]AudioTrackList object with the new
[15331]AudioTrack object.
3. Let enable be unknown.
4. If either the [15332]media resource or the [15333]URL of
the current media resource indicate a particular set of
audio tracks to enable, or if the user agent has
information that would facilitate the selection of
specific audio tracks to improve the user's experience,
then: if this audio track is one of the ones to enable,
then set enable to true, otherwise, set enable to false.
This could be triggered by [15334]media fragment syntax,
but it could also be triggered e.g. by the user agent
selecting a 5.1 surround sound audio track over a stereo
audio track.
5. If enable is still unknown, then, if the [15335]media
element does not yet have an [15336]enabled audio track,
then set enable to true, otherwise, set enable to false.
6. If enable is true, then enable this audio track,
otherwise, do not enable this audio track.
7. [15337]Fire an event named [15338]addtrack at this
[15339]AudioTrackList object, using [15340]TrackEvent,
with the [15341]track attribute initialized to the new
[15342]AudioTrack object.
If the [15343]media resource is found to have a video track
1. Create a [15344]VideoTrack object to represent the video
track.
2. Update the [15345]media element's [15346]videoTracks
attribute's [15347]VideoTrackList object with the new
[15348]VideoTrack object.
3. Let enable be unknown.
4. If either the [15349]media resource or the [15350]URL of
the current media resource indicate a particular set of
video tracks to enable, or if the user agent has
information that would facilitate the selection of
specific video tracks to improve the user's experience,
then: if this video track is the first such video track,
then set enable to true, otherwise, set enable to false.
This could again be triggered by [15351]media fragment
syntax.
5. If enable is still unknown, then, if the [15352]media
element does not yet have a [15353]selected video track,
then set enable to true, otherwise, set enable to false.
6. If enable is true, then select this track and unselect
any previously selected video tracks, otherwise, do not
select this video track. If other tracks are unselected,
then [15354]a change event will be fired.
7. [15355]Fire an event named [15356]addtrack at this
[15357]VideoTrackList object, using [15358]TrackEvent,
with the [15359]track attribute initialized to the new
[15360]VideoTrack object.
Once enough of the [15361]media data has been fetched to determine
the duration of the [15362]media resource, its dimensions,
and other metadata
This indicates that the resource is usable. The user agent
must follow these substeps:
1. [15363]Establish the media timeline for the purposes of
the [15364]current playback position and the
[15365]earliest possible position, based on the
[15366]media data.
2. Update the [15367]timeline offset to the date and time
that corresponds to the zero time in the [15368]media
timeline established in the previous step, if any. If no
explicit time and date is given by the [15369]media
resource, the [15370]timeline offset must be set to
Not-a-Number (NaN).
3. Set the [15371]current playback position and the
[15372]official playback position to the [15373]earliest
possible position.
4. Update the [15374]duration attribute with the time of the
last frame of the resource, if known, on the [15375]media
timeline established above. If it is not known (e.g. a
stream that is in principle infinite), update the
[15376]duration attribute to the value positive Infinity.
The user agent [15377]will [15378]queue a media element
task given the [15379]media element to [15380]fire an
event named [15381]durationchange at the element at this
point.
5. For [15382]video elements, set the [15383]videoWidth and
[15384]videoHeight attributes, and [15385]queue a media
element task given the [15386]media element to
[15387]fire an event named [15388]resize at the
[15389]media element.
Further [15390]resize events will be fired if the
dimensions subsequently change.
6. Set the [15391]readyState attribute to
[15392]HAVE_METADATA.
A [15393]loadedmetadata DOM event [15394]will be fired as
part of setting the [15395]readyState attribute to a new
value.
7. Let jumped be false.
8. If the [15396]media element's [15397]default playback
start position is greater than zero, then [15398]seek to
that time, and let jumped be true.
9. Let the [15399]media element's [15400]default playback
start position be zero.
10. Let the initial playback position be zero.
11. If either the [15401]media resource or the [15402]URL of
the current media resource indicate a particular start
time, then set the initial playback position to that time
and, if jumped is still false, [15403]seek to that time.
For example, with media formats that support [15404]media
fragment syntax, the [15405]fragment can be used to
indicate a start position.
12. If there is no [15406]enabled audio track, then enable an
audio track. This [15407]will cause a change event to be
fired.
13. If there is no [15408]selected video track, then select a
video track. This [15409]will cause a change event to be
fired.
Once the [15410]readyState attribute reaches
[15411]HAVE_CURRENT_DATA, [15412]after the loadeddata
event has been fired, set the element's
[15413]delaying-the-load-event flag to false. This stops
[15414]delaying the load event.
A user agent that is attempting to reduce network usage
while still fetching the metadata for each [15415]media
resource would also stop buffering at this point,
following [15416]the rules described previously, which
involve the [15417]networkState attribute switching to the
[15418]NETWORK_IDLE value and a [15419]suspend event
firing.
The user agent is required to determine the duration of
the [15420]media resource and go through this step before
playing.
Once the entire [15421]media resource has been fetched (but
potentially before any of it has been decoded)
[15422]Fire an event named [15423]progress at the
[15424]media element.
Set the [15425]networkState to [15426]NETWORK_IDLE and
[15427]fire an event named [15428]suspend at the
[15429]media element.
If the user agent ever discards any [15430]media data and
then needs to resume the network activity to obtain it
again, then it must [15431]queue a media element task
given the [15432]media element to set the
[15433]networkState to [15434]NETWORK_LOADING.
If the user agent can keep the [15435]media resource
loaded, then the algorithm will continue to its final step
below, which aborts the algorithm.
If the connection is interrupted after some [15436]media data has
been received, causing the user agent to give up trying to
fetch the resource
Fatal network errors that occur after the user agent has
established whether the current media resource is usable
(i.e. once the [15437]media element's [15438]readyState
attribute is no longer [15439]HAVE_NOTHING) must cause the
user agent to execute the following steps:
1. The user agent should cancel the fetching process.
2. Set the [15440]error attribute to the result of
[15441]creating a MediaError with
[15442]MEDIA_ERR_NETWORK.
3. Set the element's [15443]networkState attribute to the
[15444]NETWORK_IDLE value.
4. Set the element's [15445]delaying-the-load-event flag to
false. This stops [15446]delaying the load event.
5. [15447]Fire an event named [15448]error at the
[15449]media element.
6. Abort the overall [15450]resource selection algorithm.
If the [15451]media data is corrupted
Fatal errors in decoding the [15452]media data that occur
after the user agent has established whether the current
media resource is usable (i.e. once the [15453]media
element's [15454]readyState attribute is no longer
[15455]HAVE_NOTHING) must cause the user agent to execute
the following steps:
1. The user agent should cancel the fetching process.
2. Set the [15456]error attribute to the result of
[15457]creating a MediaError with
[15458]MEDIA_ERR_DECODE.
3. Set the element's [15459]networkState attribute to the
[15460]NETWORK_IDLE value.
4. Set the element's [15461]delaying-the-load-event flag to
false. This stops [15462]delaying the load event.
5. [15463]Fire an event named [15464]error at the
[15465]media element.
6. Abort the overall [15466]resource selection algorithm.
If the [15467]media data fetching process is aborted by the user
The fetching process is aborted by the user, e.g. because
the user pressed a "stop" button, the user agent must
execute the following steps. These steps are not followed
if the [15468]load() method itself is invoked while these
steps are running, as the steps above handle that
particular kind of abort.
1. The user agent should cancel the fetching process.
2. Set the [15469]error attribute to the result of
[15470]creating a MediaError with
[15471]MEDIA_ERR_ABORTED.
3. [15472]Fire an event named [15473]abort at the
[15474]media element.
4. If the [15475]media element's [15476]readyState attribute
has a value equal to [15477]HAVE_NOTHING, set the
element's [15478]networkState attribute to the
[15479]NETWORK_EMPTY value, set the element's [15480]show
poster flag to true, and [15481]fire an event named
[15482]emptied at the element.
Otherwise, set the element's [15483]networkState
attribute to the [15484]NETWORK_IDLE value.
5. Set the element's [15485]delaying-the-load-event flag to
false. This stops [15486]delaying the load event.
6. Abort the overall [15487]resource selection algorithm.
If the [15488]media data can be fetched but has non-fatal errors
or uses, in part, codecs that are unsupported, preventing
the user agent from rendering the content completely
correctly but not preventing playback altogether
The server returning data that is partially usable but
cannot be optimally rendered must cause the user agent to
render just the bits it can handle, and ignore the rest.
If the [15489]media resource is found to declare a
[15490]media-resource-specific text track that the user
agent supports
If the [15491]media data is [15492]CORS-same-origin, run
the [15493]steps to expose a media-resource-specific text
track with the relevant data.
Cross-origin videos do not expose their subtitles, since
that would allow attacks such as hostile sites reading
subtitles from confidential videos on a user's intranet.
6. Final step: If the user agent ever reaches this step (which can
only happen if the entire resource gets loaded and kept available):
abort the overall [15494]resource selection algorithm.
When a [15495]media element is to forget the media element's
media-resource-specific tracks, the user agent must remove from the
[15496]media element's [15497]list of text tracks all the
[15498]media-resource-specific text tracks, then empty the [15499]media
element's [15500]audioTracks attribute's [15501]AudioTrackList object,
then empty the [15502]media element's [15503]videoTracks attribute's
[15504]VideoTrackList object. No events (in particular, no
[15505]removetrack events) are fired as part of this; the [15506]error
and [15507]emptied events, fired by the algorithms that invoke this
one, can be used instead.
__________________________________________________________________
The preload attribute is an [15508]enumerated attribute with the
following keywords and states:
Keyword State Brief description
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)
none None 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 [15509]media element will
end up with its [15510]readyState attribute set to
[15511]HAVE_METADATA; typically though, some frames will be obtained as
well and it will probably be [15512]HAVE_CURRENT_DATA or
[15513]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.
The attribute's [15514]missing value default and [15515]invalid value
default are both [15516]implementation-defined, though the
[15517]Metadata state is suggested as a compromise between reducing
server load and providing an optimal user experience.
The attribute can be changed even once the [15518]media resource is
being buffered or played; the descriptions in the table above are to be
interpreted with that in mind.
Authors might switch the attribute from "[15519]none" or
"[15520]metadata" to "[15521]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 [15522]preload attribute is intended to provide a hint to the user
agent about what the author thinks will lead to the best user
experience. The attribute may be ignored altogether, for example based
on explicit user preferences or based on the available connectivity.
The preload IDL attribute must [15523]reflect the content attribute of
the same name, [15524]limited to only known values.
The [15525]autoplay attribute can override the [15526]preload attribute
(since if the media plays, it naturally has to buffer first, regardless
of the hint given by the [15527]preload attribute). Including both is
not an error, however.
__________________________________________________________________
Firefox Android?Safari iOS3+Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
Returns a [15530]TimeRanges object that represents the ranges of
the [15531]media resource that the user agent has buffered.
The buffered attribute must return a new static [15532]normalized
TimeRanges object that represents the ranges of the [15533]media
resource, if any, that the user agent has buffered, at the time the
attribute is evaluated. Users agents must accurately determine the
ranges available, even for media streams where this can only be
determined by tedious inspection.
Typically this will be a single range anchored at the zero point, but
if, e.g. the user agent uses HTTP range requests in response to
seeking, then there could be multiple ranges.
User agents may discard previously buffered data.
Thus, a time position included within a range of the objects return by
the [15534]buffered attribute at one time can end up being not included
in the range(s) of objects returned by the same attribute at later
times.
Returning a new object each time is a bad pattern for attribute getters
and is only enshrined here as it would be costly to change it. It is
not to be copied to new APIs.
Firefox Android?Safari iOS3+Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
Returns the length of the [15537]media resource, in seconds,
assuming that the start of the [15538]media resource is at time
zero.
Firefox Android?Safari iOS3+Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
Returns the [15541]official playback position, in seconds.
Can be set, to seek to the given time.
A [15542]media resource has a media timeline that maps times (in
seconds) to positions in the [15543]media resource. The origin of a
timeline is its earliest defined position. The duration of a timeline
is its last defined position.
Establishing the media timeline: if the [15544]media resource somehow
specifies an explicit timeline whose origin is not negative (i.e. gives
each frame a specific time offset and gives the first frame a zero or
positive offset), then the [15545]media timeline should be that
timeline. (Whether the [15546]media resource can specify a timeline or
not depends on the [15547]media resource's format.) If the [15548]media
resource specifies an explicit start time and date, then that time and
date should be considered the zero point in the [15549]media timeline;
the [15550]timeline offset will be the time and date, exposed using the
[15551]getStartDate() method.
If the [15552]media resource has a discontinuous timeline, the user
agent must extend the timeline used at the start of the resource across
the entire resource, so that the [15553]media timeline of the
[15554]media resource increases linearly starting from the
[15555]earliest possible position (as defined below), even if the
underlying [15556]media data has out-of-order or even overlapping time
codes.
For example, if two clips have been concatenated into one video file,
but the video format exposes the original times for the two clips, the
video data might expose a timeline that goes, say, 00:15..00:29 and
then 00:05..00:38. However, the user agent would not expose those
times; it would instead expose the times as 00:15..00:29 and
00:29..01:02, as a single video.
[15557](This is a tracking vector.) In the rare case of a [15558]media
resource that does not have an explicit timeline, the zero time on the
[15559]media timeline should correspond to the first frame of the
[15560]media resource. In the even rarer case of a [15561]media
resource with no explicit timings of any kind, not even frame
durations, the user agent must itself determine the time for each frame
in an [15562]implementation-defined manner.
An example of a file format with no explicit timeline but with explicit
frame durations is the Animated GIF format. An example of a file format
with no explicit timings at all is the JPEG-push format
([15563]multipart/x-mixed-replace with JPEG frames, often used as the
format for MJPEG streams).
If, in the case of a resource with no timing information, the user
agent will nonetheless be able to seek to an earlier point than the
first frame originally provided by the server, then the zero time
should correspond to the earliest seekable time of the [15564]media
resource; otherwise, it should correspond to the first frame received
from the server (the point in the [15565]media resource at which the
user agent began receiving the stream).
At the time of writing, there is no known format that lacks explicit
frame time offsets yet still supports seeking to a frame before the
first frame sent by the server.
Consider a stream from a TV broadcaster, which begins streaming on a
sunny Friday afternoon in October, and always sends connecting user
agents the media data on the same media timeline, with its zero time
set to the start of this stream. Months later, user agents connecting
to this stream will find that the first frame they receive has a time
with millions of seconds. The [15566]getStartDate() method would always
return the date that the broadcast started; this would allow
controllers to display real times in their scrubber (e.g. "2:30pm")
rather than a time relative to when the broadcast began ("8 months, 4
hours, 12 minutes, and 23 seconds").
Consider a stream that carries a video with several concatenated
fragments, broadcast by a server that does not allow user agents to
request specific times but instead just streams the video data in a
predetermined order, with the first frame delivered always being
identified as the frame with time zero. If a user agent connects to
this stream and receives fragments defined as covering timestamps
2010-03-20 23:15:00 UTC to 2010-03-21 00:05:00 UTC and 2010-02-12
14:25:00 UTC to 2010-02-12 14:35:00 UTC, it would expose this with a
[15567]media timeline starting at 0s and extending to 3,600s (one
hour). Assuming the streaming server disconnected at the end of the
second clip, the [15568]duration attribute would then return 3,600. The
[15569]getStartDate() method would return a [15570]Date object with a
time corresponding to 2010-03-20 23:15:00 UTC. However, if a different
user agent connected five minutes later, it would (presumably) receive
fragments covering timestamps 2010-03-20 23:20:00 UTC to 2010-03-21
00:05:00 UTC and 2010-02-12 14:25:00 UTC to 2010-02-12 14:35:00 UTC,
and would expose this with a [15571]media timeline starting at 0s and
extending to 3,300s (fifty five minutes). In this case, the
[15572]getStartDate() method would return a [15573]Date object with a
time corresponding to 2010-03-20 23:20:00 UTC.
In both of these examples, the [15574]seekable attribute would give the
ranges that the controller would want to actually display in its UI;
typically, if the servers don't support seeking to arbitrary times,
this would be the range of time from the moment the user agent
connected to the stream up to the latest frame that the user agent has
obtained; however, if the user agent starts discarding earlier
information, the actual range might be shorter.
In any case, the user agent must ensure that the [15575]earliest
possible position (as defined below) using the established [15576]media
timeline, is greater than or equal to zero.
The [15577]media timeline also has an associated clock. Which clock is
used is user-agent defined, and may be [15578]media resource-dependent,
but it should approximate the user's wall clock.
[15579]Media elements have a current playback position, which must
initially (i.e. in the absence of [15580]media data) be zero seconds.
The [15581]current playback position is a time on the [15582]media
timeline.
[15583]Media elements also have an official playback position, which
must initially be set to zero seconds. The [15584]official playback
position is an approximation of the [15585]current playback position
that is kept stable while scripts are running.
[15586]Media elements also have a default playback start position,
which must initially be set to zero seconds. This time is used to allow
the element to be seeked even before the media is loaded.
Each [15587]media element has a show poster flag. When a [15588]media
element is created, this flag must be set to true. This flag is used to
control when the user agent is to show a poster frame for a
[15589]video element instead of showing the video contents.
The currentTime attribute must, on getting, return the [15590]media
element's [15591]default playback start position, unless that is zero,
in which case it must return the element's [15592]official playback
position. The returned value must be expressed in seconds. On setting,
if the [15593]media element's [15594]readyState is [15595]HAVE_NOTHING,
then it must set the [15596]media element's [15597]default playback
start position to the new value; otherwise, it must set the
[15598]official playback position to the new value and then [15599]seek
to the new value. The new value must be interpreted as being in
seconds.
If the [15600]media resource is a streaming resource, then the user
agent might be unable to obtain certain parts of the resource after it
has expired from its buffer. Similarly, some [15601]media resources
might have a [15602]media timeline that doesn't start at zero. The
earliest possible position is the earliest position in the stream or
resource that the user agent can ever obtain again. It is also a time
on the [15603]media timeline.
The [15604]earliest possible position is not explicitly exposed in the
API; it corresponds to the start time of the first range in the
[15605]seekable attribute's [15606]TimeRanges object, if any, or the
[15607]current playback position otherwise.
When the [15608]earliest possible position changes, then: if the
[15609]current playback position is before the [15610]earliest possible
position, the user agent must [15611]seek to the [15612]earliest
possible position; otherwise, if the user agent has not fired a
[15613]timeupdate event at the element in the past 15 to 250ms and is
not still running event handlers for such an event, then the user agent
must [15614]queue a media element task given the [15615]media element
to [15616]fire an event named [15617]timeupdate at the element.
Because of the above requirement and the requirement in the
[15618]resource fetch algorithm that kicks in [15619]when the metadata
of the clip becomes known, the [15620]current playback position can
never be less than the [15621]earliest possible position.
If at any time the user agent learns that an audio or video track has
ended and all [15622]media data relating to that track corresponds to
parts of the [15623]media timeline that are before the [15624]earliest
possible position, the user agent may [15625]queue a media element task
given the [15626]media element to run these steps:
1. Remove the track from the [15627]audioTracks attribute's
[15628]AudioTrackList object or the [15629]videoTracks attribute's
[15630]VideoTrackList object as appropriate.
2. [15631]Fire an event named [15632]removetrack at the [15633]media
element's aforementioned [15634]AudioTrackList or
[15635]VideoTrackList object, using [15636]TrackEvent, with the
[15637]track attribute initialized to the [15638]AudioTrack or
[15639]VideoTrack object representing the track.
The duration attribute must return the time of the end of the
[15640]media resource, in seconds, on the [15641]media timeline. If no
[15642]media data is available, then the attributes must return the
Not-a-Number (NaN) value. If the [15643]media resource is not known to
be bounded (e.g. streaming radio, or a live event with no announced end
time), then the attribute must return the positive Infinity value.
The user agent must determine the duration of the [15644]media resource
before playing any part of the [15645]media data and before setting
[15646]readyState to a value greater than or equal to
[15647]HAVE_METADATA, even if doing so requires fetching multiple parts
of the resource.
When the length of the [15648]media resource changes to a known value
(e.g. from being unknown to known, or from a previously established
length to a new length) the user agent must [15649]queue a media
element task given the [15650]media element to [15651]fire an event
named [15652]durationchange at the [15653]media element. (The event is
not fired when the duration is reset as part of loading a new media
resource.) If the duration is changed such that the [15654]current
playback position ends up being greater than the time of the end of the
[15655]media resource, then the user agent must also [15656]seek to the
time of the end of the [15657]media resource.
If an "infinite" stream ends for some reason, then the duration would
change from positive Infinity to the time of the last frame or sample
in the stream, and the [15658]durationchange event would be fired.
Similarly, if the user agent initially estimated the [15659]media
resource's duration instead of determining it precisely, and later
revises the estimate based on new information, then the duration would
change and the [15660]durationchange event would be fired.
Some video files also have an explicit date and time corresponding to
the zero time in the [15661]media timeline, known as the timeline
offset. Initially, the [15662]timeline offset must be set to
Not-a-Number (NaN).
The getStartDate() method must return [15663]a new Date object
representing the current [15664]timeline offset.
__________________________________________________________________
The loop attribute is a [15665]boolean attribute that, if specified,
indicates that the [15666]media element is to seek back to the start of
the [15667]media resource upon reaching the end.
(BUTTON) ✔MDN
[15668]HTMLMediaElement/loop
Support in all current engines.
Firefox11+Safari4+Chrome3+
__________________________________________________________________
Firefox Android?Safari iOS3+Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
Returns a value that expresses the current state of the element
with respect to rendering the [15672]current playback position,
from the codes in the list below.
[15673]Media elements have a ready state, which describes to what
degree they are ready to be rendered at the [15674]current playback
position. The possible values are as follows; the ready state of a
media element at any particular time is the greatest value describing
the state of the element:
HAVE_NOTHING (numeric value 0)
No information regarding the [15675]media resource is available.
No data for the [15676]current playback position is available.
[15677]Media elements whose [15678]networkState attribute are
set to [15679]NETWORK_EMPTY are always in the
[15680]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 [15681]video
element, the dimensions of the video are also available. No
[15682]media data is available for the immediate [15683]current
playback position.
HAVE_CURRENT_DATA (numeric value 2)
Data for the immediate [15684]current playback position is
available, but either not enough data is available that the user
agent could successfully advance the [15685]current playback
position in the [15686]direction of playback at all without
immediately reverting to the [15687]HAVE_METADATA state, or
there is no more data to obtain in the [15688]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 [15689]current playback position is at the end
of the current frame; and to when [15690]playback has ended.
HAVE_FUTURE_DATA (numeric value 3)
Data for the immediate [15691]current playback position is
available, as well as enough data for the user agent to advance
the [15692]current playback position in the [15693]direction of
playback at least a little without immediately reverting to the
[15694]HAVE_METADATA state, and [15695]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 [15696]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 [15697]current playback position is
in the middle of a frame. The user agent cannot be in this state
if [15698]playback has ended, as the [15699]current playback
position can never advance in this case.
HAVE_ENOUGH_DATA (numeric value 4)
All the conditions described for the [15700]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 [15701]current playback position, if it were to
advance at the element's [15702]playbackRate, would not
overtake the available data before playback reaches the end of
the [15703]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 [15704]HAVE_METADATA and
[15705]HAVE_CURRENT_DATA is negligible. Really the only time the
difference is relevant is when painting a [15706]video element onto a
[15707]canvas, where it distinguishes the case where something will be
drawn ([15708]HAVE_CURRENT_DATA or greater) from the case where nothing
is drawn ([15709]HAVE_METADATA or less). Similarly, the difference
between [15710]HAVE_CURRENT_DATA (only the current frame) and
[15711]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.
When the ready state of a [15712]media element whose
[15713]networkState is not [15714]NETWORK_EMPTY changes, the user agent
must follow the steps given below:
1. Apply the first applicable set of substeps from the following list:
If the previous ready state was [15715]HAVE_NOTHING, and the new
ready state is [15716]HAVE_METADATA
[15717]Queue a media element task given the [15718]media
element to [15719]fire an event named
[15720]loadedmetadata at the element.
Before this task is run, as part of the [15721]event loop
mechanism, the rendering will have been updated to resize
the [15722]video element if appropriate.
If the previous ready state was [15723]HAVE_METADATA and the new
ready state is [15724]HAVE_CURRENT_DATA or greater
If this is the first time this occurs for this
[15725]media element since the [15726]load() algorithm was
last invoked, the user agent must [15727]queue a media
element task given the [15728]media element to [15729]fire
an event named [15730]loadeddata at the element.
If the new ready state is [15731]HAVE_FUTURE_DATA or
[15732]HAVE_ENOUGH_DATA, then the relevant steps below
must then be run also.
If the previous ready state was [15733]HAVE_FUTURE_DATA or more,
and the new ready state is [15734]HAVE_CURRENT_DATA or
less
If the [15735]media element was [15736]potentially playing
before its [15737]readyState attribute changed to a value
lower than [15738]HAVE_FUTURE_DATA, and the element has
not [15739]ended playback, and playback has not
[15740]stopped due to errors, [15741]paused for user
interaction, or [15742]paused for in-band content, the
user agent must [15743]queue a media element task given
the [15744]media element to [15745]fire an event named
[15746]timeupdate at the element, and [15747]queue a media
element task given the [15748]media element to [15749]fire
an event named [15750]waiting at the element.
If the previous ready state was [15751]HAVE_CURRENT_DATA or less,
and the new ready state is [15752]HAVE_FUTURE_DATA
The user agent must [15753]queue a media element task
given the [15754]media element to [15755]fire an event
named [15756]canplay at the element.
If the element's [15757]paused attribute is false, the
user agent must [15758]notify about playing for the
element.
If the new ready state is [15759]HAVE_ENOUGH_DATA
If the previous ready state was [15760]HAVE_CURRENT_DATA
or less, the user agent must [15761]queue a media element
task given the [15762]media element to [15763]fire an
event named [15764]canplay at the element, and, if the
element's [15765]paused attribute is false, [15766]notify
about playing for the element.
The user agent must [15767]queue a media element task
given the [15768]media element to [15769]fire an event
named [15770]canplaythrough at the element.
If the element is not [15771]eligible for autoplay, then
the user agent must abort these substeps.
The user agent may run the following substeps:
1. Set the [15772]paused attribute to false.
2. If the element's [15773]show poster flag is true, set it
to false and run the [15774]time marches on steps.
3. [15775]Queue a media element task given the element to
[15776]fire an event named [15777]play at the element.
4. [15778]Notify about playing for the element.
Alternatively, if the element is a [15779]video element,
the user agent may start observing whether the element
[15780]intersects the viewport. When the element starts
[15781]intersecting the viewport, if the element is still
[15782]eligible for autoplay, run the substeps above.
Optionally, when the element stops [15783]intersecting the
viewport, if the [15784]can autoplay flag is still true
and the [15785]autoplay attribute is still specified, run
the following substeps:
1. Run the [15786]internal pause steps and set the
[15787]can autoplay flag to true.
2. [15788]Queue a media element task given the element to
[15789]fire an event named [15790]pause at the element.
The substeps for playing and pausing can run multiple
times as the element starts or stops [15791]intersecting
the viewport, as long as the [15792]can autoplay flag is
true.
User agents do not need to support autoplay, and it is
suggested that user agents honor user preferences on the
matter. Authors are urged to use the [15793]autoplay
attribute rather than using script to force the video to
play, so as to allow the user to override the behavior if
so desired.
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 [15794]HAVE_METADATA to [15795]HAVE_ENOUGH_DATA
without passing through the [15796]HAVE_CURRENT_DATA and
[15797]HAVE_FUTURE_DATA states.
The readyState IDL attribute must, on getting, return the value
described above that describes the current ready state of the
[15798]media element.
The autoplay attribute is a [15799]boolean attribute. When present, the
user agent (as described in the algorithm described herein) will
automatically begin playback of the [15800]media resource as soon as it
can do so without stopping.
Authors are urged to use the [15801]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.
(BUTTON) ✔MDN
[15802]HTMLMediaElement/autoplay
Support in all current engines.
Firefox3.5+Safari3.1+Chrome3+
__________________________________________________________________
Firefox Android?Safari iOS3+Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
Returns true if playback has reached the end of the [15808]media
resource.
Firefox Android?Safari iOS3+Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
Returns the default rate of playback, for when the user is not
fast-forwarding or reversing through the [15811]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.
Firefox Android?Safari iOS3+Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
Returns the current rate playback, where 1.0 is normal speed.
Firefox Android?Safari iOS🔰 4+Chrome Android?WebView
Android?Samsung Internet?Opera Android?
Returns true if pitch-preserving algorithms are used when the
[15816]playbackRate is not 1.0. The default value is true.
Can be set to false to have the [15817]media resource's audio
pitch change up or down depending on the [15818]playbackRate.
This is useful for aesthetic and performance reasons.
media.[15819]played
Returns a [15820]TimeRanges object that represents the ranges of
the [15821]media resource that the user agent has played.
Firefox Android?Safari iOS3+Chrome Android?WebView
Android37+Samsung Internet?Opera Android11+
Sets the [15824]paused attribute to false, loading the
[15825]media resource and beginning playback if necessary. If
the playback had ended, will restart it from the start.
Firefox Android?Safari iOS3+Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
Sets the [15828]paused attribute to true, loading the
[15829]media resource if necessary.
The paused attribute represents whether the [15830]media element is
paused or not. The attribute must initially be true.
A [15831]media element is a blocked media element if its
[15832]readyState attribute is in the [15833]HAVE_NOTHING state, the
[15834]HAVE_METADATA state, or the [15835]HAVE_CURRENT_DATA state, or
if the element has [15836]paused for user interaction or [15837]paused
for in-band content.
A [15838]media element is said to be potentially playing when its
[15839]paused attribute is false, the element has not [15840]ended
playback, playback has not [15841]stopped due to errors, and the
element is not a [15842]blocked media element.
A [15843]waiting DOM event [15844]can be fired as a result of an
element that is [15845]potentially playing stopping playback due to its
[15846]readyState attribute changing to a value lower than
[15847]HAVE_FUTURE_DATA.
A [15848]media element is said to be eligible for autoplay when all of
the following are true:
* its [15849]can autoplay flag is true;
* its [15850]paused attribute is true;
* it has an [15851]autoplay attribute specified;
* its [15852]node document's [15853]active sandboxing flag set does
not have the [15854]sandboxed automatic features browsing context
flag set; and
* its [15855]node document is [15856]allowed to use the
"[15857]autoplay" feature.
A [15858]media element is said to be allowed to play if the user agent
and the system allow media playback in the current context.
For example, a user agent could allow playback only when the
[15859]media element's [15860]Window object has [15861]transient
activation, but an exception could be made to allow playback while
[15862]muted.
A [15863]media element is said to have ended playback when:
* The element's [15864]readyState attribute is [15865]HAVE_METADATA
or greater, and
* Either:
+ The [15866]current playback position is the end of the
[15867]media resource, and
+ The [15868]direction of playback is forwards, and
+ The [15869]media element does not have a [15870]loop attribute
specified.
Or:
+ The [15871]current playback position is the [15872]earliest
possible position, and
+ The [15873]direction of playback is backwards.
The ended attribute must return true if, the last time the [15874]event
loop reached [15875]step 1, the [15876]media element had [15877]ended
playback and the [15878]direction of playback was forwards, and false
otherwise.
A [15879]media element is said to have stopped due to errors when the
element's [15880]readyState attribute is [15881]HAVE_METADATA or
greater, and the user agent [15882]encounters a non-fatal error during
the processing of the [15883]media data, and due to that error, is not
able to play the content at the [15884]current playback position.
A [15885]media element is said to have paused for user interaction when
its [15886]paused attribute is false, the [15887]readyState attribute
is either [15888]HAVE_FUTURE_DATA or [15889]HAVE_ENOUGH_DATA and the
user agent has reached a point in the [15890]media resource where the
user has to make a selection for the resource to continue.
It is possible for a [15891]media element to have both [15892]ended
playback and [15893]paused for user interaction at the same time.
When a [15894]media element that is [15895]potentially playing stops
playing because it has [15896]paused for user interaction, the user
agent must [15897]queue a media element task given the [15898]media
element to [15899]fire an event named [15900]timeupdate at the element.
A [15901]media element is said to have paused for in-band content when
its [15902]paused attribute is false, the [15903]readyState attribute
is either [15904]HAVE_FUTURE_DATA or [15905]HAVE_ENOUGH_DATA and the
user agent has suspended playback of the [15906]media resource in order
to play content that is temporally anchored to the [15907]media
resource and has a nonzero length, or to play content that is
temporally anchored to a segment of the [15908]media resource but has a
length longer than that segment.
One example of when a [15909]media element would be [15910]paused for
in-band content is when the user agent is playing [15911]audio
descriptions from an external WebVTT file, and the synthesized speech
generated for a cue is longer than the time between the [15912]text
track cue start time and the [15913]text track cue end time.
__________________________________________________________________
When the [15914]current playback position reaches the end of the
[15915]media resource when the [15916]direction of playback is
forwards, then the user agent must follow these steps:
1. If the [15917]media element has a [15918]loop attribute specified,
then [15919]seek to the [15920]earliest possible position of the
[15921]media resource and return.
2. As defined above, the [15922]ended IDL attribute starts returning
true once the [15923]event loop returns to [15924]step 1.
3. [15925]Queue a media element task given the [15926]media element
and the following steps:
1. [15927]Fire an event named [15928]timeupdate at the
[15929]media element.
2. If the [15930]media element has [15931]ended playback, the
[15932]direction of playback is forwards, and [15933]paused is
false, then:
1. Set the [15934]paused attribute to true.
2. [15935]Fire an event named [15936]pause at the
[15937]media element.
3. [15938]Take pending play promises and [15939]reject
pending play promises with the result and an
[15940]"AbortError" [15941]DOMException.
3. [15942]Fire an event named [15943]ended at the [15944]media
element.
When the [15945]current playback position reaches the [15946]earliest
possible position of the [15947]media resource when the
[15948]direction of playback is backwards, then the user agent must
only [15949]queue a media element task given the [15950]media element
to [15951]fire an event named [15952]timeupdate at the element.
The word "reaches" here does not imply that the [15953]current playback
position needs to have changed during normal playback; it could be via
[15954]seeking, for instance.
__________________________________________________________________
The defaultPlaybackRate attribute gives the desired speed at which the
[15955]media resource is to play, as a multiple of its intrinsic speed.
The attribute is mutable: on getting it must return the last value it
was set to, or 1.0 if it hasn't yet been set; on setting the attribute
must be set to the new value.
The [15956]defaultPlaybackRate is used by the user agent when it
[15957]exposes a user interface to the user.
The playbackRate attribute gives the effective playback rate, which is
the speed at which the [15958]media resource plays, as a multiple of
its intrinsic speed. If it is not equal to the
[15959]defaultPlaybackRate, then the implication is that the user is
using a feature such as fast forward or slow motion playback. The
attribute is mutable: on getting it must return the last value it was
set to, or 1.0 if it hasn't yet been set; on setting, the user agent
must follow these steps:
1. If the given value is not supported by the user agent, then throw a
[15960]"NotSupportedError" [15961]DOMException.
2. Set [15962]playbackRate to the new value, and if the element is
[15963]potentially playing, change the playback speed.
When the [15964]defaultPlaybackRate or [15965]playbackRate attributes
change value (either by being set by script or by being changed
directly by the user agent, e.g. in response to user control) the user
agent must [15966]queue a media element task given the [15967]media
element to [15968]fire an event named [15969]ratechange at the
[15970]media element. The user agent must process attribute changes
smoothly and must not introduce any perceivable gaps or muting of
playback in response.
The preservesPitch getter steps are to return true if a
pitch-preserving algorithm is in effect during playback. The setter
steps are to correspondingly switch the pitch-preserving algorithm on
or off, without any perceivable gaps or muting of playback. By default,
such a pitch-preserving algorithm must be in effect (i.e., the getter
will initially return true).
__________________________________________________________________
The played attribute must return a new static [15971]normalized
TimeRanges object that represents the ranges of points on the
[15972]media timeline of the [15973]media resource reached through the
usual monotonic increase of the [15974]current playback position during
normal playback, if any, at the time the attribute is evaluated.
Returning a new object each time is a bad pattern for attribute getters
and is only enshrined here as it would be costly to change it. It is
not to be copied to new APIs.
__________________________________________________________________
Each [15975]media element has a list of pending play promises, which
must initially be empty.
To take pending play promises for a [15976]media element, the user
agent must run the following steps:
1. Let promises be an empty list of promises.
2. Copy the [15977]media element's [15978]list of pending play
promises to promises.
3. Clear the [15979]media element's [15980]list of pending play
promises.
4. Return promises.
To resolve pending play promises for a [15981]media element with a list
of promises promises, the user agent must resolve each promise in
promises with undefined.
To reject pending play promises for a [15982]media element with a list
of promises promises and an exception name error, the user agent must
reject each promise in promises with error.
To notify about playing for a [15983]media element, the user agent must
run the following steps:
1. [15984]Take pending play promises and let promises be the result.
2. [15985]Queue a media element task given the element and the
following steps:
1. [15986]Fire an event named [15987]playing at the element.
2. [15988]Resolve pending play promises with promises.
When the play() method on a [15989]media element is invoked, the user
agent must run the following steps.
1. If the [15990]media element is not [15991]allowed to play, then
return [15992]a promise rejected with a [15993]"NotAllowedError"
[15994]DOMException.
2. If the [15995]media element's [15996]error attribute is not null
and its [15997]code is [15998]MEDIA_ERR_SRC_NOT_SUPPORTED, then
return [15999]a promise rejected with a [16000]"NotSupportedError"
[16001]DOMException.
This means that the [16002]dedicated media source failure steps
have run. Playback is not possible until the [16003]media element
load algorithm clears the [16004]error attribute.
3. Let promise be a new promise and append promise to the [16005]list
of pending play promises.
4. Run the [16006]internal play steps for the [16007]media element.
5. Return promise.
The internal play steps for a [16008]media element are as follows:
1. If the [16009]media element's [16010]networkState attribute has the
value [16011]NETWORK_EMPTY, invoke the [16012]media element's
[16013]resource selection algorithm.
2. If the [16014]playback has ended and the [16015]direction of
playback is forwards, [16016]seek to the [16017]earliest possible
position of the [16018]media resource.
This [16019]will cause the user agent to [16020]queue a media
element task given the [16021]media element to [16022]fire an event
named [16023]timeupdate at the [16024]media element.
3. If the [16025]media element's [16026]paused attribute is true,
then:
1. Change the value of [16027]paused to false.
2. If the [16028]show poster flag is true, set the element's
[16029]show poster flag to false and run the [16030]time
marches on steps.
3. [16031]Queue a media element task given the [16032]media
element to [16033]fire an event named [16034]play at the
element.
4. If the [16035]media element's [16036]readyState attribute has
the value [16037]HAVE_NOTHING, [16038]HAVE_METADATA, or
[16039]HAVE_CURRENT_DATA, [16040]queue a media element task
given the [16041]media element to [16042]fire an event named
[16043]waiting at the element.
Otherwise, the [16044]media element's [16045]readyState
attribute has the value [16046]HAVE_FUTURE_DATA or
[16047]HAVE_ENOUGH_DATA: [16048]notify about playing for the
element.
4. Otherwise, if the [16049]media element's [16050]readyState
attribute has the value [16051]HAVE_FUTURE_DATA or
[16052]HAVE_ENOUGH_DATA, [16053]take pending play promises and
[16054]queue a media element task given the [16055]media element to
[16056]resolve pending play promises with the result.
The media element is already playing. However, it's possible that
promise will be [16057]rejected before the queued task is run.
5. Set the [16058]media element's [16059]can autoplay flag to false.
__________________________________________________________________
When the pause() method is invoked, and when the user agent is required
to pause the [16060]media element, the user agent must run the
following steps:
1. If the [16061]media element's [16062]networkState attribute has the
value [16063]NETWORK_EMPTY, invoke the [16064]media element's
[16065]resource selection algorithm.
2. Run the [16066]internal pause steps for the [16067]media element.
The internal pause steps for a [16068]media element are as follows:
1. Set the [16069]media element's [16070]can autoplay flag to false.
2. If the [16071]media element's [16072]paused attribute is false, run
the following steps:
1. Change the value of [16073]paused to true.
2. [16074]Take pending play promises and let promises be the
result.
3. [16075]Queue a media element task given the [16076]media
element and the following steps:
1. [16077]Fire an event named [16078]timeupdate at the
element.
2. [16079]Fire an event named [16080]pause at the element.
3. [16081]Reject pending play promises with promises and an
[16082]"AbortError" [16083]DOMException.
4. Set the [16084]official playback position to the
[16085]current playback position.
__________________________________________________________________
If the element's [16086]playbackRate is positive or zero, then the
direction of playback is forwards. Otherwise, it is backwards.
When a [16087]media element is [16088]potentially playing and its
[16089]Document is a [16090]fully active [16091]Document, its
[16092]current playback position must increase monotonically at the
element's [16093]playbackRate units of media time per unit time of the
[16094]media timeline's clock. (This specification always refers to
this as an increase, but that increase could actually be a decrease if
the element's [16095]playbackRate is negative.)
The element's [16096]playbackRate can be 0.0, in which case the
[16097]current playback position doesn't move, despite playback not
being paused ([16098]paused doesn't become true, and the [16099]pause
event doesn't fire).
This specification doesn't define how the user agent achieves the
appropriate playback rate — depending on the protocol and media
available, it is plausible that the user agent could negotiate with the
server to have the server provide the media data at the appropriate
rate, so that (except for the period between when the rate is changed
and when the server updates the stream's playback rate) the client
doesn't actually have to drop or interpolate any frames.
Any time the user agent [16100]provides a stable state, the
[16101]official playback position must be set to the [16102]current
playback position.
While the [16103]direction of playback is backwards, any corresponding
audio must be [16104]muted. While the element's [16105]playbackRate is
so low or so high that the user agent cannot play audio usefully, the
corresponding audio must also be [16106]muted. If the element's
[16107]playbackRate is not 1.0 and [16108]preservesPitch is true, the
user agent must apply pitch adjustment to preserve the original pitch
of the audio. Otherwise, the user agent must speed up or slow down the
audio without any pitch adjustment.
When a [16109]media element is [16110]potentially playing, its audio
data played must be synchronized with the [16111]current playback
position, at the element's [16112]effective media volume. The user
agent must play the audio from audio tracks that were enabled when the
[16113]event loop last reached [16114]step 1.
When a [16115]media element is not [16116]potentially playing, audio
must not play for the element.
[16117]Media elements that are [16118]potentially playing while not
[16119]in a document must not play any video, but should play any audio
component. Media elements must not stop playing just because all
references to them have been removed; only once a media element is in a
state where no further audio could ever be played by that element may
the element be garbage collected.
It is possible for an element to which no explicit references exist to
play audio, even if such an element is not still actively playing: for
instance, it could be unpaused but stalled waiting for content to
buffer, or it could be still buffering, but with a [16120]suspend event
listener that begins playback. Even a media element whose [16121]media
resource has no audio tracks could eventually play audio again if it
had an event listener that changes the [16122]media resource.
__________________________________________________________________
Each [16123]media element has a list of newly introduced cues, which
must be initially empty. Whenever a [16124]text track cue is added to
the [16125]list of cues of a [16126]text track that is in the
[16127]list of text tracks for a [16128]media element, that [16129]cue
must be added to the [16130]media element's [16131]list of newly
introduced cues. Whenever a [16132]text track is added to the
[16133]list of text tracks for a [16134]media element, all of the
[16135]cues in that [16136]text track's [16137]list of cues must be
added to the [16138]media element's [16139]list of newly introduced
cues. When a [16140]media element's [16141]list of newly introduced
cues has new cues added while the [16142]media element's [16143]show
poster flag is not set, then the user agent must run the [16144]time
marches on steps.
When a [16145]text track cue is removed from the [16146]list of cues of
a [16147]text track that is in the [16148]list of text tracks for a
[16149]media element, and whenever a [16150]text track is removed from
the [16151]list of text tracks of a [16152]media element, if the
[16153]media element's [16154]show poster flag is not set, then the
user agent must run the [16155]time marches on steps.
When the [16156]current playback position of a [16157]media element
changes (e.g. due to playback or seeking), the user agent must run the
[16158]time marches on steps. To support use cases that depend on the
timing accuracy of cue event firing, such as synchronizing captions
with shot changes in a video, user agents should fire cue events as
close as possible to their position on the media timeline, and ideally
within 20 milliseconds. If the [16159]current playback position changes
while the steps are running, then the user agent must wait for the
steps to complete, and then must immediately rerun the steps. These
steps are thus run as often as possible or needed.
If one iteration takes a long time, this can cause short duration
[16160]cues to be skipped over as the user agent rushes ahead to "catch
up", so these cues will not appear in the [16161]activeCues list.
The time marches on steps are as follows:
1. Let current cues be a list of [16162]cues, initialized to contain
all the [16163]cues of all the [16164]hidden or [16165]showing
[16166]text tracks of the [16167]media element (not the
[16168]disabled ones) whose [16169]start times are less than or
equal to the [16170]current playback position and whose [16171]end
times are greater than the [16172]current playback position.
2. Let other cues be a list of [16173]cues, initialized to contain all
the [16174]cues of [16175]hidden and [16176]showing [16177]text
tracks of the [16178]media element that are not present in current
cues.
3. Let last time be the [16179]current playback position at the time
this algorithm was last run for this [16180]media element, if this
is not the first time it has run.
4. If the [16181]current playback position has, since the last time
this algorithm was run, only changed through its usual monotonic
increase during normal playback, then let missed cues be the list
of [16182]cues in other cues whose [16183]start times are greater
than or equal to last time and whose [16184]end times are less than
or equal to the [16185]current playback position. Otherwise, let
missed cues be an empty list.
5. Remove all the [16186]cues in missed cues that are also in the
[16187]media element's [16188]list of newly introduced cues, and
then empty the element's [16189]list of newly introduced cues.
6. If the time was reached through the usual monotonic increase of the
[16190]current playback position during normal playback, and if the
user agent has not fired a [16191]timeupdate event at the element
in the past 15 to 250ms and is not still running event handlers for
such an event, then the user agent must [16192]queue a media
element task given the [16193]media element to [16194]fire an event
named [16195]timeupdate at the element. (In the other cases, such
as explicit seeks, relevant events get fired as part of the overall
process of changing the [16196]current playback position.)
The event thus is not to be fired faster than about 66Hz or slower
than 4Hz (assuming the event handlers don't take longer than 250ms
to run). User agents are encouraged to vary the frequency of the
event based on the system load and the average cost of processing
the event each time, so that the UI updates are not any more
frequent than the user agent can comfortably handle while decoding
the video.
7. If all of the [16197]cues in current cues have their [16198]text
track cue active flag set, none of the [16199]cues in other cues
have their [16200]text track cue active flag set, and missed cues
is empty, then return.
8. If the time was reached through the usual monotonic increase of the
[16201]current playback position during normal playback, and there
are [16202]cues in other cues that have their [16203]text track cue
pause-on-exit flag set and that either have their [16204]text track
cue active flag set or are also in missed cues, then
[16205]immediately [16206]pause the [16207]media element.
In the other cases, such as explicit seeks, playback is not paused
by going past the end time of a [16208]cue, even if that [16209]cue
has its [16210]text track cue pause-on-exit flag set.
9. Let events be a list of [16211]tasks, initially empty. Each
[16212]task in this list will be associated with a [16213]text
track, a [16214]text track cue, and a time, which are used to sort
the list before the [16215]tasks are queued.
Let affected tracks be a list of [16216]text tracks, initially
empty.
When the steps below say to prepare an event named event for a
[16217]text track cue target with a time time, the user agent must
run these steps:
1. Let track be the [16218]text track with which the [16219]text
track cue target is associated.
2. Create a [16220]task to [16221]fire an event named event at
target.
3. Add the newly created [16222]task to events, associated with
the time time, the [16223]text track track, and the
[16224]text track cue target.
4. Add track to affected tracks.
10. For each [16225]text track cue in missed cues, [16226]prepare an
event named [16227]enter for the [16228]TextTrackCue object with
the [16229]text track cue start time.
11. For each [16230]text track cue in other cues that either has its
[16231]text track cue active flag set or is in missed cues,
[16232]prepare an event named [16233]exit for the
[16234]TextTrackCue object with the later of the [16235]text track
cue end time and the [16236]text track cue start time.
12. For each [16237]text track cue in current cues that does not have
its [16238]text track cue active flag set, [16239]prepare an event
named [16240]enter for the [16241]TextTrackCue object with the
[16242]text track cue start time.
13. Sort the [16243]tasks in events in ascending time order
([16244]tasks with earlier times first).
Further sort [16245]tasks in events that have the same time by the
relative [16246]text track cue order of the [16247]text track cues
associated with these [16248]tasks.
Finally, sort [16249]tasks in events that have the same time and
same [16250]text track cue order by placing [16251]tasks that fire
[16252]enter events before those that fire [16253]exit events.
14. [16254]Queue a media element task given the [16255]media element
for each [16256]task in events, in list order.
15. Sort affected tracks in the same order as the [16257]text tracks
appear in the [16258]media element's [16259]list of text tracks,
and remove duplicates.
16. For each [16260]text track in affected tracks, in the list order,
[16261]queue a media element task given the [16262]media element to
[16263]fire an event named [16264]cuechange at the [16265]TextTrack
object, and, if the [16266]text track has a corresponding
[16267]track element, to then [16268]fire an event named
[16269]cuechange at the [16270]track element as well.
17. Set the [16271]text track cue active flag of all the [16272]cues in
the current cues, and unset the [16273]text track cue active flag
of all the [16274]cues in the other cues.
18. Run the [16275]rules for updating the text track rendering of each
of the [16276]text tracks in affected tracks that are
[16277]showing, providing the [16278]text track's [16279]text track
language as the fallback language if it is not the empty string.
For example, for [16280]text tracks based on WebVTT, the
[16281]rules for updating the display of WebVTT text tracks.
[16282][WEBVTT]
For the purposes of the algorithm above, a [16283]text track cue is
considered to be part of a [16284]text track only if it is listed in
the [16285]text track list of cues, not merely if it is associated with
the [16286]text track.
If the [16287]media element's [16288]node document stops being a
[16289]fully active document, then the playback will [16290]stop until
the document is active again.
When a [16291]media element is [16292]removed from a Document, the user
agent must run the following steps:
1. [16293]Await a stable state, allowing the [16294]task that removed
the [16295]media element from the [16296]Document to continue. The
[16297]synchronous section consists of all the remaining steps of
this algorithm. (Steps in the [16298]synchronous section are marked
with ⌛.)
2. ⌛ If the [16299]media element is [16300]in a document, return.
3. ⌛ Run the [16301]internal pause steps for the [16302]media element.
4.8.11.9 Seeking
media.[16303]seeking
Returns true if the user agent is currently seeking.
Firefox Android?Safari iOS3+Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
Returns a [16306]TimeRanges object that represents the ranges of
the [16307]media resource to which it is possible for the user
agent to seek.
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
Seeks to near the given time as fast as possible, trading
precision for speed. (To seek to a precise time, use the
[16310]currentTime attribute.)
This does nothing if the media resource has not been loaded.
The seeking attribute must initially have the value false.
The fastSeek(time) method must [16311]seek to the time given by time,
with the approximate-for-speed flag set.
When the user agent is required to seek to a particular new playback
position in the [16312]media resource, optionally with the
approximate-for-speed flag set, it means that the user agent must run
the following steps. This algorithm interacts closely with the
[16313]event loop mechanism; in particular, it has a [16314]synchronous
section (which is triggered as part of the [16315]event loop
algorithm). Steps in that section are marked with ⌛.
1. Set the [16316]media element's [16317]show poster flag to false.
2. If the [16318]media element's [16319]readyState is
[16320]HAVE_NOTHING, return.
3. If the element's [16321]seeking IDL attribute is true, then another
instance of this algorithm is already running. Abort that other
instance of the algorithm without waiting for the step that it is
running to complete.
4. Set the [16322]seeking IDL attribute to true.
5. If the seek was in response to a DOM method call or setting of an
IDL attribute, then continue the script. The remainder of these
steps must be run [16323]in parallel. With the exception of the
steps marked with ⌛, they could be aborted at any time by another
instance of this algorithm being invoked.
6. If the new playback position is later than the end of the
[16324]media resource, then let it be the end of the [16325]media
resource instead.
7. If the new playback position is less than the [16326]earliest
possible position, let it be that position instead.
8. If the (possibly now changed) new playback position is not in one
of the ranges given in the [16327]seekable attribute, then let it
be the position in one of the ranges given in the [16328]seekable
attribute that is the nearest to the new playback position. If two
positions both satisfy that constraint (i.e. the new playback
position is exactly in the middle between two ranges in the
[16329]seekable attribute) then use the position that is closest to
the [16330]current playback position. If there are no ranges given
in the [16331]seekable attribute then set the [16332]seeking IDL
attribute to false and return.
9. If the approximate-for-speed flag is set, adjust the new playback
position to a value that will allow for playback to resume
promptly. If new playback position before this step is before
[16333]current playback position, then the adjusted new playback
position must also be before the [16334]current playback position.
Similarly, if the new playback position before this step is after
[16335]current playback position, then the adjusted new playback
position must also be after the [16336]current playback position.
For example, the user agent could snap to a nearby key frame, so
that it doesn't have to spend time decoding then discarding
intermediate frames before resuming playback.
10. [16337]Queue a media element task given the [16338]media element to
[16339]fire an event named [16340]seeking at the element.
11. Set the [16341]current playback position to the new playback
position.
If the [16342]media element was [16343]potentially playing
immediately before it started seeking, but seeking caused its
[16344]readyState attribute to change to a value lower than
[16345]HAVE_FUTURE_DATA, then a [16346]waiting event [16347]will be
fired at the element.
This step sets the [16348]current playback position, and thus can
immediately trigger other conditions, such as the rules regarding
when playback "[16349]reaches the end of the media resource" (part
of the logic that handles looping), even before the user agent is
actually able to render the media data for that position (as
determined in the next step).
The [16350]currentTime attribute returns the [16351]official
playback position, not the [16352]current playback position, and
therefore gets updated before script execution, separate from this
algorithm.
12. Wait until the user agent has established whether or not the
[16353]media data for the new playback position is available, and,
if it is, until it has decoded enough data to play back that
position.
13. [16354]Await a stable state. The [16355]synchronous section
consists of all the remaining steps of this algorithm. (Steps in
the [16356]synchronous section are marked with ⌛.)
14. ⌛ Set the [16357]seeking IDL attribute to false.
15. ⌛ Run the [16358]time marches on steps.
16. ⌛ [16359]Queue a media element task given the [16360]media element
to [16361]fire an event named [16362]timeupdate at the element.
17. ⌛ [16363]Queue a media element task given the [16364]media element
to [16365]fire an event named [16366]seeked at the element.
__________________________________________________________________
The seekable attribute must return a new static [16367]normalized
TimeRanges object that represents the ranges of the [16368]media
resource, if any, that the user agent is able to seek to, at the time
the attribute is evaluated.
If the user agent can seek to anywhere in the [16369]media resource,
e.g. because it is a simple movie file and the user agent and the
server support HTTP Range requests, then the attribute would return an
object with one range, whose start is the time of the first frame (the
[16370]earliest possible position, typically zero), and whose end is
the same as the time of the first frame plus the [16371]duration
attribute's value (which would equal the time of the last frame, and
might be positive Infinity).
The range might be continuously changing, e.g. if the user agent is
buffering a sliding window on an infinite stream. This is the behavior
seen with DVRs viewing live TV, for instance.
Returning a new object each time is a bad pattern for attribute getters
and is only enshrined here as it would be costly to change it. It is
not to be copied to new APIs.
User agents should adopt a very liberal and optimistic view of what is
seekable. User agents should also buffer recent content where possible
to enable seeking to be fast.
For instance, consider a large video file served on an HTTP server
without support for HTTP Range requests. A browser could implement this
by only buffering the current frame and data obtained for subsequent
frames, never allow seeking, except for seeking to the very start by
restarting the playback. However, this would be a poor implementation.
A high quality implementation would buffer the last few minutes of
content (or more, if sufficient storage space is available), allowing
the user to jump back and rewatch something surprising without any
latency, and would in addition allow arbitrary seeking by reloading the
file from the start if necessary, which would be slower but still more
convenient than having to literally restart the video and watch it all
the way through just to get to an earlier unbuffered spot.
[16372]Media resources might be internally scripted or interactive.
Thus, a [16373]media element could play in a non-linear fashion. If
this happens, the user agent must act as if the algorithm for
[16374]seeking was used whenever the [16375]current playback position
changes in a discontinuous fashion (so that the relevant events fire).
4.8.11.10 Media resources with multiple media tracks
A [16376]media resource can have multiple embedded audio and video
tracks. For example, in addition to the primary video and audio tracks,
a [16377]media resource could have foreign-language dubbed dialogues,
director's commentaries, audio descriptions, alternative angles, or
sign-language overlays.
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
Returns an [16380]AudioTrackList object representing the audio
tracks available in the [16381]media resource.
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
Returns a [16384]VideoTrackList object representing the video
tracks available in the [16385]media resource.
The audioTracks attribute of a [16386]media element must return a
[16387]live [16388]AudioTrackList object representing the audio tracks
available in the [16389]media element's [16390]media resource.
The videoTracks attribute of a [16391]media element must return a
[16392]live [16393]VideoTrackList object representing the video tracks
available in the [16394]media element's [16395]media resource.
There are only ever one [16396]AudioTrackList object and one
[16397]VideoTrackList object per [16398]media element, even if another
[16399]media resource is loaded into the element: the objects are
reused. (The [16400]AudioTrack and [16401]VideoTrack objects are not,
though.)
4.8.11.10.1 [16402]AudioTrackList and [16403]VideoTrackList
objects
(BUTTON) ✔MDN
[16404]AudioTrackList
Support in all current engines.
Firefox🔰 33+Safari7+Chrome🔰 37+
__________________________________________________________________
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
Returns the [16463]AudioTrack or [16464]VideoTrack object with
the given identifier, or null if no track has that identifier.
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
Returns the ID of the given track. This is the ID that can be
used with a [16469]fragment if the format supports [16470]media
fragment syntax, and that can be used with the getTrackById()
method.
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
Returns the category the given track falls into. The
[16475]possible track categories are given below.
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
Returns the label of the given track, if known, or the empty
string otherwise.
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
Returns the language of the given track, if known, or the empty
string otherwise.
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
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.
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
Returns the index of the currently selected track, if any, or −1
otherwise.
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
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.
An [16491]AudioTrackList object represents a dynamic list of zero or
more audio tracks, of which zero or more can be enabled at a time. Each
audio track is represented by an [16492]AudioTrack object.
A [16493]VideoTrackList object represents a dynamic list of zero or
more video tracks, of which zero or one can be selected at a time. Each
video track is represented by a [16494]VideoTrack object.
Tracks in [16495]AudioTrackList and [16496]VideoTrackList objects must
be consistently ordered. If the [16497]media resource is in a format
that defines an order, then that order must be used; otherwise, the
order must be the relative order in which the tracks are declared in
the [16498]media resource. The order used is called the natural order
of the list.
Each track in one of these objects thus has an index; the first has the
index 0, and each subsequent track is numbered one higher than the
previous one. If a [16499]media resource dynamically adds or removes
audio or video tracks, then the indices of the tracks will change
dynamically. If the [16500]media resource changes entirely, then all
the previous tracks will be removed and replaced with new tracks.
The [16501]AudioTrackList length and [16502]VideoTrackList length
attribute getters must return the number of tracks represented by their
objects at the time of getting.
The [16503]supported property indices of [16504]AudioTrackList and
[16505]VideoTrackList objects at any instant are the numbers from zero
to the number of tracks represented by the respective object minus one,
if any tracks are represented. If an [16506]AudioTrackList or
[16507]VideoTrackList object represents no tracks, it has no
[16508]supported property indices.
To [16509]determine the value of an indexed property for a given index
index in an [16510]AudioTrackList or [16511]VideoTrackList object list,
the user agent must return the [16512]AudioTrack or [16513]VideoTrack
object that represents the indexth track in list.
The [16514]AudioTrackList getTrackById(id) and [16515]VideoTrackList
getTrackById(id) methods must return the first [16516]AudioTrack or
[16517]VideoTrack object (respectively) in the [16518]AudioTrackList or
[16519]VideoTrackList object (respectively) whose identifier is equal
to the value of the id argument (in the natural order of the list, as
defined above). When no tracks match the given argument, the methods
must return null.
The [16520]AudioTrack and [16521]VideoTrack objects represent specific
tracks of a [16522]media resource. Each track can have an identifier,
category, label, and language. These aspects of a track are permanent
for the lifetime of the track; even if a track is removed from a
[16523]media resource's [16524]AudioTrackList or [16525]VideoTrackList
objects, those aspects do not change.
In addition, [16526]AudioTrack objects can each be enabled or disabled;
this is the audio track's enabled state. When an [16527]AudioTrack is
created, its enabled state must be set to false (disabled). The
[16528]resource fetch algorithm can override this.
Similarly, a single [16529]VideoTrack object per [16530]VideoTrackList
object can be selected, this is the video track's selection state. When
a [16531]VideoTrack is created, its selection state must be set to
false (not selected). The [16532]resource fetch algorithm can override
this.
The [16533]AudioTrack id and [16534]VideoTrack id attributes must
return the identifier of the track, if it has one, or the empty string
otherwise. If the [16535]media resource is in a format that supports
[16536]media fragment syntax, the identifier returned for a particular
track must be the same identifier that would enable the track if used
as the name of a track in the track dimension of such a
[16537]fragment. [16538][INBAND]
For example, in Ogg files, this would be the Name header field of the
track. [16539][OGGSKELETONHEADERS]
The [16540]AudioTrack kind and [16541]VideoTrack kind attributes must
return the category of the track, if it has one, or the empty string
otherwise.
The category of a track is the string given in the first column of the
table below that is the most appropriate for the track based on the
definitions in the table's second and third columns, as determined by
the metadata included in the track in the [16542]media resource. The
cell in the third column of a row says what the category given in the
cell in the first column of that row applies to; a category is only
appropriate for an audio track if it applies to audio tracks, and a
category is only appropriate for video tracks if it applies to video
tracks. Categories must only be returned for [16543]AudioTrack objects
if they are appropriate for audio, and must only be returned for
[16544]VideoTrack objects if they are appropriate for video.
For Ogg files, the Role header field of the track gives the relevant
metadata. For DASH media resources, the Role element conveys the
information. For WebM, only the FlagDefault element currently maps to a
value. Sourcing In-band Media Resource Tracks from Media Containers
into HTML has further details. [16545][OGGSKELETONHEADERS]
[16546][DASH] [16547][WEBMCG] [16548][INBAND]
CAPTION: Return values for [16549]AudioTrack's [16550]kind and
[16551]VideoTrack's [16552]kind
Category Definition Applies to... Examples
"alternative" A possible alternative to the main track, e.g. a
different take of a song (audio), or a different angle (video). Audio
and video. Ogg: "audio/alternate" or "video/alternate"; 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 legacy content; new content would use text tracks.) Video only.
DASH: "subtitle" and "main" roles together (other roles ignored).
"translation" A translated version of the main audio track. Audio only.
Ogg: "audio/dub". DASH: "dub" and "main" roles together (other roles
ignored).
"commentary" Commentary on the primary audio or video track, e.g. a
director's commentary. Audio and video. DASH: "commentary" role without
"main" role (other roles ignored).
"" (empty string) No explicit kind, or the kind given by the track's
metadata is not recognized by the user agent. Audio and video.
The [16553]AudioTrack label and [16554]VideoTrack label attributes must
return the label of the track, if it has one, or the empty string
otherwise. [16555][INBAND]
The [16556]AudioTrack language and [16557]VideoTrack language
attributes must return the BCP 47 language tag of the language of the
track, if it has one, or the empty string otherwise. If the user agent
is not able to express that language as a BCP 47 language tag (for
example because the language information in the [16558]media resource's
format is a free-form string without a defined interpretation), then
the method must return the empty string, as if the track had no
language. [16559][INBAND]
The [16560]AudioTrack enabled attribute, on getting, must return true
if the track is currently enabled, and false otherwise. On setting, it
must enable the track if the new value is true, and disable it
otherwise. (If the track is no longer in an [16561]AudioTrackList
object, then the track being enabled or disabled has no effect beyond
changing the value of the attribute on the [16562]AudioTrack object.)
Whenever an audio track in an [16563]AudioTrackList that was disabled
is enabled, and whenever one that was enabled is disabled, the user
agent must [16564]queue a media element task given the [16565]media
element to [16566]fire an event named [16567]change at the
[16568]AudioTrackList object.
An audio track that has no data for a particular position on the
[16569]media timeline, or that does not exist at that position, must be
interpreted as being silent at that point on the timeline.
The [16570]VideoTrackList selectedIndex attribute must return the index
of the currently selected track, if any. If the [16571]VideoTrackList
object does not currently represent any tracks, or if none of the
tracks are selected, it must instead return −1.
The [16572]VideoTrack selected attribute, on getting, must return true
if the track is currently selected, and false otherwise. On setting, it
must select the track if the new value is true, and unselect it
otherwise. If the track is in a [16573]VideoTrackList, then all the
other [16574]VideoTrack objects in that list must be unselected. (If
the track is no longer in a [16575]VideoTrackList object, then the
track being selected or unselected has no effect beyond changing the
value of the attribute on the [16576]VideoTrack object.)
Whenever a track in a [16577]VideoTrackList that was previously not
selected is selected, and whenever the selected track in a
[16578]VideoTrackList is unselected without a new track being selected
in its stead, the user agent must [16579]queue a media element task
given the [16580]media element to [16581]fire an event named
[16582]change at the [16583]VideoTrackList object. This [16584]task
must be [16585]queued before the [16586]task that fires the
[16587]resize event, if any.
A video track that has no data for a particular position on the
[16588]media timeline must be interpreted as being [16589]transparent
black at that point on the timeline, with the same dimensions as the
last frame before that position, or, if the position is before all the
data for that track, the same dimensions as the first frame for that
track. A track that does not exist at all at the current position must
be treated as if it existed but had no data.
For instance, if a video has a track that is only introduced after one
hour of playback, and the user selects that track then goes back to the
start, then the user agent will act as if that track started at the
start of the [16590]media resource but was simply transparent until one
hour in.
__________________________________________________________________
The following are the [16591]event handlers (and their corresponding
[16592]event handler event types) that must be supported, as
[16593]event handler IDL attributes, by all objects implementing the
[16594]AudioTrackList and [16595]VideoTrackList interfaces:
[16596]Event handler [16597]Event handler event type
onchange
(BUTTON) ✔MDN
[16598]AudioTrackList/change_event
Support in all current engines.
Firefox🔰 33+Safari7+Chrome🔰 37+
__________________________________________________________________
4.8.11.10.2 Selecting specific audio and video tracks
declaratively
The [16610]audioTracks and [16611]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
[16612]fragment of the [16613]URL of the [16614]media resource. The
format of the [16615]fragment depends on the [16616]MIME type of the
[16617]media resource. [16618][RFC2046] [16619][URL]
In this example, a video that uses a format that supports [16620]media
fragment syntax is embedded in such a way that the alternative angles
labeled "Alternative" are enabled instead of the default video track.
4.8.11.11 Timed text tracks
4.8.11.11.1 Text track model
A [16621]media element can have a group of associated text tracks,
known as the [16622]media element's list of text tracks. The
[16623]text tracks are sorted as follows:
1. The [16624]text tracks corresponding to [16625]track element
children of the [16626]media element, in [16627]tree order.
2. Any [16628]text tracks added using the [16629]addTextTrack()
method, in the order they were added, oldest first.
3. Any [16630]media-resource-specific text tracks ([16631]text tracks
corresponding to data in the [16632]media resource), in the order
defined by the [16633]media resource's format specification.
A [16634]text track consists of:
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:
The [16635]kind of track can change dynamically, in the case of
a [16636]text track corresponding to a [16637]track element.
A label
This is a human-readable string intended to identify the track
for the user.
The [16638]label of a track can change dynamically, in the case
of a [16639]text track corresponding to a [16640]track element.
When a [16641]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 [16642]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 [16643]in-band
metadata track dispatch type is the empty string. How this value
is populated for different media formats is described in
[16644]steps to expose a media-resource-specific text track.
A language
This is a string (a BCP 47 language tag) representing the
language of the text track's cues. [16645][BCP47]
The [16646]language of a text track can change dynamically, in
the case of a [16647]text track corresponding to a [16648]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., [16649]URL could not be [16650]parsed, network
error, unknown text track format). Some or all of the cues
are likely missing and will not be obtained.
The [16651]readiness state of a [16652]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 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 [16653]kind is [16654]subtitles or [16655]captions,
the cues are being overlaid on the video as appropriate;
for text tracks whose [16656]kind is [16657]descriptions,
the user agent is making the cues available to the user in
a non-visual fashion; and for text tracks whose
[16658]kind is [16659]chapters, the user agent is making
available to the user a mechanism by which the user can
navigate to any point in the [16660]media resource by
selecting a cue.
A list of zero or more cues
A list of [16661]text track cues, along with rules for updating
the text track rendering. For example, for WebVTT, the
[16662]rules for updating the display of WebVTT text tracks.
[16663][WEBVTT]
The [16664]list of cues of a text track can change dynamically,
either because the [16665]text track has [16666]not yet been
loaded or is still [16667]loading, or due to DOM manipulation.
Each [16668]text track has a corresponding [16669]TextTrack object.
__________________________________________________________________
Each [16670]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 did-perform-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 [16671]media element, the user agent must add to the
element's [16672]list of pending text tracks each [16673]text track in
the element's [16674]list of text tracks whose [16675]text track mode
is not [16676]disabled and whose [16677]text track readiness state is
[16678]loading.
Whenever a [16679]track element's parent node changes, the user agent
must remove the corresponding [16680]text track from any [16681]list of
pending text tracks that it is in.
Whenever a [16682]text track's [16683]text track readiness state
changes to either [16684]loaded or [16685]failed to load, the user
agent must remove it from any [16686]list of pending text tracks that
it is in.
When a [16687]media element is created by an [16688]HTML parser or
[16689]XML parser, the user agent must set the element's
[16690]blocked-on-parser flag to true. When a [16691]media element is
popped off the [16692]stack of open elements of an [16693]HTML parser
or [16694]XML parser, the user agent must [16695]honor user preferences
for automatic text track selection, [16696]populate the list of pending
text tracks, and set the element's [16697]blocked-on-parser flag to
false.
The [16698]text tracks of a [16699]media element are ready when both
the element's [16700]list of pending text tracks is empty and the
element's [16701]blocked-on-parser flag is false.
Each [16702]media element has a pending text track change notification
flag, which must initially be unset.
Whenever a [16703]text track that is in a [16704]media element's
[16705]list of text tracks has its [16706]text track mode change value,
the user agent must run the following steps for the [16707]media
element:
1. If the [16708]media element's [16709]pending text track change
notification flag is set, return.
2. Set the [16710]media element's [16711]pending text track change
notification flag.
3. [16712]Queue a media element task given the [16713]media element to
run these steps:
1. Unset the [16714]media element's [16715]pending text track
change notification flag.
2. [16716]Fire an event named [16717]change at the [16718]media
element's [16719]textTracks attribute's [16720]TextTrackList
object.
4. If the [16721]media element's [16722]show poster flag is not set,
run the [16723]time marches on steps.
The [16724]task source for the [16725]tasks listed in this section is
the [16726]DOM manipulation task source.
__________________________________________________________________
A text track cue is the unit of time-sensitive data in a [16727]text
track, corresponding for instance for subtitles and captions to the
text that appears at a particular time and disappears at another time.
Each [16728]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 [16729]media data to which the
cue applies.
An end time
The time, in seconds and fractions of a second, that describes
the end of the range of the [16730]media data to which the cue
applies, or positive Infinity for an [16731]unbounded text track
cue.
A pause-on-exit flag
A boolean indicating whether playback of the [16732]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, including the
actual data of the cue. For example, WebVTT has a [16733]text
track cue writing direction and so forth. [16734][WEBVTT]
An unbounded text track cue is a text track cue with a [16735]text
track cue end time set to positive Infinity. An active [16736]unbounded
text track cue cannot become inactive through the usual monotonic
increase of the [16737]current playback position during normal playback
(e.g. a metadata cue for a chapter in a live event with no announced
end time.)
The [16738]text track cue start time and [16739]text track cue end time
can be negative. (The [16740]current playback position can never be
negative, though, so cues entirely before time zero cannot be active.)
Each [16741]text track cue has a corresponding [16742]TextTrackCue
object (or more specifically, an object that inherits from
[16743]TextTrackCue — for example, WebVTT cues use the [16744]VTTCue
interface). A [16745]text track cue's in-memory representation can be
dynamically changed through this [16746]TextTrackCue API.
[16747][WEBVTT]
A [16748]text track cue is associated with [16749]rules for updating
the text track rendering, as defined by the specification for the
specific kind of [16750]text track cue. These rules are used
specifically when the object representing the cue is added to a
[16751]TextTrack object using the [16752]addCue() method.
In addition, each [16753]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
[16754]text track cue is removed from its [16755]text track's
[16756]text track list of cues; whenever the [16757]text track
itself is removed from its [16758]media element's [16759]list of
text tracks or has its [16760]text track mode changed to
[16761]disabled; and whenever the [16762]media element's
[16763]readyState is changed back to [16764]HAVE_NOTHING. When
the flag is unset in this way for one or more cues in
[16765]text tracks that were [16766]showing prior to the
relevant incident, the user agent must, after having unset the
flag for all the affected cues, apply the [16767]rules for
updating the text track rendering of those [16768]text tracks.
For example, for [16769]text tracks based on WebVTT, the
[16770]rules for updating the display of WebVTT text tracks.
[16771][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
[16772]text track cue active flag is unset, the user agent must
empty the [16773]text track cue display state.
The [16774]text track cues of a [16775]media element's [16776]text
tracks are ordered relative to each other in the text track cue order,
which is determined as follows: first group the [16777]cues by their
[16778]text track, with the groups being sorted in the same order as
their [16779]text tracks appear in the [16780]media element's
[16781]list of text tracks; then, within each group, [16782]cues must
be sorted by their [16783]start time, earliest first; then, any
[16784]cues with the same [16785]start time must be sorted by their
[16786]end time, latest first; and finally, any [16787]cues with
identical [16788]end times must be sorted in the order they were last
added to their respective [16789]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). [16790][WEBVTT]
4.8.11.11.2 Sourcing in-band text tracks
A media-resource-specific text track is a [16791]text track that
corresponds to data found in the [16792]media resource.
Rules for processing and rendering such data are defined by the
relevant specifications, e.g. the specification of the video format if
the [16793]media resource is a video. Details for some legacy formats
can be found in Sourcing In-band Media Resource Tracks from Media
Containers into HTML. [16794][INBAND]
When a [16795]media resource contains data that the user agent
recognizes and supports as being equivalent to a [16796]text track, the
user agent [16797]runs the steps to expose a media-resource-specific
text track with the relevant data, as follows.
1. Associate the relevant data with a new [16798]text track and its
corresponding new [16799]TextTrack object. The [16800]text track is
a [16801]media-resource-specific text track.
2. Set the new [16802]text track's [16803]kind, [16804]label, and
[16805]language based on the semantics of the relevant data, as
defined by the relevant specification. If there is no label in that
data, then the [16806]label must be set to the empty string.
3. Associate the [16807]text track list of cues with the [16808]rules
for updating the text track rendering appropriate for the format in
question.
4. If the new [16809]text track's [16810]kind is [16811]chapters or
[16812]metadata, then set the [16813]text track in-band metadata
track dispatch type as follows, based on the type of the
[16814]media resource:
If the [16815]media resource is an Ogg file
The [16816]text track in-band metadata track dispatch type
must be set to the value of the Name header field.
[16817][OGGSKELETONHEADERS]
If the [16818]media resource is a WebM file
The [16819]text track in-band metadata track dispatch type
must be set to the value of the CodecID element.
[16820][WEBMCG]
If the [16821]media resource is an MPEG-2 file
Let stream type be the value of the "stream_type" field
describing the text track's type in the file's program map
section, interpreted as an 8-bit unsigned integer. Let
length be the value of the "ES_info_length" field for the
track in the same part of the program map section,
interpreted as an integer as defined by Generic coding of
moving pictures and associated audio information. Let
descriptor bytes be the length bytes following the
"ES_info_length" field. The [16822]text track in-band
metadata track dispatch type must be set to the
concatenation of the stream type byte and the zero or more
descriptor bytes bytes, expressed in hexadecimal using
[16823]ASCII upper hex digits. [16824][MPEG2]
If the [16825]media resource is an MPEG-4 file
Let the first stsd box of the first stbl box of the first
minf box of the first mdia box of the [16826]text track's
trak box in the first moov box of the file be the stsd
box, if any. If the file has no stsd box, or if the stsd
box has neither a mett box nor a metx box, then the
[16827]text track in-band metadata track dispatch type
must be set to the empty string. Otherwise, if the stsd
box has a mett box then the [16828]text track in-band
metadata track dispatch type must be set to the
concatenation of the string "mett", a U+0020 SPACE
character, and the value of the first mime_format field of
the first mett box of the stsd box, or the empty string if
that field is absent in that box. Otherwise, if the stsd
box has no mett box but has a metx box then the
[16829]text track in-band metadata track dispatch type
must be set to the concatenation of the string "metx", a
U+0020 SPACE character, and the value of the first
namespace field of the first metx box of the stsd box, or
the empty string if that field is absent in that box.
[16830][MPEG4]
5. Populate the new [16831]text track's [16832]list of cues with the
cues parsed so far, following the [16833]guidelines for exposing
cues, and begin updating it dynamically as necessary.
6. Set the new [16834]text track's [16835]readiness state to
[16836]loaded.
7. Set the new [16837]text track's [16838]mode to the mode consistent
with the user's preferences and the requirements of the relevant
specification for the data.
For instance, if there are no other active subtitles, and this is a
forced subtitle track (a subtitle track giving subtitles in the
audio track's primary language, but only for audio that is actually
in another language), then those subtitles might be activated here.
8. Add the new [16839]text track to the [16840]media element's
[16841]list of text tracks.
9. [16842]Fire an event named [16843]addtrack at the [16844]media
element's [16845]textTracks attribute's [16846]TextTrackList
object, using [16847]TrackEvent, with the [16848]track attribute
initialized to the [16849]text track's [16850]TextTrack object.
4.8.11.11.3 Sourcing out-of-band text tracks
When a [16851]track element is created, it must be associated with a
new [16852]text track (with its value set as defined below) and its
corresponding new [16853]TextTrack object.
The [16854]text track kind is determined from the state of the
element's [16855]kind attribute according to the following table; for a
state given in a cell of the first column, the [16856]kind is the
string given in the second column:
The [16867]text track label is the element's [16868]track label.
The [16869]text track language is the element's [16870]track language,
if any, or the empty string otherwise.
As the [16871]kind, [16872]label, and [16873]srclang attributes are
set, changed, or removed, the [16874]text track must update
accordingly, as per the definitions above.
Changes to the [16875]track URL are handled in the algorithm below.
The [16876]text track readiness state is initially [16877]not loaded,
and the [16878]text track mode is initially [16879]disabled.
The [16880]text track list of cues is initially empty. It is
dynamically modified when the referenced file is parsed. Associated
with the list are the [16881]rules for updating the text track
rendering appropriate for the format in question; for WebVTT, this is
the [16882]rules for updating the display of WebVTT text tracks.
[16883][WEBVTT]
When a [16884]track element's parent element changes and the new parent
is a [16885]media element, then the user agent must add the
[16886]track element's corresponding [16887]text track to the
[16888]media element's [16889]list of text tracks, and then
[16890]queue a media element task given the [16891]media element to
[16892]fire an event named [16893]addtrack at the [16894]media
element's [16895]textTracks attribute's [16896]TextTrackList object,
using [16897]TrackEvent, with the [16898]track attribute initialized to
the [16899]text track's [16900]TextTrack object.
When a [16901]track element's parent element changes and the old parent
was a [16902]media element, then the user agent must remove the
[16903]track element's corresponding [16904]text track from the
[16905]media element's [16906]list of text tracks, and then
[16907]queue a media element task given the [16908]media element to
[16909]fire an event named [16910]removetrack at the [16911]media
element's [16912]textTracks attribute's [16913]TextTrackList object,
using [16914]TrackEvent, with the [16915]track attribute initialized to
the [16916]text track's [16917]TextTrack object.
__________________________________________________________________
When a [16918]text track corresponding to a [16919]track element is
added to a [16920]media element's [16921]list of text tracks, the user
agent must [16922]queue a media element task given the [16923]media
element to run the following steps for the [16924]media element:
1. If the element's [16925]blocked-on-parser flag is true, then
return.
2. If the element's [16926]did-perform-automatic-track-selection flag
is true, then return.
3. [16927]Honor user preferences for automatic text track selection
for this element.
When the user agent is required to honor user preferences for automatic
text track selection for a [16928]media element, the user agent must
run the following steps:
1. [16929]Perform automatic text track selection for [16930]subtitles
and [16931]captions.
2. [16932]Perform automatic text track selection for
[16933]descriptions.
3. If there are any [16934]text tracks in the [16935]media element's
[16936]list of text tracks whose [16937]text track kind is
[16938]chapters or [16939]metadata that correspond to [16940]track
elements with a [16941]default attribute set whose [16942]text
track mode is set to [16943]disabled, then set the [16944]text
track mode of all such tracks to [16945]hidden.
4. Set the element's [16946]did-perform-automatic-track-selection flag
to true.
When the steps above say to perform automatic text track selection for
one or more [16947]text track kinds, it means to run the following
steps:
1. Let candidates be a list consisting of the [16948]text tracks in
the [16949]media element's [16950]list of text tracks whose
[16951]text track kind is one of the kinds that were passed to the
algorithm, if any, in the order given in the [16952]list of text
tracks.
2. If candidates is empty, then return.
3. If any of the [16953]text tracks in candidates have a [16954]text
track mode set to [16955]showing, return.
4. If the user has expressed an interest in having a track from
candidates enabled based on its [16956]text track kind, [16957]text
track language, and [16958]text track label, then set its
[16959]text track mode to [16960]showing.
For example, the user could have set a browser preference to the
effect of "I want French captions whenever possible", or "If there
is a subtitle track with 'Commentary' in the title, enable it", or
"If there are audio description tracks available, enable one,
ideally in Swiss German, but failing that in Standard Swiss German
or Standard German".
Otherwise, if there are any [16961]text tracks in candidates that
correspond to [16962]track elements with a [16963]default attribute
set whose [16964]text track mode is set to [16965]disabled, then
set the [16966]text track mode of the first such track to
[16967]showing.
When a [16968]text track corresponding to a [16969]track element
experiences any of the following circumstances, the user agent must
[16970]start the track processing model for that [16971]text track and
its [16972]track element:
* The [16973]track element is created.
* The [16974]text track has its [16975]text track mode changed.
* The [16976]track element's parent element changes and the new
parent is a [16977]media element.
When a user agent is to start the track processing model for a
[16978]text track and its [16979]track element, it must run the
following algorithm. This algorithm interacts closely with the
[16980]event loop mechanism; in particular, it has a [16981]synchronous
section (which is triggered as part of the [16982]event loop
algorithm). The steps in that section are marked with ⌛.
1. If another occurrence of this algorithm is already running for this
[16983]text track and its [16984]track element, return, letting
that other algorithm take care of this element.
2. If the [16985]text track's [16986]text track mode is not set to one
of [16987]hidden or [16988]showing, then return.
3. If the [16989]text track's [16990]track element does not have a
[16991]media element as a parent, return.
4. Run the remainder of these steps [16992]in parallel, allowing
whatever caused these steps to run to continue.
5. Top: [16993]Await a stable state. The [16994]synchronous section
consists of the following steps. (The steps in the
[16995]synchronous section are marked with ⌛.)
6. ⌛ Set the [16996]text track readiness state to [16997]loading.
7. ⌛ Let URL be the [16998]track URL of the [16999]track element.
8. ⌛ If the [17000]track element's parent is a [17001]media element
then let corsAttributeState be the state of the parent [17002]media
element's [17003]crossorigin content attribute. Otherwise, let
corsAttributeState be [17004]No CORS.
9. End the [17005]synchronous section, continuing the remaining steps
[17006]in parallel.
10. If URL is not the empty string, then:
1. Let request be the result of [17007]creating a potential-CORS
request given URL, "track", and corsAttributeState, and with
the same-origin fallback flag set.
2. Set request's [17008]client to the [17009]track element's
[17010]node document's [17011]relevant settings object.
3. Set request's [17012]initiator type to "track".
4. [17013]Fetch request.
The [17014]tasks [17015]queued by the fetching algorithm on the
[17016]networking task source to process the data as it is being
fetched must determine the type of the resource. If the type of the
resource is not a supported text track format, the load will fail,
as described below. Otherwise, the resource's data must be passed
to the appropriate parser (e.g., the [17017]WebVTT parser) as it is
received, with the [17018]text track list of cues being used for
that parser's output. [17019][WEBVTT]
The appropriate parser will incrementally update the [17020]text
track list of cues during these [17021]networking task source
[17022]tasks, as each such task is run with whatever data has been
received from the network).
This specification does not currently say whether or how to check
the MIME types of text tracks, or whether or how to perform file
type sniffing using the actual file data. Implementers differ in
their intentions on this matter and it is therefore unclear what
the right solution is. In the absence of any requirement here, the
HTTP specifications' strict requirement to follow the Content-Type
header prevails ("Content-Type specifies the media type of the
underlying data." ... "If and only if the media type is not given
by a Content-Type field, the recipient MAY attempt to guess the
media type via inspection of its content and/or the name
extension(s) of the URI used to identify the resource.").
If fetching fails for any reason (network error, the server returns
an error code, CORS fails, etc.), or if URL is the empty string,
then [17023]queue an element task on the [17024]DOM manipulation
task source given the [17025]media element to first change the
[17026]text track readiness state to [17027]failed to load and then
[17028]fire an event named [17029]error at the [17030]track
element.
If fetching does not fail, but the type of the resource is not a
supported text track format, or the file was not successfully
processed (e.g., the format in question is an XML format and the
file contained a well-formedness error that XML requires be
detected and reported to the application), then the [17031]task
that is [17032]queued on the [17033]networking task source in which
the aforementioned problem is found must change the [17034]text
track readiness state to [17035]failed to load and [17036]fire an
event named [17037]error at the [17038]track element.
If fetching does not fail, and the file was successfully processed,
then the final [17039]task that is [17040]queued by the
[17041]networking task source, after it has finished parsing the
data, must change the [17042]text track readiness state to
[17043]loaded, and [17044]fire an event named [17045]load at the
[17046]track element.
If, while fetching is ongoing, either:
+ the [17047]track URL changes so that it is no longer equal to
URL, while the [17048]text track mode is set to [17049]hidden
or [17050]showing; or
+ the [17051]text track mode changes to [17052]hidden or
[17053]showing, while the [17054]track URL is not equal to
URL,
...then the user agent must abort [17055]fetching, discarding any
pending [17056]tasks generated by that algorithm (and in
particular, not adding any cues to the [17057]text track list of
cues after the moment the URL changed), and then [17058]queue an
element task on the [17059]DOM manipulation task source given the
[17060]track element that first changes the [17061]text track
readiness state to [17062]failed to load and then [17063]fires an
event named [17064]error at the [17065]track element.
11. Wait until the [17066]text track readiness state is no longer set
to [17067]loading.
12. Wait until the [17068]track URL is no longer equal to URL, at the
same time as the [17069]text track mode is set to [17070]hidden or
[17071]showing.
13. Jump to the step labeled top.
Whenever a [17072]track element has its [17073]src attribute set,
changed, or removed, the user agent must [17074]immediately empty the
element's [17075]text track's [17076]text track list of cues. (This
also causes the algorithm above to stop adding cues from the resource
being obtained using the previously given URL, if any.)
4.8.11.11.4 Guidelines for exposing cues in various formats as
[17077]text track cues
How a specific format's text track cues are to be interpreted for the
purposes of processing by an HTML user agent is defined by that format.
In the absence of such a specification, this section provides some
constraints within which implementations can attempt to consistently
expose such formats.
To support the [17078]text track model of HTML, each unit of timed data
is converted to a [17079]text track cue. Where the mapping of the
format's features to the aspects of a [17080]text track cue as defined
in this specification are not defined, implementations must ensure that
the mapping is consistent with the definitions of the aspects of a
[17081]text track cue as defined above, as well as with the following
constraints:
The [17082]text track cue identifier
Should be set to the empty string if the format has no obvious
analogue to a per-cue identifier.
The [17083]text track cue pause-on-exit flag
Should be set to false.
4.8.11.11.5 Text track API
(BUTTON) ✔MDN
[17084]TextTrackList
Support in all current engines.
Firefox31+Safari6+Chrome23+
__________________________________________________________________
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet1.0+Opera Android12.1+
Returns the number of [17099]text tracks associated with the
[17100]media element (e.g. from [17101]track elements). This is
the number of [17102]text tracks in the [17103]media element's
[17104]list of text tracks.
media.[17105]textTracks[ n ]
Returns the [17106]TextTrack object representing the nth
[17107]text track in the [17108]media element's [17109]list of
text tracks.
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
Returns the [17113]TextTrack object with the given identifier,
or null if no track has that identifier.
A [17114]TextTrackList object represents a dynamically updating list of
[17115]text tracks in a given order.
The textTracks attribute of [17116]media elements must return a
[17117]TextTrackList object representing the [17118]TextTrack objects
of the [17119]text tracks in the [17120]media element's [17121]list of
text tracks, in the same order as in the [17122]list of text tracks.
(BUTTON) ✔MDN
[17123]TextTrackList/length
Support in all current engines.
Firefox31+Safari6+Chrome23+
__________________________________________________________________
The length attribute of a [17124]TextTrackList object must return the
number of [17125]text tracks in the list represented by the
[17126]TextTrackList object.
The [17127]supported property indices of a [17128]TextTrackList object
at any instant are the numbers from zero to the number of [17129]text
tracks in the list represented by the [17130]TextTrackList object minus
one, if any. If there are no [17131]text tracks in the list, there are
no [17132]supported property indices.
To [17133]determine the value of an indexed property of a
[17134]TextTrackList object for a given index index, the user agent
must return the indexth [17135]text track in the list represented by
the [17136]TextTrackList object.
The getTrackById(id) method must return the first [17137]TextTrack in
the [17138]TextTrackList object whose [17139]id IDL attribute would
return a value equal to the value of the id argument. When no tracks
match the given argument, the method must return null.
__________________________________________________________________
(BUTTON) ✔MDN
[17140]TextTrack
Support in all current engines.
Firefox31+Safari6+Chrome23+
__________________________________________________________________
textTrack = media.[17168]addTextTrack(kind [, label [, language ] ])
Creates and returns a new [17169]TextTrack object, which is also
added to the [17170]media element's [17171]list of text tracks.
Firefox Android?Safari iOS7+Chrome Android?WebView
Android?Samsung Internet?Opera Android12.1+
Returns the [17177]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).
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
Returns the ID of the given track.
For in-band tracks, this is the ID that can be used with a
[17183]fragment if the format supports [17184]media fragment
syntax, and that can be used with the [17185]getTrackById()
method.
For [17186]TextTrack objects corresponding to [17187]track
elements, this is the ID of the [17188]track element.
Firefox Android31+Safari iOS7+Chrome Android?WebView
Android?Samsung Internet?Opera Android12.1+
Returns the [17194]text track mode, represented by a string from
the following list:
"[17195]disabled"
The [17196]text track disabled mode.
"[17197]hidden"
The [17198]text track hidden mode.
"[17199]showing"
The [17200]text track showing mode.
Firefox Android31+Safari iOS7+Chrome Android?WebView
Android?Samsung Internet?Opera Android12.1+
Returns the [17203]text track list of cues, as a
[17204]TextTrackCueList object.
Firefox Android31+Safari iOS7+Chrome Android?WebView
Android?Samsung Internet?Opera Android12.1+
Returns the [17207]text track cues from the [17208]text track
list of cues that are currently active (i.e. that start before
the [17209]current playback position and end after it), as a
[17210]TextTrackCueList object.
Firefox Android?Safari iOS7+Chrome Android?WebView
Android?Samsung Internet?Opera Android12.1+
Adds the given cue to textTrack's [17213]text track list of
cues.
Firefox Android?Safari iOS7+Chrome Android?WebView
Android?Samsung Internet?Opera Android12.1+
Removes the given cue from textTrack's [17216]text track list of
cues.
The addTextTrack(kind, label, language) method of [17217]media
elements, when invoked, must run the following steps:
1. Create a new [17218]TextTrack object.
2. Create a new [17219]text track corresponding to the new object, and
set its [17220]text track kind to kind, its [17221]text track label
to label, its [17222]text track language to language, its
[17223]text track readiness state to the [17224]text track loaded
state, its [17225]text track mode to the [17226]text track hidden
mode, and its [17227]text track list of cues to an empty list.
Initially, the [17228]text track list of cues is not associated
with any [17229]rules for updating the text track rendering. When a
[17230]text track cue is added to it, the [17231]text track list of
cues has its rules permanently set accordingly.
3. Add the new [17232]text track to the [17233]media element's
[17234]list of text tracks.
4. [17235]Queue a media element task given the [17236]media element to
[17237]fire an event named [17238]addtrack at the [17239]media
element's [17240]textTracks attribute's [17241]TextTrackList
object, using [17242]TrackEvent, with the [17243]track attribute
initialized to the new [17244]text track's [17245]TextTrack object.
5. Return the new [17246]TextTrack object.
__________________________________________________________________
The kind attribute must return the [17247]text track kind of the
[17248]text track that the [17249]TextTrack object represents.
The label attribute must return the [17250]text track label of the
[17251]text track that the [17252]TextTrack object represents.
The language attribute must return the [17253]text track language of
the [17254]text track that the [17255]TextTrack object represents.
The id attribute returns the track's identifier, if it has one, or the
empty string otherwise. For tracks that correspond to [17256]track
elements, the track's identifier is the value of the element's
[17257]id attribute, if any. For in-band tracks, the track's identifier
is specified by the [17258]media resource. If the [17259]media resource
is in a format that supports [17260]media fragment syntax, the
identifier returned for a particular track must be the same identifier
that would enable the track if used as the name of a track in the track
dimension of such a [17261]fragment.
The inBandMetadataTrackDispatchType attribute must return the
[17262]text track in-band metadata track dispatch type of the
[17263]text track that the [17264]TextTrack object represents.
The mode attribute, on getting, must return the string corresponding to
the [17265]text track mode of the [17266]text track that the
[17267]TextTrack object represents, as defined by the following list:
"disabled"
The [17268]text track disabled mode.
"hidden"
The [17269]text track hidden mode.
"showing"
The [17270]text track showing mode.
On setting, if the new value isn't equal to what the attribute would
currently return, the new value must be processed as follows:
If the new value is "[17271]disabled"
Set the [17272]text track mode of the [17273]text track that the
[17274]TextTrack object represents to the [17275]text track
disabled mode.
If the new value is "[17276]hidden"
Set the [17277]text track mode of the [17278]text track that the
[17279]TextTrack object represents to the [17280]text track
hidden mode.
If the new value is "[17281]showing"
Set the [17282]text track mode of the [17283]text track that the
[17284]TextTrack object represents to the [17285]text track
showing mode.
If the [17286]text track mode of the [17287]text track that the
[17288]TextTrack object represents is not the [17289]text track
disabled mode, then the cues attribute must return a [17290]live
[17291]TextTrackCueList object that represents the subset of the
[17292]text track list of cues of the [17293]text track that the
[17294]TextTrack object represents whose [17295]end times occur at or
after the [17296]earliest possible position when the script started, in
[17297]text track cue order. Otherwise, it must return null. For each
[17298]TextTrack object, when an object is returned, the same
[17299]TextTrackCueList object must be returned each time.
The earliest possible position when the script started is whatever the
[17300]earliest possible position was the last time the [17301]event
loop reached step 1.
If the [17302]text track mode of the [17303]text track that the
[17304]TextTrack object represents is not the [17305]text track
disabled mode, then the activeCues attribute must return a [17306]live
[17307]TextTrackCueList object that represents the subset of the
[17308]text track list of cues of the [17309]text track that the
[17310]TextTrack object represents whose [17311]active flag was set
when the script started, in [17312]text track cue order. Otherwise, it
must return null. For each [17313]TextTrack object, when an object is
returned, the same [17314]TextTrackCueList object must be returned each
time.
A [17315]text track cue's active flag was set when the script started
if its [17316]text track cue active flag was set the last time the
[17317]event loop reached [17318]step 1.
__________________________________________________________________
The addCue(cue) method of [17319]TextTrack objects, when invoked, must
run the following steps:
1. If the [17320]text track list of cues does not yet have any
associated [17321]rules for updating the text track rendering, then
associate the [17322]text track list of cues with the [17323]rules
for updating the text track rendering appropriate to cue.
2. If [17324]text track list of cues' associated [17325]rules for
updating the text track rendering are not the same [17326]rules for
updating the text track rendering as appropriate for cue, then
throw an [17327]"InvalidStateError" [17328]DOMException.
3. If the given cue is in a [17329]text track list of cues, then
remove cue from that [17330]text track list of cues.
4. Add cue to the [17331]TextTrack object's [17332]text track's
[17333]text track list of cues.
The removeCue(cue) method of [17334]TextTrack objects, when invoked,
must run the following steps:
1. If the given cue is not in the [17335]TextTrack object's
[17336]text track's [17337]text track list of cues, then throw a
[17338]"NotFoundError" [17339]DOMException.
2. Remove cue from the [17340]TextTrack object's [17341]text track's
[17342]text track list of cues.
In this example, an [17343]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) {
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,
// and have the browser ask them to stay
window.onbeforeunload = function (e) {
playSound(ʼkitten mewʼ);
e.preventDefault();
}
__________________________________________________________________
(BUTTON) ✔MDN
[17344]TextTrackCueList
Support in all current engines.
Firefox31+Safari6+Chrome23+
__________________________________________________________________
The length attribute must return the number of [17361]cues in the list
represented by the [17362]TextTrackCueList object.
The [17363]supported property indices of a [17364]TextTrackCueList
object at any instant are the numbers from zero to the number of
[17365]cues in the list represented by the [17366]TextTrackCueList
object minus one, if any. If there are no [17367]cues in the list,
there are no [17368]supported property indices.
To [17369]determine the value of an indexed property for a given index
index, the user agent must return the indexth [17370]text track cue in
the list represented by the [17371]TextTrackCueList object.
(BUTTON) ✔MDN
[17372]TextTrackCueList/getCueById
Support in all current engines.
Firefox31+Safari6+Chrome23+
__________________________________________________________________
The getCueById(id) method, when called with an argument other than the
empty string, must return the first [17373]text track cue in the list
represented by the [17374]TextTrackCueList object whose [17375]text
track cue identifier is id, if any, or null otherwise. If the argument
is the empty string, then the method must return null.
__________________________________________________________________
(BUTTON) ✔MDN
[17376]TextTrackCue
Support in all current engines.
Firefox31+Safari6+Chrome23+
__________________________________________________________________
The track attribute, on getting, must return the [17401]TextTrack
object of the [17402]text track in whose [17403]list of cues the
[17404]text track cue that the [17405]TextTrackCue object represents
finds itself, if any; or null otherwise.
(BUTTON) ✔MDN
[17406]TextTrackCue/id
Support in all current engines.
Firefox31+Safari6+Chrome23+
__________________________________________________________________
The id attribute, on getting, must return the [17407]text track cue
identifier of the [17408]text track cue that the [17409]TextTrackCue
object represents. On setting, the [17410]text track cue identifier
must be set to the new value.
(BUTTON) ✔MDN
[17411]TextTrackCue/startTime
Support in all current engines.
Firefox31+Safari6+Chrome23+
__________________________________________________________________
The startTime attribute, on getting, must return the [17412]text track
cue start time of the [17413]text track cue that the
[17414]TextTrackCue object represents, in seconds. On setting, the
[17415]text track cue start time must be set to the new value,
interpreted in seconds; then, if the [17416]TextTrackCue object's
[17417]text track cue is in a [17418]text track's [17419]list of cues,
and that [17420]text track is in a [17421]media element's [17422]list
of text tracks, and the [17423]media element's [17424]show poster flag
is not set, then run the [17425]time marches on steps for that
[17426]media element.
(BUTTON) ✔MDN
[17427]TextTrackCue/endTime
Support in all current engines.
Firefox31+Safari6+Chrome23+
__________________________________________________________________
The endTime attribute, on getting, must return the [17428]text track
cue end time of the [17429]text track cue that the [17430]TextTrackCue
object represents, in seconds or positive Infinity. On setting, if the
new value is negative Infinity or a Not-a-Number (NaN) value, then
throw a [17431]TypeError exception. Otherwise, the [17432]text track
cue end time must be set to the new value. Then, if the
[17433]TextTrackCue object's [17434]text track cue is in a [17435]text
track's [17436]list of cues, and that [17437]text track is in a
[17438]media element's [17439]list of text tracks, and the [17440]media
element's [17441]show poster flag is not set, then run the [17442]time
marches on steps for that [17443]media element.
(BUTTON) ✔MDN
[17444]TextTrackCue/pauseOnExit
Support in all current engines.
Firefox31+Safari6+Chrome23+
__________________________________________________________________
The pauseOnExit attribute, on getting, must return true if the
[17445]text track cue pause-on-exit flag of the [17446]text track cue
that the [17447]TextTrackCue object represents is set; or false
otherwise. On setting, the [17448]text track cue pause-on-exit flag
must be set if the new value is true, and must be unset otherwise.
4.8.11.11.6 Event handlers for objects of the text track APIs
The following are the [17449]event handlers that (and their
corresponding [17450]event handler event types) that must be supported,
as [17451]event handler IDL attributes, by all objects implementing the
[17452]TextTrackList interface:
The following are the [17458]event handlers that (and their
corresponding [17459]event handler event types) that must be supported,
as [17460]event handler IDL attributes, by all objects implementing the
[17461]TextTrack interface:
[17462]Event handler [17463]Event handler event type
oncuechange
(BUTTON) ✔MDN
[17464]TextTrack/cuechange_event
Support in all current engines.
Firefox31+Safari6+Chrome23+
__________________________________________________________________
The following are the [17466]event handlers (and their corresponding
[17467]event handler event types) that must be supported, as
[17468]event handler IDL attributes, by all objects implementing the
[17469]TextTrackCue interface:
[17470]Event handler [17471]Event handler event type
onenter
(BUTTON) ✔MDN
[17472]TextTrackCue/enter_event
Support in all current engines.
Firefox31+Safari6+Chrome23+
__________________________________________________________________
4.8.11.11.7 Best practices for metadata text tracks
This section is non-normative.
Text tracks can be used for storing data relating to the media data,
for interactive or augmented views.
For example, a page showing a sports broadcast could include
information about the current score. Suppose a robotics competition was
being streamed live. The image could be overlaid with the scores, as
follows:
In order to make the score display render correctly whenever the user
seeks to an arbitrary point in the video, the metadata text track cues
need to be as long as is appropriate for the score. For example, in the
frame above, there would be maybe one cue that lasts the length of the
match that gives the match number, one cue that lasts until the blue
alliance's score changes, and one cue that lasts until the red
alliance's score changes. If the video is just a stream of the live
event, the time in the bottom right would presumably be automatically
derived from the current video time, rather than based on a cue.
However, if the video was just the highlights, then that might be given
in cues also.
The following shows what fragments of this could look like in a WebVTT
file:
WEBVTT
The key here is to notice that the information is given in cues that
span the length of time to which the relevant event applies. If,
instead, the scores were given as zero-length (or very brief, nearly
zero-length) cues when the score changes, for example saying "red+2" at
05:11:17.198, "red+3" at 05:11:25.912, etc, problems arise: primarily,
seeking is much harder to implement, as the script has to walk the
entire list of cues to make sure that no notifications have been
missed; but also, if the cues are short it's possible the script will
never see that they are active unless it listens to them specifically.
When using cues in this manner, authors are encouraged to use the
[17477]cuechange event to update the current annotations. (In
particular, using the [17478]timeupdate event would be less appropriate
as it would require doing work even when the cues haven't changed, and,
more importantly, would introduce a higher latency between when the
metadata cues become active and when the display is updated, since
[17479]timeupdate events are rate-limited.)
4.8.11.12 Identifying a track kind through a URL
Other specifications or formats that need a [17480]URL to identify the
return values of the [17481]AudioTrack [17482]kind or [17483]VideoTrack
[17484]kind IDL attributes, or identify the [17485]kind of text track,
must use the [17486]about:html-kind [17487]URL.
4.8.11.13 User interface
The controls attribute is a [17488]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.
If the attribute is present, or if [17489]scripting is disabled for the
[17490]media element, then the user agent should expose a user
interface to the user. This user interface should include features to
begin playback, pause playback, seek to an arbitrary position in the
content (if the content supports arbitrary seeking), change the volume,
change the display of closed captions or embedded sign-language tracks,
select different audio tracks or turn on audio descriptions, and show
the media content in manners more suitable to the user (e.g. fullscreen
video or in an independent resizable window). Other controls may also
be made available.
Even when the attribute is absent, however, user agents may provide
controls to affect playback of the media resource (e.g. play, pause,
seeking, track selection, and volume controls), but such features
should not interfere with the page's normal rendering. For example,
such features could be exposed in the [17491]media element's context
menu, platform media keys, or a remote control. The user agent may
implement this simply by [17492]exposing a user interface to the user
as described above (as if the [17493]controls attribute was present).
If the user agent [17494]exposes a user interface to the user by
displaying controls over the [17495]media element, then the user agent
should suppress any user interaction events while the user agent is
interacting with this interface. (For example, if the user clicks on a
video's playback control, [17496]mousedown events and so forth would
not simultaneously be fired at elements on the page.)
Where possible (specifically, for starting, stopping, pausing, and
unpausing playback, for seeking, for changing the rate of playback, for
fast-forwarding or rewinding, for listing, enabling, and disabling text
tracks, and for muting or changing the volume of the audio), user
interface features exposed by the user agent must be implemented in
terms of the DOM API described above, so that, e.g., all the same
events fire.
Features such as fast-forward or rewind must be implemented by only
changing the playbackRate attribute (and not the defaultPlaybackRate
attribute).
Seeking must be implemented in terms of [17497]seeking to the requested
position in the [17498]media element's [17499]media timeline. For media
resources where seeking to an arbitrary position would be slow, user
agents are encouraged to use the approximate-for-speed flag when
seeking in response to the user manipulating an approximate position
interface such as a seek bar.
(BUTTON) ✔MDN
[17500]HTMLMediaElement/controls
Support in all current engines.
Firefox3.5+Safari3.1+Chrome3+
__________________________________________________________________
The controls IDL attribute must [17501]reflect the content attribute of
the same name.
__________________________________________________________________
Firefox Android?Safari iOS🔰 3+Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
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 [17504]"IndexSizeError" [17505]DOMException if the new
value is not in the range 0.0 .. 1.0.
Firefox Android?Safari iOS3+Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
Returns true if audio is muted, overriding the [17508]volume
attribute, and false if the [17509]volume attribute is being
honored.
Can be set, to change whether the audio is muted or not.
A [17510]media element has a playback volume, which is a fraction in
the range 0.0 (silent) to 1.0 (loudest). Initially, the volume should
be 1.0, but user agents may remember the last set value across
sessions, on a per-site basis or otherwise, so the volume may start at
other values.
The volume IDL attribute must return the [17511]playback volume of any
audio portions of the [17512]media element. On setting, if the new
value is in the range 0.0 to 1.0 inclusive, the [17513]media element's
[17514]playback volume must be set to the new value. If the new value
is outside the range 0.0 to 1.0 inclusive, then, on setting, an
[17515]"IndexSizeError" [17516]DOMException must be thrown instead.
A [17517]media element can also be muted. If anything is muting the
element, then it is muted. (For example, when the [17518]direction of
playback is backwards, the element is muted.)
The muted IDL attribute must return the value to which it was last set.
When a [17519]media element is created, if the element has a
[17520]muted content attribute specified, then the [17521]muted IDL
attribute should be set to true; otherwise, the user agents may set the
value to the user's preferred value (e.g. remembering the last set
value across sessions, on a per-site basis or otherwise). While the
[17522]muted IDL attribute is set to true, the [17523]media element
must be [17524]muted.
Whenever either of the values that would be returned by the
[17525]volume and [17526]muted IDL attributes change, the user agent
must [17527]queue a media element task given the [17528]media element
to [17529]fire an event named [17530]volumechange at the [17531]media
element. Then, if the [17532]media element is not [17533]allowed to
play, the user agent must run the [17534]internal pause steps for the
[17535]media element.
A user agent has an associated volume locked (a boolean). Its value is
[17536]implementation-defined and determines whether the
[17537]playback volume takes effect.
An element's effective media volume is determined as follows:
1. If the user has indicated that the user agent is to override the
volume of the element, then return the volume desired by the user.
2. If the user agent's [17538]volume locked is true, then return the
system volume.
3. If the element's audio output is [17539]muted, then return zero.
4. Let volume be the [17540]playback volume of the audio portions of
the [17541]media element, in range 0.0 (silent) to 1.0 (loudest).
5. Return volume, interpreted relative to the range 0.0 to 1.0, with
0.0 being silent, and 1.0 being the loudest setting, values in
between increasing in loudness. The range need not be linear. The
loudest setting may be lower than the system's loudest possible
setting; for example the user could have set a maximum volume.
The muted content attribute on [17542]media elements is a
[17543]boolean attribute that controls the default state of the audio
output of the [17544]media resource, potentially overriding user
preferences.
(BUTTON) ✔MDN
[17545]HTMLMediaElement/defaultMuted
Support in all current engines.
Firefox11+Safari6+Chrome15+
__________________________________________________________________
The defaultMuted IDL attribute must [17546]reflect the [17547]muted
content attribute.
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. The
user agent can pause the video if it's unmuted without a user
interaction.
4.8.11.14 Time ranges
(BUTTON) ✔MDN
[17548]TimeRanges
Support in all current engines.
Firefox4+Safari3.1+Chrome6+
__________________________________________________________________
Objects implementing the [17549]TimeRanges interface represent a list
of ranges (periods) of time.
[Exposed=Window]
interface TimeRanges {
readonly attribute unsigned long [17550]length;
double [17551]start(unsigned long index);
double [17552]end(unsigned long index);
};
Firefox Android?Safari iOS?Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
Returns the time for the start of the range with the given
index.
Throws an [17557]"IndexSizeError" [17558]DOMException if the
index is out of range.
Firefox Android?Safari iOS?Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
Returns the time for the end of the range with the given index.
Throws an [17561]"IndexSizeError" [17562]DOMException if the
index is out of range.
The length IDL attribute must return the number of ranges represented
by the object.
The start(index) method must return the position of the start of the
indexth range represented by the object, in seconds measured from the
start of the timeline that the object covers.
The end(index) method must return the position of the end of the
indexth range represented by the object, in seconds measured from the
start of the timeline that the object covers.
These methods must throw [17563]"IndexSizeError" [17564]DOMExceptions
if called with an index argument greater than or equal to the number of
ranges represented by the object.
When a [17565]TimeRanges object is said to be a normalized TimeRanges
object, the ranges it represents must obey the following criteria:
* The start of a range must be greater than the end of all earlier
ranges.
* The start of a range must be less than or equal to the end of that
same range.
In other words, the ranges in such an object are ordered, don't
overlap, and don't touch (adjacent ranges are folded into one bigger
range). A range can be empty (referencing just a single moment in
time), e.g. to indicate that only one frame is currently buffered in
the case that the user agent has discarded the entire [17566]media
resource except for the current frame, when a [17567]media element is
paused.
Ranges in a [17568]TimeRanges object must be inclusive.
Thus, the end of a range would be equal to the start of a following
adjacent (touching but not overlapping) range. Similarly, a range
covering a whole timeline anchored at zero would have a start equal to
zero and an end equal to the duration of the timeline.
The timelines used by the objects returned by the [17569]buffered,
[17570]seekable, and [17571]played IDL attributes of [17572]media
elements must be that element's [17573]media timeline.
4.8.11.15 The [17574]TrackEvent interface
(BUTTON) ✔MDN
[17575]TrackEvent
Support in all current engines.
Firefox27+Safari6+Chrome23+
__________________________________________________________________
Firefox Android?Safari iOS7+Chrome Android?WebView
Android?Samsung Internet?Opera Android12.1+
Returns the track object ([17588]TextTrack, [17589]AudioTrack,
or [17590]VideoTrack) to which the event relates.
The track attribute must return the value it was initialized to. It
represents the context information for the event.
4.8.11.16 Events summary
This section is non-normative.
The following events fire on [17591]media elements as part of the
processing model described above:
Event name Interface Fired when... Preconditions
loadstart
(BUTTON) ✔MDN
[17592]HTMLMediaElement/loadstart_event
Support in all current engines.
Firefox6+Safari4+Chrome3+
__________________________________________________________________
Firefox Android?Safari iOS3+Chrome Android?WebView Android?Samsung
Internet?Opera Android12.1+
[17593]Event The user agent begins looking for [17594]media data, as
part of the [17595]resource selection algorithm. [17596]networkState
equals [17597]NETWORK_LOADING
progress
(BUTTON) ✔MDN
[17598]HTMLMediaElement/progress_event
Support in all current engines.
Firefox6+Safari3.1+Chrome3+
__________________________________________________________________
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung
Internet?Opera Android11+
[17604]Event The user agent is intentionally not currently fetching
[17605]media data. [17606]networkState equals [17607]NETWORK_IDLE
abort
(BUTTON) ✔MDN
[17608]HTMLMediaElement/abort_event
Support in all current engines.
Firefox9+Safari3.1+Chrome3+
__________________________________________________________________
Firefox Android?Safari iOS3+Chrome Android?WebView Android?Samsung
Internet?Opera Android12.1+
[17609]Event The user agent stops fetching the [17610]media data before
it is completely downloaded, but not due to an error. [17611]error is
an object with the code [17612]MEDIA_ERR_ABORTED. [17613]networkState
equals either [17614]NETWORK_EMPTY or [17615]NETWORK_IDLE, depending on
when the download was aborted.
error
(BUTTON) ✔MDN
[17616]HTMLMediaElement/error_event
Support in all current engines.
Firefox6+Safari3.1+Chrome3+
__________________________________________________________________
Firefox Android?Safari iOS3+Chrome Android?WebView Android?Samsung
Internet?Opera Android12+
[17617]Event An error occurs while fetching the [17618]media data or
the type of the resource is not a supported media format. [17619]error
is an object with the code [17620]MEDIA_ERR_NETWORK or higher.
[17621]networkState equals either [17622]NETWORK_EMPTY or
[17623]NETWORK_IDLE, depending on when the download was aborted.
emptied
(BUTTON) ✔MDN
[17624]HTMLMediaElement/emptied_event
Support in all current engines.
Firefox3.5+Safari3.1+Chrome3+
__________________________________________________________________
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung
Internet?Opera Android11+
[17625]Event A [17626]media element whose [17627]networkState was
previously not in the [17628]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 [17629]load() method was invoked while the
[17630]resource selection algorithm was already running).
[17631]networkState is [17632]NETWORK_EMPTY; all the IDL attributes are
in their initial states.
stalled
(BUTTON) ✔MDN
[17633]HTMLMediaElement/stalled_event
Support in all current engines.
Firefox3.5+Safari3.1+Chrome3+
__________________________________________________________________
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung
Internet?Opera Android11+
[17634]Event The user agent is trying to fetch [17635]media data, but
data is unexpectedly not forthcoming. [17636]networkState is
[17637]NETWORK_LOADING.
loadedmetadata
(BUTTON) ✔MDN
[17638]HTMLMediaElement/loadedmetadata_event
Support in all current engines.
Firefox3.5+Safari3.1+Chrome3+
__________________________________________________________________
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung
Internet?Opera Android11+
[17639]Event The user agent has just determined the duration and
dimensions of the [17640]media resource and [17641]the text tracks are
ready. [17642]readyState is newly equal to [17643]HAVE_METADATA or
greater for the first time.
loadeddata
(BUTTON) ✔MDN
[17644]HTMLMediaElement/loadeddata_event
Support in all current engines.
Firefox3.5+Safari3.1+Chrome3+
__________________________________________________________________
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung
Internet?Opera Android11+
[17645]Event The user agent can render the [17646]media data at the
[17647]current playback position for the first time. [17648]readyState
newly increased to [17649]HAVE_CURRENT_DATA or greater for the first
time.
canplay
(BUTTON) ✔MDN
[17650]HTMLMediaElement/canplay_event
Support in all current engines.
Firefox3.5+Safari3.1+Chrome3+
__________________________________________________________________
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung
Internet?Opera Android11+
[17651]Event The user agent can resume playback of the [17652]media
data, but estimates that if playback were to be started now, the
[17653]media resource could not be rendered at the current playback
rate up to its end without having to stop for further buffering of
content. [17654]readyState newly increased to [17655]HAVE_FUTURE_DATA
or greater.
canplaythrough
(BUTTON) ✔MDN
[17656]HTMLMediaElement/canplaythrough_event
Support in all current engines.
Firefox3.5+Safari3.1+Chrome3+
__________________________________________________________________
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung
Internet?Opera Android11+
[17657]Event The user agent estimates that if playback were to be
started now, the [17658]media resource could be rendered at the current
playback rate all the way to its end without having to stop for further
buffering. [17659]readyState is newly equal to [17660]HAVE_ENOUGH_DATA.
playing
(BUTTON) ✔MDN
[17661]HTMLMediaElement/playing_event
Support in all current engines.
Firefox3.5+Safari3.1+Chrome3+
__________________________________________________________________
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung
Internet?Opera Android11+
[17662]Event Playback is ready to start after having been paused or
delayed due to lack of [17663]media data. [17664]readyState is newly
greater than or equal to [17665]HAVE_FUTURE_DATA and [17666]paused is
false, or [17667]paused is newly false and [17668]readyState is greater
than or equal to [17669]HAVE_FUTURE_DATA. Even if this event fires, the
element might still not be [17670]potentially playing, e.g. if the
element is [17671]paused for user interaction or [17672]paused for
in-band content.
waiting
(BUTTON) ✔MDN
[17673]HTMLMediaElement/waiting_event
Support in all current engines.
Firefox6+Safari3.1+Chrome3+
__________________________________________________________________
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung
Internet?Opera Android12.1+
[17674]Event Playback has stopped because the next frame is not
available, but the user agent expects that frame to become available in
due course. [17675]readyState is less than or equal to
[17676]HAVE_CURRENT_DATA, and [17677]paused is false. Either
[17678]seeking is true, or the [17679]current playback position is not
contained in any of the ranges in [17680]buffered. It is possible for
playback to stop for other reasons without [17681]paused being false,
but those reasons do not fire this event (and when those situations
resolve, a separate [17682]playing event is not fired either): e.g.,
[17683]playback has ended, or playback [17684]stopped due to errors, or
the element has [17685]paused for user interaction or [17686]paused for
in-band content.
seeking
(BUTTON) ✔MDN
[17687]HTMLMediaElement/seeking_event
Support in all current engines.
Firefox3.5+Safari3.1+Chrome3+
__________________________________________________________________
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung
Internet?Opera Android11+
[17688]Event The [17689]seeking IDL attribute changed to true, and the
user agent has started seeking to a new position.
seeked
(BUTTON) ✔MDN
[17690]HTMLMediaElement/seeked_event
Support in all current engines.
Firefox3.5+Safari3.1+Chrome3+
__________________________________________________________________
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung
Internet?Opera Android11+
[17691]Event The [17692]seeking IDL attribute changed to false after
the [17693]current playback position was changed.
ended
(BUTTON) ✔MDN
[17694]HTMLMediaElement/ended_event
Support in all current engines.
Firefox3.5+Safari3.1+Chrome3+
__________________________________________________________________
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung
Internet?Opera Android11+
[17695]Event Playback has stopped because the end of the [17696]media
resource was reached. [17697]currentTime equals the end of the
[17698]media resource; [17699]ended is true.
durationchange
(BUTTON) ✔MDN
[17700]HTMLMediaElement/durationchange_event
Support in all current engines.
Firefox3.5+Safari3.1+Chrome3+
__________________________________________________________________
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung
Internet?Opera Android11+
[17701]Event The [17702]duration attribute has just been updated.
timeupdate
(BUTTON) ✔MDN
[17703]HTMLMediaElement/timeupdate_event
Support in all current engines.
Firefox3.5+Safari3.1+Chrome3+
__________________________________________________________________
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung
Internet?Opera Android11+
[17704]Event The [17705]current playback position changed as part of
normal playback or in an especially interesting way, for example
discontinuously.
play
(BUTTON) ✔MDN
[17706]HTMLMediaElement/play_event
Support in all current engines.
Firefox3.5+Safari3.1+Chrome3+
__________________________________________________________________
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung
Internet?Opera Android11+
[17707]Event The element is no longer paused. Fired after the
[17708]play() method has returned, or when the [17709]autoplay
attribute has caused playback to begin. [17710]paused is newly false.
pause
(BUTTON) ✔MDN
[17711]HTMLMediaElement/pause_event
Support in all current engines.
Firefox3.5+Safari3.1+Chrome3+
__________________________________________________________________
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung
Internet?Opera Android11+
[17712]Event The element has been paused. Fired after the
[17713]pause() method has returned. [17714]paused is newly true.
ratechange
(BUTTON) ✔MDN
[17715]HTMLMediaElement/ratechange_event
Support in all current engines.
Firefox3.5+Safari3.1+Chrome3+
__________________________________________________________________
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung
Internet?Opera Android11+
[17716]Event Either the [17717]defaultPlaybackRate or the
[17718]playbackRate attribute has just been updated.
resize [17719]Event One or both of the [17720]videoWidth and
[17721]videoHeight attributes have just been updated. [17722]Media
element is a [17723]video element; [17724]readyState is not
[17725]HAVE_NOTHING
volumechange
(BUTTON) ✔MDN
[17726]HTMLMediaElement/volumechange_event
Support in all current engines.
Firefox6+Safari3.1+Chrome3+
__________________________________________________________________
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung
Internet?Opera Android12.1+
[17727]Event Either the [17728]volume attribute or the [17729]muted
attribute has changed. Fired after the relevant attribute's setter has
returned.
The following event fires on [17730]source elements:
Event name Interface Fired when...
error [17731]Event An error occurs while fetching the [17732]media data
or the type of the resource is not a supported media format.
The following events fire on [17733]AudioTrackList,
[17734]VideoTrackList, and [17735]TextTrackList objects:
Event name Interface Fired when...
change
(BUTTON) ✔MDN
[17736]AudioTrackList/change_event
Support in all current engines.
Firefox🔰 33+Safari7+Chrome🔰 37+
__________________________________________________________________
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung
Internet?Opera Android?
[17739]Event One or more tracks in the track list have been enabled or
disabled.
addtrack
(BUTTON) ✔MDN
[17740]AudioTrackList/addtrack_event
Support in all current engines.
Firefox🔰 33+Safari7+Chrome🔰 37+
__________________________________________________________________
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung
Internet?Opera Android?
[17743]TrackEvent A track has been added to the track list.
removetrack
(BUTTON) ✔MDN
[17744]AudioTrackList/removetrack_event
Support in all current engines.
Firefox🔰 33+Safari7+Chrome🔰 37+
__________________________________________________________________
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung
Internet?Opera Android?
[17747]TrackEvent A track has been removed from the track list.
The following event fires on [17748]TextTrack objects and [17749]track
elements:
Event name Interface Fired when...
cuechange
(BUTTON) ✔MDN
[17750]HTMLTrackElement/cuechange_event
Support in all current engines.
Firefox68+Safari10+Chrome32+
__________________________________________________________________
Firefox Android?Safari iOS7+Chrome Android?WebView Android?Samsung
Internet?Opera Android12.1+
[17752]Event One or more cues in the track have become active or
stopped being active.
The following events fire on [17753]track elements:
Event name Interface Fired when...
error [17754]Event An error occurs while fetching the track data or the
type of the resource is not supported text track format.
load [17755]Event A track data has been fetched and successfully
processed.
The following events fire on [17756]TextTrackCue objects:
Event name Interface Fired when...
enter
(BUTTON) ✔MDN
[17757]TextTrackCue/enter_event
Support in all current engines.
Firefox31+Safari6+Chrome23+
__________________________________________________________________
Firefox Android?Safari iOS7+Chrome Android?WebView Android?Samsung
Internet?Opera Android12.1+
[17760]Event The cue has stopped being active.
4.8.11.17 Security and privacy considerations
The main security and privacy implications of the [17761]video and
[17762]audio elements come from the ability to embed media
cross-origin. There are two directions that threats can flow: from
hostile content to a victim page, and from a hostile page to victim
content.
__________________________________________________________________
If a victim page embeds hostile content, the threat is that the content
might contain scripted code that attempts to interact with the
[17763]Document that embeds the content. To avoid this, user agents
must ensure that there is no access from the content to the embedding
page. In the case of media content that uses DOM concepts, the embedded
content must be treated as if it was in its own unrelated
[17764]top-level traversable.
For instance, if an SVG animation was embedded in a [17765]video
element, the user agent would not give it access to the DOM of the
outer page. From the perspective of scripts in the SVG resource, the
SVG file would appear to be in a lone top-level traversable with no
parent.
__________________________________________________________________
If a hostile page embeds victim content, the threat is that the
embedding page could obtain information from the content that it would
not otherwise have access to. The API does expose some information: the
existence of the media, its type, its duration, its size, and the
performance characteristics of its host. Such information is already
potentially problematic, but in practice the same information can more
or less be obtained using the [17766]img element, and so it has been
deemed acceptable.
However, significantly more sensitive information could be obtained if
the user agent further exposes metadata within the content, such as
subtitles. That information is therefore only exposed if the video
resource uses CORS. The [17767]crossorigin attribute allows authors to
enable CORS. [17768][FETCH]
Without this restriction, an attacker could trick a user running within
a corporate network into visiting a site that attempts to load a video
from a previously leaked location on the corporation's intranet. If
such a video included confidential plans for a new product, then being
able to read the subtitles would present a serious confidentiality
breach.
4.8.11.18 Best practices for authors using media elements
This section is non-normative.
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 [17769]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
setting the element's [17770]src attribute to an empty string. In cases
where [17771]srcObject was set, instead set the [17772]srcObject to
null.
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.
4.8.11.19 Best practices for implementers of media elements
This section is non-normative.
How accurately various aspects of the [17773]media element API are
implemented is considered a quality-of-implementation issue.
For example, when implementing the [17774]buffered attribute, how
precise an implementation reports the ranges that have been buffered
depends on how carefully the user agent inspects the data. Since the
API reports ranges as times, but the data is obtained in byte streams,
a user agent receiving a variable-bitrate stream might only be able to
determine precise times by actually decoding all of the data. User
agents aren't required to do this, however; they can instead return
estimates (e.g. based on the average bitrate seen so far) which get
revised as more information becomes available.
As a general rule, user agents are urged to be conservative rather than
optimistic. For example, it would be bad to report that everything had
been buffered when it had not.
Another quality-of-implementation issue would be playing a video
backwards when the codec is designed only for forward playback (e.g.
there aren't many key frames, and they are far apart, and the
intervening frames only have deltas from the previous frame). User
agents could do a poor job, e.g. only showing key frames; however,
better implementations would do more work and thus do a better job,
e.g. actually decoding parts of the video forwards, storing the
complete frames, and then playing the frames backwards.
Similarly, while implementations are allowed to drop buffered data at
any time (there is no requirement that a user agent keep all the media
data obtained for the lifetime of the media element), it is again a
quality of implementation issue: user agents with sufficient resources
to keep all the data around are encouraged to do so, as this allows for
a better user experience. For example, if the user is watching a live
stream, a user agent could allow the user only to view the live video;
however, a better user agent would buffer everything and allow the user
to seek through the earlier material, pause it, play it forwards and
backwards, etc.
__________________________________________________________________
When a [17775]media element that is paused is [17776]removed from a
document and not reinserted before the next time the [17777]event loop
reaches [17778]step 1, implementations that are resource constrained
are encouraged to take that opportunity to release all hardware
resources (like video planes, networking resources, and data buffers)
used by the [17779]media element. (User agents still have to keep track
of the playback position and so forth, though, in case playback is
later restarted.)
4.8.12 The map element
(BUTTON) ✔MDN
[17780]Element/map
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
The [17807]map element, in conjunction with an [17808]img element and
any [17809]area element descendants, defines an [17810]image map. The
element [17811]represents its children.
The name attribute gives the map a name so that it can be
[17812]referenced. The attribute must be present and must have a
non-empty value with no [17813]ASCII whitespace. The value of the
[17814]name attribute must not be equal to the value of the [17815]name
attribute of another [17816]map element in the same [17817]tree. If the
[17818]id attribute is also specified, both attributes must have the
same value.
map.[17819]areas
Returns an [17820]HTMLCollection of the [17821]area elements in
the [17822]map.
The areas attribute must return an [17823]HTMLCollection rooted at the
[17824]map element, whose filter matches only [17825]area elements.
The IDL attribute name must [17826]reflect the content attribute of the
same name.
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.
Babies™: Toys
Toys
...
4.8.13 The area element
(BUTTON) ✔MDN
[17827]Element/area
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
[17832]Contexts in which this element can be used:
Where [17833]phrasing content is expected, but only if there is
a [17834]map element ancestor.
[17835]Content model:
[17836]Nothing.
[17837]Tag omission in text/html:
No [17838]end tag.
[17839]Content attributes:
[17840]Global attributes
[17841]alt — Replacement text for use when images are not
available
[17842]coords — Coordinates for the shape to be created in an
[17843]image map
[17844]shape — The kind of shape to be created in an
[17845]image map
[17846]href — Address of the [17847]hyperlink
[17848]target — [17849]Navigable for [17850]hyperlink
[17851]navigation
[17852]download — Whether to download the resource instead of
navigating to it, and its filename if so
[17853]ping — [17854]URLs to ping
[17855]rel — Relationship between the location in the document
containing the [17856]hyperlink and the destination resource
[17857]referrerpolicy — [17858]Referrer policy for
[17859]fetches initiated by the element
[17860]Accessibility considerations:
If the element has an [17861]href attribute: [17862]for authors;
[17863]for implementers.
Otherwise: [17864]for authors; [17865]for implementers.
// [17888]also has obsolete members
};
[17889]HTMLAreaElement includes [17890]HTMLHyperlinkElementUtils;
The [17891]area element [17892]represents either a hyperlink with some
text and a corresponding area on an [17893]image map, or a dead area on
an image map.
An [17894]area element with a parent node must have a [17895]map
element ancestor.
If the [17896]area element has an [17897]href attribute, then the
[17898]area element represents a [17899]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 [17900]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
[17901]alt attribute may be left blank if there is another [17902]area
element in the same [17903]image map that points to the same resource
and has a non-blank [17904]alt attribute.
If the [17905]area element has no [17906]href attribute, then the area
represented by the element cannot be selected, and the [17907]alt
attribute must be omitted.
In both cases, the [17908]shape and [17909]coords attributes specify
the area.
The shape attribute is an [17910]enumerated attribute with the
following keywords and states:
Keyword Conforming State Brief description
circle [17911]Circle state Designates a circle, using exactly three
integers in the [17912]coords attribute.
circ No
default [17913]Default state This area is the whole image. (The
[17914]coords attribute is not used.)
poly [17915]Polygon state Designates a polygon, using at-least six
integers in the [17916]coords attribute.
polygon No
rect [17917]Rectangle state Designates a rectangle, using exactly four
integers in the [17918]coords attribute.
rectangle No
The attribute's [17919]missing value default and [17920]invalid value
default are both the [17921]rectangle state.
The coords attribute must, if specified, contain a [17922]valid list of
floating-point numbers. This attribute gives the coordinates for the
shape described by the [17923]shape attribute. The processing for this
attribute is described as part of the [17924]image map processing
model.
In the circle state, [17925]area elements must have a [17926]coords
attribute present, with three integers, the last of which must be
non-negative. The first integer must be the distance in [17927]CSS
pixels from the left edge of the image to the center of the circle, the
second integer must be the distance in [17928]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 [17929]CSS pixels.
In the default state, [17930]area elements must not have a
[17931]coords attribute. (The area is the whole image.)
In the polygon state, [17932]area elements must have a [17933]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 [17934]CSS pixels
respectively, and all the coordinates together must represent the
points of the polygon, in order.
In the rectangle state, [17935]area elements must have a [17936]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 [17937]CSS pixels.
When user agents allow users to [17938]follow hyperlinks or
[17939]download hyperlinks created using the [17940]area element, the
[17941]href, [17942]target, [17943]download, and [17944]ping attributes
decide how the link is followed. The [17945]rel attribute may be used
to indicate to the user the likely nature of the target resource before
the user follows the link.
The [17946]target, [17947]download, [17948]ping, [17949]rel, and
[17950]referrerpolicy attributes must be omitted if the [17951]href
attribute is not present.
If the [17952]itemprop attribute is specified on an [17953]area
element, then the [17954]href attribute must also be specified.
(BUTTON) ✔MDN
[17955]HTMLAreaElement/rel
Support in all current engines.
Firefox30+Safari9+Chrome54+
__________________________________________________________________
The IDL attribute referrerPolicy must [17961]reflect the
[17962]referrerpolicy content attribute, [17963]limited to only known
values.
4.8.14 Image maps
4.8.14.1 Authoring
An image map allows geometric areas on an image to be associated with
[17964]hyperlinks.
An image, in the form of an [17965]img element, may be associated with
an image map (in the form of a [17966]map element) by specifying a
usemap attribute on the [17967]img element. The [17968]usemap
attribute, if specified, must be a [17969]valid hash-name reference to
a [17970]map element.
Consider an image that looks as follows:
A line with four shapes in it, equally spaced: a red hollow box, a
green circle, a blue triangle, and a yellow four-pointed star.
If we wanted just the colored areas to be clickable, we could do it as
follows:
Please select a shape:
4.8.14.2 Processing model
If an [17971]img element has a [17972]usemap attribute specified, user
agents must process it as follows:
1. Parse the attribute's value using the [17973]rules for parsing a
hash-name reference to a [17974]map element, with the element as
the context node. This will return either an element (the map) or
null.
2. If that returned null, then return. The image is not associated
with an image map after all.
3. Otherwise, the user agent must collect all the [17975]area elements
that are descendants of the map. Let those be the areas.
Having obtained the list of [17976]area elements that form the image
map (the areas), interactive user agents must process the list in one
of two ways.
If the user agent intends to show the text that the [17977]img element
represents, then it must use the following steps.
1. Remove all the [17978]area elements in areas that have no
[17979]href attribute.
2. Remove all the [17980]area elements in areas that have no
[17981]alt attribute, or whose [17982]alt attribute's value is the
empty string, if there is another [17983]area element in areas with
the same value in the [17984]href attribute and with a non-empty
[17985]alt attribute.
3. Each remaining [17986]area element in areas represents a
[17987]hyperlink. Those hyperlinks should all be made available to
the user in a manner associated with the text of the [17988]img.
In this context, user agents may represent [17989]area and
[17990]img elements with no specified alt attributes, or whose alt
attributes are the empty string or some other non-visible text, in
an [17991]implementation-defined fashion intended to indicate the
lack of suitable author-provided text.
If the user agent intends to show the image and allow interaction with
the image to select hyperlinks, then the image must be associated with
a set of layered shapes, taken from the [17992]area elements in areas,
in reverse [17993]tree order (so the last specified [17994]area element
in the map is the bottom-most shape, and the first element in the map,
in [17995]tree order, is the top-most shape).
Each [17996]area element in areas must be processed as follows to
obtain a shape to layer onto the image:
1. Find the state that the element's [17997]shape attribute
represents.
2. Use the [17998]rules for parsing a list of floating-point numbers
to parse the element's [17999]coords attribute, if it is present,
and let the result be the coords list. If the attribute is absent,
let the coords list be the empty list.
3. If the number of items in the coords list is less than the minimum
number given for the [18000]area element's current state, as per
the following table, then the shape is empty; return.
State Minimum number of items
[18001]Circle state 3
[18002]Default state 0
[18003]Polygon state 6
[18004]Rectangle state 4
4. Check for excess items in the coords list as per the entry in the
following list corresponding to the [18005]shape attribute's state:
[18006]Circle state
Drop any items in the list beyond the third.
[18007]Default state
Drop all items in the list.
[18008]Polygon state
Drop the last item if there's an odd number of items.
[18009]Rectangle state
Drop any items in the list beyond the fourth.
5. If the [18010]shape attribute represents the [18011]rectangle
state, and the first number in the list is numerically greater than
the third number in the list, then swap those two numbers around.
6. If the [18012]shape attribute represents the [18013]rectangle
state, and the second number in the list is numerically greater
than the fourth number in the list, then swap those two numbers
around.
7. If the [18014]shape attribute represents the [18015]circle state,
and the third number in the list is less than or equal to zero,
then the shape is empty; return.
8. Now, the shape represented by the element is the one described for
the entry in the list below corresponding to the state of the
[18016]shape attribute:
[18017]Circle state
Let x be the first number in coords, y be the second
number, and r be the third number.
The shape is a circle whose center is x [18018]CSS pixels
from the left edge of the image and y [18019]CSS pixels
from the top edge of the image, and whose radius is r
[18020]CSS pixels.
[18021]Default state
The shape is a rectangle that exactly covers the entire
image.
[18022]Polygon state
Let x[i] be the (2i)th entry in coords, and y[i] be the
(2i+1)th entry in coords (the first entry in coords being
the one with index 0).
Let the coordinates be (x[i], y[i]), interpreted in
[18023]CSS pixels measured from the top left of the image,
for all integer values of i from 0 to (N/2)-1, where N is
the number of items in coords.
The shape is a polygon whose vertices are given by the
coordinates, and whose interior is established using the
even-odd rule. [18024][GRAPHICS]
[18025]Rectangle state
Let x[1] be the first number in coords, y[1] be the second
number, x[2] be the third number, and y[2] be the fourth
number.
The shape is a rectangle whose top-left corner is given by
the coordinate (x[1], y[1]) and whose bottom right corner
is given by the coordinate (x[2], y[2]), those coordinates
being interpreted as [18026]CSS pixels from the top left
corner of the image.
For historical reasons, the coordinates must be interpreted
relative to the displayed image after any stretching caused by the
CSS [18027]'width' and [18028]'height' properties (or, for non-CSS
browsers, the image element's width and height attributes — CSS
browsers map those attributes to the aforementioned CSS
properties).
Browser zoom features and transforms applied using CSS or SVG do
not affect the coordinates.
Pointing device interaction with an image associated with a set of
layered shapes per the above algorithm must result in the relevant user
interaction events being first fired to the top-most shape covering the
point that the pointing device indicated, if any, or to the image
element itself, if there is no shape covering that point. User agents
may also allow individual [18029]area elements representing
[18030]hyperlinks to be selected and activated (e.g. using a keyboard).
Because a [18031]map element (and its [18032]area elements) can be
associated with multiple [18033]img elements, it is possible for an
[18034]area element to correspond to multiple [18035]focusable areas of
the document.
Image maps are [18036]live; if the DOM is mutated, then the user agent
must act as if it had rerun the algorithms for image maps.
The [18038]MathML math element falls into the [18039]embedded content,
[18040]phrasing content, [18041]flow content, and [18042]palpable
content categories for the purposes of the content models in this
specification.
When the [18043]MathML annotation-xml element contains elements from
the [18044]HTML namespace, such elements must all be [18045]flow
content.
When the MathML token elements ([18046]mi, [18047]mo, [18048]mn,
[18049]ms, and [18050]mtext) are descendants of HTML elements, they may
contain [18051]phrasing content elements from the [18052]HTML
namespace.
User agents must handle text other than [18053]inter-element whitespace
found in MathML elements whose content models do not allow straight
text by pretending for the purposes of MathML content models, layout,
and rendering that the text is actually wrapped in a [18054]MathML
mtext element. (Such text is not, however, conforming.)
User agents must act as if any MathML element whose contents does not
match the element's content model was replaced, for the purposes of
MathML layout and rendering, by a [18055]MathML merror element
containing some appropriate error message.
The semantics of MathML elements are defined by MathML and [18056]other
applicable specifications. [18057][MATHML]
Here is an example of the use of MathML in an HTML document:
The [18059]SVG svg element falls into the [18060]embedded content,
[18061]phrasing content, [18062]flow content, and [18063]palpable
content categories for the purposes of the content models in this
specification.
When the [18064]SVG foreignObject element contains elements from the
[18065]HTML namespace, such elements must all be [18066]flow content.
The content model for the [18067]SVG title element inside [18068]HTML
documents is [18069]phrasing content. (This further constrains the
requirements given in SVG 2.)
The semantics of SVG elements are defined by SVG 2 and [18070]other
applicable specifications. [18071][SVG]
__________________________________________________________________
doc = iframe.[18072]getSVGDocument()
doc = embed.[18073]getSVGDocument()
doc = object.[18074]getSVGDocument()
Returns the [18075]Document object, in the case of
[18076]iframe, [18077]embed, or [18078]object elements being
used to embed SVG.
The getSVGDocument() method steps are:
1. Let document be [18079]this's [18080]content document.
2. If document is non-null and was created by the [18081]page load
processing model for XML files section because the [18082]computed
type of the resource in the [18083]navigate algorithm was
[18084]image/svg+xml, then return document.
3. Return null.
4.8.17 Dimension attributes
Author requirements: The width and height attributes on [18085]img,
[18086]iframe, [18087]embed, [18088]object, [18089]video, [18090]source
when the parent is a [18091]picture element and, when their [18092]type
attribute is in the [18093]Image Button state, [18094]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 [18095]CSS pixels. The attributes,
if specified, must have values that are [18096]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, [18097]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 [18098]natural width to the
[18099]natural height in the resource. The specified width and
specified height are the values of the [18100]width and [18101]height
attributes respectively.
The two attributes must be omitted if the resource in question does not
have both a [18102]natural width and a [18103]natural height.
If the two attributes are both 0, 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.
User agent requirements: User agents are expected to use these
attributes [18104]as hints for the rendering.
(BUTTON) ✔MDN
[18105]HTMLObjectElement/width
Support in all current engines.
Firefox1+Safari3+Chrome1+
__________________________________________________________________
The width and height IDL attributes on the [18107]iframe, [18108]embed,
[18109]object, [18110]source, and [18111]video elements must
[18112]reflect the respective content attributes of the same name.
For [18113]iframe, [18114]embed and [18115]object the IDL attributes
are [18116]DOMString; for [18117]video and [18118]source the IDL
attributes are [18119]unsigned long.
The corresponding IDL attributes for [18120]img and [18121]input
elements are defined in those respective elements' sections, as they
are slightly more specific to those elements' other behaviors.
4.9 Tabular data
4.9.1 The table element
(BUTTON) ✔MDN
[18122]Element/table
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
[18127]Contexts in which this element can be used:
Where [18128]flow content is expected.
[18129]Content model:
In this order: optionally a [18130]caption element, followed by
zero or more [18131]colgroup elements, followed optionally by a
[18132]thead element, followed by either zero or more
[18133]tbody elements or one or more [18134]tr elements,
followed optionally by a [18135]tfoot element, optionally
intermixed with one or more [18136]script-supporting elements.
[18137]Tag omission in text/html:
Neither tag is omissible.
[SameObject] readonly attribute [18171]HTMLCollection [18172]rows;
[18173]HTMLTableRowElement [18174]insertRow(optional long index = -1);
[[18175]CEReactions] undefined [18176]deleteRow(long index);
// [18177]also has obsolete members
};
The [18178]table element [18179]represents data with more than one
dimension, in the form of a [18180]table.
The [18181]table element takes part in the [18182]table model. 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.
Precise rules for determining whether this conformance requirement is
met are described in the description of the [18183]table model.
Authors are encouraged to provide information describing how to
interpret complex tables. Guidance on how to [18184]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,
such as CSS grid layout, CSS flexible box layout ("flexbox"), CSS
multi-column layout, CSS positioning, and the CSS table model.
[18185][CSS]
__________________________________________________________________
Tables can be complicated to understand and navigate. To help users
with this, user agents should clearly delineate cells in a table from
each other, unless the user agent has classified the table as a
(non-conforming) layout table.
Authors and implementers are encouraged to consider using some of the
[18186]table design techniques described below to make tables easier to
navigate for users.
User agents, especially those that do table analysis on arbitrary
content, are encouraged to find heuristics to determine which tables
actually contain data and which are merely being used for layout. This
specification does not define a precise heuristic, but the following
are suggested as possible indicators:
Feature Indication
The use of the [18187]role attribute with the value [18188]presentation
Probably a layout table
The use of the non-conforming [18189]border attribute with the
non-conforming value 0 Probably a layout table
The use of the non-conforming [18190]cellspacing and [18191]cellpadding
attributes with the value 0 Probably a layout table
The use of [18192]caption, [18193]thead, or [18194]th elements Probably
a non-layout table
The use of the [18195]headers and [18196]scope attributes Probably a
non-layout table
The use of the non-conforming [18197]border attribute with a value
other than 0 Probably a non-layout table
Explicit visible borders set using CSS Probably a non-layout table
The use of the [18198]summary attribute Not a good indicator (both
layout and non-layout tables have historically been given this
attribute)
It is quite possible that the above suggestions are wrong. Implementers
are urged to provide feedback elaborating on their experiences with
trying to create a layout table detection heuristic.
If a [18199]table element has a (non-conforming) [18200]summary
attribute, and the user agent has not classified the table as a layout
table, the user agent may report the contents of that attribute to the
user.
__________________________________________________________________
Firefox Android?Safari iOS1+Chrome Android?WebView
Android?Samsung Internet?Opera Android12.1+
Ensures the table has a [18207]caption element, and returns it.
Firefox Android?Safari iOS1+Chrome Android?WebView
Android?Samsung Internet?Opera Android12.1+
Ensures the table does not have a [18210]caption element.
Can be set, to replace the [18214]thead element. If the new
value is not a [18215]thead element, throws a
[18216]"HierarchyRequestError" [18217]DOMException.
Firefox Android?Safari iOS1+Chrome Android?WebView
Android?Samsung Internet?Opera Android12.1+
Ensures the table has a [18220]thead element, and returns it.
Can be set, to replace the [18227]tfoot element. If the new
value is not a [18228]tfoot element, throws a
[18229]"HierarchyRequestError" [18230]DOMException.
Firefox Android?Safari iOS1+Chrome Android?WebView
Android?Samsung Internet?Opera Android12.1+
Ensures the table has a [18233]tfoot element, and returns it.
Firefox Android?Safari iOS1+Chrome Android?WebView
Android?Samsung Internet?Opera Android12.1+
Returns an [18239]HTMLCollection of the [18240]tbody elements of
the table.
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
Creates a [18243]tbody element, inserts it into the table, and
returns it.
Firefox Android?Safari iOS1+Chrome Android?WebView
Android?Samsung Internet?Opera Android12.1+
Returns an [18246]HTMLCollection of the [18247]tr elements of
the table.
Firefox Android?Safari iOS3+Chrome Android?WebView
Android37+Samsung Internet?Opera Android10.1+
Creates a [18250]tr element, along with a [18251]tbody if
required, inserts them into the table at the position given by
the argument, and returns the [18252]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 [18253]"IndexSizeError" [18254]DOMException.
Firefox Android?Safari iOS1+Chrome Android?WebView
Android?Samsung Internet?Opera Android12.1+
Removes the [18257]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
[18258]"IndexSizeError" [18259]DOMException.
In all of the following attribute and method definitions, when an
element is to be table-created, that means to [18260]create an element
given the [18261]table element's [18262]node document, the given local
name, and the [18263]HTML namespace.
The caption IDL attribute must return, on getting, the first
[18264]caption element child of the [18265]table element, if any, or
null otherwise. On setting, the first [18266]caption element child of
the [18267]table element, if any, must be removed, and the new value,
if not null, must be inserted as the first node of the [18268]table
element.
The createCaption() method must return the first [18269]caption element
child of the [18270]table element, if any; otherwise a new
[18271]caption element must be [18272]table-created, inserted as the
first node of the [18273]table element, and then returned.
The deleteCaption() method must remove the first [18274]caption element
child of the [18275]table element, if any.
The tHead IDL attribute must return, on getting, the first [18276]thead
element child of the [18277]table element, if any, or null otherwise.
On setting, if the new value is null or a [18278]thead element, the
first [18279]thead element child of the [18280]table element, if any,
must be removed, and the new value, if not null, must be inserted
immediately before the first element in the [18281]table element that
is neither a [18282]caption element nor a [18283]colgroup element, if
any, or at the end of the table if there are no such elements. If the
new value is neither null nor a [18284]thead element, then a
[18285]"HierarchyRequestError" [18286]DOMException must be thrown
instead.
The createTHead() method must return the first [18287]thead element
child of the [18288]table element, if any; otherwise a new [18289]thead
element must be [18290]table-created and inserted immediately before
the first element in the [18291]table element that is neither a
[18292]caption element nor a [18293]colgroup element, if any, or at the
end of the table if there are no such elements, and then that new
element must be returned.
The deleteTHead() method must remove the first [18294]thead element
child of the [18295]table element, if any.
The tFoot IDL attribute must return, on getting, the first [18296]tfoot
element child of the [18297]table element, if any, or null otherwise.
On setting, if the new value is null or a [18298]tfoot element, the
first [18299]tfoot element child of the [18300]table element, if any,
must be removed, and the new value, if not null, must be inserted at
the end of the table. If the new value is neither null nor a
[18301]tfoot element, then a [18302]"HierarchyRequestError"
[18303]DOMException must be thrown instead.
The createTFoot() method must return the first [18304]tfoot element
child of the [18305]table element, if any; otherwise a new [18306]tfoot
element must be [18307]table-created and inserted at the end of the
table, and then that new element must be returned.
The deleteTFoot() method must remove the first [18308]tfoot element
child of the [18309]table element, if any.
The tBodies attribute must return an [18310]HTMLCollection rooted at
the [18311]table node, whose filter matches only [18312]tbody elements
that are children of the [18313]table element.
The createTBody() method must [18314]table-create a new [18315]tbody
element, insert it immediately after the last [18316]tbody element
child in the [18317]table element, if any, or at the end of the
[18318]table element if the [18319]table element has no [18320]tbody
element children, and then must return the new [18321]tbody element.
The rows attribute must return an [18322]HTMLCollection rooted at the
[18323]table node, whose filter matches only [18324]tr elements that
are either children of the [18325]table element, or children of
[18326]thead, [18327]tbody, or [18328]tfoot elements that are
themselves children of the [18329]table element. The elements in the
collection must be ordered such that those elements whose parent is a
[18330]thead are included first, in [18331]tree order, followed by
those elements whose parent is either a [18332]table or [18333]tbody
element, again in [18334]tree order, followed finally by those elements
whose parent is a [18335]tfoot element, still in [18336]tree order.
The behavior of the insertRow(index) method depends on the state of the
table. When it is called, the method must act as required by the first
item in the following list of conditions that describes the state of
the table and the index argument:
If index is less than −1 or greater than the number of elements in
[18337]rows collection:
The method must throw an [18338]"IndexSizeError"
[18339]DOMException.
If the [18340]rows collection has zero elements in it, and the
[18341]table has no [18342]tbody elements in it:
The method must [18343]table-create a [18344]tbody element, then
[18345]table-create a [18346]tr element, then append the
[18347]tr element to the [18348]tbody element, then append the
[18349]tbody element to the [18350]table element, and finally
return the [18351]tr element.
If the [18352]rows collection has zero elements in it:
The method must [18353]table-create a [18354]tr element, append
it to the last [18355]tbody element in the table, and return the
[18356]tr element.
If index is −1 or equal to the number of items in [18357]rows
collection:
The method must [18358]table-create a [18359]tr element, and
append it to the parent of the last [18360]tr element in the
[18361]rows collection. Then, the newly created [18362]tr
element must be returned.
Otherwise:
The method must [18363]table-create a [18364]tr element, insert
it immediately before the indexth [18365]tr element in the
[18366]rows collection, in the same parent, and finally must
return the newly created [18367]tr element.
When the deleteRow(index) method is called, the user agent must run the
following steps:
1. If index is less than −1 or greater than or equal to the number of
elements in the [18368]rows collection, then throw an
[18369]"IndexSizeError" [18370]DOMException.
2. If index is −1, then [18371]remove the last element in the
[18372]rows collection from its parent, or do nothing if the
[18373]rows collection is empty.
3. Otherwise, [18374]remove the indexth element in the [18375]rows
collection from its parent.
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.
Todayʼs Sudoku
1
3
6
4
7
9
2
9
1
7
6
2
4
3
9
8
5
9
7
1
6
5
2
7
9
8
2
5
4.9.1.1 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:
CAPTION: Characteristics with positive and negative sides
Negative Characteristic Positive
Sad Mood Happy
Failing Grade 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".
There are a variety of ways to include this information, such as:
In prose, surrounding the table
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.
Characteristics with positive and negative sides
Negative
Characteristic
Positive
Sad
Mood
Happy
Failing
Grade
Passing
In the table's [18376]caption
Characteristics with positive and negative sides.
Characteristics are given in the second column, with the
negative side in the left column and the positive side in the right
column.
Negative
Characteristic
Positive
Sad
Mood
Happy
Failing
Grade
Passing
In the table's [18377]caption, in a [18378]details element
Characteristics with positive and negative sides.Help
Characteristics are given in the second column, with the
negative side in the left column and the positive side in the right
column.
Negative
Characteristic
Positive
Sad
Mood
Happy
Failing
Grade
Passing
Next to the table, in the same [18379]figure
Characteristics with positive and negative sides
Characteristics are given in the second column, with the
negative side in the left column and the positive side in the right
column.
Negative
Characteristic
Positive
Sad
Mood
Happy
Failing
Grade
Passing
Next to the table, in a [18380]figure's [18381]figcaption
Characteristics with positive and negative sides
Characteristics are given in the second column, with the
negative side in the left column and the positive side in the right
column.
Negative
Characteristic
Positive
Sad
Mood
Happy
Failing
Grade
Passing
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 [18382]headers attributes:
Characteristics with positive and negative sides
Characteristic
Negative
Positive
Mood
Sad
Happy
Grade
Failing
Passing
4.9.1.2 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.
User agents are encouraged to render tables using these techniques
whenever the page does not use CSS and the table is not classified as a
layout table.
4.9.2 The caption element
(BUTTON) ✔MDN
[18383]Element/caption
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
[18386]Contexts in which this element can be used:
As the first element child of a [18387]table element.
[18388]Content model:
[18389]Flow content, but with no descendant [18390]table
elements.
[18391]Tag omission in text/html:
A [18392]caption element's [18393]end tag can be omitted if the
[18394]caption element is not immediately followed by
[18395]ASCII whitespace or a [18396]comment.
The [18406]caption element [18407]represents the title of the
[18408]table that is its parent, if it has a parent and that is a
[18409]table element.
The [18410]caption element takes part in the [18411]table model.
When a [18412]table element is the only content in a [18413]figure
element other than the [18414]figcaption, the [18415]caption element
should be omitted in favor of the [18416]figcaption.
A caption can introduce context for a table, making it significantly
easier to understand.
In the abstract, this table is not clear. However, with a caption
giving the table's number (for [18417]reference in the main prose) and
explaining its use, it makes more sense:
Table 1.
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.
This provides the user with more context:
CAPTION:
Table 1.
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.
1 2 3 4 5 6
1 2 3 4 5 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
4.9.3 The colgroup element
(BUTTON) ✔MDN
[18418]Element/colgroup
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
[18421]Contexts in which this element can be used:
As a child of a [18422]table element, after any [18423]caption
elements and before any [18424]thead, [18425]tbody,
[18426]tfoot, and [18427]tr elements.
[18428]Content model:
If the [18429]span attribute is present: [18430]Nothing.
If the [18431]span attribute is absent: Zero or more [18432]col
and [18433]template elements.
[18434]Tag omission in text/html:
A [18435]colgroup element's [18436]start tag can be omitted if
the first thing inside the [18437]colgroup element is a
[18438]col element, and if the element is not immediately
preceded by another [18439]colgroup element whose [18440]end tag
has been omitted. (It can't be omitted if the element is empty.)
A [18441]colgroup element's [18442]end tag can be omitted if the
[18443]colgroup element is not immediately followed by
[18444]ASCII whitespace or a [18445]comment.
[18446]Content attributes:
[18447]Global attributes
[18448]span — Number of columns spanned by the element
[[18455]CEReactions] attribute unsigned long [18456]span;
// [18457]also has obsolete members
};
The [18458]colgroup element [18459]represents a [18460]group of one or
more [18461]columns in the [18462]table that is its parent, if it has a
parent and that is a [18463]table element.
If the [18464]colgroup element contains no [18465]col elements, then
the element may have a span content attribute specified, whose value
must be a [18466]valid non-negative integer greater than zero and less
than or equal to 1000.
The [18467]colgroup element and its [18468]span attribute take part in
the [18469]table model.
The span IDL attribute must [18470]reflect the content attribute of the
same name. It is [18471]clamped to the range [1, 1000], and its
[18472]default value is 1.
4.9.4 The col element
(BUTTON) ✔MDN
[18473]Element/col
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
[18488]DOM interface:
Uses [18489]HTMLTableColElement, as defined for [18490]colgroup
elements.
If a [18491]col element has a parent and that is a [18492]colgroup
element that itself has a parent that is a [18493]table element, then
the [18494]col element [18495]represents one or more [18496]columns in
the [18497]column group represented by that [18498]colgroup.
The element may have a span content attribute specified, whose value
must be a [18499]valid non-negative integer greater than zero and less
than or equal to 1000.
The [18500]col element and its [18501]span attribute take part in the
[18502]table model.
4.9.5 The tbody element
(BUTTON) ✔MDN
[18503]Element/tbody
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
[18506]Contexts in which this element can be used:
As a child of a [18507]table element, after any [18508]caption,
[18509]colgroup, and [18510]thead elements, but only if there
are no [18511]tr elements that are children of the [18512]table
element.
[18513]Content model:
Zero or more [18514]tr and [18515]script-supporting elements.
[18516]Tag omission in text/html:
A [18517]tbody element's [18518]start tag can be omitted if the
first thing inside the [18519]tbody element is a [18520]tr
element, and if the element is not immediately preceded by a
[18521]tbody, [18522]thead, or [18523]tfoot element whose
[18524]end tag has been omitted. (It can't be omitted if the
element is empty.)
A [18525]tbody element's [18526]end tag can be omitted if the
[18527]tbody element is immediately followed by a [18528]tbody
or [18529]tfoot element, or if there is no more content in the
parent element.
[SameObject] readonly attribute [18538]HTMLCollection [18539]rows;
[18540]HTMLTableRowElement [18541]insertRow(optional long index = -1);
[[18542]CEReactions] undefined [18543]deleteRow(long index);
// [18544]also has obsolete members
};
The [18545]HTMLTableSectionElement interface is also used for
[18546]thead and [18547]tfoot elements.
The [18548]tbody element [18549]represents a [18550]block of
[18551]rows that consist of a body of data for the parent [18552]table
element, if the [18553]tbody element has a parent and it is a
[18554]table.
The [18555]tbody element takes part in the [18556]table model.
tbody.[18557]rows
Returns an [18558]HTMLCollection of the [18559]tr elements of
the table section.
tr = tbody.[18560]insertRow([ index ])
Creates a [18561]tr element, inserts it into the table section
at the position given by the argument, and returns the
[18562]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 [18563]"IndexSizeError" [18564]DOMException.
tbody.[18565]deleteRow(index)
Removes the [18566]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
[18567]"IndexSizeError" [18568]DOMException.
The rows attribute must return an [18569]HTMLCollection rooted at this
element, whose filter matches only [18570]tr elements that are children
of this element.
The insertRow(index) method must act as follows:
1. If index is less than −1 or greater than the number of elements in
the [18571]rows collection, throw an [18572]"IndexSizeError"
[18573]DOMException.
2. Let table row be the result of [18574]creating an element given
this element's [18575]node document, "tr", and the [18576]HTML
namespace.
3. If index is −1 or equal to the number of items in the [18577]rows
collection, then [18578]append table row to this element.
4. Otherwise, [18579]insert table row as a child of this element,
immediately before the indexth [18580]tr element in the [18581]rows
collection.
5. Return table row.
The deleteRow(index) method must, when invoked, act as follows:
1. If index is less than −1 or greater than or equal to the number of
elements in the [18582]rows collection, then throw an
[18583]"IndexSizeError" [18584]DOMException.
2. If index is −1, then [18585]remove the last element in the
[18586]rows collection from this element, or do nothing if the
[18587]rows collection is empty.
3. Otherwise, [18588]remove the indexth element in the [18589]rows
collection from this element.
4.9.6 The thead element
(BUTTON) ✔MDN
[18590]Element/thead
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
[18592]Contexts in which this element can be used:
As a child of a [18593]table element, after any [18594]caption,
and [18595]colgroup elements and before any [18596]tbody,
[18597]tfoot, and [18598]tr elements, but only if there are no
other [18599]thead elements that are children of the
[18600]table element.
[18601]Content model:
Zero or more [18602]tr and [18603]script-supporting elements.
[18604]Tag omission in text/html:
A [18605]thead element's [18606]end tag can be omitted if the
[18607]thead element is immediately followed by a [18608]tbody
or [18609]tfoot element.
[18615]DOM interface:
Uses [18616]HTMLTableSectionElement, as defined for [18617]tbody
elements.
The [18618]thead element [18619]represents the [18620]block of
[18621]rows that consist of the column labels (headers) and any
ancillary non-header cells for the parent [18622]table element, if the
[18623]thead element has a parent and it is a [18624]table.
The [18625]thead element takes part in the [18626]table model.
This example shows a [18627]thead element being used. Notice the use of
both [18628]th and [18629]td elements in the [18630]thead element: the
first row is the headers, and the second row is an explanation of how
to fill in the table.
School auction sign-up sheet
Your name here
What are you selling?
Link to a picture
Your reserve price
Ms Danus
Doughnuts
$45
4.9.7 The tfoot element
(BUTTON) ✔MDN
[18631]Element/tfoot
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
[18633]Contexts in which this element can be used:
As a child of a [18634]table element, after any [18635]caption,
[18636]colgroup, [18637]thead, [18638]tbody, and [18639]tr
elements, but only if there are no other [18640]tfoot elements
that are children of the [18641]table element.
[18642]Content model:
Zero or more [18643]tr and [18644]script-supporting elements.
[18645]Tag omission in text/html:
A [18646]tfoot element's [18647]end tag can be omitted if there
is no more content in the parent element.
[18653]DOM interface:
Uses [18654]HTMLTableSectionElement, as defined for [18655]tbody
elements.
The [18656]tfoot element [18657]represents the [18658]block of
[18659]rows that consist of the column summaries (footers) for the
parent [18660]table element, if the [18661]tfoot element has a parent
and it is a [18662]table.
The [18663]tfoot element takes part in the [18664]table model.
4.9.8 The tr element
(BUTTON) ✔MDN
[18665]Element/tr
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
[18668]Contexts in which this element can be used:
As a child of a [18669]thead element.
As a child of a [18670]tbody element.
As a child of a [18671]tfoot element.
As a child of a [18672]table element, after any [18673]caption,
[18674]colgroup, and [18675]thead elements, but only if there
are no [18676]tbody elements that are children of the
[18677]table element.
[18678]Content model:
Zero or more [18679]td, [18680]th, and [18681]script-supporting
elements.
[18682]Tag omission in text/html:
A [18683]tr element's [18684]end tag can be omitted if the
[18685]tr element is immediately followed by another [18686]tr
element, or if there is no more content in the parent element.
Firefox Android?Safari iOS1+Chrome Android?WebView
Android?Samsung Internet?Opera Android12.1+
Returns the position of the row in the table's [18713]rows list.
Returns −1 if the element isn't in a table.
tr.[18714]sectionRowIndex
Returns the position of the row in the table section's
[18715]rows list.
Returns −1 if the element isn't in a table section.
tr.[18716]cells
Returns an [18717]HTMLCollection of the [18718]td and [18719]th
elements of the row.
Firefox Android?Safari iOS1+Chrome Android?WebView
Android?Samsung Internet?Opera Android12.1+
Creates a [18722]td element, inserts it into the table row at
the position given by the argument, and returns the [18723]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 [18724]"IndexSizeError" [18725]DOMException.
tr.[18726]deleteCell(index)
Removes the [18727]td or [18728]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.
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
[18729]"IndexSizeError" [18730]DOMException.
The rowIndex attribute must, if this element has a parent [18731]table
element, or a parent [18732]tbody, [18733]thead, or [18734]tfoot
element and a grandparent [18735]table element, return the index of
this [18736]tr element in that [18737]table element's [18738]rows
collection. If there is no such [18739]table element, then the
attribute must return −1.
The sectionRowIndex attribute must, if this element has a parent
[18740]table, [18741]tbody, [18742]thead, or [18743]tfoot element,
return the index of the [18744]tr element in the parent element's rows
collection (for tables, that's [18745]HTMLTableElement's [18746]rows
collection; for table sections, that's [18747]HTMLTableSectionElement's
[18748]rows collection). If there is no such parent element, then the
attribute must return −1.
The cells attribute must return an [18749]HTMLCollection rooted at this
[18750]tr element, whose filter matches only [18751]td and [18752]th
elements that are children of the [18753]tr element.
The insertCell(index) method must act as follows:
1. If index is less than −1 or greater than the number of elements in
the [18754]cells collection, then throw an [18755]"IndexSizeError"
[18756]DOMException.
2. Let table cell be the result of [18757]creating an element given
this [18758]tr element's [18759]node document, "td", and the
[18760]HTML namespace.
3. If index is equal to −1 or equal to the number of items in
[18761]cells collection, then [18762]append table cell to this
[18763]tr element.
4. Otherwise, [18764]insert table cell as a child of this [18765]tr
element, immediately before the indexth [18766]td or [18767]th
element in the [18768]cells collection.
5. Return table cell.
The deleteCell(index) method must act as follows:
1. If index is less than −1 or greater than or equal to the number of
elements in the [18769]cells collection, then throw an
[18770]"IndexSizeError" [18771]DOMException.
2. If index is −1, then [18772]remove the last element in the
[18773]cells collection from its parent, or do nothing if the
[18774]cells collection is empty.
3. Otherwise, [18775]remove the indexth element in the [18776]cells
collection from its parent.
4.9.9 The td element
(BUTTON) ✔MDN
[18777]Element/td
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
[18780]Contexts in which this element can be used:
As a child of a [18781]tr element.
[18782]Content model:
[18783]Flow content.
[18784]Tag omission in text/html:
A [18785]td element's [18786]end tag can be omitted if the
[18787]td element is immediately followed by a [18788]td or
[18789]th element, or if there is no more content in the parent
element.
[18790]Content attributes:
[18791]Global attributes
[18792]colspan — Number of columns that the cell is to span
[18793]rowspan — Number of rows that the cell is to span
[18794]headers — The header cells for this cell
[[18801]CEReactions] attribute unsigned long [18802]colSpan;
[[18803]CEReactions] attribute unsigned long [18804]rowSpan;
[[18805]CEReactions] attribute DOMString [18806]headers;
readonly attribute long [18807]cellIndex;
[[18808]CEReactions] attribute DOMString [18809]scope; // only conforming for
th elements
[[18810]CEReactions] attribute DOMString [18811]abbr; // only conforming for
th elements
// [18812]also has obsolete members
};
The [18813]HTMLTableCellElement interface is also used for
[18814]th elements.
The [18815]td element [18816]represents a data [18817]cell in a table.
The [18818]td element and its [18819]colspan, [18820]rowspan, and
[18821]headers attributes take part in the [18822]table model.
User agents, especially in non-visual environments or where displaying
the table as a 2D grid is impractical, may give the user context for
the cell when rendering the contents of a cell; for instance, giving
its position in the [18823]table model, or listing the cell's header
cells (as determined by the [18824]algorithm for assigning header
cells). When a cell's header cells are being listed, user agents may
use the value of [18825]abbr attributes on those header cells, if any,
instead of the contents of the header cells themselves.
In this example, we see a snippet of a web application consisting of a
grid of editable cells (essentially a simple spreadsheet). One of the
cells has been configured to show the sum of the cells above it. Three
have been marked as headings, which use [18826]th elements instead of
[18827]td elements. A script would attach event handlers to these
elements to maintain the total.
4.9.10 The th element
(BUTTON) ✔MDN
[18828]Element/th
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
[18830]Contexts in which this element can be used:
As a child of a [18831]tr element.
[18832]Content model:
[18833]Flow content, but with no [18834]header, [18835]footer,
[18836]sectioning content, or [18837]heading content
descendants.
[18838]Tag omission in text/html:
A [18839]th element's [18840]end tag can be omitted if the
[18841]th element is immediately followed by a [18842]td or
[18843]th element, or if there is no more content in the parent
element.
[18844]Content attributes:
[18845]Global attributes
[18846]colspan — Number of columns that the cell is to span
[18847]rowspan — Number of rows that the cell is to span
[18848]headers — The header cells for this cell
[18849]scope — Specifies which cells the header cell applies to
[18850]abbr — Alternative label to use for the header cell when
referencing the cell in other contexts
[18854]DOM interface:
Uses [18855]HTMLTableCellElement, as defined for [18856]td
elements.
The [18857]th element [18858]represents a header [18859]cell in a
table.
The [18860]th element may have a scope content attribute specified.
The [18861]scope attribute is an [18862]enumerated attribute with the
following keywords and states:
Keyword State Brief description
row row The header cell applies to some of the subsequent cells in the
same row(s).
col column The header cell applies to some of the subsequent cells in
the same column(s).
rowgroup row group The header cell applies to all the remaining cells
in the row group.
colgroup column group The header cell applies to all the remaining
cells in the column group.
The attribute's [18863]missing value default and [18864]invalid value
default are both the auto state. (In this state the header cell applies
to a set of cells selected based on context.)
A [18865]th element's [18866]scope attribute must not be in the
[18867]row group state if the element is not anchored in a [18868]row
group, nor in the [18869]column group state if the element is not
anchored in a [18870]column group.
The [18871]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 [18872]th element and its [18873]colspan, [18874]rowspan,
[18875]headers, and [18876]scope attributes take part in the
[18877]table model.
The following example shows how the [18878]scope attribute's
[18879]rowgroup value affects which data cells a header cell applies
to.
Here is a markup fragment showing a table:
ID
Measurement
Average
Maximum
Cats
93
Legs
3.5
4
10
Tails
1
1
English speakers
32
Legs
2.67
4
35
Tails
0.33
1
This would result in the following table:
ID Measurement Average Maximum
Cats
93 Legs 3.5 4
10 Tails 1 1
English speakers
32 Legs 2.67 4
35 Tails 0.33 1
The headers in the first row all apply directly down to the rows in
their column.
The headers with a [18880]scope attribute in the [18881]rowgroup state
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.
4.9.11 Attributes common to [18882]td and [18883]th elements
The [18884]td and [18885]th elements may have a colspan content
attribute specified, whose value must be a [18886]valid non-negative
integer greater than zero and less than or equal to 1000.
The [18887]td and [18888]th elements may also have a rowspan content
attribute specified, whose value must be a [18889]valid non-negative
integer less than or equal to 65534. 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, as described in the description of the [18890]table model.
__________________________________________________________________
The [18891]td and [18892]th element may have a headers content
attribute specified. The [18893]headers attribute, if specified, must
contain a string consisting of an [18894]unordered set of unique
space-separated tokens, none of which are [18895]identical to another
token and each of which must have the value of an [18896]ID of a
[18897]th element taking part in the same [18898]table as the [18899]td
or [18900]th element (as defined by the [18901]table model).
A [18902]th element with [18903]ID id is said to be directly targeted
by all [18904]td and [18905]th elements in the same [18906]table that
have [18907]headers attributes whose values include as one of their
tokens the [18908]ID id. A [18909]th element A is said to be targeted
by a [18910]th or [18911]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 [18912]th element must not be targeted by itself.
The [18913]colspan, [18914]rowspan, and [18915]headers attributes take
part in the [18916]table model.
__________________________________________________________________
cell.[18917]cellIndex
Returns the position of the cell in the row's [18918]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.
The colSpan IDL attribute must [18919]reflect the [18920]colspan
content attribute. It is [18921]clamped to the range [1, 1000], and its
[18922]default value is 1.
The rowSpan IDL attribute must [18923]reflect the [18924]rowspan
content attribute. It is [18925]clamped to the range [0, 65534], and
its [18926]default value is 1.
The headers IDL attribute must [18927]reflect the content attribute of
the same name.
The cellIndex IDL attribute must, if the element has a parent [18928]tr
element, return the index of the cell's element in the parent element's
[18929]cells collection. If there is no such parent element, then the
attribute must return −1.
The scope IDL attribute must [18930]reflect the content attribute of
the same name, [18931]limited to only known values.
The abbr IDL attribute must [18932]reflect the content attribute of the
same name.
4.9.12 Processing model
The various table elements and their content attributes together define
the table model.
A table consists of cells aligned on a two-dimensional grid of slots
with coordinates (x, y). The grid is finite, and is either empty or has
one or more slots. If the grid has one or more slots, then the x
coordinates are always in the range 0 ≤ x < x[width], and the y
coordinates are always in the range 0 ≤ y < y[height]. If one or both
of x[width] and y[height] are zero, then the table is empty (has no
slots). Tables correspond to [18933]table elements.
A cell is a set of slots anchored at a slot (cell[x], cell[y]), and
with a particular width and height such that the cell covers all the
slots with coordinates (x, y) where cell[x] ≤ x < cell[x]+width and
cell[y] ≤ y < cell[y]+height. Cells can either be data cells or header
cells. Data cells correspond to [18934]td elements, and header cells
correspond to [18935]th elements. Cells of both types can have zero or
more associated header cells.
It is possible, in certain error cases, for two cells to occupy the
same slot.
A row is a complete set of slots from x=0 to x=x[width]-1, for a
particular value of y. Rows usually correspond to [18936]tr elements,
though a [18937]row group can have some implied [18938]rows at the end
in some cases involving [18939]cells spanning multiple rows.
A column is a complete set of slots from y=0 to y=y[height]-1, for a
particular value of x. Columns can correspond to [18940]col elements.
In the absence of [18941]col elements, columns are implied.
A row group is a set of [18942]rows anchored at a slot (0, group[y])
with a particular height such that the row group covers all the slots
with coordinates (x, y) where 0 ≤ x < x[width] and
group[y] ≤ y < group[y]+height. Row groups correspond to [18943]tbody,
[18944]thead, and [18945]tfoot elements. Not every row is necessarily
in a row group.
A column group is a set of [18946]columns anchored at a slot (group[x],
0) with a particular width such that the column group covers all the
slots with coordinates (x, y) where group[x] ≤ x < group[x]+width and
0 ≤ y < y[height]. Column groups correspond to [18947]colgroup
elements. Not every column is necessarily in a column group.
[18948]Row groups cannot overlap each other. Similarly, [18949]column
groups cannot overlap each other.
A [18950]cell cannot cover slots that are from two or more [18951]row
groups. It is, however, possible for a cell to be in multiple
[18952]column groups. All the slots that form part of one cell are part
of zero or one [18953]row groups and zero or more [18954]column groups.
In addition to [18955]cells, [18956]columns, [18957]rows, [18958]row
groups, and [18959]column groups, [18960]tables can have a
[18961]caption element associated with them. This gives the table a
heading, or legend.
A table model error is an error with the data represented by
[18962]table elements and their descendants. Documents must not have
table model errors.
4.9.12.1 Forming a table
To determine which elements correspond to which slots in a [18963]table
associated with a [18964]table element, to determine the dimensions of
the table (x[width] and y[height]), and to determine if there are any
[18965]table model errors, user agents must use the following
algorithm:
1. Let x[width] be zero.
2. Let y[height] be zero.
3. Let pending [18966]tfoot elements be a list of [18967]tfoot
elements, initially empty.
4. Let the table be the [18968]table represented by the [18969]table
element. The x[width] and y[height] variables give the table's
dimensions. The table is initially empty.
5. If the [18970]table element has no children elements, then return
the table (which will be empty).
6. Associate the first [18971]caption element child of the
[18972]table element with the table. If there are no such children,
then it has no associated [18973]caption element.
7. Let the current element be the first element child of the
[18974]table element.
If a step in this algorithm ever requires the current element to be
advanced to the next child of the table when there is no such next
child, then the user agent must jump to the step labeled end, near
the end of this algorithm.
8. While the current element is not one of the following elements,
[18975]advance the current element to the next child of the
[18976]table:
+ [18977]colgroup
+ [18978]thead
+ [18979]tbody
+ [18980]tfoot
+ [18981]tr
9. If the current element is a [18982]colgroup, follow these substeps:
1. Column groups: Process the current element according to the
appropriate case below:
If the current element has any [18983]col element children
Follow these steps:
1. Let x[start] have the value of x[width].
2. Let the current column be the first [18984]col
element child of the [18985]colgroup element.
3. Columns: If the current column [18986]col element
has a [18987]span attribute, then parse its value
using the [18988]rules for parsing non-negative
integers.
If the result of parsing the value is not an error
or zero, then let span be that value.
Otherwise, if the [18989]col element has no
[18990]span attribute, or if trying to parse the
attribute's value resulted in an error or zero, then
let span be 1.
If span is greater than 1000, let it be 1000
instead.
4. Increase x[width] by span.
5. Let the last span [18991]columns in the table
correspond to the current column [18992]col element.
6. If current column is not the last [18993]col element
child of the [18994]colgroup element, then let the
current column be the next [18995]col element child
of the [18996]colgroup element, and return to the
step labeled columns.
7. Let all the last [18997]columns in the table from
x=x[start] to x=x[width]-1 form a new [18998]column
group, anchored at the slot (x[start], 0), with
width x[width]-x[start], corresponding to the
[18999]colgroup element.
If the current element has no [19000]col element children
1. If the [19001]colgroup element has a [19002]span
attribute, then parse its value using the
[19003]rules for parsing non-negative integers.
If the result of parsing the value is not an error
or zero, then let span be that value.
Otherwise, if the [19004]colgroup element has no
[19005]span attribute, or if trying to parse the
attribute's value resulted in an error or zero, then
let span be 1.
If span is greater than 1000, let it be 1000
instead.
2. Increase x[width] by span.
3. Let the last span [19006]columns in the table form a
new [19007]column group, anchored at the slot
(x[width]-span, 0), with width span, corresponding
to the [19008]colgroup element.
2. [19009]Advance the current element to the next child of the
[19010]table.
3. While the current element is not one of the following
elements, [19011]advance the current element to the next child
of the [19012]table:
o [19013]colgroup
o [19014]thead
o [19015]tbody
o [19016]tfoot
o [19017]tr
4. If the current element is a [19018]colgroup element, jump to
the step labeled column groups above.
10. Let y[current] be zero.
11. Let the list of downward-growing cells be an empty list.
12. Rows: While the current element is not one of the following
elements, [19019]advance the current element to the next child of
the [19020]table:
+ [19021]thead
+ [19022]tbody
+ [19023]tfoot
+ [19024]tr
13. If the current element is a [19025]tr, then run the
[19026]algorithm for processing rows, [19027]advance the current
element to the next child of the [19028]table, and return to the
step labeled rows.
14. Run the [19029]algorithm for ending a row group.
15. If the current element is a [19030]tfoot, then add that element to
the list of pending [19031]tfoot elements, [19032]advance the
current element to the next child of the [19033]table, and return
to the step labeled rows.
16. The current element is either a [19034]thead or a [19035]tbody.
Run the [19036]algorithm for processing row groups.
17. [19037]Advance the current element to the next child of the
[19038]table.
18. Return to the step labeled rows.
19. End: For each [19039]tfoot element in the list of pending
[19040]tfoot elements, in [19041]tree order, run the
[19042]algorithm for processing row groups.
20. If there exists a [19043]row or [19044]column in the table
containing only [19045]slots that do not have a [19046]cell
anchored to them, then this is a [19047]table model error.
21. Return the table.
The algorithm for processing row groups, which is invoked by the set of
steps above for processing [19048]thead, [19049]tbody, and [19050]tfoot
elements, is:
1. Let y[start] have the value of y[height].
2. For each [19051]tr element that is a child of the element being
processed, in tree order, run the [19052]algorithm for processing
rows.
3. If y[height] > y[start], then let all the last [19053]rows in the
table from y=y[start] to y=y[height]-1 form a new [19054]row group,
anchored at the slot with coordinate (0, y[start]), with height
y[height]-y[start], corresponding to the element being processed.
4. Run the [19055]algorithm for ending a row group.
The algorithm for ending a row group, which is invoked by the set of
steps above when starting and ending a block of rows, is:
1. While y[current] is less than y[height], follow these steps:
1. Run the [19056]algorithm for growing downward-growing cells.
2. Increase y[current] by 1.
2. Empty the list of downward-growing cells.
The algorithm for processing rows, which is invoked by the set of steps
above for processing [19057]tr elements, is:
1. If y[height] is equal to y[current], then increase y[height] by 1.
(y[current] is never greater than y[height].)
2. Let x[current] be 0.
3. Run the [19058]algorithm for growing downward-growing cells.
4. If the [19059]tr element being processed has no [19060]td or
[19061]th element children, then increase y[current] by 1, abort
this set of steps, and return to the algorithm above.
5. Let current cell be the first [19062]td or [19063]th element child
in the [19064]tr element being processed.
6. Cells: While x[current] is less than x[width] and the slot with
coordinate (x[current], y[current]) already has a cell assigned to
it, increase x[current] by 1.
7. If x[current] is equal to x[width], increase x[width] by 1.
(x[current] is never greater than x[width].)
8. If the current cell has a [19065]colspan attribute, then
[19066]parse that attribute's value, and let colspan be the result.
If parsing that value failed, or returned zero, or if the attribute
is absent, then let colspan be 1, instead.
If colspan is greater than 1000, let it be 1000 instead.
9. If the current cell has a [19067]rowspan attribute, then
[19068]parse that attribute's value, and let rowspan be the result.
If parsing that value failed or if the attribute is absent, then
let rowspan be 1, instead.
If rowspan is greater than 65534, let it be 65534 instead.
10. If rowspan is zero and the [19069]table element's [19070]node
document is not set to [19071]quirks mode, then let cell grows
downward be true, and set rowspan to 1. Otherwise, let cell grows
downward be false.
11. If x[width] < x[current]+colspan, then let x[width] be
x[current]+colspan.
12. If y[height] < y[current]+rowspan, then let y[height] be
y[current]+rowspan.
13. Let the slots with coordinates (x, y) such that
x[current] ≤ x < x[current]+colspan and
y[current] ≤ y < y[current]+rowspan be covered by a new [19072]cell
c, anchored at (x[current], y[current]), which has width colspan
and height rowspan, corresponding to the current cell element.
If the current cell element is a [19073]th element, let this new
cell c be a header cell; otherwise, let it be a data cell.
To establish which header cells apply to the current cell element,
use the [19074]algorithm for assigning header cells described in
the next section.
If any of the slots involved already had a [19075]cell covering
them, then this is a [19076]table model error. Those slots now have
two cells overlapping.
14. If cell grows downward is true, then add the tuple {c, x[current],
colspan} to the list of downward-growing cells.
15. Increase x[current] by colspan.
16. If current cell is the last [19077]td or [19078]th element child in
the [19079]tr element being processed, then increase y[current] by
1, abort this set of steps, and return to the algorithm above.
17. Let current cell be the next [19080]td or [19081]th element child
in the [19082]tr element being processed.
18. Return to the step labeled cells.
When the algorithms above require the user agent to run the algorithm
for growing downward-growing cells, the user agent must, for each
{cell, cell[x], width} tuple in the list of downward-growing cells, if
any, extend the [19083]cell cell so that it also covers the slots with
coordinates (x, y[current]), where cell[x] ≤ x < cell[x]+width.
4.9.12.2 Forming relationships between data cells and header cells
Each cell can be assigned zero or more header cells. The algorithm for
assigning header cells to a cell principal cell is as follows.
1. Let header list be an empty list of cells.
2. Let (principal[x], principal[y]) be the coordinate of the slot to
which the principal cell is anchored.
3.
If the principal cell has a [19084]headers attribute specified
1. Take the value of the principal cell's [19085]headers
attribute and [19086]split it on ASCII whitespace,
letting id list be the list of tokens obtained.
2. For each token in the id list, if the first element in
the [19087]Document with an [19088]ID equal to the token
is a cell in the same [19089]table, and that cell is not
the principal cell, then add that cell to header list.
If principal cell does not have a [19090]headers attribute
specified
1. Let principal[width] be the width of the principal cell.
2. Let principal[height] be the height of the principal
cell.
3. For each value of y from principal[y] to
principal[y]+principal[height]-1, run the [19091]internal
algorithm for scanning and assigning header cells, with
the principal cell, the header list, the initial
coordinate (principal[x], y), and the increments Δx=−1
and Δy=0.
4. For each value of x from principal[x] to
principal[x]+principal[width]-1, run the [19092]internal
algorithm for scanning and assigning header cells, with
the principal cell, the header list, the initial
coordinate (x, principal[y]), and the increments Δx=0 and
Δy=−1.
5. If the principal cell is anchored in a [19093]row group,
then add all header cells that are [19094]row group
headers and are anchored in the same row group with an
x-coordinate less than or equal to
principal[x]+principal[width]-1 and a y-coordinate less
than or equal to principal[y]+principal[height]-1 to
header list.
6. If the principal cell is anchored in a [19095]column
group, then add all header cells that are [19096]column
group headers and are anchored in the same column group
with an x-coordinate less than or equal to
principal[x]+principal[width]-1 and a y-coordinate less
than or equal to principal[y]+principal[height]-1 to
header list.
4. Remove all the [19097]empty cells from the header list.
5. Remove any duplicates from the header list.
6. Remove principal cell from the header list if it is there.
7. Assign the headers in the header list to the principal cell.
The internal algorithm for scanning and assigning header cells, given a
principal cell, a header list, an initial coordinate (initial[x],
initial[y]), and Δx and Δy increments, is as follows:
1. Let x equal initial[x].
2. Let y equal initial[y].
3. Let opaque headers be an empty list of cells.
4.
If principal cell is a header cell
Let in header block be true, and let headers from current
header block be a list of cells containing just the
principal cell.
Otherwise
Let in header block be false and let headers from current
header block be an empty list of cells.
5. Loop: Increment x by Δx; increment y by Δy.
For each invocation of this algorithm, one of Δx and Δy will be −1,
and the other will be 0.
6. If either x or y are less than 0, then abort this internal
algorithm.
7. If there is no cell covering slot (x, y), or if there is more than
one cell covering slot (x, y), return to the substep labeled loop.
8. Let current cell be the cell covering slot (x, y).
9.
If current cell is a header cell
1. Set in header block to true.
2. Add current cell to headers from current header block.
3. Let blocked be false.
4.
If Δx is 0
If there are any cells in the opaque headers
list anchored with the same x-coordinate as
the current cell, and with the same width as
current cell, then let blocked be true.
If the current cell is not a [19098]column
header, then let blocked be true.
If Δy is 0
If there are any cells in the opaque headers
list anchored with the same y-coordinate as
the current cell, and with the same height as
current cell, then let blocked be true.
If the current cell is not a [19099]row
header, then let blocked be true.
5. If blocked is false, then add the current cell to the
header list.
If current cell is a data cell and in header block is true
Set in header block to false. Add all the cells in headers
from current header block to the opaque headers list, and
empty the headers from current header block list.
10. Return to the step labeled loop.
A header cell anchored at the slot with coordinate (x, y) with width
width and height height is said to be a column header if any of the
following are true:
* the cell's [19100]scope attribute is in the [19101]column state; or
* the cell's [19102]scope attribute is in the [19103]auto state, and
there are no data cells in any of the cells covering slots with
y-coordinates y .. y+height-1.
A header cell anchored at the slot with coordinate (x, y) with width
width and height height is said to be a row header if any of the
following are true:
* the cell's [19104]scope attribute is in the [19105]row state; or
* the cell's [19106]scope attribute is in the [19107]auto state, the
cell is not a [19108]column header, and there are no data cells in
any of the cells covering slots with x-coordinates x .. x+width-1.
A header cell is said to be a column group header if its [19109]scope
attribute is in the [19110]column group state.
A header cell is said to be a row group header if its [19111]scope
attribute is in the [19112]row group state.
A cell is said to be an empty cell if it contains no elements and its
[19113]child text content, if any, consists only of [19114]ASCII
whitespace.
4.9.13 Examples
This section is non-normative.
The following shows how one might mark up the bottom part of table 45
of the Smithsonian physical tables, Volume 71:
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
Per cent elong. 50.8 mm or 2 in.
Per cent reduct. area.
kg/mm2
lb/in2
Hard
0.45 ultimate
56.2
80,000
15
20
Medium
0.45 ultimate
49.2
70,000
18
25
Soft
0.45 ultimate
42.2
60,000
22
30
This table could look like this:
CAPTION: 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 Per cent elong. 50.8 mm
or 2 in. Per cent reduct. area.
kg/mm^2 lb/in^2
Hard 0.45 ultimate 56.2 80,000 15 20
Medium 0.45 ultimate 49.2 70,000 18 25
Soft 0.45 ultimate 42.2 60,000 22 30
__________________________________________________________________
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:
The following shows how one might mark up the operating expenses table
from lower on the same page of that document:
2008
2007
2006
Research and development
$ 1,109
$ 782
$ 712
Percentage of net sales
3.4%
3.3%
3.7%
Selling, general, and administrative
$ 3,761
$ 2,963
$ 2,433
Percentage of net sales
11.6%
12.3%
12.6%
This table could look like this:
2008 2007 2006
Research and development $ 1,109 $ 782 $ 712
Percentage of net sales 3.4% 3.3% 3.7%
Selling, general, and administrative $ 3,761 $ 2,963 $ 2,433
Percentage of net sales 11.6% 12.3% 12.6%
4.10 Forms
(BUTTON) ✔MDN
[19115]Element#Forms
Support in all current engines.
Firefox4+Safari4+Chrome61+
__________________________________________________________________
A form is a component of a web page that has form controls, such as
text, buttons, checkboxes, range, or color picker controls. 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: writing the user interface, implementing the server-side
processing, and configuring the user interface to communicate with the
server.
4.10.1.1 Writing a form's user interface
This section is non-normative.
For the purposes of this brief introduction, we will create a pizza
ordering form.
Any form starts with a [19116]form element, inside which are placed the
controls. Most controls are represented by the [19117]input element,
which by default provides a text control. To label a control, the
[19118]label element is used; the label text and the control itself go
inside the [19119]label element. Each part of a form is considered a
[19120]paragraph, and is typically separated from other parts using
[19121]p elements. Putting this together, here is how one might ask for
the customer's name:
To let the user select the size of the pizza, we can use a set of radio
buttons. Radio buttons also use the [19122]input element, this time
with a [19123]type attribute with the value [19124]radio. To make the
radio buttons work as a group, they are given a common name using the
[19125]name attribute. To group a batch of controls together, such as,
in this case, the radio buttons, one can use the [19126]fieldset
element. The title of such a group of controls is given by the first
element in the [19127]fieldset, which has to be a [19128]legend
element.
Changes from the previous step are highlighted.
To pick toppings, we can use checkboxes. These use the [19129]input
element with a [19130]type attribute with the value [19131]checkbox:
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
([19132]input elements with their [19133]type attribute set to
[19134]tel) and email addresses ([19135]input elements with their
[19136]type attribute set to [19137]email):
We can use an [19138]input element with its [19139]type attribute set
to [19140]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 [19141]min,
[19142]max, and [19143]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:
The [19144]textarea element can be used to provide a multiline text
control. In this instance, we are going to use it to provide a space
for the customer to give delivery instructions:
Finally, to make the form submittable we use the [19145]button element:
4.10.1.2 Implementing the server-side processing for a form
This section is non-normative.
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
[19146]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 email 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
4.10.1.3 Configuring a form to communicate with a server
This section is non-normative.
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 [19147]method attribute is specified on the [19148]form
element. This doesn't specify how the form data is encoded, though; to
specify that, you use the [19149]enctype attribute. You also have to
specify the [19150]URL of the service that will handle the submitted
data, using the [19151]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
([19152]name) also specifies the submission name. Radio buttons can be
distinguished from each other in the submission by giving them
different values, using the [19153]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 [19154]value attribute.
Given the settings in the previous section, this all becomes:
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
[19155]in the syntax section.
For example, if the customer entered "Denise Lawrence" as their name,
"555-321-8642" as their telephone number, did not specify an email
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 control blank, the user agent would submit
the following to the online web service:
custname=Denise+Lawrence&custtel=555-321-8642&custemail=&size=medium&topping=che
ese&topping=mushroom&delivery=19%3A00&comments=
4.10.1.4 Client-side form validation
(BUTTON) ✔MDN
[19156]Form_validation
Support in all current engines.
Firefox4+Safari5+Chrome4+
__________________________________________________________________
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 [19157]required attribute, which can be
specified on [19158]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:
It is also possible to limit the length of the input, using the
[19159]maxlength attribute. By adding this to the [19160]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:
When a form is submitted, [19161]invalid events are fired at each form
control that is invalid. 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.
4.10.1.5 Enabling client-side automatic filling of form controls
This section is non-normative.
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, the [19162]autocomplete attribute can
be used to describe the field's purpose. 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:
4.10.1.6 Improving the user experience on mobile devices
This section is non-normative.
Some devices, in particular those with virtual keyboards 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 capitalizes each word.
Using the [19163]inputmode attribute we can select appropriate input
modalities:
4.10.1.7 The difference between the field type, the autofill field name,
and the input modality
This section is non-normative.
The [19164]type, [19165]autocomplete, and [19166]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 [19167]type attribute on [19168]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 [19169]input element, a [19170]textarea element, a
[19171]select element, etc.
The [19172]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 [19173]. However, which [19174]autocomplete value to use depends on
which phone number the page is asking for, whether they expect a
telephone number in the international 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:
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 [19175]tel-national
rather than [19176]tel):
Please enter complete UK phone numbers, as in "(01632) 960 123".
Now, consider a person's preferred languages. The right
[19177]autocomplete value is [19178]language. However, there could be a
number of different form controls used for the purpose: a text control
([19179]), a drop-down list ([19180]
Finally, consider names. If a page just wants one name from the user,
then the relevant control is [19182]. If the page is
asking for the user's full name, then the relevant [19183]autocomplete
value is [19184]name.
In this example, the "[19185]section-*" keywords in the
[19186]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.
Separate from the choices regarding [19187]type and
[19188]autocomplete, the [19189]inputmode attribute decides what kind
of input modality (e.g., virtual keyboard) to use, when the control is
a text control.
Consider credit card numbers. The appropriate input type is not
[19190], [19191]as explained below; it is instead
[19192]. To encourage the user agent to use a numeric
input modality anyway (e.g., a virtual keyboard displaying only
digits), the page would use
4.10.1.8 Date, time, and number formats
This section is non-normative.
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
"2003年02月01日" — 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 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". While some
users might see this format, others might see it as "01.02.2003" or
"February 1, 2003".
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.
See also the [19193]implementation notes regarding localization of form
controls.
4.10.2 Categories
Mostly for historical reasons, elements in this section fall into
several overlapping (but subtly different) categories in addition to
the usual ones like [19194]flow content, [19195]phrasing content, and
[19196]interactive content.
A number of the elements are form-associated elements, which means they
can have a [19197]form owner.
* [19198]button
* [19199]fieldset
* [19200]input
* [19201]object
* [19202]output
* [19203]select
* [19204]textarea
* [19205]img
* [19206]form-associated custom elements
The [19207]form-associated elements fall into several subcategories:
Listed elements
Denotes elements that are listed in the [19208]form.elements and
[19209]fieldset.elements APIs. These elements also have a
[19210]form content attribute, and a matching [19211]form IDL
attribute, that allow authors to specify an explicit [19212]form
owner.
Some [19229]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 [19230]form element
is [19231]reset.
Autocapitalize-and-autocorrect-inheriting elements
Denotes elements that inherit the [19237]autocapitalize and
[19238]autocorrect attributes from their [19239]form owner.
Some elements, not all of them [19246]form-associated, are categorized
as labelable elements. These are elements that can be associated with a
[19247]label element.
* [19248]button
* [19249]input (if the [19250]type attribute is not in the
[19251]Hidden state)
* [19252]meter
* [19253]output
* [19254]progress
* [19255]select
* [19256]textarea
* [19257]form-associated custom elements
4.10.3 The form element
(BUTTON) ✔MDN
[19258]Element/form
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
[19263]Contexts in which this element can be used:
Where [19264]flow content is expected.
[19265]Content model:
[19266]Flow content, but with no [19267]form element
descendants.
[19268]Tag omission in text/html:
Neither tag is omissible.
[19269]Content attributes:
[19270]Global attributes
[19271]accept-charset — Character encodings to use for
[19272]form submission
[19273]action — [19274]URL to use for [19275]form submission
[19276]autocomplete — Default setting for autofill feature for
controls in the form
[19277]enctype — [19278]Entry list encoding type to use for
[19279]form submission
[19280]method — Variant to use for [19281]form submission
[19282]name — Name of form to use in the [19283]document.forms
API
[19284]novalidate — Bypass form control validation for
[19285]form submission
[19286]target — [19287]Navigable for [19288]form submission
[19289]rel
The [19336]form element [19337]represents a [19338]hyperlink that can
be manipulated through a collection of [19339]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
[19340]ASCII case-insensitive match for "UTF-8". [19341][ENCODING]
The name attribute represents the [19342]form's name within the
[19343]forms collection. The value must not be the empty string, and
the value must be unique amongst the [19344]form elements in the
[19345]forms collection that it is in, if any.
The autocomplete attribute is an [19346]enumerated attribute with the
following keywords and states:
Keyword State Brief description
on on Form controls will have their [19347]autofill field name set to
"[19348]on" by default.
off off Form controls will have their [19349]autofill field name set to
"[19350]off" by default.
The attribute's [19351]missing value default and [19352]invalid value
default are both the [19353]on state.
The [19354]action, [19355]enctype, [19356]method, [19357]novalidate,
and [19358]target attributes are [19359]attributes for form submission.
The rel attribute on [19360]form elements controls what kinds of links
the elements create. The attribute's value must be a [19361]unordered
set of unique space-separated tokens. The [19362]allowed keywords and
their meanings are defined in an earlier section.
[19363]rel's [19364]supported tokens are the keywords defined in
[19365]HTML link types which are allowed on [19366]form elements,
impact the processing model, and are supported by the user agent. The
possible [19367]supported tokens are [19368]noreferrer,
[19369]noopener, and [19370]opener. [19371]rel's [19372]supported
tokens must only include the tokens from this list that the user agent
implements the processing model for.
Firefox Android?Safari iOS1+Chrome Android?WebView
Android?Samsung Internet?Opera Android10.1+
Returns an [19375]HTMLFormControlsCollection of the form
controls in the form (excluding image buttons for historical
reasons).
Firefox Android?Safari iOS1+Chrome Android?WebView
Android?Samsung Internet?Opera Android12.1+
Returns the number of form controls in the form (excluding image
buttons for 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
[19378]RadioNodeList of the form controls) in the form with the
given [19379]ID or [19380]name (excluding image buttons for
historical reasons); or, if there are none, returns the
[19381]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
[19382]ID or [19383]name changes, for as long as the element
remains in the [19384]tree.
If there are multiple matching items, then a
[19385]RadioNodeList object containing all those elements is
returned.
Firefox Android?Safari iOS1+Chrome Android?WebView
Android?Samsung Internet?Opera Android12.1+
Submits the form, bypassing [19388]interactive constraint
validation and without firing a [19389]submit event.
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
Requests to submit the form. Unlike [19392]submit(), this method
includes [19393]interactive constraint validation and firing a
[19394]submit event, either of which can cancel submission.
The submitter argument can be used to point to a specific
[19395]submit button, whose [19396]formaction,
[19397]formenctype, [19398]formmethod, [19399]formnovalidate,
and [19400]formtarget attributes can impact submission.
Additionally, the submitter will be included when
[19401]constructing the entry list for submission; normally,
buttons are excluded.
The acceptCharset IDL attribute must [19411]reflect the
[19412]accept-charset content attribute.
The relList IDL attribute must [19413]reflect the [19414]rel content
attribute.
__________________________________________________________________
The elements IDL attribute must return an
[19415]HTMLFormControlsCollection rooted at the [19416]form element's
[19417]root, whose filter matches [19418]listed elements whose
[19419]form owner is the [19420]form element, with the exception of
[19421]input elements whose [19422]type attribute is in the
[19423]Image Button state, which must, for historical reasons, be
excluded from this particular collection.
The length IDL attribute must return the number of nodes
[19424]represented by the [19425]elements collection.
The [19426]supported property indices at any instant are the indices
supported by the object returned by the [19427]elements attribute at
that instant.
To [19428]determine the value of an indexed property for a [19429]form
element, the user agent must return the value returned by the
[19430]item method on the [19431]elements collection, when invoked with
the given index as its argument.
__________________________________________________________________
Each [19432]form element has a mapping of names to elements called the
past names map. It is used to persist names of controls even when they
change names.
The [19433]supported property names consist of the names obtained from
the following algorithm, in the order obtained from this algorithm:
1. Let sourced names be an initially empty ordered list of tuples
consisting of a string, an element, a source, where the source is
either id, name, or past, and, if the source is past, an age.
2. For each [19434]listed element candidate whose [19435]form owner is
the [19436]form element, with the exception of any [19437]input
elements whose [19438]type attribute is in the [19439]Image Button
state:
1. If candidate has an [19440]id attribute, add an entry to
sourced names with that [19441]id attribute's value as the
string, candidate as the element, and id as the source.
2. If candidate has a [19442]name attribute, add an entry to
sourced names with that [19443]name attribute's value as the
string, candidate as the element, and name as the source.
3. For each [19444]img element candidate whose [19445]form owner is
the [19446]form element:
1. If candidate has an [19447]id attribute, add an entry to
sourced names with that [19448]id attribute's value as the
string, candidate as the element, and id as the source.
2. If candidate has a [19449]name attribute, add an entry to
sourced names with that [19450]name attribute's value as the
string, candidate as the element, and name as the source.
4. For each entry past entry in the [19451]past names map, add an
entry to sourced names with the past entry's name as the string,
past entry's element as the element, past as the source, and the
length of time past entry has been in the [19452]past names map as
the age.
5. Sort sourced names by [19453]tree order of the element entry of
each tuple, sorting entries with the same element by putting
entries whose source is id first, then entries whose source is
name, and finally entries whose source is past, and sorting entries
with the same element and source by their age, oldest first.
6. Remove any entries in sourced names that have the empty string as
their name.
7. Remove any entries in sourced names that have the same name as an
earlier entry in the map.
8. Return the list of names from sourced names, maintaining their
relative order.
To [19454]determine the value of a named property name for a
[19455]form element, the user agent must run the following steps:
1. Let candidates be a [19456]live [19457]RadioNodeList object
containing all the [19458]listed elements, whose [19459]form owner
is the [19460]form element, that have either an [19461]id attribute
or a [19462]name attribute equal to name, with the exception of
[19463]input elements whose [19464]type attribute is in the
[19465]Image Button state, in [19466]tree order.
2. If candidates is empty, let candidates be a [19467]live
[19468]RadioNodeList object containing all the [19469]img elements,
whose [19470]form owner is the [19471]form element, that have
either an [19472]id attribute or a [19473]name attribute equal to
name, in [19474]tree order.
3. If candidates is empty, name is the name of one of the entries in
the [19475]form element's [19476]past names map: return the object
associated with name in that map.
4. If candidates contains more than one node, return candidates.
5. Otherwise, candidates contains exactly one node. Add a mapping from
name to the node in candidates in the [19477]form element's
[19478]past names map, replacing the previous entry with the same
name, if any.
6. Return the node in candidates.
If an element listed in a [19479]form element's [19480]past names map
changes [19481]form owner, then its entries must be removed from that
map.
__________________________________________________________________
The submit() method steps are to [19482]submit [19483]this from
[19484]this, with [19485]submitted from submit() method set to true.
The requestSubmit(submitter) method, when invoked, must run the
following steps:
1. If submitter is not null, then:
1. If submitter is not a [19486]submit button, then throw a
[19487]TypeError.
2. If submitter's [19488]form owner is not this [19489]form
element, then throw a [19490]"NotFoundError"
[19491]DOMException.
2. Otherwise, set submitter to this [19492]form element.
3. [19493]Submit this [19494]form element, from submitter.
The reset() method, when invoked, must run the following steps:
1. If the [19495]form element is marked as [19496]locked for reset,
then return.
2. Mark the [19497]form element as locked for reset.
3. [19498]Reset the [19499]form element.
4. Unmark the [19500]form element as [19501]locked for reset.
If the checkValidity() method is invoked, the user agent must
[19502]statically validate the constraints of the [19503]form element,
and return true if the constraint validation return a positive result,
and false if it returned a negative result.
If the reportValidity() method is invoked, the user agent must
[19504]interactively validate the constraints of the [19505]form
element, and return true if the constraint validation return a positive
result, and false if it returned a negative result.
This example shows two search forms:
4.10.4 The label element
(BUTTON) ✔MDN
[19506]Element/label
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
[19513]Contexts in which this element can be used:
Where [19514]phrasing content is expected.
[19515]Content model:
[19516]Phrasing content, but with no descendant [19517]labelable
elements unless it is the element's [19518]labeled control, and
no descendant [19519]label elements.
[19520]Tag omission in text/html:
Neither tag is omissible.
[19521]Content attributes:
[19522]Global attributes
[19523]for — Associate the label with form control
The [19536]label element [19537]represents a caption in a user
interface. The caption can be associated with a specific form control,
known as the [19538]label element's labeled control, either using the
[19539]for attribute, or by putting the form control inside the
[19540]label element itself.
Except where otherwise specified by the following rules, a [19541]label
element has no [19542]labeled control.
(BUTTON) ✔MDN
[19543]Attributes/for
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
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 [19544]ID of a [19545]labelable
element in the same [19546]tree as the [19547]label element. If the
attribute is specified and there is an element in the [19548]tree whose
[19549]ID is equal to the value of the [19550]for attribute, and the
first such element in [19551]tree order is a [19552]labelable element,
then that element is the [19553]label element's [19554]labeled control.
If the [19555]for attribute is not specified, but the [19556]label
element has a [19557]labelable element descendant, then the first such
descendant in [19558]tree order is the [19559]label element's
[19560]labeled control.
The [19561]label element's exact default presentation and behavior, in
particular what its [19562]activation behavior might be, if anything,
should match the platform's label behavior. The [19563]activation
behavior of a [19564]label element for events targeted at
[19565]interactive content descendants of a [19566]label element, and
any descendants of those [19567]interactive content descendants, must
be to do nothing.
[19568]Form-associated custom elements are [19569]labelable elements,
so for user agents where the [19570]label element's [19571]activation
behavior impacts the [19572]labeled control, both built-in and custom
elements will be impacted.
For example, on platforms where clicking a label activates the form
control, clicking the [19573]label in the following snippet could
trigger the user agent to [19574]fire a click event at the [19575]input
element, as if the element itself had been triggered by the user:
Similarly, assuming my-checkbox was declared as a
[19576]form-associated custom element (like in [19577]this example),
then the code
would have the same behavior, [19578]firing a click event at the
my-checkbox element.
On other platforms, the behavior in both cases might be just to focus
the control, or to do nothing.
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.
Firefox Android?Safari iOS?Chrome Android?WebView
Android3+Samsung Internet?Opera Android12.1+
Returns the form control that is associated with this element.
Firefox Android?Safari iOS1+Chrome Android?WebView
Android?Samsung Internet?Opera Android12.1+
Returns the [19583]form owner of the form control that is
associated with this element.
Returns null if there isn't one.
(BUTTON) ✔MDN
[19584]HTMLLabelElement/htmlFor
Support in all current engines.
Firefox1+Safari3+Chrome1+
__________________________________________________________________
The htmlFor IDL attribute must [19585]reflect the [19586]for content
attribute.
The control IDL attribute must return the [19587]label element's
[19588]labeled control, if any, or null if there isn't one.
The form IDL attribute must run the following steps:
1. If the [19589]label element has no [19590]labeled control, then
return null.
2. If the [19591]label element's [19592]labeled control is not a
[19593]form-associated element, then return null.
3. Return the [19594]label element's [19595]labeled control's
[19596]form owner (which can still be null).
The [19597]form IDL attribute on the [19598]label element is different
from the [19599]form IDL attribute on [19600]listed
[19601]form-associated elements, and the [19602]label element does not
have a [19603]form content attribute.
__________________________________________________________________
Firefox Android?Safari iOS?Chrome Android?WebView
Android3+Samsung Internet?Opera Android12.1+
Returns a [19612]NodeList of all the [19613]label elements that
the form control is associated with.
[19614]Labelable elements and all [19615]input elements have a
[19616]live [19617]NodeList object associated with them that represents
the list of [19618]label elements, in [19619]tree order, whose
[19620]labeled control is the element in question. The labels IDL
attribute of [19621]labelable elements that are not
[19622]form-associated custom elements, and the [19623]labels IDL
attribute of [19624]input elements, on getting, must return that
[19625]NodeList object, and that same value must always be returned,
unless this element is an [19626]input element whose [19627]type
attribute is in the [19628]Hidden state, in which case it must instead
return null.
(BUTTON) ✔MDN
[19629]ElementInternals/labels
Support in all current engines.
Firefox98+Safari16.4+Chrome77+
__________________________________________________________________
[19630]Form-associated custom elements don't have a [19631]labels IDL
attribute. Instead, their [19632]ElementInternals object has a labels
IDL attribute. On getting, it must throw a [19633]"NotSupportedError"
[19634]DOMException if the [19635]target element is not a
[19636]form-associated custom element. Otherwise, it must return that
[19637]NodeList object, and that same value must always be returned.
This (non-conforming) example shows what happens to the [19638]NodeList
and what [19639]labels returns when an [19640]input element has its
[19641]type attribute changed.
4.10.5 The input element
(BUTTON) ✔MDN
[19644]Element/input
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
[19647]Categories:
[19648]Flow content.
[19649]Phrasing content.
If the [19650]type attribute is not in the [19651]Hidden state:
[19652]Interactive content.
If the [19653]type attribute is not in the [19654]Hidden state:
[19655]Listed, [19656]labelable, [19657]submittable,
[19658]resettable, and [19659]autocapitalize-and-autocorrect
inheriting [19660]form-associated element.
If the [19661]type attribute is in the [19662]Hidden state:
[19663]Listed, [19664]submittable, [19665]resettable, and
[19666]autocapitalize-and-autocorrect inheriting
[19667]form-associated element.
If the [19668]type attribute is not in the [19669]Hidden state:
[19670]Palpable content.
[19671]Contexts in which this element can be used:
Where [19672]phrasing content is expected.
[19673]Content model:
[19674]Nothing.
[19675]Tag omission in text/html:
No [19676]end tag.
[19677]Content attributes:
[19678]Global attributes
[19679]accept — Hint for expected file type in [19680]file
upload controls
[19681]alpha — Allow the color's alpha component to be set
[19682]alt — Replacement text for use when images are not
available
[19683]autocomplete — Hint for form autofill feature
[19684]checked — Whether the control is checked
[19685]colorspace — The color space of the serialized color
[19686]dirname — Name of form control to use for sending the
element's [19687]directionality in [19688]form submission
[19689]disabled — Whether the form control is disabled
[19690]form — Associates the element with a [19691]form element
[19692]formaction — [19693]URL to use for [19694]form submission
[19695]formenctype — [19696]Entry list encoding type to use for
[19697]form submission
[19698]formmethod — Variant to use for [19699]form submission
[19700]formnovalidate — Bypass form control validation for
[19701]form submission
[19702]formtarget — [19703]Navigable for [19704]form submission
[19705]height — Vertical dimension
[19706]list — List of autocomplete options
[19707]max — Maximum value
[19708]maxlength — Maximum [19709]length of value
[19710]min — Minimum value
[19711]minlength — Minimum [19712]length of value
[19713]multiple — Whether to allow multiple values
[19714]name — Name of the element to use for [19715]form
submission and in the [19716]form.elements API
[19717]pattern — Pattern to be matched by the form control's
value
[19718]placeholder — User-visible label to be placed within the
form control
[19719]popovertarget — Targets a popover element to toggle,
show, or hide
[19720]popovertargetaction — Indicates whether a targeted
popover element is to be toggled, shown, or hidden
[19721]readonly — Whether to allow the value to be edited by the
user
[19722]required — Whether the control is required for
[19723]form submission
[19724]size — Size of the control
[19725]src — Address of the resource
[19726]step — Granularity to be matched by the form control's
value
[19727]type — Type of form control
[19728]value — Value of the form control
[19729]width — Horizontal dimension
Also, the [19730]title attribute [19731]has special semantics on
this element: Description of pattern (when used with
[19732]pattern attribute)
[19733]Accessibility considerations:
[19734]type attribute in the [19735]Hidden state: [19736]for
authors; [19737]for implementers.
[19738]type attribute in the [19739]Text state: [19740]for
authors; [19741]for implementers.
[19742]type attribute in the [19743]Search state: [19744]for
authors; [19745]for implementers.
[19746]type attribute in the [19747]Telephone state: [19748]for
authors; [19749]for implementers.
[19750]type attribute in the [19751]URL state: [19752]for
authors; [19753]for implementers.
[19754]type attribute in the [19755]Email state: [19756]for
authors; [19757]for implementers.
[19758]type attribute in the [19759]Password state: [19760]for
authors; [19761]for implementers.
[19762]type attribute in the [19763]Date state: [19764]for
authors; [19765]for implementers.
[19766]type attribute in the [19767]Month state: [19768]for
authors; [19769]for implementers.
[19770]type attribute in the [19771]Week state: [19772]for
authors; [19773]for implementers.
[19774]type attribute in the [19775]Time state: [19776]for
authors; [19777]for implementers.
[19778]type attribute in the [19779]Local Date and Time state:
[19780]for authors; [19781]for implementers.
[19782]type attribute in the [19783]Number state: [19784]for
authors; [19785]for implementers.
[19786]type attribute in the [19787]Range state: [19788]for
authors; [19789]for implementers.
[19790]type attribute in the [19791]Color state: [19792]for
authors; [19793]for implementers.
[19794]type attribute in the [19795]Checkbox state: [19796]for
authors; [19797]for implementers.
[19798]type attribute in the [19799]Radio Button state:
[19800]for authors; [19801]for implementers.
[19802]type attribute in the [19803]File Upload state:
[19804]for authors; [19805]for implementers.
[19806]type attribute in the [19807]Submit Button state:
[19808]for authors; [19809]for implementers.
[19810]type attribute in the [19811]Image Button state:
[19812]for authors; [19813]for implementers.
[19814]type attribute in the [19815]Reset Button state:
[19816]for authors; [19817]for implementers.
[19818]type attribute in the [19819]Button state: [19820]for
authors; [19821]for implementers.
// [19919]also has obsolete members
};
[19920]HTMLInputElement includes [19921]PopoverInvokerElement;
The [19922]input element [19923]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 [19924]enumerated attribute with the following
keywords and states:
Keyword State Data type Control type
hidden [19925]Hidden An arbitrary string n/a
text [19926]Text Text with no line breaks A text control
search [19927]Search Text with no line breaks Search control
tel [19928]Telephone Text with no line breaks A text control
url [19929]URL An absolute URL A text control
email [19930]Email An email address or list of email addresses A text
control
password [19931]Password Text with no line breaks (sensitive
information) A text control that obscures data entry
date [19932]Date A date (year, month, day) with no time zone A date
control
month [19933]Month A date consisting of a year and a month with no time
zone A month control
week [19934]Week A date consisting of a week-year number and a week
number with no time zone A week control
time [19935]Time A time (hour, minute, seconds, fractional seconds)
with no time zone A time control
datetime-local [19936]Local Date and Time A date and time (year, month,
day, hour, minute, second, fraction of a second) with no time zone A
date and time control
number [19937]Number A numerical value A text control or spinner
control
range [19938]Range A numerical value, with the extra semantic that the
exact value is not important A slider control or similar
color [19939]Color An sRGB color with 8-bit red, green, and blue
components A color picker
checkbox [19940]Checkbox A set of zero or more values from a predefined
list A checkbox
radio [19941]Radio Button An enumerated value A radio button
file [19942]File Upload Zero or more files each with a [19943]MIME type
and optionally a filename A label and a button
submit [19944]Submit Button An enumerated value, with the extra
semantic that it must be the last value selected and initiates form
submission A button
image [19945]Image Button 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 Either a clickable image, or a
button
reset [19946]Reset Button n/a A button
button [19947]Button n/a A button
The attribute's [19948]missing value default and [19949]invalid value
default are both the [19950]Text state.
Which of the [19951]accept, [19952]alpha, [19953]alt,
[19954]autocomplete, [19955]checked, [19956]colorspace, [19957]dirname,
[19958]formaction, [19959]formenctype, [19960]formmethod,
[19961]formnovalidate, [19962]formtarget, [19963]height, [19964]list,
[19965]max, [19966]maxlength, [19967]min, [19968]minlength,
[19969]multiple, [19970]pattern, [19971]placeholder, [19972]readonly,
[19973]required, [19974]size, [19975]src, [19976]step, and [19977]width
content attributes, the [19978]checked, [19979]files,
[19980]valueAsDate, [19981]valueAsNumber, and [19982]list IDL
attributes, the [19983]select() method, the [19984]selectionStart,
[19985]selectionEnd, and [19986]selectionDirection, IDL attributes, the
[19987]setRangeText() and [19988]setSelectionRange() methods, the
[19989]stepUp() and [19990]stepDown() methods, and the [19991]input and
[19992]change events apply to an [19993]input element depends on the
state of its [19994]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 whether they apply or not, as defined in
their various sections (q.v. for [19995]content attributes, for
[19996]APIs, for [19997]events).
The following table is non-normative and summarizes which of those
content attributes, IDL attributes, methods, and events [19998]apply to
each state:
† If the control has no selectable text, the [20081]select() method
results in a no-op, with no [20082]"InvalidStateError"
[20083]DOMException.
Some states of the [20084]type attribute define a value sanitization
algorithm.
Each [20085]input element has a [20086]value, which is exposed by the
[20087]value IDL attribute. Some states define an algorithm to convert
a string to a number, an algorithm to convert a number to a string, an
algorithm to convert a string to a Date object, and an algorithm to
convert a Date object to a string, which are used by [20088]max,
[20089]min, [20090]step, [20091]valueAsDate, [20092]valueAsNumber, and
[20093]stepUp().
An [20094]input element's [20095]dirty value flag must be set to true
whenever the user interacts with the control in a way that changes the
[20096]value. (It is also set to true when the value is
programmatically changed, as described in the definition of the
[20097]value IDL attribute.)
The value content attribute gives the default [20098]value of the
[20099]input element. When the [20100]value content attribute is added,
set, or removed, if the control's [20101]dirty value flag is false, the
user agent must set the [20102]value of the element to the value of the
[20103]value content attribute, if there is one, or the empty string
otherwise, and then run the current [20104]value sanitization
algorithm, if one is defined.
Each [20105]input element has a [20106]checkedness, which is exposed by
the [20107]checked IDL attribute.
Each [20108]input element has a boolean dirty checkedness flag. When it
is true, the element is said to have a dirty checkedness. The
[20109]dirty checkedness flag must be initially set to false when the
element is created, and must be set to true whenever the user interacts
with the control in a way that changes the [20110]checkedness.
(BUTTON) ✔MDN
[20111]Element/input#checked
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
The checked content attribute is a [20112]boolean attribute that gives
the default [20113]checkedness of the [20114]input element. When the
[20115]checked content attribute is added, if the control does not have
[20116]dirty checkedness, the user agent must set the
[20117]checkedness of the element to true; when the [20118]checked
content attribute is removed, if the control does not have [20119]dirty
checkedness, the user agent must set the [20120]checkedness of the
element to false.
The [20121]reset algorithm for [20122]input elements is to set its
[20123]user validity, [20124]dirty value flag, and [20125]dirty
checkedness flag back to false, set the [20126]value of the element to
the value of the [20127]value content attribute, if there is one, or
the empty string otherwise, set the [20128]checkedness of the element
to true if the element has a [20129]checked content attribute and false
if it does not, empty the list of [20130]selected files, and then
invoke the [20131]value sanitization algorithm, if the [20132]type
attribute's current state defines one.
Each [20133]input element can be [20134]mutable. Except where otherwise
specified, an [20135]input element is always [20136]mutable. Similarly,
except where otherwise specified, the user agent should not allow the
user to modify the element's [20137]value or [20138]checkedness.
When an [20139]input element is [20140]disabled, it is not
[20141]mutable.
The [20142]readonly attribute can also in some cases (e.g. for the
[20143]Date state, but not the [20144]Checkbox state) stop an
[20145]input element from being [20146]mutable.
The [20147]input element can support a picker. A picker is a user
interface element that allows the end user to choose a value. Whether
an [20148]input element supports a picker depends on the [20149]type
attribute state and [20150]implementation-defined behavior. An
[20151]input element must support a picker when its [20152]type
attribute is in the [20153]File Upload state.
As of the time of this writing, typical browser implementations show
such picker UI for:
* [20154]input elements whose [20155]type attributes are in the
[20156]Date, [20157]Month, [20158]Week, [20159]Time, [20160]Local
Date and Time, and [20161]Color states;
* [20162]input elements in various states that have a
[20163]suggestions source element;
* [20164]input elements whose [20165]type attribute is in the
[20166]File Upload state; and
* [20167]select elements.
The [20168]cloning steps for [20169]input elements given node, copy,
and subtree are to propagate the [20170]value, [20171]dirty value flag,
[20172]checkedness, and [20173]dirty checkedness flag from node to
copy.
The [20174]activation behavior for [20175]input elements element, given
event, are these steps:
1. If element is not [20176]mutable, and element's [20177]type
attribute is neither in the [20178]Checkbox nor in the [20179]Radio
state, then return.
2. Run element's input activation behavior, if any, and do nothing
otherwise.
3. If element has a [20180]form owner and element's [20181]type
attribute is not in the [20182]Button state, then return.
4. Run the [20183]popover target attribute activation behavior given
element and event's [20184]target.
Recall that an element's [20185]activation behavior runs for both
user-initiated activations and for synthetic activations (e.g., via
el.click()). User agents might also have behaviors for a given control
— not specified here — that are triggered only by true user-initiated
activations. A common choice is to [20186]show the picker, if
applicable, for the control. In contrast, the [20187]input activation
behavior only shows pickers for the special historical cases of the
[20188]File Upload and [20189]Color states.
The [20190]legacy-pre-activation behavior for [20191]input elements are
these steps:
1. If this element's [20192]type attribute is in the [20193]Checkbox
state, then set this element's [20194]checkedness to its opposite
value (i.e. true if it is false, false if it is true) and set this
element's [20195]indeterminate IDL attribute to false.
2. If this element's [20196]type attribute is in the [20197]Radio
Button state, then get a reference to the element in this element's
[20198]radio button group that has its [20199]checkedness set to
true, if any, and then set this element's [20200]checkedness to
true.
The [20201]legacy-canceled-activation behavior for [20202]input
elements are these steps:
1. If the element's [20203]type attribute is in the [20204]Checkbox
state, then set the element's [20205]checkedness and the element's
[20206]indeterminate IDL attribute back to the values they had
before the [20207]legacy-pre-activation behavior was run.
2. If this element's [20208]type attribute is in the [20209]Radio
Button state, then if the element to which a reference was obtained
in the [20210]legacy-pre-activation behavior, if any, is still in
what is now this element's [20211]radio button group, if it still
has one, and if so, setting that element's [20212]checkedness to
true; or else, if there was no such element, or that element is no
longer in this element's [20213]radio button group, or if this
element no longer has a [20214]radio button group, setting this
element's [20215]checkedness to false.
__________________________________________________________________
When an [20216]input element is first created, the element's rendering
and behavior must be set to the rendering and behavior defined for the
[20217]type attribute's state, and the [20218]value sanitization
algorithm, if one is defined for the [20219]type attribute's state,
must be invoked.
When an [20220]input element's [20221]type attribute changes state, the
user agent must run the following steps:
1. If the previous state of the element's [20222]type attribute put
the [20223]value IDL attribute in the [20224]value mode, and the
element's [20225]value is not the empty string, and the new state
of the element's [20226]type attribute puts the [20227]value IDL
attribute in either the [20228]default mode or the
[20229]default/on mode, then set the element's [20230]value content
attribute to the element's [20231]value.
2. Otherwise, if the previous state of the element's [20232]type
attribute put the [20233]value IDL attribute in any mode other than
the [20234]value mode, and the new state of the element's
[20235]type attribute puts the [20236]value IDL attribute in the
[20237]value mode, then set the [20238]value of the element to the
value of the [20239]value content attribute, if there is one, or
the empty string otherwise, and then set the control's [20240]dirty
value flag to false.
3. Otherwise, if the previous state of the element's [20241]type
attribute put the [20242]value IDL attribute in any mode other than
the [20243]filename mode, and the new state of the element's
[20244]type attribute puts the [20245]value IDL attribute in the
[20246]filename mode, then set the [20247]value of the element to
the empty string.
4. Update the element's rendering and behavior to the new state's.
5. Signal a type change for the element. (The [20248]Radio Button
state uses this, in particular.)
6. Invoke the [20249]value sanitization algorithm, if one is defined
for the [20250]type attribute's new state.
7. Let previouslySelectable be true if [20251]setRangeText()
previously [20252]applied to the element, and false otherwise.
8. Let nowSelectable be true if [20253]setRangeText() now
[20254]applies to the element, and false otherwise.
9. If previouslySelectable is false and nowSelectable is true, set the
element's [20255]text entry cursor position to the beginning of the
text control, and [20256]set its selection direction to "none".
__________________________________________________________________
The [20257]name attribute represents the element's name. The
[20258]dirname attribute controls how the element's
[20259]directionality is submitted. The [20260]disabled attribute is
used to make the control non-interactive and to prevent its value from
being submitted. The [20261]form attribute is used to explicitly
associate the [20262]input element with its [20263]form owner. The
[20264]autocomplete attribute controls how the user agent provides
autofill behavior.
(BUTTON) ✔MDN
[20265]HTMLInputElement#indeterminate
Support in all current engines.
Firefox3.6+Safari3+Chrome1+
__________________________________________________________________
The indeterminate IDL attribute must initially be set to false. On
getting, it must return the last value it was set to. On setting, it
must be set to the new value. It has no effect except for changing the
appearance of [20267]checkbox controls.
(BUTTON) ✔MDN
[20268]HTMLInputElement/multiple
Support in all current engines.
Firefox3.6+Safari4+Chrome2+
__________________________________________________________________
The accept, alpha, alt, max, min, multiple, pattern, placeholder,
required, size, src, and step IDL attributes must [20269]reflect the
respective content attributes of the same name. The dirName IDL
attribute must [20270]reflect the [20271]dirname content attribute. The
readOnly IDL attribute must [20272]reflect the [20273]readonly content
attribute. The defaultChecked IDL attribute must [20274]reflect the
[20275]checked content attribute. The defaultValue IDL attribute must
[20276]reflect the [20277]value content attribute.
The colorSpace IDL attribute must [20278]reflect the [20279]colorspace
content attribute, [20280]limited to only known values. The type IDL
attribute must [20281]reflect the respective content attribute of the
same name, [20282]limited to only known values. The maxLength IDL
attribute must [20283]reflect the [20284]maxlength content attribute,
[20285]limited to only non-negative numbers. The minLength IDL
attribute must [20286]reflect the [20287]minlength content attribute,
[20288]limited to only non-negative numbers.
The IDL attributes width and height must return the rendered width and
height of the image, in [20289]CSS pixels, if an image is [20290]being
rendered; or else the [20291]natural width and height of the image, in
[20292]CSS pixels, if an image is [20293]available but not [20294]being
rendered; or else 0, if no image is [20295]available. When the
[20296]input element's [20297]type attribute is not in the [20298]Image
Button state, then no image is [20299]available. [20300][CSS]
On setting, they must act as if they [20301]reflected the respective
content attributes of the same name.
The [20302]willValidate, [20303]validity, and [20304]validationMessage
IDL attributes, and the [20305]checkValidity(),
[20306]reportValidity(), and [20307]setCustomValidity() methods, are
part of the [20308]constraint validation API. The [20309]labels IDL
attribute provides a list of the element's [20310]labels. The
[20311]select(), [20312]selectionStart, [20313]selectionEnd,
[20314]selectionDirection, [20315]setRangeText(), and
[20316]setSelectionRange() methods and IDL attributes expose the
element's text selection. The [20317]disabled, [20318]form, and
[20319]name IDL attributes are part of the element's forms API.
4.10.5.1 States of the [20320]type attribute
4.10.5.1.1 Hidden state (type=hidden)
(BUTTON) ✔MDN
[20321]Element/input/hidden
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
When an [20322]input element's [20323]type attribute is in the
[20324]Hidden state, the rules in this section apply.
The [20325]input element [20326]represents a value that is not intended
to be examined or manipulated by the user.
Constraint validation: If an [20327]input element's [20328]type
attribute is in the [20329]Hidden state, it is [20330]barred from
constraint validation.
If the [20331]name attribute is present and has a value that is an
[20332]ASCII case-insensitive match for "[20333]_charset_", then the
element's [20334]value attribute must be omitted.
The [20335]autocomplete and [20336]dirname content attributes
[20337]apply to this element.
The [20338]value IDL attribute [20339]applies to this element and is in
mode [20340]default.
The following content attributes must not be specified and [20341]do
not apply to the element: [20342]accept, [20343]alpha, [20344]alt,
[20345]checked, [20346]colorspace, [20347]formaction,
[20348]formenctype, [20349]formmethod, [20350]formnovalidate,
[20351]formtarget, [20352]height, [20353]list, [20354]max,
[20355]maxlength, [20356]min, [20357]minlength, [20358]multiple,
[20359]pattern, [20360]placeholder, [20361]popovertarget,
[20362]popovertargetaction, [20363]readonly, [20364]required,
[20365]size, [20366]src, [20367]step, and [20368]width.
The following IDL attributes and methods [20369]do not apply to the
element: [20370]checked, [20371]files, [20372]list,
[20373]selectionStart, [20374]selectionEnd, [20375]selectionDirection,
[20376]valueAsDate, and [20377]valueAsNumber IDL attributes;
[20378]select(), [20379]setRangeText(), [20380]setSelectionRange(),
[20381]stepDown(), and [20382]stepUp() methods.
The [20383]input and [20384]change events [20385]do not apply.
4.10.5.1.2 Text (type=text) state and Search state (type=search)
(BUTTON) ✔MDN
[20386]Element/input/search
Support in all current engines.
Firefox4+Safari5+Chrome5+
__________________________________________________________________
When an [20388]input element's [20389]type attribute is in the
[20390]Text state or the [20391]Search state, the rules in this section
apply.
The [20392]input element [20393]represents a one line plain text edit
control for the element's [20394]value.
The difference between the [20395]Text state and the [20396]Search
state is primarily stylistic: on platforms where search controls are
distinguished from regular text controls, the [20397]Search state might
result in an appearance consistent with the platform's search controls
rather than appearing like a regular text control.
If the element is [20398]mutable, its [20399]value should be editable
by the user. User agents must not allow users to insert U+000A LINE
FEED (LF) or U+000D CARRIAGE RETURN (CR) characters into the element's
[20400]value.
If the element is [20401]mutable, the user agent should allow the user
to change the writing direction of the element, setting it either to a
left-to-right writing direction or a right-to-left writing direction.
If the user does so, the user agent must then run the following steps:
1. Set the element's [20402]dir attribute to "[20403]ltr" if the user
selected a left-to-right writing direction, and "[20404]rtl" if the
user selected a right-to-left writing direction.
2. [20405]Queue an element task on the [20406]user interaction task
source given the element to [20407]fire an event named [20408]input
at the element, with the [20409]bubbles and [20410]composed
attributes initialized to true.
The [20411]value attribute, if specified, must have a value that
contains no U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR)
characters.
The [20412]value sanitization algorithm is as follows: [20413]Strip
newlines from the [20414]value.
The following common [20415]input element content attributes, IDL
attributes, and methods [20416]apply to the element:
[20417]autocomplete, [20418]dirname, [20419]list, [20420]maxlength,
[20421]minlength, [20422]pattern, [20423]placeholder, [20424]readonly,
[20425]required, and [20426]size content attributes; [20427]list,
[20428]selectionStart, [20429]selectionEnd, [20430]selectionDirection,
and [20431]value IDL attributes; [20432]select(),
[20433]setRangeText(), and [20434]setSelectionRange() methods.
The [20435]value IDL attribute is in mode [20436]value.
The [20437]input and [20438]change events [20439]apply.
The following content attributes must not be specified and [20440]do
not apply to the element: [20441]accept, [20442]alpha, [20443]alt,
[20444]checked, [20445]colorspace, [20446]formaction,
[20447]formenctype, [20448]formmethod, [20449]formnovalidate,
[20450]formtarget, [20451]height, [20452]max, [20453]min,
[20454]multiple, [20455]popovertarget, [20456]popovertargetaction,
[20457]src, [20458]step, and [20459]width.
The following IDL attributes and methods [20460]do not apply to the
element: [20461]checked, [20462]files, [20463]valueAsDate, and
[20464]valueAsNumber IDL attributes; [20465]stepDown() and
[20466]stepUp() methods.
4.10.5.1.3 Telephone state (type=tel)
(BUTTON) ✔MDN
[20467]Element/input/tel
Support in all current engines.
FirefoxYesSafari4+Chrome3+
__________________________________________________________________
When an [20468]input element's [20469]type attribute is in the
[20470]Telephone state, the rules in this section apply.
The [20471]input element [20472]represents a control for editing a
telephone number given in the element's [20473]value.
If the element is [20474]mutable, its [20475]value should be editable
by the user. User agents may change the spacing and, with care, the
punctuation of [20476]values that the user enters. User agents must not
allow users to insert U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN
(CR) characters into the element's [20477]value.
The [20478]value attribute, if specified, must have a value that
contains no U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR)
characters.
The [20479]value sanitization algorithm is as follows: [20480]Strip
newlines from the [20481]value.
Unlike the [20482]URL and [20483]Email types, the [20484]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 [20485]pattern attribute or
the [20486]setCustomValidity() method to hook into the client-side
validation mechanism.
The following common [20487]input element content attributes, IDL
attributes, and methods [20488]apply to the element:
[20489]autocomplete, [20490]dirname, [20491]list, [20492]maxlength,
[20493]minlength, [20494]pattern, [20495]placeholder, [20496]readonly,
[20497]required, and [20498]size content attributes; [20499]list,
[20500]selectionStart, [20501]selectionEnd, [20502]selectionDirection,
and [20503]value IDL attributes; [20504]select(),
[20505]setRangeText(), and [20506]setSelectionRange() methods.
The [20507]value IDL attribute is in mode [20508]value.
The [20509]input and [20510]change events [20511]apply.
The following content attributes must not be specified and [20512]do
not apply to the element: [20513]accept, [20514]alpha, [20515]alt,
[20516]checked, [20517]colorspace, [20518]formaction,
[20519]formenctype, [20520]formmethod, [20521]formnovalidate,
[20522]formtarget, [20523]height, [20524]max, [20525]min,
[20526]multiple, [20527]popovertarget, [20528]popovertargetaction,
[20529]src, [20530]step, and [20531]width.
The following IDL attributes and methods [20532]do not apply to the
element: [20533]checked, [20534]files, [20535]valueAsDate, and
[20536]valueAsNumber IDL attributes; [20537]stepDown() and
[20538]stepUp() methods.
4.10.5.1.4 URL state (type=url)
(BUTTON) ✔MDN
[20539]Element/input/url
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
When an [20540]input element's [20541]type attribute is in the
[20542]URL state, the rules in this section apply.
The [20543]input element [20544]represents a control for editing a
single [20545]absolute URL given in the element's [20546]value.
If the element is [20547]mutable, the user agent should allow the user
to change the URL represented by its [20548]value. User agents may
allow the user to set the [20549]value to a string that is not a
[20550]valid [20551]absolute URL, but may also or instead automatically
escape characters entered by the user so that the [20552]value is
always a [20553]valid [20554]absolute URL (even if that isn't the
actual value seen and edited by the user in the interface). User agents
should allow the user to set the [20555]value to the empty string. User
agents must not allow users to insert U+000A LINE FEED (LF) or U+000D
CARRIAGE RETURN (CR) characters into the [20556]value.
The [20557]value attribute, if specified and not empty, must have a
value that is a [20558]valid URL potentially surrounded by spaces that
is also an [20559]absolute URL.
The [20560]value sanitization algorithm is as follows: [20561]Strip
newlines from the [20562]value, then [20563]strip leading and trailing
ASCII whitespace from the [20564]value.
Constraint validation: While the [20565]value of the element is neither
the empty string nor a [20566]valid [20567]absolute URL, the element is
[20568]suffering from a type mismatch.
The following common [20569]input element content attributes, IDL
attributes, and methods [20570]apply to the element:
[20571]autocomplete, [20572]dirname, [20573]list, [20574]maxlength,
[20575]minlength, [20576]pattern, [20577]placeholder, [20578]readonly,
[20579]required, and [20580]size content attributes; [20581]list,
[20582]selectionStart, [20583]selectionEnd, [20584]selectionDirection,
and [20585]value IDL attributes; [20586]select(),
[20587]setRangeText(), and [20588]setSelectionRange() methods.
The [20589]value IDL attribute is in mode [20590]value.
The [20591]input and [20592]change events [20593]apply.
The following content attributes must not be specified and [20594]do
not apply to the element: [20595]accept, [20596]alpha, [20597]alt,
[20598]checked, [20599]colorspace, [20600]formaction,
[20601]formenctype, [20602]formmethod, [20603]formnovalidate,
[20604]formtarget, [20605]height, [20606]max, [20607]min,
[20608]multiple, [20609]popovertarget, [20610]popovertargetaction,
[20611]src, [20612]step, and [20613]width.
The following IDL attributes and methods [20614]do not apply to the
element: [20615]checked, [20616]files, [20617]valueAsDate, and
[20618]valueAsNumber IDL attributes; [20619]stepDown() and
[20620]stepUp() methods.
If a document contained the following markup:
...and the user had typed "spec.w", and the user agent had also found
that the user had visited https://url.spec.whatwg.org/#url-parsing and
https://streams.spec.whatwg.org/ in the recent past, then the rendering
might look like this:
A text box with an icon on the left followed by the text "spec.w" and a
cursor, with a drop down button on the right hand side; with, below, a
drop down box containing a list of six URLs on the left, with the first
four having grayed out labels on the right; and a scrollbar to the
right of the drop down box, indicating further values are available.
The first four URLs in this sample consist of the four URLs in the
author-specified list that match the text the user has entered, sorted
in some [20621]implementation-defined 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.
4.10.5.1.5 Email state (type=email)
(BUTTON) ✔MDN
[20622]Element/input/email
Support in all current engines.
Firefox1+Safari5+Chrome5+
__________________________________________________________________
When an [20623]input element's [20624]type attribute is in the
[20625]Email state, the rules in this section apply.
How the [20626]Email state operates depends on whether the
[20627]multiple attribute is specified or not.
When the [20628]multiple attribute is not specified on the element
The [20629]input element [20630]represents a control for editing
an email address given in the element's [20631]value.
If the element is [20632]mutable, the user agent should allow
the user to change the email address represented by its
[20633]value. User agents may allow the user to set the
[20634]value to a string that is not a [20635]valid email
address. The user agent should act in a manner consistent with
expecting the user to provide a single email address. User
agents should allow the user to set the [20636]value to the
empty string. User agents must not allow users to insert U+000A
LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters into
the [20637]value. User agents may transform the [20638]value for
display and editing; in particular, user agents should convert
punycode in the domain labels of the [20639]value to IDN in the
display and vice versa.
Constraint validation: While the user interface is representing
input that the user agent cannot convert to punycode, the
control is [20640]suffering from bad input.
The [20641]value attribute, if specified and not empty, must
have a value that is a single [20642]valid email address.
The [20643]value sanitization algorithm is as follows:
[20644]Strip newlines from the [20645]value, then [20646]strip
leading and trailing ASCII whitespace from the [20647]value.
Constraint validation: While the [20648]value of the element is
neither the empty string nor a single [20649]valid email
address, the element is [20650]suffering from a type mismatch.
When the [20651]multiple attribute is specified on the element
The [20652]input element [20653]represents a control for adding,
removing, and editing the email addresses given in the element's
[20654]values.
If the element is [20655]mutable, the user agent should allow
the user to add, remove, and edit the email addresses
represented by its [20656]values. User agents may allow the user
to set any individual value in the list of [20657]values to a
string that is not a [20658]valid email address, but must not
allow users to set any individual value to a string containing
U+002C COMMA (,), U+000A LINE FEED (LF), or U+000D CARRIAGE
RETURN (CR) characters. User agents should allow the user to
remove all the addresses in the element's [20659]values. User
agents may transform the [20660]values for display and editing;
in particular, user agents should convert punycode in the domain
labels of the [20661]value to IDN in the display and vice versa.
Constraint validation: While the user interface describes a
situation where an individual value contains a U+002C COMMA (,)
or is representing input that the user agent cannot convert to
punycode, the control is [20662]suffering from bad input.
Whenever the user changes the element's [20663]values, the user
agent must run the following steps:
1. Let latest values be a copy of the element's [20664]values.
2. [20665]Strip leading and trailing ASCII whitespace from each
value in latest values.
3. Let the element's [20666]value be the result of concatenating
all the values in latest values, separating each value from
the next by a single U+002C COMMA character (,), maintaining
the list's order.
The [20667]value attribute, if specified, must have a value that
is a [20668]valid email address list.
The [20669]value sanitization algorithm is as follows:
1. [20670]Split on commas the element's [20671]value,
[20672]strip leading and trailing ASCII whitespace from each
resulting token, if any, and let the element's [20673]values
be the (possibly empty) resulting list of (possibly empty)
tokens, maintaining the original order.
2. Let the element's [20674]value be the result of concatenating
the element's [20675]values, separating each value from the
next by a single U+002C COMMA character (,), maintaining the
list's order.
Constraint validation: While the [20676]value of the element is
not a [20677]valid email address list, the element is
[20678]suffering from a type mismatch.
When the [20679]multiple attribute is set or removed, the user agent
must run the [20680]value sanitization algorithm.
A valid email 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. [20681][ABNF]
[20682][RFC5322] [20683][RFC1034] [20684][RFC1123]
email = 1*( atext / "." ) "@" label *( "." label )
label = let-dig [ [ ldh-str ] let-dig ] ; limited to a length of 63 cha
racters by [20685]RFC 1034 section 3.5
atext = < as defined in [20686]RFC 5322 section 3.2.3 >
let-dig = < as defined in [20687]RFC 1034 section 3.5 >
ldh-str = < as defined in [20688]RFC 1034 section 3.5 >
This requirement is a [20689]willful violation of RFC 5322, which
defines a syntax for email 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}[a-zA-Z0-9])?)*$/
A valid email address list is a [20690]set of comma-separated tokens,
where each token is itself a [20691]valid email address. To obtain the
list of tokens from a [20692]valid email address list, an
implementation must [20693]split the string on commas.
The following common [20694]input element content attributes, IDL
attributes, and methods [20695]apply to the element:
[20696]autocomplete, [20697]dirname, [20698]list, [20699]maxlength,
[20700]minlength, [20701]multiple, [20702]pattern, [20703]placeholder,
[20704]readonly, [20705]required, and [20706]size content attributes;
[20707]list and [20708]value IDL attributes; [20709]select() method.
The [20710]value IDL attribute is in mode [20711]value.
The [20712]input and [20713]change events [20714]apply.
The following content attributes must not be specified and [20715]do
not apply to the element: [20716]accept, [20717]alpha, [20718]alt,
[20719]checked, [20720]colorspace, [20721]formaction,
[20722]formenctype, [20723]formmethod, [20724]formnovalidate,
[20725]formtarget, [20726]height, [20727]max, [20728]min,
[20729]popovertarget, [20730]popovertargetaction, [20731]src,
[20732]step, and [20733]width.
The following IDL attributes and methods [20734]do not apply to the
element: [20735]checked, [20736]files, [20737]selectionStart,
[20738]selectionEnd, [20739]selectionDirection, [20740]valueAsDate, and
[20741]valueAsNumber IDL attributes; [20742]setRangeText(),
[20743]setSelectionRange(), [20744]stepDown() and [20745]stepUp()
methods.
4.10.5.1.6 Password state (type=password)
(BUTTON) ✔MDN
[20746]Element/input/password
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
When an [20747]input element's [20748]type attribute is in the
[20749]Password state, the rules in this section apply.
The [20750]input element [20751]represents a one line plain text edit
control for the element's [20752]value. The user agent should obscure
the value so that people other than the user cannot see it.
If the element is [20753]mutable, its [20754]value should be editable
by the user. User agents must not allow users to insert U+000A LINE
FEED (LF) or U+000D CARRIAGE RETURN (CR) characters into the
[20755]value.
The [20756]value attribute, if specified, must have a value that
contains no U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR)
characters.
The [20757]value sanitization algorithm is as follows: [20758]Strip
newlines from the [20759]value.
The following common [20760]input element content attributes, IDL
attributes, and methods [20761]apply to the element:
[20762]autocomplete, [20763]dirname, [20764]maxlength,
[20765]minlength, [20766]pattern, [20767]placeholder, [20768]readonly,
[20769]required, and [20770]size content attributes;
[20771]selectionStart, [20772]selectionEnd, [20773]selectionDirection,
and [20774]value IDL attributes; [20775]select(),
[20776]setRangeText(), and [20777]setSelectionRange() methods.
The [20778]value IDL attribute is in mode [20779]value.
The [20780]input and [20781]change events [20782]apply.
The following content attributes must not be specified and [20783]do
not apply to the element: [20784]accept, [20785]alpha, [20786]alt,
[20787]checked, [20788]colorspace, [20789]formaction,
[20790]formenctype, [20791]formmethod, [20792]formnovalidate,
[20793]formtarget, [20794]height, [20795]list, [20796]max, [20797]min,
[20798]multiple, [20799]popovertarget, [20800]popovertargetaction,
[20801]src, [20802]step, and [20803]width.
The following IDL attributes and methods [20804]do not apply to the
element: [20805]checked, [20806]files, [20807]list, [20808]valueAsDate,
and [20809]valueAsNumber IDL attributes; [20810]stepDown() and
[20811]stepUp() methods.
4.10.5.1.7 Date state (type=date)
(BUTTON) ✔MDN
[20812]Element/input/date
Support in all current engines.
Firefox57+Safari14.1+Chrome20+
__________________________________________________________________
When an [20813]input element's [20814]type attribute is in the
[20815]Date state, the rules in this section apply.
The [20816]input element [20817]represents a control for setting the
element's [20818]value to a string representing a specific [20819]date.
If the element is [20820]mutable, the user agent should allow the user
to change the [20821]date represented by its [20822]value, as obtained
by [20823]parsing a date from it. User agents must not allow the user
to set the [20824]value to a non-empty string that is not a
[20825]valid date string. If the user agent provides a user interface
for selecting a [20826]date, then the [20827]value must be set to a
[20828]valid date string representing the user's selection. User agents
should allow the user to set the [20829]value to the empty string.
Constraint validation: While the user interface describes input that
the user agent cannot convert to a [20830]valid date string, the
control is [20831]suffering from bad input.
See the [20832]introduction section for a discussion of the difference
between the input format and submission format for date, time, and
number form controls, and the [20833]implementation notes regarding
localization of form controls.
The [20834]value attribute, if specified and not empty, must have a
value that is a [20835]valid date string.
The [20836]value sanitization algorithm is as follows: If the
[20837]value of the element is not a [20838]valid date string, then set
it to the empty string instead.
The [20839]min attribute, if specified, must have a value that is a
[20840]valid date string. The [20841]max attribute, if specified, must
have a value that is a [20842]valid date string.
The [20843]step attribute is expressed in days. The [20844]step scale
factor is 86,400,000 (which converts the days to milliseconds, as used
in the other algorithms). The [20845]default step is 1 day.
When the element is [20846]suffering from a step mismatch, the user
agent may round the element's [20847]value to the nearest [20848]date
for which the element would not [20849]suffer from a step mismatch.
The [20850]algorithm to convert a string to a number, given a string
input, is as follows: If [20851]parsing a date from input results in an
error, then return an error; otherwise, return the number of
milliseconds elapsed from midnight UTC on the morning of 1970-01-01
(the time represented by the value "1970-01-01T00:00:00.0Z") to
midnight UTC on the morning of the parsed [20852]date, ignoring leap
seconds.
The [20853]algorithm to convert a number to a string, given a number
input, is as follows: Return a [20854]valid date string that represents
the [20855]date that, in UTC, is current input milliseconds after
midnight UTC on the morning of 1970-01-01 (the time represented by the
value "1970-01-01T00:00:00.0Z").
The [20856]algorithm to convert a string to a Date object, given a
string input, is as follows: If [20857]parsing a date from input
results in an error, then return an error; otherwise, return [20858]a
new Date object representing midnight UTC on the morning of the parsed
[20859]date.
The [20860]algorithm to convert a Date object to a string, given a
[20861]Date object input, is as follows: Return a [20862]valid date
string that represents the [20863]date current at the time represented
by input in the UTC time zone.
The [20864]Date 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 [20865]Date 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 fine-grained input
controls using the [20866]select element and [20867]input elements with
the [20868]Number state.
The following common [20869]input element content attributes, IDL
attributes, and methods [20870]apply to the element:
[20871]autocomplete, [20872]list, [20873]max, [20874]min,
[20875]readonly, [20876]required, and [20877]step content attributes;
[20878]list, [20879]value, [20880]valueAsDate, and [20881]valueAsNumber
IDL attributes; [20882]select(), [20883]stepDown(), and [20884]stepUp()
methods.
The [20885]value IDL attribute is in mode [20886]value.
The [20887]input and [20888]change events [20889]apply.
The following content attributes must not be specified and [20890]do
not apply to the element: [20891]accept, [20892]alpha, [20893]alt,
[20894]checked, [20895]colorspace, [20896]dirname, [20897]formaction,
[20898]formenctype, [20899]formmethod, [20900]formnovalidate,
[20901]formtarget, [20902]height, [20903]maxlength, [20904]minlength,
[20905]multiple, [20906]pattern, [20907]placeholder,
[20908]popovertarget, [20909]popovertargetaction, [20910]size,
[20911]src, and [20912]width.
The following IDL attributes and methods [20913]do not apply to the
element: [20914]checked, [20915]selectionStart, [20916]selectionEnd,
and [20917]selectionDirection IDL attributes; [20918]setRangeText(),
and [20919]setSelectionRange() methods.
4.10.5.1.8 Month state (type=month)
(BUTTON) ✔MDN
[20920]Element/input/month
Support in all current engines.
FirefoxNoSafariNoChrome20+
__________________________________________________________________
When an [20921]input element's [20922]type attribute is in the
[20923]Month state, the rules in this section apply.
The [20924]input element [20925]represents a control for setting the
element's [20926]value to a string representing a specific
[20927]month.
If the element is [20928]mutable, the user agent should allow the user
to change the [20929]month represented by its [20930]value, as obtained
by [20931]parsing a month from it. User agents must not allow the user
to set the [20932]value to a non-empty string that is not a
[20933]valid month string. If the user agent provides a user interface
for selecting a [20934]month, then the [20935]value must be set to a
[20936]valid month string representing the user's selection. User
agents should allow the user to set the [20937]value to the empty
string.
Constraint validation: While the user interface describes input that
the user agent cannot convert to a [20938]valid month string, the
control is [20939]suffering from bad input.
See the [20940]introduction section for a discussion of the difference
between the input format and submission format for date, time, and
number form controls, and the [20941]implementation notes regarding
localization of form controls.
The [20942]value attribute, if specified and not empty, must have a
value that is a [20943]valid month string.
The [20944]value sanitization algorithm is as follows: If the
[20945]value of the element is not a [20946]valid month string, then
set it to the empty string instead.
The [20947]min attribute, if specified, must have a value that is a
[20948]valid month string. The [20949]max attribute, if specified, must
have a value that is a [20950]valid month string.
The [20951]step attribute is expressed in months. The [20952]step scale
factor is 1 (there is no conversion needed as the algorithms use
months). The [20953]default step is 1 month.
When the element is [20954]suffering from a step mismatch, the user
agent may round the element's [20955]value to the nearest [20956]month
for which the element would not [20957]suffer from a step mismatch.
The [20958]algorithm to convert a string to a number, given a string
input, is as follows: If [20959]parsing a month from input results in
an error, then return an error; otherwise, return the number of months
between January 1970 and the parsed [20960]month.
The [20961]algorithm to convert a number to a string, given a number
input, is as follows: Return a [20962]valid month string that
represents the [20963]month that has input months between it and
January 1970.
The [20964]algorithm to convert a string to a Date object, given a
string input, is as follows: If [20965]parsing a month from input
results in an error, then return an error; otherwise, return [20966]a
new Date object representing midnight UTC on the morning of the first
day of the parsed [20967]month.
The [20968]algorithm to convert a Date object to a string, given a
[20969]Date object input, is as follows: Return a [20970]valid month
string that represents the [20971]month current at the time represented
by input in the UTC time zone.
The following common [20972]input element content attributes, IDL
attributes, and methods [20973]apply to the element:
[20974]autocomplete, [20975]list, [20976]max, [20977]min,
[20978]readonly, [20979]required, and [20980]step content attributes;
[20981]list, [20982]value, [20983]valueAsDate, and [20984]valueAsNumber
IDL attributes; [20985]select(), [20986]stepDown(), and [20987]stepUp()
methods.
The [20988]value IDL attribute is in mode [20989]value.
The [20990]input and [20991]change events [20992]apply.
The following content attributes must not be specified and [20993]do
not apply to the element: [20994]accept, [20995]alpha, [20996]alt,
[20997]checked, [20998]colorspace, [20999]dirname, [21000]formaction,
[21001]formenctype, [21002]formmethod, [21003]formnovalidate,
[21004]formtarget, [21005]height, [21006]maxlength, [21007]minlength,
[21008]multiple, [21009]pattern, [21010]placeholder,
[21011]popovertarget, [21012]popovertargetaction, [21013]size,
[21014]src, and [21015]width.
The following IDL attributes and methods [21016]do not apply to the
element: [21017]checked, [21018]files, [21019]selectionStart,
[21020]selectionEnd, and [21021]selectionDirection IDL attributes;
[21022]setRangeText(), and [21023]setSelectionRange() methods.
When an [21025]input element's [21026]type attribute is in the
[21027]Week state, the rules in this section apply.
The [21028]input element [21029]represents a control for setting the
element's [21030]value to a string representing a specific [21031]week.
If the element is [21032]mutable, the user agent should allow the user
to change the [21033]week represented by its [21034]value, as obtained
by [21035]parsing a week from it. User agents must not allow the user
to set the [21036]value to a non-empty string that is not a
[21037]valid week string. If the user agent provides a user interface
for selecting a [21038]week, then the [21039]value must be set to a
[21040]valid week string representing the user's selection. User agents
should allow the user to set the [21041]value to the empty string.
Constraint validation: While the user interface describes input that
the user agent cannot convert to a [21042]valid week string, the
control is [21043]suffering from bad input.
See the [21044]introduction section for a discussion of the difference
between the input format and submission format for date, time, and
number form controls, and the [21045]implementation notes regarding
localization of form controls.
The [21046]value attribute, if specified and not empty, must have a
value that is a [21047]valid week string.
The [21048]value sanitization algorithm is as follows: If the
[21049]value of the element is not a [21050]valid week string, then set
it to the empty string instead.
The [21051]min attribute, if specified, must have a value that is a
[21052]valid week string. The [21053]max attribute, if specified, must
have a value that is a [21054]valid week string.
The [21055]step attribute is expressed in weeks. The [21056]step scale
factor is 604,800,000 (which converts the weeks to milliseconds, as
used in the other algorithms). The [21057]default step is 1 week. The
[21058]default step base is −259,200,000 (the start of week 1970-W01).
When the element is [21059]suffering from a step mismatch, the user
agent may round the element's [21060]value to the nearest [21061]week
for which the element would not [21062]suffer from a step mismatch.
The [21063]algorithm to convert a string to a number, given a string
input, is as follows: If [21064]parsing a week string from input
results in an error, then return an error; otherwise, return the number
of milliseconds elapsed from midnight UTC on the morning of 1970-01-01
(the time represented by the value "1970-01-01T00:00:00.0Z") to
midnight UTC on the morning of the Monday of the parsed [21065]week,
ignoring leap seconds.
The [21066]algorithm to convert a number to a string, given a number
input, is as follows: Return a [21067]valid week string that represents
the [21068]week that, in UTC, is current input milliseconds after
midnight UTC on the morning of 1970-01-01 (the time represented by the
value "1970-01-01T00:00:00.0Z").
The [21069]algorithm to convert a string to a Date object, given a
string input, is as follows: If [21070]parsing a week from input
results in an error, then return an error; otherwise, return [21071]a
new Date object representing midnight UTC on the morning of the Monday
of the parsed [21072]week.
The [21073]algorithm to convert a Date object to a string, given a
[21074]Date object input, is as follows: Return a [21075]valid week
string that represents the [21076]week current at the time represented
by input in the UTC time zone.
The following common [21077]input element content attributes, IDL
attributes, and methods [21078]apply to the element:
[21079]autocomplete, [21080]list, [21081]max, [21082]min,
[21083]readonly, [21084]required, and [21085]step content attributes;
[21086]list, [21087]value, [21088]valueAsDate, and [21089]valueAsNumber
IDL attributes; [21090]select(), [21091]stepDown(), and [21092]stepUp()
methods.
The [21093]value IDL attribute is in mode [21094]value.
The [21095]input and [21096]change events [21097]apply.
The following content attributes must not be specified and [21098]do
not apply to the element: [21099]accept, [21100]alpha, [21101]alt,
[21102]checked, [21103]colorspace, [21104]dirname, [21105]formaction,
[21106]formenctype, [21107]formmethod, [21108]formnovalidate,
[21109]formtarget, [21110]height, [21111]maxlength, [21112]minlength,
[21113]multiple, [21114]pattern, [21115]placeholder,
[21116]popovertarget, [21117]popovertargetaction, [21118]size,
[21119]src, and [21120]width.
The following IDL attributes and methods [21121]do not apply to the
element: [21122]checked, [21123]files, [21124]selectionStart,
[21125]selectionEnd, and [21126]selectionDirection IDL attributes;
[21127]setRangeText(), and [21128]setSelectionRange() methods.
4.10.5.1.10 Time state (type=time)
(BUTTON) ✔MDN
[21129]Element/input/time
Support in all current engines.
Firefox57+Safari14.1+Chrome20+
__________________________________________________________________
When an [21130]input element's [21131]type attribute is in the
[21132]Time state, the rules in this section apply.
The [21133]input element [21134]represents a control for setting the
element's [21135]value to a string representing a specific [21136]time.
If the element is [21137]mutable, the user agent should allow the user
to change the [21138]time represented by its [21139]value, as obtained
by [21140]parsing a time from it. User agents must not allow the user
to set the [21141]value to a non-empty string that is not a
[21142]valid time string. If the user agent provides a user interface
for selecting a [21143]time, then the [21144]value must be set to a
[21145]valid time string representing the user's selection. User agents
should allow the user to set the [21146]value to the empty string.
Constraint validation: While the user interface describes input that
the user agent cannot convert to a [21147]valid time string, the
control is [21148]suffering from bad input.
See the [21149]introduction section for a discussion of the difference
between the input format and submission format for date, time, and
number form controls, and the [21150]implementation notes regarding
localization of form controls.
The [21151]value attribute, if specified and not empty, must have a
value that is a [21152]valid time string.
The [21153]value sanitization algorithm is as follows: If the
[21154]value of the element is not a [21155]valid time string, then set
it to the empty string instead.
The form control [21156]has a periodic domain.
The [21157]min attribute, if specified, must have a value that is a
[21158]valid time string. The [21159]max attribute, if specified, must
have a value that is a [21160]valid time string.
The [21161]step attribute is expressed in seconds. The [21162]step
scale factor is 1000 (which converts the seconds to milliseconds, as
used in the other algorithms). The [21163]default step is 60 seconds.
When the element is [21164]suffering from a step mismatch, the user
agent may round the element's [21165]value to the nearest [21166]time
for which the element would not [21167]suffer from a step mismatch.
The [21168]algorithm to convert a string to a number, given a string
input, is as follows: If [21169]parsing a time from input results in an
error, then return an error; otherwise, return the number of
milliseconds elapsed from midnight to the parsed [21170]time on a day
with no time changes.
The [21171]algorithm to convert a number to a string, given a number
input, is as follows: Return a [21172]valid time string that represents
the [21173]time that is input milliseconds after midnight on a day with
no time changes.
The [21174]algorithm to convert a string to a Date object, given a
string input, is as follows: If [21175]parsing a time from input
results in an error, then return an error; otherwise, return [21176]a
new Date object representing the parsed [21177]time in UTC on
1970-01-01.
The [21178]algorithm to convert a Date object to a string, given a
[21179]Date object input, is as follows: Return a [21180]valid time
string that represents the UTC [21181]time component that is
represented by input.
The following common [21182]input element content attributes, IDL
attributes, and methods [21183]apply to the element:
[21184]autocomplete, [21185]list, [21186]max, [21187]min,
[21188]readonly, [21189]required, and [21190]step content attributes;
[21191]list, [21192]value, [21193]valueAsDate, and [21194]valueAsNumber
IDL attributes; [21195]select(), [21196]stepDown(), and [21197]stepUp()
methods.
The [21198]value IDL attribute is in mode [21199]value.
The [21200]input and [21201]change events [21202]apply.
The following content attributes must not be specified and [21203]do
not apply to the element: [21204]accept, [21205]alpha, [21206]alt,
[21207]checked, [21208]colorspace, [21209]dirname, [21210]formaction,
[21211]formenctype, [21212]formmethod, [21213]formnovalidate,
[21214]formtarget, [21215]height, [21216]maxlength, [21217]minlength,
[21218]multiple, [21219]pattern, [21220]placeholder,
[21221]popovertarget, [21222]popovertargetaction, [21223]size,
[21224]src, and [21225]width.
The following IDL attributes and methods [21226]do not apply to the
element: [21227]checked, [21228]files, [21229]selectionStart,
[21230]selectionEnd, and [21231]selectionDirection IDL attributes;
[21232]setRangeText(), and [21233]setSelectionRange() methods.
4.10.5.1.11 Local Date and Time state (type=datetime-local)
(BUTTON) ✔MDN
[21234]Element/input/datetime-local
Support in all current engines.
Firefox93+Safari14.1+Chrome20+
__________________________________________________________________
When an [21235]input element's [21236]type attribute is in the
[21237]Local Date and Time state, the rules in this section apply.
The [21238]input element [21239]represents a control for setting the
element's [21240]value to a string representing a [21241]local date and
time, with no time-zone offset information.
If the element is [21242]mutable, the user agent should allow the user
to change the [21243]date and time represented by its [21244]value, as
obtained by [21245]parsing a date and time from it. User agents must
not allow the user to set the [21246]value to a non-empty string that
is not a [21247]valid normalized local date and time string. If the
user agent provides a user interface for selecting a [21248]local date
and time, then the [21249]value must be set to a [21250]valid
normalized local date and time string representing the user's
selection. User agents should allow the user to set the [21251]value to
the empty string.
Constraint validation: While the user interface describes input that
the user agent cannot convert to a [21252]valid normalized local date
and time string, the control is [21253]suffering from bad input.
See the [21254]introduction section for a discussion of the difference
between the input format and submission format for date, time, and
number form controls, and the [21255]implementation notes regarding
localization of form controls.
The [21256]value attribute, if specified and not empty, must have a
value that is a [21257]valid local date and time string.
The [21258]value sanitization algorithm is as follows: If the
[21259]value of the element is a [21260]valid local date and time
string, then set it to a [21261]valid normalized local date and time
string representing the same date and time; otherwise, set it to the
empty string instead.
The [21262]min attribute, if specified, must have a value that is a
[21263]valid local date and time string. The [21264]max attribute, if
specified, must have a value that is a [21265]valid local date and time
string.
The [21266]step attribute is expressed in seconds. The [21267]step
scale factor is 1000 (which converts the seconds to milliseconds, as
used in the other algorithms). The [21268]default step is 60 seconds.
When the element is [21269]suffering from a step mismatch, the user
agent may round the element's [21270]value to the nearest [21271]local
date and time for which the element would not [21272]suffer from a step
mismatch.
The [21273]algorithm to convert a string to a number, given a string
input, is as follows: If [21274]parsing a date and time from input
results in an error, then return an error; otherwise, return the number
of milliseconds elapsed from midnight on the morning of 1970-01-01 (the
time represented by the value "1970-01-01T00:00:00.0") to the parsed
[21275]local date and time, ignoring leap seconds.
The [21276]algorithm to convert a number to a string, given a number
input, is as follows: Return a [21277]valid normalized local date and
time string that represents the date and time that is input
milliseconds after midnight on the morning of 1970-01-01 (the time
represented by the value "1970-01-01T00:00:00.0").
See [21278]the note on historical dates in the [21279]Date state
section.
The following common [21280]input element content attributes, IDL
attributes, and methods [21281]apply to the element:
[21282]autocomplete, [21283]list, [21284]max, [21285]min,
[21286]readonly, [21287]required, and [21288]step content attributes;
[21289]list, [21290]value, and [21291]valueAsNumber IDL attributes;
[21292]select(), [21293]stepDown(), and [21294]stepUp() methods.
The [21295]value IDL attribute is in mode [21296]value.
The [21297]input and [21298]change events [21299]apply.
The following content attributes must not be specified and [21300]do
not apply to the element: [21301]accept, [21302]alpha, [21303]alt,
[21304]checked, [21305]colorspace, [21306]dirname, [21307]formaction,
[21308]formenctype, [21309]formmethod, [21310]formnovalidate,
[21311]formtarget, [21312]height, [21313]maxlength, [21314]minlength,
[21315]multiple, [21316]pattern, [21317]placeholder,
[21318]popovertarget, [21319]popovertargetaction, [21320]size,
[21321]src, and [21322]width.
The following IDL attributes and methods [21323]do not apply to the
element: [21324]checked, [21325]files, [21326]selectionStart,
[21327]selectionEnd, [21328]selectionDirection, and [21329]valueAsDate
IDL attributes; [21330]setRangeText(), and [21331]setSelectionRange()
methods.
The following example shows part of a flight booking application. The
application uses an [21332]input element with its [21333]type attribute
set to [21334]datetime-local, and it then interprets the given date and
time in the time zone of the selected airport.
4.10.5.1.12 Number state (type=number)
(BUTTON) ✔MDN
[21335]Element/input/number
Support in all current engines.
Firefox29+Safari5.1+Chrome7+
__________________________________________________________________
When an [21336]input element's [21337]type attribute is in the
[21338]Number state, the rules in this section apply.
The [21339]input element [21340]represents a control for setting the
element's [21341]value to a string representing a number.
If the element is [21342]mutable, the user agent should allow the user
to change the number represented by its [21343]value, as obtained from
applying the [21344]rules for parsing floating-point number values to
it. User agents must not allow the user to set the [21345]value to a
non-empty string that is not a [21346]valid floating-point number. If
the user agent provides a user interface for selecting a number, then
the [21347]value must be set to the [21348]best representation of the
number representing the user's selection as a floating-point number.
User agents should allow the user to set the [21349]value to the empty
string.
Constraint validation: While the user interface describes input that
the user agent cannot convert to a [21350]valid floating-point number,
the control is [21351]suffering from bad input.
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 [21352]value attribute, if specified and not empty, must have a
value that is a [21353]valid floating-point number.
The [21354]value sanitization algorithm is as follows: If the
[21355]value of the element is not a [21356]valid floating-point
number, then set it to the empty string instead.
The [21357]min attribute, if specified, must have a value that is a
[21358]valid floating-point number. The [21359]max attribute, if
specified, must have a value that is a [21360]valid floating-point
number.
The [21361]step scale factor is 1. The [21362]default step is 1
(allowing only integers to be selected by the user, unless the
[21363]step base has a non-integer value).
When the element is [21364]suffering from a step mismatch, the user
agent may round the element's [21365]value to the nearest number for
which the element would not [21366]suffer from a step mismatch. If
there are two such numbers, user agents are encouraged to pick the one
nearest positive infinity.
The [21367]algorithm to convert a string to a number, given a string
input, is as follows: If applying the [21368]rules for parsing
floating-point number values to input results in an error, then return
an error; otherwise, return the resulting number.
The [21369]algorithm to convert a number to a string, given a number
input, is as follows: Return a [21370]valid floating-point number that
represents input.
The following common [21371]input element content attributes, IDL
attributes, and methods [21372]apply to the element:
[21373]autocomplete, [21374]list, [21375]max, [21376]min,
[21377]placeholder, [21378]readonly, [21379]required, and [21380]step
content attributes; [21381]list, [21382]value, and [21383]valueAsNumber
IDL attributes; [21384]select(), [21385]stepDown(), and [21386]stepUp()
methods.
The [21387]value IDL attribute is in mode [21388]value.
The [21389]input and [21390]change events [21391]apply.
The following content attributes must not be specified and [21392]do
not apply to the element: [21393]accept, [21394]alpha, [21395]alt,
[21396]checked, [21397]colorspace, [21398]dirname, [21399]formaction,
[21400]formenctype, [21401]formmethod, [21402]formnovalidate,
[21403]formtarget, [21404]height, [21405]maxlength, [21406]minlength,
[21407]multiple, [21408]pattern, [21409]popovertarget,
[21410]popovertargetaction, [21411]size, [21412]src, and [21413]width.
The following IDL attributes and methods [21414]do not apply to the
element: [21415]checked, [21416]files, [21417]selectionStart,
[21418]selectionEnd, [21419]selectionDirection, and [21420]valueAsDate
IDL attributes; [21421]setRangeText(), and [21422]setSelectionRange()
methods.
Here is an example of using a numeric input control:
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 an [21423]inputmode or [21424]pattern
attribute).
4.10.5.1.13 Range state (type=range)
(BUTTON) ✔MDN
[21425]Element/input/range
Support in all current engines.
Firefox23+Safari3.1+Chrome4+
__________________________________________________________________
When an [21426]input element's [21427]type attribute is in the
[21428]Range state, the rules in this section apply.
The [21429]input element [21430]represents a control for setting the
element's [21431]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 [21432]Number state.
If the element is [21433]mutable, the user agent should allow the user
to change the number represented by its [21434]value, as obtained from
applying the [21435]rules for parsing floating-point number values to
it. User agents must not allow the user to set the [21436]value to a
string that is not a [21437]valid floating-point number. If the user
agent provides a user interface for selecting a number, then the
[21438]value must be set to a [21439]best representation of the number
representing the user's selection as a floating-point number. User
agents must not allow the user to set the [21440]value to the empty
string.
Constraint validation: While the user interface describes input that
the user agent cannot convert to a [21441]valid floating-point number,
the control is [21442]suffering from bad input.
The [21443]value attribute, if specified, must have a value that is a
[21444]valid floating-point number.
The [21445]value sanitization algorithm is as follows: If the
[21446]value of the element is not a [21447]valid floating-point
number, then set it to the [21448]best representation, as a
floating-point number, of the [21449]default value.
The default value is the [21450]minimum plus half the difference
between the [21451]minimum and the [21452]maximum, unless the
[21453]maximum is less than the [21454]minimum, in which case the
[21455]default value is the [21456]minimum.
When the element is [21457]suffering from an underflow, the user agent
must set the element's [21458]value to the [21459]best representation,
as a floating-point number, of the [21460]minimum.
When the element is [21461]suffering from an overflow, if the
[21462]maximum is not less than the [21463]minimum, the user agent must
set the element's [21464]value to a [21465]valid floating-point number
that represents the [21466]maximum.
When the element is [21467]suffering from a step mismatch, the user
agent must round the element's [21468]value to the nearest number for
which the element would not [21469]suffer from a step mismatch, and
which is greater than or equal to the [21470]minimum, and, if the
[21471]maximum is not less than the [21472]minimum, which is less than
or equal to the [21473]maximum, if there is a number that matches these
constraints. If two numbers match these constraints, then user agents
must use the one nearest to positive infinity.
For example, the markup
results in a range
control whose initial value is 60.
Here is an example of a range control using an autocomplete list with
the [21474]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:
...with the following style sheet applied:
input { writing-mode: vertical-lr; height: 75px; width: 49px; background: #D5CCB
B; color: black; }
...might render as:
A vertical slider control whose primary color is black and whose
background color is beige, with the slider having five tick marks, one
long one at each extremity, and three short ones clustered around the
midpoint.
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 [21475]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 ignored.
For another example, consider the following markup fragment:
A user agent could display in a variety of ways, for instance:
As a dial.
Or, alternatively, for instance:
As a long horizontal slider with tick marks.
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 for the tick marks, despite the differences in width.
Finally, here is an example of a range control with two labeled values:
With styles that make the control draw vertically, it might look as
follows:
A vertical slider control with two tick marks, one near the top labeled
'High', and one near the bottom labeled 'Low'.
In this state, the range and step constraints are enforced even during
user input, and there is no way to set the value to the empty string.
The [21476]min attribute, if specified, must have a value that is a
[21477]valid floating-point number. The [21478]default minimum is 0.
The [21479]max attribute, if specified, must have a value that is a
[21480]valid floating-point number. The [21481]default maximum is 100.
The [21482]step scale factor is 1. The [21483]default step is 1
(allowing only integers, unless the [21484]min attribute has a
non-integer value).
The [21485]algorithm to convert a string to a number, given a string
input, is as follows: If applying the [21486]rules for parsing
floating-point number values to input results in an error, then return
an error; otherwise, return the resulting number.
The [21487]algorithm to convert a number to a string, given a number
input, is as follows: Return the [21488]best representation, as a
floating-point number, of input.
The following common [21489]input element content attributes, IDL
attributes, and methods [21490]apply to the element:
[21491]autocomplete, [21492]list, [21493]max, [21494]min, and
[21495]step content attributes; [21496]list, [21497]value, and
[21498]valueAsNumber IDL attributes; [21499]stepDown() and
[21500]stepUp() methods.
The [21501]value IDL attribute is in mode [21502]value.
The [21503]input and [21504]change events [21505]apply.
The following content attributes must not be specified and [21506]do
not apply to the element: [21507]accept, [21508]alpha, [21509]alt,
[21510]checked, [21511]colorspace, [21512]dirname, [21513]formaction,
[21514]formenctype, [21515]formmethod, [21516]formnovalidate,
[21517]formtarget, [21518]height, [21519]maxlength, [21520]minlength,
[21521]multiple, [21522]pattern, [21523]placeholder,
[21524]popovertarget, [21525]popovertargetaction, [21526]readonly,
[21527]required, [21528]size, [21529]src, and [21530]width.
The following IDL attributes and methods [21531]do not apply to the
element: [21532]checked, [21533]files, [21534]selectionStart,
[21535]selectionEnd, [21536]selectionDirection, and [21537]valueAsDate
IDL attributes; [21538]select(), [21539]setRangeText(), and
[21540]setSelectionRange() methods.
4.10.5.1.14 Color state (type=color)
(BUTTON) ✔MDN
[21541]Element/input/color
Support in all current engines.
Firefox29+Safari12.1+Chrome20+
__________________________________________________________________
When an [21542]input element's [21543]type attribute is in the
[21544]Color state, the rules in this section apply.
The [21545]input element [21546]represents a color well control, for
setting the element's [21547]value to a string representing the
serialization of a CSS color.
In this state, there is always a CSS color picked, and there is no way
for the end user to set the value to the empty string.
The alpha attribute is a [21548]boolean attribute. If present, it
indicates the CSS color's alpha component can be manipulated by the end
user and does not have to be fully opaque.
The colorspace attribute indicates the color space of the serialized
CSS color. It also hints at the desired user interface for selecting a
CSS color. It is an [21549]enumerated attribute with the following
keywords and states:
Keyword State Brief description
limited-srgb Limited sRGB The CSS color is converted to the
[21550]'srgb' color space and limited to 8-bits per component, e.g.,
"#123456" or "color(srgb 0 1 0 / 0.5)".
display-p3 Display P3 The CSS color is converted to the
[21551]'display-p3' color space, e.g., "color(display-p3 1.84 -0.19
0.72 / 0.6)".
The attribute's [21552]missing value default and [21553]invalid value
default are both the [21554]Limited sRGB state.
Whenever the element's [21555]alpha or [21556]colorspace attributes are
changed, the user agent must run [21557]update a color well control
color given the element.
If the element is [21558]mutable, the user agent should allow the user
to change the color represented by its [21559]value, as obtained from
[21560]parsing it. User agents must not allow the user to set the
[21561]value to a string that running [21562]update a color well
control color for the element would not set it to. If the user agent
provides a user interface for selecting a CSS color, then the
[21563]value must be set to the result of [21564]serializing a color
well control color given the element and the end user's selection.
The [21565]input activation behavior for such an element element is to
[21566]show the picker, if applicable, for element.
Constraint validation: While the element's [21567]value is not the
empty string and [21568]parsing it returns failure, the control is
[21569]suffering from bad input.
The [21570]value attribute, if specified and not the empty string, must
have a value that is a CSS color.
The [21571]value sanitization algorithm is as follows: Run
[21572]update a color well control color for the element.
To update a color well control color, given an element element:
1. [21573]Assert: element is an [21574]input element whose [21575]type
attribute is in the [21576]Color state.
2. Let color be the result of [21577]parsing element's [21578]value.
3. If color is failure, then set color to [21579]opaque black.
4. Set element's [21580]value to the result of [21581]serializing a
color well control color given element and color.
To serialize a color well control color, given an element element and a
CSS color color:
1. [21582]Assert: element is an [21583]input element whose [21584]type
attribute is in the [21585]Color state.
2. Let htmlCompatible be false.
3. If element's [21586]alpha attribute is not specified, then set
color's alpha component to be fully opaque.
4. If element's [21587]colorspace attribute is in the [21588]Limited
sRGB state:
1. Set color to color [21589]converted to the [21590]'srgb' color
space.
2. Round each of color's components so they are in the range 0 to
255, inclusive. Components are to be [21591]rounded towards
+∞.
3. If element's [21592]alpha attribute is not specified, then set
htmlCompatible to true.
This intentionally uses a different serialization path for
compatibility with an earlier version of the color well
control.
4. Otherwise, set color to color converted to using the
[21593]'color()' function.
5. Otherwise:
1. [21594]Assert: element's [21595]colorspace attribute is in the
[21596]Display P3 state.
2. Set color to color [21597]converted to the [21598]'display-p3'
color space.
6. Return the result of [21599]serializing color. If htmlCompatible is
true, then do so with [21600]HTML-compatible serialization
requested.
The following common [21601]input element content attributes and IDL
attributes [21602]apply to the element: [21603]alpha,
[21604]autocomplete, [21605]colorspace, and [21606]list content
attributes; [21607]list and [21608]value IDL attributes;
[21609]select() method.
The [21610]value IDL attribute is in mode [21611]value.
The [21612]input and [21613]change events [21614]apply.
The following content attributes must not be specified and [21615]do
not apply to the element: [21616]accept, [21617]alt, [21618]checked,
[21619]dirname, [21620]formaction, [21621]formenctype,
[21622]formmethod, [21623]formnovalidate, [21624]formtarget,
[21625]height, [21626]max, [21627]maxlength, [21628]min,
[21629]minlength, [21630]multiple, [21631]pattern, [21632]placeholder,
[21633]popovertarget, [21634]popovertargetaction, [21635]readonly,
[21636]required, [21637]size, [21638]src, [21639]step, and
[21640]width.
The following IDL attributes and methods [21641]do not apply to the
element: [21642]checked, [21643]files, [21644]selectionStart,
[21645]selectionEnd, [21646]selectionDirection, [21647]valueAsDate and,
[21648]valueAsNumber IDL attributes; [21649]setRangeText(),
[21650]setSelectionRange(), [21651]stepDown(), and [21652]stepUp()
methods.
4.10.5.1.15 Checkbox state (type=checkbox)
(BUTTON) ✔MDN
[21653]Element/input/checkbox
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
When an [21654]input element's [21655]type attribute is in the
[21656]Checkbox state, the rules in this section apply.
The [21657]input element [21658]represents a two-state control that
represents the element's [21659]checkedness state. If the element's
[21660]checkedness state is true, the control represents a positive
selection, and if it is false, a negative selection. If the element's
[21661]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
[21662]indeterminate IDL attribute is set to true. The
[21663]indeterminate IDL attribute only gives the appearance of a third
state.
The [21664]input activation behavior is to run the following steps:
1. If the element is not [21665]connected, then return.
2. [21666]Fire an event named [21667]input at the element with the
[21668]bubbles and [21669]composed attributes initialized to true.
3. [21670]Fire an event named [21671]change at the element with the
[21672]bubbles attribute initialized to true.
Constraint validation: If the element is [21673]required and its
[21674]checkedness is false, then the element is [21675]suffering from
being missing.
input.[21676]indeterminate [ = value ]
When set, overrides the rendering of [21677]checkbox controls so
that the current value is not visible.
The following common [21678]input element content attributes and IDL
attributes [21679]apply to the element: [21680]checked, and
[21681]required content attributes; [21682]checked and [21683]value IDL
attributes.
The [21684]value IDL attribute is in mode [21685]default/on.
The [21686]input and [21687]change events [21688]apply.
The following content attributes must not be specified and [21689]do
not apply to the element: [21690]accept, [21691]alpha, [21692]alt,
[21693]autocomplete, [21694]colorspace, [21695]dirname,
[21696]formaction, [21697]formenctype, [21698]formmethod,
[21699]formnovalidate, [21700]formtarget, [21701]height, [21702]list,
[21703]max, [21704]maxlength, [21705]min, [21706]minlength,
[21707]multiple, [21708]pattern, [21709]placeholder,
[21710]popovertarget, [21711]popovertargetaction, [21712]readonly,
[21713]size, [21714]src, [21715]step, and [21716]width.
The following IDL attributes and methods [21717]do not apply to the
element: [21718]files, [21719]list, [21720]selectionStart,
[21721]selectionEnd, [21722]selectionDirection, [21723]valueAsDate, and
[21724]valueAsNumber IDL attributes; [21725]select(),
[21726]setRangeText(), [21727]setSelectionRange(), [21728]stepDown(),
and [21729]stepUp() methods.
4.10.5.1.16 Radio Button state (type=radio)
(BUTTON) ✔MDN
[21730]Element/input/radio
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
When an [21731]input element's [21732]type attribute is in the
[21733]Radio Button state, the rules in this section apply.
The [21734]input element [21735]represents a control that, when used in
conjunction with other [21736]input elements, forms a [21737]radio
button group in which only one control can have its [21738]checkedness
state set to true. If the element's [21739]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 [21740]input element a also
contains all the other [21741]input elements b that fulfill all of the
following conditions:
* The [21742]input element b's [21743]type attribute is in the
[21744]Radio Button state.
* Either a and b have the same [21745]form owner, or they both have
no [21746]form owner.
* Both a and b are in the same [21747]tree.
* They both have a [21748]name attribute, their [21749]name
attributes are not empty, and the value of a's [21750]name
attribute equals the value of b's [21751]name attribute.
A [21752]tree must not contain an [21753]input element whose
[21754]radio button group contains only that element.
When any of the following phenomena occur, if the element's
[21755]checkedness state is true after the occurrence, the
[21756]checkedness state of all the other elements in the same
[21757]radio button group must be set to false:
* The element's [21758]checkedness state is set to true (for whatever
reason).
* The element's [21759]name attribute is set, changed, or removed.
* The element's [21760]form owner changes.
* [21761]A type change is signalled for the element.
* The element [21762]becomes connected.
The [21763]input activation behavior is to run the following steps:
1. If the element is not [21764]connected, then return.
2. [21765]Fire an event named [21766]input at the element with the
[21767]bubbles and [21768]composed attributes initialized to true.
3. [21769]Fire an event named [21770]change at the element with the
[21771]bubbles attribute initialized to true.
Constraint validation: If an element in the [21772]radio button group
is [21773]required, and all of the [21774]input elements in the
[21775]radio button group have a [21776]checkedness that is false, then
the element is [21777]suffering from being missing.
The following example, for some reason, has specified that puppers are
both [21778]required and [21779]disabled:
If the user tries to submit this form without first selecting "Doggo",
then both [21780]input elements will be [21781]suffering from being
missing, since an element in the [21782]radio button group is
[21783]required (viz. the first element), and both of the elements in
the radio button group have a false [21784]checkedness.
On the other hand, if the user selects "Doggo" and then submits the
form, then neither [21785]input element will be [21786]suffering from
being missing, since while one of them is [21787]required, not all of
them have a false [21788]checkedness.
If none of the radio buttons in a [21789]radio button group are
checked, 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 [21790]input element content attributes and IDL
attributes [21791]apply to the element: [21792]checked and
[21793]required content attributes; [21794]checked and [21795]value IDL
attributes.
The [21796]value IDL attribute is in mode [21797]default/on.
The [21798]input and [21799]change events [21800]apply.
The following content attributes must not be specified and [21801]do
not apply to the element: [21802]accept, [21803]alpha, [21804]alt,
[21805]autocomplete, [21806]colorspace, [21807]dirname,
[21808]formaction, [21809]formenctype, [21810]formmethod,
[21811]formnovalidate, [21812]formtarget, [21813]height, [21814]list,
[21815]max, [21816]maxlength, [21817]min, [21818]minlength,
[21819]multiple, [21820]pattern, [21821]placeholder,
[21822]popovertarget, [21823]popovertargetaction, [21824]readonly,
[21825]size, [21826]src, [21827]step, and [21828]width.
The following IDL attributes and methods [21829]do not apply to the
element: [21830]files, [21831]list, [21832]selectionStart,
[21833]selectionEnd, [21834]selectionDirection, [21835]valueAsDate, and
[21836]valueAsNumber IDL attributes; [21837]select(),
[21838]setRangeText(), [21839]setSelectionRange(), [21840]stepDown(),
and [21841]stepUp() methods.
4.10.5.1.17 File Upload state (type=file)
(BUTTON) ✔MDN
[21842]Element/input/file
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
When an [21843]input element's [21844]type attribute is in the
[21845]File Upload state, the rules in this section apply.
The [21846]input element [21847]represents a list of selected files,
each file consisting of a filename, a file type, and a file body (the
contents of the file).
Filenames must not contain [21848]path components, even in the case
that a user has selected an entire directory hierarchy or multiple
files with the same name from different directories. Path components,
for the purposes of the [21849]File Upload state, are those parts of
filenames that are separated by U+005C REVERSE SOLIDUS character (\)
characters.
Unless the [21850]multiple attribute is set, there must be no more than
one file in the list of [21851]selected files.
The [21852]input activation behavior for such an element element is to
[21853]show the picker, if applicable, for element.
If the element is [21854]mutable, the user agent should allow the user
to change the files on the list in other ways also, e.g., adding or
removing files by drag-and-drop. When the user does so, the user agent
must [21855]update the file selection for the element.
If the element is not [21856]mutable, the user agent must not allow the
user to change the element's selection.
To update the file selection for an element element:
1. [21857]Queue an element task on the [21858]user interaction task
source given element and the following steps:
1. Update element's [21859]selected files so that it represents
the user's selection.
2. [21860]Fire an event named [21861]input at the [21862]input
element, with the [21863]bubbles and [21864]composed
attributes initialized to true.
3. [21865]Fire an event named [21866]change at the [21867]input
element, with the [21868]bubbles attribute initialized to
true.
Constraint validation: If the element is [21869]required and the list
of [21870]selected files is empty, then the element is [21871]suffering
from being missing.
__________________________________________________________________
(BUTTON) ✔MDN
[21872]Attributes/accept
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
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 [21874]set of
comma-separated tokens, each of which must be an [21875]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 [21876]valid MIME type string 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 [21877]ASCII case-insensitive matches for any of
the other tokens (i.e. duplicates are not allowed). To obtain the list
of tokens from the attribute, the user agent must [21878]split the
attribute value on commas.
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/*, 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.
User agents should prevent the user from selecting files that are not
accepted by one (or more) of these tokens.
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:
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 filenames 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
[21879]accept attribute's requirements.
(BUTTON) MDN
[21880]Element/input/file
For historical reasons, the [21881]value IDL attribute prefixes the
filename 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 filename from the [21882]value IDL
attribute in a backwards-compatible way is non-trivial. The following
function extracts the filename 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 filename
}
The following common [21883]input element content attributes and IDL
attributes [21884]apply to the element: [21885]accept, [21886]multiple,
and [21887]required content attributes; [21888]files and [21889]value
IDL attributes; [21890]select() method.
The [21891]value IDL attribute is in mode [21892]filename.
The [21893]input and [21894]change events [21895]apply.
The following content attributes must not be specified and [21896]do
not apply to the element: [21897]alpha, [21898]alt,
[21899]autocomplete, [21900]checked, [21901]colorspace, [21902]dirname,
[21903]formaction, [21904]formenctype, [21905]formmethod,
[21906]formnovalidate, [21907]formtarget, [21908]height, [21909]list,
[21910]max, [21911]maxlength, [21912]min, [21913]minlength,
[21914]pattern, [21915]popovertarget, [21916]popovertargetaction,
[21917]placeholder, [21918]readonly, [21919]size, [21920]src,
[21921]step, and [21922]width.
The element's [21923]value attribute must be omitted.
The following IDL attributes and methods [21924]do not apply to the
element: [21925]checked, [21926]list, [21927]selectionStart,
[21928]selectionEnd, [21929]selectionDirection, [21930]valueAsDate, and
[21931]valueAsNumber IDL attributes; [21932]setRangeText(),
[21933]setSelectionRange(), [21934]stepDown(), and [21935]stepUp()
methods.
4.10.5.1.18 Submit Button state (type=submit)
(BUTTON) ✔MDN
[21936]Element/input/submit
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
When an [21937]input element's [21938]type attribute is in the
[21939]Submit Button state, the rules in this section apply.
[21940](This is a tracking vector.) The [21941]input element
[21942]represents a button that, when activated, submits the form. If
the element has a [21943]value attribute, the button's label must be
the value of that attribute; otherwise, it must be an
[21944]implementation-defined string that means "Submit" or some such.
The element is a [21945]button, specifically a [21946]submit button.
Since the default label is [21947]implementation-defined, and the width
of the button typically depends on the button's label, the button's
width can leak a few bits of fingerprintable information. These bits
are likely to be strongly correlated to the identity of the user agent
and the user's locale.
The element's [21948]input activation behavior given event is as
follows:
1. If the element does not have a [21949]form owner, then return.
2. If the element's [21950]node document is not [21951]fully active,
then return.
3. [21952]Submit the element's [21953]form owner from the element with
[21954]userInvolvement set to event's [21955]user navigation
involvement.
The [21956]formaction, [21957]formenctype, [21958]formmethod,
[21959]formnovalidate, and [21960]formtarget attributes are
[21961]attributes for form submission.
The [21962]formnovalidate attribute can be used to make submit buttons
that do not trigger the constraint validation.
The following common [21963]input element content attributes and IDL
attributes [21964]apply to the element: [21965]dirname,
[21966]formaction, [21967]formenctype, [21968]formmethod,
[21969]formnovalidate, [21970]formtarget, [21971]popovertarget, and
[21972]popovertargetaction content attributes; [21973]value IDL
attribute.
The [21974]value IDL attribute is in mode [21975]default.
The following content attributes must not be specified and [21976]do
not apply to the element: [21977]accept, [21978]alpha, [21979]alt,
[21980]autocomplete, [21981]checked, [21982]colorspace, [21983]height,
[21984]list, [21985]max, [21986]maxlength, [21987]min,
[21988]minlength, [21989]multiple, [21990]pattern, [21991]placeholder,
[21992]readonly, [21993]required, [21994]size, [21995]src, [21996]step,
and [21997]width.
The following IDL attributes and methods [21998]do not apply to the
element: [21999]checked, [22000]files, [22001]list,
[22002]selectionStart, [22003]selectionEnd, [22004]selectionDirection,
[22005]valueAsDate, and [22006]valueAsNumber IDL attributes;
[22007]select(), [22008]setRangeText(), [22009]setSelectionRange(),
[22010]stepDown(), and [22011]stepUp() methods.
The [22012]input and [22013]change events [22014]do not apply.
4.10.5.1.19 Image Button state (type=image)
(BUTTON) ✔MDN
[22015]Element/input/image
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
When an [22016]input element's [22017]type attribute is in the
[22018]Image Button state, the rules in this section apply.
The [22019]input element [22020]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
[22021]button, specifically a [22022]submit button.
The coordinate is sent to the server [22023]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.
__________________________________________________________________
(BUTTON) ✔MDN
[22024]Element/input#src
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
The image is given by the src attribute. The [22025]src attribute must
be present, and must contain a [22026]valid non-empty URL potentially
surrounded by spaces referencing a non-interactive, optionally
animated, image resource that is neither paged nor scripted.
When any of the these events occur
* the [22027]input element's [22028]type attribute is first set to
the [22029]Image Button state (possibly when the element is first
created), and the [22030]src attribute is present
* the [22031]input element's [22032]type attribute is changed back to
the [22033]Image Button state, and the [22034]src attribute is
present, and its value has changed since the last time the
[22035]type attribute was in the [22036]Image Button state
* the [22037]input element's [22038]type attribute is in the
[22039]Image Button state, and the [22040]src attribute is set or
changed
then unless the user agent cannot support images, or its support for
images has been disabled, or the user agent only fetches images on
demand, or the [22041]src attribute's value is the empty string, run
these steps:
1. Let url be the result of [22042]encoding-parsing a URL given the
[22043]src attribute's value, relative to the element's [22044]node
document.
2. If url is failure, then return.
3. Let request be a new [22045]request whose [22046]URL is url,
[22047]client is the element's [22048]node document's
[22049]relevant settings object, [22050]destination is "image",
[22051]initiator type is "input", [22052]credentials mode is
"include", and whose [22053]use-URL-credentials flag is set.
4. [22054]Fetch request, with [22055]processResponseEndOfBody set to
the following steps given [22056]response response:
1. If the download was successful and the image is
[22057]available, [22058]queue an element task on the
[22059]user interaction task source given the [22060]input
element to [22061]fire an event named [22062]load at the
[22063]input element.
2. Otherwise, if the fetching process fails without a response
from the remote server, or completes but the image is not a
valid or supported image, then [22064]queue an element task on
the [22065]user interaction task source given the [22066]input
element to [22067]fire an event named [22068]error on the
[22069]input element.
Fetching the image must [22070]delay the load event of the element's
[22071]node document until the [22072]task that is [22073]queued by the
[22074]networking task source once the resource has been fetched
(defined below) has been run.
If the image was successfully obtained, with no network errors, and the
image's type is a supported image type, and the image is a valid image
of that type, then the image is said to be available. If this is true
before the image is completely downloaded, each [22075]task that is
[22076]queued by the [22077]networking task source while the image is
being fetched must update the presentation of the image appropriately.
The user agent should apply the [22078]image sniffing rules to
determine the type of the image, with the image's [22079]associated
Content-Type headers giving the official type. If these rules are not
applied, then the type of the image must be the type given by the
image's [22080]associated Content-Type headers.
User agents must not support non-image resources with the [22081]input
element. User agents must not run executable code embedded in the image
resource. User agents must only display the first page of a multipage
resource. User agents must not allow the resource to act in an
interactive fashion, but should honor any animation in the resource.
__________________________________________________________________
(BUTTON) ✔MDN
[22082]Element/input#alt
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
The alt attribute provides the textual label for the button for users
and user agents who cannot use the image. The [22083]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 [22084]input element supports [22085]dimension attributes.
__________________________________________________________________
If the [22086]src attribute is set, and the image is [22087]available
and the user agent is configured to display that image, then the
element [22088]represents a control for selecting a [22089]coordinate
from the image specified by the [22090]src attribute. In that case, if
the element is [22091]mutable, the user agent should allow the user to
select this [22092]coordinate.
Otherwise, the element [22093]represents a submit button whose label is
given by the value of the [22094]alt attribute.
The element's [22095]input activation behavior given event is as
follows:
1. If the element does not have a [22096]form owner, then return.
2. If the element's [22097]node document is not [22098]fully active,
then return.
3. If the user activated the control while explicitly selecting a
coordinate, then set the element's [22099]selected coordinate to
that coordinate.
This is only possible under the conditions outlined above, when the
element [22100]represents a control for selecting such a
coordinate. Even then, the user might activate the control without
explicitly selecting a coordinate.
4. [22101]Submit the element's [22102]form owner from the element with
[22103]userInvolvement set to event's [22104]user navigation
involvement.
The element's selected coordinate consists of an x-component and a
y-component. It is initially (0, 0). The coordinates represent the
position relative to the edge of the element's image, with the
coordinate space having the positive x direction to the right, and the
positive y direction downwards.
The x-component must be a [22105]valid integer representing a number x
in the range −(border[left]+padding[left]) ≤ x ≤
width+border[right]+padding[right], where width is the rendered width
of the image, border[left] is the width of the border on the left of
the image, padding[left] is the width of the padding on the left of the
image, border[right] is the width of the border on the right of the
image, and padding[right] is the width of the padding on the right of
the image, with all dimensions given in [22106]CSS pixels.
The y-component must be a [22107]valid integer representing a number y
in the range −(border[top]+padding[top]) ≤ y ≤
height+border[bottom]+padding[bottom], where height is the rendered
height of the image, border[top] is the width of the border above the
image, padding[top] is the width of the padding above the image,
border[bottom] is the width of the border below the image, and
padding[bottom] is the width of the padding below the image, with all
dimensions given in [22108]CSS pixels.
Where a border or padding is missing, its width is zero [22109]CSS
pixels.
__________________________________________________________________
The [22110]formaction, [22111]formenctype, [22112]formmethod,
[22113]formnovalidate, and [22114]formtarget attributes are
[22115]attributes for form submission.
image.[22116]width [ = value ]
image.[22117]height [ = value ]
These attributes return the actual rendered dimensions of the
image, or 0 if the dimensions are not known.
They can be set, to change the corresponding content attributes.
The following common [22118]input element content attributes and IDL
attributes [22119]apply to the element: [22120]alt, [22121]formaction,
[22122]formenctype, [22123]formmethod, [22124]formnovalidate,
[22125]formtarget, [22126]height, [22127]popovertarget,
[22128]popovertargetaction, [22129]src, and [22130]width content
attributes; [22131]value IDL attribute.
The [22132]value IDL attribute is in mode [22133]default.
The following content attributes must not be specified and [22134]do
not apply to the element: [22135]accept, [22136]alpha,
[22137]autocomplete, [22138]checked, [22139]colorspace, [22140]dirname,
[22141]list, [22142]max, [22143]maxlength, [22144]min,
[22145]minlength, [22146]multiple, [22147]pattern, [22148]placeholder,
[22149]readonly, [22150]required, [22151]size, and [22152]step.
The element's [22153]value attribute must be omitted.
The following IDL attributes and methods [22154]do not apply to the
element: [22155]checked, [22156]files, [22157]list,
[22158]selectionStart, [22159]selectionEnd, [22160]selectionDirection,
[22161]valueAsDate, and [22162]valueAsNumber IDL attributes;
[22163]select(), [22164]setRangeText(), [22165]setSelectionRange(),
[22166]stepDown(), and [22167]stepUp() methods.
The [22168]input and [22169]change events [22170]do not apply.
Many aspects of this state's behavior are similar to the behavior of
the [22171]img element. Readers are encouraged to read that section,
where many of the same requirements are described in more detail.
Take the following 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.)
4.10.5.1.20 Reset Button state (type=reset)
(BUTTON) ✔MDN
[22172]Element/input/reset
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
When an [22173]input element's [22174]type attribute is in the
[22175]Reset Button state, the rules in this section apply.
[22176](This is a tracking vector.) The [22177]input element
[22178]represents a button that, when activated, resets the form. If
the element has a [22179]value attribute, the button's label must be
the value of that attribute; otherwise, it must be an
[22180]implementation-defined string that means "Reset" or some such.
The element is a [22181]button.
Since the default label is [22182]implementation-defined, and the width
of the button typically depends on the button's label, the button's
width can leak a few bits of fingerprintable information. These bits
are likely to be strongly correlated to the identity of the user agent
and the user's locale.
The element's [22183]input activation behavior is as follows:
1. If the element does not have a [22184]form owner, then return.
2. If the element's [22185]node document is not [22186]fully active,
then return.
3. [22187]Reset the [22188]form owner from the element.
Constraint validation: The element is [22189]barred from constraint
validation.
The [22190]value IDL attribute [22191]applies to this element and is in
mode [22192]default.
The following common [22193]input element content attributes
[22194]apply to the element: [22195]popovertarget and
[22196]popovertargetaction.
The following content attributes must not be specified and [22197]do
not apply to the element: [22198]accept, [22199]alpha, [22200]alt,
[22201]autocomplete, [22202]checked, [22203]colorspace, [22204]dirname,
[22205]formaction, [22206]formenctype, [22207]formmethod,
[22208]formnovalidate, [22209]formtarget, [22210]height, [22211]list,
[22212]max, [22213]maxlength, [22214]min, [22215]minlength,
[22216]multiple, [22217]pattern, [22218]placeholder, [22219]readonly,
[22220]required, [22221]size, [22222]src, [22223]step, and
[22224]width.
The following IDL attributes and methods [22225]do not apply to the
element: [22226]checked, [22227]files, [22228]list,
[22229]selectionStart, [22230]selectionEnd, [22231]selectionDirection,
[22232]valueAsDate, and [22233]valueAsNumber IDL attributes;
[22234]select(), [22235]setRangeText(), [22236]setSelectionRange(),
[22237]stepDown(), and [22238]stepUp() methods.
The [22239]input and [22240]change events [22241]do not apply.
4.10.5.1.21 Button state (type=button)
(BUTTON) ✔MDN
[22242]Element/input/button
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
When an [22243]input element's [22244]type attribute is in the
[22245]Button state, the rules in this section apply.
The [22246]input element [22247]represents a button with no default
behavior. A label for the button must be provided in the [22248]value
attribute, though it may be the empty string. If the element has a
[22249]value attribute, the button's label must be the value of that
attribute; otherwise, it must be the empty string. The element is a
[22250]button.
The element has no [22251]input activation behavior.
Constraint validation: The element is [22252]barred from constraint
validation.
The [22253]value IDL attribute [22254]applies to this element and is in
mode [22255]default.
The following common [22256]input element content attributes
[22257]apply to the element: [22258]popovertarget and
[22259]popovertargetaction.
The following content attributes must not be specified and [22260]do
not apply to the element: [22261]accept, [22262]alpha, [22263]alt,
[22264]autocomplete, [22265]checked, [22266]colorspace, [22267]dirname,
[22268]formaction, [22269]formenctype, [22270]formmethod,
[22271]formnovalidate, [22272]formtarget, [22273]height, [22274]list,
[22275]max, [22276]maxlength, [22277]min, [22278]minlength,
[22279]multiple, [22280]pattern, [22281]placeholder, [22282]readonly,
[22283]required, [22284]size, [22285]src, [22286]step, and
[22287]width.
The following IDL attributes and methods [22288]do not apply to the
element: [22289]checked, [22290]files, [22291]list,
[22292]selectionStart, [22293]selectionEnd, [22294]selectionDirection,
[22295]valueAsDate, and [22296]valueAsNumber IDL attributes;
[22297]select(), [22298]setRangeText(), [22299]setSelectionRange(),
[22300]stepDown(), and [22301]stepUp() methods.
The [22302]input and [22303]change events [22304]do not apply.
4.10.5.2 Implementation notes regarding localization of form
controls
This section is non-normative.
The formats shown to the user in date, time, and number controls is
independent of the format used for form submission.
Browsers are encouraged to use user interfaces that present dates,
times, and numbers according to the conventions of either the locale
implied by the [22305]input element's [22306]language or the user's
preferred locale. Using the page's locale will ensure consistency with
page-provided data.
For example, it would be confusing to users if an American English page
claimed that a Cirque De Soleil show was going to be showing on 02/03,
but their browser, configured to use the British English locale, only
showed the date 03/02 in the ticket purchase date picker. Using the
page's locale would at least ensure that the date was presented in the
same format everywhere. (There's still a risk that the user would end
up arriving a month late, of course, but there's only so much that can
be done about such cultural differences...)
4.10.5.3 Common [22307]input element attributes
These attributes only [22308]apply to an [22309]input element if its
[22310]type attribute is in a state whose definition declares that the
attribute [22311]applies. When an attribute [22312]doesn't apply to an
[22313]input element, user agents must [22314]ignore the attribute,
regardless of the requirements and definitions below.
4.10.5.3.1 The [22315]maxlength and [22316]minlength attributes
(BUTTON) ✔MDN
[22317]Attributes/maxlength
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
The minlength attribute, when it [22327]applies, is a [22328]form
control minlength attribute.
If the [22329]input element has a [22330]maximum allowed value length,
then the [22331]length of the value of the element's [22332]value
attribute must be less than or equal to the element's [22333]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.
Here, a password is given a minimum length:
4.10.5.3.2 The [22334]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 [22335]value.
The [22336]size attribute, if specified, must have a value that is a
[22337]valid non-negative integer greater than zero.
If the attribute is present, then its value must be parsed using the
[22338]rules for parsing non-negative integers, and if the result is a
number greater than zero, then the user agent should ensure that at
least that many characters are visible.
The [22339]size IDL attribute is [22340]limited to only positive
numbers and has a [22341]default value of 20.
4.10.5.3.3 The [22342]readonly attribute
(BUTTON) ✔MDN
[22343]Attributes/readonly
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
The readonly attribute is a [22346]boolean attribute that controls
whether or not the user can edit the form control. When specified, the
element is not [22347]mutable.
Constraint validation: If the [22348]readonly attribute is specified on
an [22349]input element, the element is [22350]barred from constraint
validation.
The difference between [22351]disabled and [22352]readonly is that
read-only controls can still function, whereas disabled controls
generally do not function as controls until they are enabled. This is
spelled out in more detail elsewhere in this specification with
normative requirements that refer to the [22353]disabled concept (for
example, the element's [22354]activation behavior, whether or not it is
a [22355]focusable area, or when [22356]constructing the entry list).
Any other behavior related to user interaction with disabled controls,
such as whether text can be selected or copied, is not defined in this
standard.
Only text controls can be made read-only, since for other controls
(such as checkboxes and buttons) there is no useful distinction between
being read-only and being disabled, so the [22357]readonly attribute
[22358]does not apply.
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).
4.10.5.3.4 The [22359]required attribute
The required attribute is a [22360]boolean attribute. When specified,
the element is required.
Constraint validation: If the element is [22361]required, and its
[22362]value IDL attribute [22363]applies and is in the mode
[22364]value, and the element is [22365]mutable, and the element's
[22366]value is the empty string, then the element is [22367]suffering
from being missing.
The following form has two required fields, one for an email 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.
Create new account
For radio buttons, the [22368]required attribute is satisfied if any of
the radio buttons in the [22369]group is selected. Thus, in the
following example, any of the radio buttons can be checked, not just
the one marked as required:
To avoid confusion as to whether a [22370]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.
4.10.5.3.5 The [22371]multiple attribute
(BUTTON) ✔MDN
[22372]Attributes/multiple
Support in all current engines.
Firefox3.6+Safari4+Chrome2+
__________________________________________________________________
The multiple attribute is a [22374]boolean attribute that indicates
whether the user is to be allowed to specify more than one value.
The following extract shows how an email client's "To" field could
accept multiple email addresses.
If the user had, amongst many friends in their user contacts database,
two friends "Spider-Man" (with address "spider@parker.example.net") and
"Scarlet Witch" (with address "scarlet@avengers.example.net"), then,
after the user has typed "s", the user agent might suggest these two
email addresses to the user.
The page could also link in the user's contacts database from the site:
...
Suppose the user had entered "bob@example.net" into this text control,
and then started typing a second email address starting with "s". The
user agent might show both the two friends mentioned earlier, as well
as the "astrophy" and "astronomy" values given in the [22375]datalist
element.
The following extract shows how an email client's "Attachments" field
could accept multiple files for upload.
4.10.5.3.6 The [22376]pattern attribute
(BUTTON) ✔MDN
[22377]Attributes/pattern
Support in all current engines.
Firefox4+Safari5+Chrome4+
__________________________________________________________________
The pattern attribute specifies a regular expression against which the
control's [22379]value, or, when the [22380]multiple attribute
[22381]applies and is set, the control's [22382]values, are to be
checked.
If specified, the attribute's value must match the JavaScript
[22383]Pattern[[+UnicodeSetsMode, +N]] production.
The compiled pattern regular expression of an [22384]input element, if
it exists, is a JavaScript [22385]RegExp object. It is determined as
follows:
1. If the element does not have a [22386]pattern attribute specified,
then return nothing. The element has no [22387]compiled pattern
regular expression.
2. Let pattern be the value of the [22388]pattern attribute of the
element.
3. Let regexpCompletion be [22389]RegExpCreate(pattern, "v").
4. If regexpCompletion is an [22390]abrupt completion, then return
nothing. The element has no [22391]compiled pattern regular
expression.
User agents are encouraged to log this error in a developer
console, to aid debugging.
5. Let anchoredPattern be the string "^(?:", followed by pattern,
followed by ")$".
6. Return ! [22392]RegExpCreate(anchoredPattern, "v").
The reasoning behind these steps, instead of just using the value of
the [22393]pattern attribute directly, is twofold. First, we want to
ensure that when matched against a string, the regular expression's
start is anchored to the start of the string and its end to the end of
the string. Second, we want to ensure that the regular expression is
valid in standalone form, instead of only becoming valid after being
surrounded by the "^(?:" and ")$" anchors.
A [22394]RegExp object regexp matches a string input, if !
[22395]RegExpBuiltinExec(regexp, input) is not null.
Constraint validation: If the element's [22396]value is not the empty
string, and either the element's [22397]multiple attribute is not
specified or it [22398]does not apply to the [22399]input element given
its [22400]type attribute's current state, and the element has a
[22401]compiled pattern regular expression but that regular expression
does not [22402]match the element's [22403]value, then the element is
[22404]suffering from a pattern mismatch.
Constraint validation: If the element's [22405]value is not the empty
string, and the element's [22406]multiple attribute is specified and
[22407]applies to the [22408]input element, and the element has a
[22409]compiled pattern regular expression but that regular expression
does not [22410]match each of the element's [22411]values, then the
element is [22412]suffering from a pattern mismatch.
When an [22413]input element has a [22414]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 [22415]gains focus.
For example, the following snippet:
...could cause the UA to display an alert such as:
A part number is a digit followed by three uppercase letters.
You cannot submit this form when the field is incorrect.
When a control has a [22416]pattern attribute, the [22417]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 [22418]title in non-error situations (for
example, as a tooltip when hovering over the control), so authors
should be careful not to word [22419]titles as if an error has
necessarily occurred.
4.10.5.3.7 The [22420]min and [22421]max attributes
(BUTTON) ✔MDN
[22422]Attributes/max
Support in all current engines.
Firefox16+Safari5+Chrome4+
__________________________________________________________________
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 [22424]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.
Their syntax is defined by the section that defines the [22425]type
attribute's current state.
If the element has a [22426]min attribute, and the result of applying
the [22427]algorithm to convert a string to a number to the value of
the [22428]min attribute is a number, then that number is the element's
minimum; otherwise, if the [22429]type attribute's current state
defines a default minimum, then that is the [22430]minimum; otherwise,
the element has no [22431]minimum.
The [22432]min attribute also defines the [22433]step base.
If the element has a [22434]max attribute, and the result of applying
the [22435]algorithm to convert a string to a number to the value of
the [22436]max attribute is a number, then that number is the element's
maximum; otherwise, if the [22437]type attribute's current state
defines a default maximum, then that is the [22438]maximum; otherwise,
the element has no [22439]maximum.
If the element does not [22440]have a periodic domain, the [22441]max
attribute's value (the [22442]maximum) must not be less than the
[22443]min attribute's value (its [22444]minimum).
If an element that does not [22445]have a periodic domain has a
[22446]maximum that is less than its [22447]minimum, then so long as
the element has a [22448]value, it will either be [22449]suffering from
an underflow or [22450]suffering from an overflow.
An element has a reversed range if it [22451]has a periodic domain and
its [22452]maximum is less than its [22453]minimum.
An element has range limitations if it has a defined [22454]minimum or
a defined [22455]maximum.
Constraint validation: When the element has a [22456]minimum and does
not [22457]have a reversed range, and the result of applying the
[22458]algorithm to convert a string to a number to the string given by
the element's [22459]value is a number, and the number obtained from
that algorithm is less than the [22460]minimum, the element is
[22461]suffering from an underflow.
Constraint validation: When the element has a [22462]maximum and does
not [22463]have a reversed range, and the result of applying the
[22464]algorithm to convert a string to a number to the string given by
the element's [22465]value is a number, and the number obtained from
that algorithm is more than the [22466]maximum, the element is
[22467]suffering from an overflow.
Constraint validation: When an element [22468]has a reversed range, and
the result of applying the [22469]algorithm to convert a string to a
number to the string given by the element's [22470]value is a number,
and the number obtained from that algorithm is more than the
[22471]maximum and less than the [22472]minimum, the element is
simultaneously [22473]suffering from an underflow and [22474]suffering
from an overflow.
The following date control limits input to dates that are before the
1980s:
The following number control limits input to whole numbers greater than
zero:
The following time control limits input to those minutes that occur
between 9pm and 6am, defaulting to midnight:
4.10.5.3.8 The [22475]step attribute
(BUTTON) ✔MDN
[22476]Attributes/step
Support in all current engines.
Firefox16+Safari5+Chrome5+
__________________________________________________________________
The step attribute indicates the granularity that is expected (and
required) of the [22477]value or [22478]values, by limiting the allowed
values. The section that defines the [22479]type attribute's current
state also defines the default step, the step scale factor, and in some
cases the default step base, which are used in processing the attribute
as described below.
The [22480]step attribute, if specified, must either have a value that
is a [22481]valid floating-point number that [22482]parses to a number
that is greater than zero, or must have a value that is an [22483]ASCII
case-insensitive match for the string "any".
The attribute provides the allowed value step for the element, as
follows:
1. If the attribute does not [22484]apply, then there is no
[22485]allowed value step.
2. Otherwise, if the attribute is absent, then the [22486]allowed
value step is the [22487]default step multiplied by the [22488]step
scale factor.
3. Otherwise, if the attribute's value is an [22489]ASCII
case-insensitive match for the string "any", then there is no
[22490]allowed value step.
4. Otherwise, if the [22491]rules for parsing floating-point number
values, when they are applied to the attribute's value, return an
error, zero, or a number less than zero, then the [22492]allowed
value step is the [22493]default step multiplied by the [22494]step
scale factor.
5. Otherwise, the [22495]allowed value step is the number returned by
the [22496]rules for parsing floating-point number values when they
are applied to the attribute's value, multiplied by the [22497]step
scale factor.
The step base is the value returned by the following algorithm:
1. If the element has a [22498]min content attribute, and the result
of applying the [22499]algorithm to convert a string to a number to
the value of the [22500]min content attribute is not an error, then
return that result.
2. If the element has a [22501]value content attribute, and the result
of applying the [22502]algorithm to convert a string to a number to
the value of the [22503]value content attribute is not an error,
then return that result.
3. If a [22504]default step base is defined for this element given its
[22505]type attribute's state, then return it.
4. Return zero.
Constraint validation: When the element has an [22506]allowed value
step, and the result of applying the [22507]algorithm to convert a
string to a number to the string given by the element's [22508]value is
a number, and that number subtracted from the [22509]step base is not
an integral multiple of the [22510]allowed value step, the element is
[22511]suffering from a step mismatch.
The following range control only accepts values in the range 0..1, and
allows 256 steps in that range:
The following control allows any time in the day to be selected, with
any accuracy (e.g. thousandth-of-a-second accuracy or more):
Normally, time controls are limited to an accuracy of one minute.
4.10.5.3.9 The [22512]list attribute
(BUTTON) ✔MDN
[22513]Element/input#list
Support in all current engines.
Firefox4+Safari12.1+Chrome20+
__________________________________________________________________
The list attribute is used to identify an element that lists predefined
options suggested to the user.
If present, its value must be the [22514]ID of a [22515]datalist
element in the same [22516]tree.
The suggestions source element is the first element in the [22517]tree
in [22518]tree order to have an [22519]ID equal to the value of the
[22520]list attribute, if that element is a [22521]datalist element. If
there is no [22522]list attribute, or if there is no element with that
[22523]ID, or if the first element with that [22524]ID is not a
[22525]datalist element, then there is no [22526]suggestions source
element.
If there is a [22527]suggestions source element, then, when the user
agent is allowing the user to edit the [22528]input element's
[22529]value, the user agent should offer the suggestions represented
by the [22530]suggestions source element to the user in a manner
suitable for the type of control used. If appropriate, the user agent
should use the suggestion's [22531]label and [22532]value to identify
the suggestion to the user.
User agents are encouraged to filter the suggestions represented by the
[22533]suggestions source element when the number of suggestions is
large, including only the most relevant ones (e.g. based on the user's
input so far). No precise threshold is defined, but capping the list at
four to seven values is reasonable. If filtering based on the user's
input, user agents should search within both the [22534]label and
[22535]value of the suggestions for matches. User agents should
consider how input variations affect the matching process. Unicode
normalization should be applied so that different underlying Unicode
code point sequences, caused by different keyboard- or input-specific
mechanisms, do not interfere with the matching process. Case variations
should be ignored, which may require language-specific case mapping.
For examples of these, see Character Model for the World Wide Web:
String Matching. User agents may also provide other matching features:
for illustration, a few examples include matching different forms of
kana to each other (or to kanji), ignoring accents, or applying
spelling correction. [22536][CHARMODNORM]
This text field allows you to choose a type of JavaScript function.
For user agents that follow the above suggestions, both the
[22537]label and [22538]value would be shown:
A text box with a drop down button on the right hand side; with, below,
a drop down box containing a list of the six values the left and the
six labels on the right.
Then, typing "arrow" or "=>" would filter the list to the entries with
labels "arrow function" and "async arrow function". Typing "generator"
or "*" would filter the list to the entries with labels "generator
function" and "async generator function".
As always, user agents are free to make user interface decisions which
are appropriate for their particular requirements and for the user's
particular circumstances. However, this has historically been an area
of confusion for implementers, web developers, and users alike, so
we've given some "should" suggestions above.
How user selections of suggestions are handled depends on whether the
element is a control accepting a single value only, or whether it
accepts multiple values:
If the element does not have a [22539]multiple attribute specified or
if the [22540]multiple attribute [22541]does not apply
When the user selects a suggestion, the [22542]input element's
[22543]value must be set to the selected suggestion's
[22544]value, as if the user had written that value themself.
If the element's [22545]type attribute is in the [22546]Email state and
the element has a [22547]multiple attribute specified
When the user selects a suggestion, the user agent must either
add a new entry to the [22548]input element's [22549]values,
whose value is the selected suggestion's [22550]value, or change
an existing entry in the [22551]input element's [22552]values to
have the value given by the selected suggestion's [22553]value,
as if the user had themself added an entry with that value, or
edited an existing entry to be that value. Which behavior is to
be applied depends on the user interface in an
[22554]implementation-defined manner.
__________________________________________________________________
If the [22555]list attribute [22556]does not apply, there is no
[22557]suggestions source element.
This URL field offers some suggestions.
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 [22558]datalist element with children
[22559]option elements is enough. To prevent the values from being
rendered in legacy user agents, they need to be placed inside the
[22560]value attribute instead of inline.
However, if the values need to be shown in legacy UAs, then fallback
content can be placed inside the [22561]datalist element, as follows:
The fallback content will only be shown in UAs that don't support
[22562]datalist. The options, on the other hand, will be detected by
all UAs, even though they are not children of the [22563]datalist
element.
Note that if an [22564]option element used in a [22565]datalist is
[22566]selected, it will be selected by default by legacy UAs (because
it affects the [22567]select element), but it will not have any effect
on the [22568]input element in UAs that support [22569]datalist.
4.10.5.3.10 The [22570]placeholder attribute
(BUTTON) ✔MDN
[22571]Element/input#placeholder
Support in all current engines.
Firefox4+Safari4+Chrome3+
__________________________________________________________________
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 [22573]placeholder attribute should not be used as an alternative
to a [22574]label. For a longer hint or other advisory text, the
[22575]title attribute is more appropriate.
These mechanisms are very similar but subtly different: the hint given
by the control's [22576]label is shown at all times; the short hint
given in the [22577]placeholder attribute is shown before the user
enters a value; and the hint in the [22578]title attribute is shown
when the user requests further help.
User agents should present this hint to the user, after having
[22579]stripped newlines from it, when the element's [22580]value is
the empty string, especially if the control is not [22581]focused.
If a user agent normally doesn't show this hint to the user when the
control is [22582]focused, then the user agent should nonetheless show
the hint for the control if it was focused as a result of the
[22583]autofocus attribute, since in that case the user will not have
had an opportunity to examine the control before focusing it.
Here is an example of a mail configuration user interface that uses the
[22584]placeholder attribute:
In situations where the control's content has one directionality but
the placeholder needs to have a different directionality, Unicode's
bidirectional-algorithm formatting characters can be used in the
attribute value:
For slightly more clarity, here's the same example using numeric
character references instead of inline Arabic:
4.10.5.4 Common [22585]input element APIs
input.[22586]value [ = value ]
Returns the current [22587]value of the form control.
Can be set, to change the value.
Throws an [22588]"InvalidStateError" [22589]DOMException if it
is set to any value other than the empty string when the control
is a file upload control.
input.[22590]checked [ = value ]
Returns the current [22591]checkedness of the form control.
Firefox Android?Safari iOS3+Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
Returns a [22596]FileList object listing the [22597]selected
files of the form control.
Returns null if the control isn't a file control.
Can be set to a [22598]FileList object to change the
[22599]selected files of the form control. For instance, as the
result of a drag-and-drop operation.
input.[22600]valueAsDate [ = value ]
Returns a [22601]Date object representing the form control's
[22602]value, if applicable; otherwise, returns null.
Can be set, to change the value.
Throws an [22603]"InvalidStateError" [22604]DOMException if the
control isn't date- or time-based.
input.[22605]valueAsNumber [ = value ]
Returns a number representing the form control's [22606]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 [22607]"InvalidStateError" [22608]DOMException if the
control is neither date- or time-based nor numeric.
Firefox Android?Safari iOS4+Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
Changes the form control's [22613]value by the value given in
the [22614]step attribute, multiplied by n. The default value
for n is 1.
Throws [22615]"InvalidStateError" [22616]DOMException if the
control is neither date- or time-based nor numeric, or if the
[22617]step attribute's value is "any".
input.[22618]list
Returns the [22619]datalist element indicated by the [22620]list
attribute.
input.[22621]showPicker()
Shows any applicable picker UI for input, so that the user can
select a value.
If input does not [22622]support a picker, this method does
nothing.
Throws an [22623]"InvalidStateError" [22624]DOMException if
input is not [22625]mutable.
Throws a [22626]"NotAllowedError" [22627]DOMException if called
without [22628]transient user activation.
Throws a [22629]"SecurityError" [22630]DOMException if input is
inside a cross-origin [22631]iframe, unless input is in the
[22632]File Upload or [22633]Color states.
The value IDL attribute allows scripts to manipulate the [22634]value
of an [22635]input element. The attribute is in one of the following
modes, which define its behavior:
value
On getting, return the current [22636]value of the element.
On setting:
1. Let oldValue be the element's [22637]value.
2. Set the element's [22638]value to the new value.
3. Set the element's [22639]dirty value flag to true.
4. Invoke the [22640]value sanitization algorithm, if the
element's [22641]type attribute's current state defines one.
5. If the element's [22642]value (after applying the [22643]value
sanitization algorithm) is different from oldValue, and the
element has a [22644]text entry cursor position, move the
[22645]text entry cursor position to the end of the text
control, unselecting any selected text and [22646]resetting
the selection direction to "none".
default
On getting, if the element has a [22647]value content attribute,
return that attribute's value; otherwise, return the empty
string.
On setting, set the value of the element's [22648]value content
attribute to the new value.
default/on
On getting, if the element has a [22649]value content attribute,
return that attribute's value; otherwise, return the string
"on".
On setting, set the value of the element's [22650]value content
attribute to the new value.
filename
On getting, return the string "C:\fakepath\" followed by the
name of the first file in the list of [22651]selected files, if
any, or the empty string if the list is empty.
On setting, if the new value is the empty string, empty the list
of [22652]selected files; otherwise, throw an
[22653]"InvalidStateError" [22654]DOMException.
This "fakepath" requirement is a sad accident of history. See
[22655]the example in the File Upload state section for more
information.
Since [22656]path components are not permitted in filenames in
the list of [22657]selected files, the "\fakepath\" cannot be
mistaken for a path component.
__________________________________________________________________
The checked IDL attribute allows scripts to manipulate the
[22658]checkedness of an [22659]input element. On getting, it must
return the current [22660]checkedness of the element; and on setting,
it must set the element's [22661]checkedness to the new value and set
the element's [22662]dirty checkedness flag to true.
__________________________________________________________________
The files IDL attribute allows scripts to access the element's
[22663]selected files.
On getting, if the IDL attribute [22664]applies, it must return a
[22665]FileList object that represents the current [22666]selected
files. The same object must be returned until the list of
[22667]selected files changes. If the IDL attribute [22668]does not
apply, then it must instead return null. [22669][FILEAPI]
On setting, it must run these steps:
1. If the IDL attribute [22670]does not apply or the given value is
null, then return.
2. Replace the element's [22671]selected files with the given value.
__________________________________________________________________
The valueAsDate IDL attribute represents the [22672]value of the
element, interpreted as a date.
On getting, if the [22673]valueAsDate attribute [22674]does not apply,
as defined for the [22675]input element's [22676]type attribute's
current state, then return null. Otherwise, run the [22677]algorithm to
convert a string to a Date object defined for that state to the
element's [22678]value; if the algorithm returned a [22679]Date object,
then return it, otherwise, return null.
On setting, if the [22680]valueAsDate attribute [22681]does not apply,
as defined for the [22682]input element's [22683]type attribute's
current state, then throw an [22684]"InvalidStateError"
[22685]DOMException; otherwise, if the new value is not null and not a
[22686]Date object throw a [22687]TypeError exception; otherwise, if
the new value is null or a [22688]Date object representing the NaN time
value, then set the [22689]value of the element to the empty string;
otherwise, run the [22690]algorithm to convert a Date object to a
string, as defined for that state, on the new value, and set the
[22691]value of the element to the resulting string.
__________________________________________________________________
The valueAsNumber IDL attribute represents the [22692]value of the
element, interpreted as a number.
On getting, if the [22693]valueAsNumber attribute [22694]does not
apply, as defined for the [22695]input element's [22696]type
attribute's current state, then return a Not-a-Number (NaN) value.
Otherwise, run the [22697]algorithm to convert a string to a number
defined for that state to the element's [22698]value; if the algorithm
returned a number, then return it, otherwise, return a Not-a-Number
(NaN) value.
On setting, if the new value is infinite, then throw a [22699]TypeError
exception. Otherwise, if the [22700]valueAsNumber attribute [22701]does
not apply, as defined for the [22702]input element's [22703]type
attribute's current state, then throw an [22704]"InvalidStateError"
[22705]DOMException. Otherwise, if the new value is a Not-a-Number
(NaN) value, then set the [22706]value of the element to the empty
string. Otherwise, run the [22707]algorithm to convert a number to a
string, as defined for that state, on the new value, and set the
[22708]value of the element to the resulting string.
__________________________________________________________________
The stepDown(n) and stepUp(n) methods, when invoked, must run the
following algorithm:
1. If the [22709]stepDown() and [22710]stepUp() methods [22711]do not
apply, as defined for the [22712]input element's [22713]type
attribute's current state, then throw an [22714]"InvalidStateError"
[22715]DOMException.
2. If the element has no [22716]allowed value step, then throw an
[22717]"InvalidStateError" [22718]DOMException.
3. If the element has a [22719]minimum and a [22720]maximum and the
[22721]minimum is greater than the [22722]maximum, then return.
4. If the element has a [22723]minimum and a [22724]maximum and there
is no value greater than or equal to the element's [22725]minimum
and less than or equal to the element's [22726]maximum that, when
subtracted from the [22727]step base, is an integral multiple of
the [22728]allowed value step, then return.
5. If applying the [22729]algorithm to convert a string to a number to
the string given by the element's [22730]value does not result in
an error, then let value be the result of that algorithm.
Otherwise, let value be zero.
6. Let valueBeforeStepping be value.
7. If value subtracted from the [22731]step base is not an integral
multiple of the [22732]allowed value step, then set value to the
nearest value that, when subtracted from the [22733]step base, is
an integral multiple of the [22734]allowed value step, and that is
less than value if the method invoked was the [22735]stepDown()
method, and more than value otherwise.
Otherwise (value subtracted from the [22736]step base is an
integral multiple of the [22737]allowed value step):
1. Let n be the argument.
2. Let delta be the [22738]allowed value step multiplied by n.
3. If the method invoked was the [22739]stepDown() method, negate
delta.
4. Let value be the result of adding delta to value.
8. If the element has a [22740]minimum, and value is less than that
[22741]minimum, then set value to the smallest value that, when
subtracted from the [22742]step base, is an integral multiple of
the [22743]allowed value step, and that is more than or equal to
that [22744]minimum.
9. If the element has a [22745]maximum, and value is greater than that
[22746]maximum, then set value to the largest value that, when
subtracted from the [22747]step base, is an integral multiple of
the [22748]allowed value step, and that is less than or equal to
that [22749]maximum.
10. If either the method invoked was the [22750]stepDown() method and
value is greater than valueBeforeStepping, or the method invoked
was the [22751]stepUp() method and value is less than
valueBeforeStepping, then return.
This ensures that invoking the [22752]stepUp() method on the
[22753]input element in the following example does not change the
[22754]value of that element:
11. Let value as string be the result of running the [22755]algorithm
to convert a number to a string, as defined for the [22756]input
element's [22757]type attribute's current state, on value.
12. Set the [22758]value of the element to value as string.
__________________________________________________________________
The list IDL attribute must return the current [22759]suggestions
source element, if any, or null otherwise.
__________________________________________________________________
(BUTTON) ✔MDN
[22760]HTMLInputElement/showPicker
Support in all current engines.
Firefox101+Safari16+Chrome99+
__________________________________________________________________
The [22761]HTMLInputElement showPicker() and [22762]HTMLSelectElement
showPicker() method steps are:
1. If [22763]this is not [22764]mutable, then throw an
[22765]"InvalidStateError" [22766]DOMException.
2. If [22767]this's [22768]relevant settings object's [22769]origin is
not [22770]same origin with [22771]this's [22772]relevant settings
object's [22773]top-level origin, and [22774]this is a
[22775]select element, or [22776]this's [22777]type attribute is
not in the [22778]File Upload state or [22779]Color state, then
throw a [22780]"SecurityError" [22781]DOMException.
[22782]File and [22783]Color inputs are exempted from this check
for historical reason: their [22784]input activation behavior also
shows their pickers, and has never been guarded by an origin check.
3. If [22785]this's [22786]relevant global object does not have
[22787]transient activation, then throw a [22788]"NotAllowedError"
[22789]DOMException.
4. If [22790]this is a [22791]select element, and [22792]this is not
[22793]being rendered, then throw a [22794]"NotSupportedError"
[22795]DOMException.
5. [22796]Show the picker, if applicable, for [22797]this.
To show the picker, if applicable for an [22798]input or [22799]select
element element:
1. If element's [22800]relevant global object does not have
[22801]transient activation, then return.
2. If element is not [22802]mutable, then return.
3. [22803]Consume user activation given [22804]element's
[22805]relevant global object.
4. If element does not [22806]support a picker, then return.
5. If element is an [22807]input element and element's [22808]type
attribute is in the [22809]File Upload state, then run these steps
[22810]in parallel:
1. Optionally, wait until any prior execution of this algorithm
has terminated.
2. Let dismissed be the result of [22811]WebDriver BiDi file
dialog opened with element.
3. If dismissed is false:
1. Display a prompt to the user requesting that the user
specify some files. If the [22812]multiple attribute is
not set on element, there must be no more than one file
selected; otherwise, any number may be selected. Files
can be from the filesystem or created on the fly, e.g., a
picture taken from a camera connected to the user's
device.
2. Wait for the user to have made their selection.
4. If dismissed is true or if the user dismissed the prompt
without changing their selection, then [22813]queue an element
task on the [22814]user interaction task source given element
to [22815]fire an event named [22816]cancel at element, with
the [22817]bubbles attribute initialized to true.
5. Otherwise, [22818]update the file selection for element.
As with all user interface specifications, user agents have a good
deal of freedom in how they interpret these requirements. The above
text implies that a user either dismisses the prompt or changes
their selection; exactly one of these will be true. But the mapping
of these possibilities to specific user interface elements is not
mandated by the standard. For example, a user agent might interpret
clicking the "Cancel" button when files were previously selected as
a change of selection to select zero files, thus firing
[22819]input and [22820]change. Or it might interpret such a click
as a dismissal that leaves the selection unchanged, thus firing
[22821]cancel. Similarly, it's up to the user agent whether
re-selecting the same files as were previously selected counts as a
dismissal, or as a change of selection.
6. Otherwise, the user agent should show the relevant user interface
for selecting a value for element, in the way it normally would
when the user interacts with the control.
When showing such a user interface, it must respect the
requirements stated in the relevant parts of the specification for
how element behaves given its [22822]type attribute state. (For
example, various sections describe restrictions on the resulting
[22823]value string.)
This step can have side effects, such as closing other pickers that
were previously shown by this algorithm. (If this closes a file
selection picker, then per the above that will lead to firing
either [22824]input and [22825]change events, or a [22826]cancel
event.)
4.10.5.5 Common event behaviors
When the [22827]input and [22828]change events [22829]apply (which is
the case for all [22830]input controls other than [22831]buttons and
those with the [22832]type attribute in the [22833]Hidden state), the
events are fired to indicate that the user has interacted with the
control. The [22834]input event fires whenever the user has modified
the data of the control. The [22835]change event fires when the value
is committed, if that makes sense for the control, or else when the
control [22836]loses focus. In all cases, the [22837]input event comes
before the corresponding [22838]change event (if any).
When an [22839]input element has a defined [22840]input activation
behavior, the rules for dispatching these events, if they [22841]apply,
are given in the section above that defines the [22842]type attribute's
state. (This is the case for all [22843]input controls with the
[22844]type attribute in the [22845]Checkbox state, the [22846]Radio
Button state, or the [22847]File Upload state.)
For [22848]input elements without a defined [22849]input activation
behavior, but to which these events [22850]apply, and for which the
user interface involves both interactive manipulation and an explicit
commit action, then when the user changes the element's [22851]value,
the user agent must [22852]queue an element task on the [22853]user
interaction task source given the [22854]input element to [22855]fire
an event named [22856]input at the [22857]input element, with the
[22858]bubbles and [22859]composed attributes initialized to true, and
any time the user commits the change, the user agent must [22860]queue
an element task on the [22861]user interaction task source given the
[22862]input element to set its [22863]user validity to true and
[22864]fire an event named [22865]change at the [22866]input element,
with the [22867]bubbles attribute initialized to true.
An example of a user interface involving both interactive manipulation
and a commit action would be a [22868]Range controls that use a slider,
when manipulated using a pointing device. While the user is dragging
the control's knob, [22869]input events would fire whenever the
position changed, whereas the [22870]change event would only fire when
the user let go of the knob, committing to a specific value.
For [22871]input elements without a defined [22872]input activation
behavior, but to which these events [22873]apply, and for which the
user interface involves an explicit commit action but no intermediate
manipulation, then any time the user commits a change to the element's
[22874]value, the user agent must [22875]queue an element task on the
[22876]user interaction task source given the [22877]input element to
first [22878]fire an event named [22879]input at the [22880]input
element, with the [22881]bubbles and [22882]composed attributes
initialized to true, and then [22883]fire an event named [22884]change
at the [22885]input element, with the [22886]bubbles attribute
initialized to true.
An example of a user interface with a commit action would be a
[22887]Color control that consists of a single button that brings up a
color wheel: if the [22888]value only changes when the dialog is
closed, then that would be the explicit commit action. On the other
hand, if manipulating the control changes the color interactively, then
there might be no commit action.
Another example of a user interface with a commit action would be a
[22889]Date control that allows both text-based user input and user
selection from a drop-down calendar: while text input might not have an
explicit commit step, selecting a date from the drop down calendar and
then dismissing the drop down would be a commit action.
For [22890]input elements without a defined [22891]input activation
behavior, but to which these events [22892]apply, any time the user
causes the element's [22893]value to change without an explicit commit
action, the user agent must [22894]queue an element task on the
[22895]user interaction task source given the [22896]input element to
[22897]fire an event named [22898]input at the [22899]input element,
with the [22900]bubbles and [22901]composed attributes initialized to
true. The corresponding [22902]change event, if any, will be fired when
the control [22903]loses focus.
Examples of a user changing the element's [22904]value would include
the user typing into a text control, pasting a new value into the
control, or undoing an edit in that control. Some user interactions do
not cause changes to the value, e.g., hitting the "delete" key in an
empty text control, or replacing some text in the control with text
from the clipboard that happens to be exactly the same text.
A [22905]Range control in the form of a slider that the user has
[22906]focused and is interacting with using a keyboard would be
another example of the user changing the element's [22907]value without
a commit step.
In the case of [22908]tasks that just fire an [22909]input event, user
agents may wait for a suitable break in the user's interaction before
[22910]queuing the tasks; for example, a user agent could wait for the
user to have not hit a key for 100ms, so as to only fire the event when
the user pauses, instead of continuously for each keystroke.
When the user agent is to change an [22911]input element's [22912]value
on behalf of the user (e.g. as part of a form prefilling feature), the
user agent must [22913]queue an element task on the [22914]user
interaction task source given the [22915]input element to first update
the [22916]value accordingly, then [22917]fire an event named
[22918]input at the [22919]input element, with the [22920]bubbles and
[22921]composed attributes initialized to true, then [22922]fire an
event named [22923]change at the [22924]input element, with the
[22925]bubbles attribute initialized to true.
These events are not fired in response to changes made to the values of
form controls by scripts. (This is to make it easier to update the
values of form controls in response to the user manipulating the
controls, without having to then filter out the script's own changes to
avoid an infinite loop.)
These events are also not fired when the browser changes the values of
form controls as part of [22926]state restoration during navigation.
4.10.6 The button element
(BUTTON) ✔MDN
[22927]Element/button
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
[22939]Contexts in which this element can be used:
Where [22940]phrasing content is expected.
[22941]Content model:
[22942]Phrasing content, but there must be no [22943]interactive
content descendant and no descendant with the [22944]tabindex
attribute specified.
[22945]Tag omission in text/html:
Neither tag is omissible.
[22946]Content attributes:
[22947]Global attributes
[22948]command — Indicates to the targeted element which action
to take.
[22949]commandfor — Targets another element to be invoked.
[22950]disabled — Whether the form control is disabled
[22951]form — Associates the element with a [22952]form element
[22953]formaction — [22954]URL to use for [22955]form submission
[22956]formenctype — [22957]Entry list encoding type to use for
[22958]form submission
[22959]formmethod — Variant to use for [22960]form submission
[22961]formnovalidate — Bypass form control validation for
[22962]form submission
[22963]formtarget — [22964]Navigable for [22965]form submission
[22966]name — Name of the element to use for [22967]form
submission and in the [22968]form.elements API
[22969]popovertarget — Targets a popover element to toggle,
show, or hide
[22970]popovertargetaction — Indicates whether a targeted
popover element is to be toggled, shown, or hidden
[22971]type — Type of button
[22972]value — Value to be used for [22973]form submission
readonly attribute [23011]NodeList [23012]labels;
};
[23013]HTMLButtonElement includes [23014]PopoverInvokerElement;
The [23015]button element [23016]represents a button labeled by its
contents.
The element is a [23017]button.
The type attribute controls the behavior of the button when it is
activated. It is an [23018]enumerated attribute with the following
keywords and states:
Keyword State Brief description
submit Submit Button Submits the form.
reset Reset Button Resets the form.
button Button Does nothing.
The attribute's [23019]missing value default and [23020]invalid value
default are both the Auto state.
A [23021]button element is said to be a [23022]submit button if any of
the following are true:
* the [23023]type attribute is in the [23024]Auto state and both the
[23025]command and [23026]commandfor content attributes are not
present; or
* the [23027]type attribute is in the [23028]Submit Button state.
Constraint validation: If the element is not a [23029]submit button,
the element is [23030]barred from constraint validation.
If specified, the commandfor attribute value must be the [23031]ID of
an element in the same [23032]tree as the [23033]button with the
[23034]commandfor attribute.
The command attribute is an [23035]enumerated attribute with the
following keywords and states:
Keyword State Brief description
toggle-popover Toggle Popover Shows or hides the targeted
[23036]popover element.
show-popover Show Popover Shows the targeted [23037]popover element.
hide-popover Hide Popover Hides the targeted [23038]popover element.
close Close Closes the targeted [23039]dialog element.
show-modal Show Modal Opens the targeted [23040]dialog element as
modal.
A [23041]custom command keyword Custom Only dispatches the
[23042]command event on the targeted element.
The attribute's [23043]missing value default and [23044]invalid value
default are both the Unknown state.
A custom command keyword is a string that [23045]starts with "--".
A [23046]button element element's [23047]activation behavior given
event is:
1. If element is [23048]disabled, then return.
2. If element's [23049]node document is not [23050]fully active, then
return.
3. If element has a [23051]form owner:
1. If element is a [23052]submit button, then [23053]submit
element's [23054]form owner from element with
[23055]userInvolvement set to event's [23056]user navigation
involvement, and return.
2. If element's [23057]type attribute is in the [23058]Reset
Button state, then [23059]reset element's [23060]form owner,
and return.
3. If element's [23061]type attribute is in the [23062]Auto
state, then return.
4. Let target be the result of running element's [23063]get the
commandfor associated element.
5. If target is not null:
1. Let command be element's [23064]command attribute.
2. If command is in the [23065]Unknown state, then return.
3. Let isPopover be true if target's [23066]popover attribute is
not in the [23067]no popover state; otherwise false.
4. If isPopover is false and command is not in the [23068]Custom
state:
1. [23069]Assert: target's [23070]namespace is the
[23071]HTML namespace.
2. If this standard does not define [23072]is valid invoker
command steps for target's [23073]local name, then
return.
3. Otherwise, if the result of running target's
corresponding [23074]is valid invoker command steps given
command is false, then return.
5. Let continue be the result of [23075]firing an event named
[23076]command at target, using [23077]CommandEvent, with its
[23078]command attribute initialized to command, its
[23079]source attribute initialized to element, and its
[23080]cancelable and [23081]composed attributes initialized
to true.
[23082]DOM standard issue #1328 tracks how to better
standardize associated event data in a way which makes sense
on Events. Currently an event attribute initialized to a value
cannot also have a getter, and so an internal slot (or map of
additional fields) is required to properly specify this.
6. If continue is false, then return.
7. If target is not [23083]connected, then return.
8. If command is in the [23084]Custom state, then return.
9. If command is in the [23085]Hide Popover state:
1. If the result of running [23086]check popover validity
given target, true, false, and null is true, then run the
[23087]hide popover algorithm given target, true, true,
and false.
10. Otherwise, if command is in the [23088]Toggle Popover state:
1. If the result of running [23089]check popover validity
given target, false, false, and null is true, then run
the [23090]show popover algorithm given target, true,
true, and false.
2. Otheriwse, if the result of running [23091]check popover
validity given target, true, false, and null is true,
then run the [23092]hide popover algorithm given target,
true, true, and false.
11. Otherwise, if command is in the [23093]Show Popover state:
1. If the result of running [23094]check popover validity
given target, false, false, and null is true, then run
the [23095]show popover algorithm given target, true,
true, and false.
12. Otherwise, if this standard defines [23096]invoker command
steps for target's [23097]local name, then run the
corresponding [23098]invoker command steps given target,
element and command.
6. Otherwise, run the [23099]popover target attribute activation
behavior given element and event's [23100]target.
An [23101]HTML element can have specific is valid invoker command steps
and invoker command steps defined for the element's [23102]local name.
The [23103]form attribute is used to explicitly associate the
[23104]button element with its [23105]form owner. The [23106]name
attribute represents the element's name. The [23107]disabled attribute
is used to make the control non-interactive and to prevent its value
from being submitted. The [23108]formaction, [23109]formenctype,
[23110]formmethod, [23111]formnovalidate, and [23112]formtarget
attributes are [23113]attributes for form submission.
The [23114]formnovalidate attribute can be used to make submit buttons
that do not trigger the constraint validation.
The [23115]formaction, [23116]formenctype, [23117]formmethod,
[23118]formnovalidate, and [23119]formtarget must not be specified if
the element is not a [23120]submit button.
The commandForElement IDL attribute must [23121]reflect the element's
[23122]commandfor content attribute.
The command getter steps are:
1. Let command be [23123]this's [23124]command attribute.
2. If command is in the [23125]Custom state, then return command's
value.
3. If command is in the [23126]Unknown state, then return the empty
string.
4. Return the keword corresponding to the value of command.
The [23127]command setter steps are to set the [23128]command content
attribute to the given value.
The value attribute gives the element's value for the purposes of form
submission. The element's [23129]value is the value of the element's
[23130]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.
__________________________________________________________________
The value IDL attribute must [23131]reflect the content attribute of
the same name.
The type getter steps are:
1. If this is a [23132]submit button, then return "submit".
2. Let state be [23133]this's [23134]type attribute.
3. [23135]Assert: state is not in the [23136]Submit Button state.
4. If state is in the [23137]Auto state, then return "button".
5. Return the keyword value corresponding to state.
The [23138]type setter steps are to set the [23139]type content
attribute to the given value.
The [23140]willValidate, [23141]validity, and [23142]validationMessage
IDL attributes, and the [23143]checkValidity(),
[23144]reportValidity(), and [23145]setCustomValidity() methods, are
part of the [23146]constraint validation API. The [23147]labels IDL
attribute provides a list of the element's [23148]labels. The
[23149]disabled, [23150]form, and [23151]name IDL attributes are part
of the element's forms API.
The following button is labeled "Show hint" and pops up a dialog box
when activated:
The following shows how [23152]buttons can use [23153]commandfor to
show and hide an element with the [23154]popover attribute when
activated:
The following shows how buttons can use [23155]commandfor with a
[23156]custom command keyword on an element, demonstrating how one
could use custom commands for unspecified behavior:
4.10.7 The select element
(BUTTON) ✔MDN
[23157]Element/select
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
[23170]Contexts in which this element can be used:
Where [23171]phrasing content is expected.
[23172]Content model:
Zero or more [23173]option, [23174]optgroup, [23175]hr, and
[23176]script-supporting elements.
[23177]Tag omission in text/html:
Neither tag is omissible.
[23178]Content attributes:
[23179]Global attributes
[23180]autocomplete — Hint for form autofill feature
[23181]disabled — Whether the form control is disabled
[23182]form — Associates the element with a [23183]form element
[23184]multiple — Whether to allow multiple values
[23185]name — Name of the element to use for [23186]form
submission and in the [23187]form.elements API
[23188]required — Whether the control is required for
[23189]form submission
[23190]size — Size of the control
[23191]Accessibility considerations:
If the element has a [23192]multiple attribute or a [23193]size
attribute with a value > 1: [23194]for authors; [23195]for
implementers.
Otherwise: [23196]for authors; [23197]for implementers.
The multiple attribute is a [23252]boolean attribute. If the attribute
is present, then the [23253]select element [23254]represents a control
for selecting zero or more options from the [23255]list of options. If
the attribute is absent, then the [23256]select element
[23257]represents a control for selecting a single option from the
[23258]list of options.
(BUTTON) ✔MDN
[23259]Attributes/size
Support in all current engines.
Firefox1+Safari3+Chrome1+
__________________________________________________________________
The size attribute gives the number of options to show to the user. The
[23260]size attribute, if specified, must have a value that is a
[23261]valid non-negative integer greater than zero.
The display size of a [23262]select element is the result of applying
the [23263]rules for parsing non-negative integers to the value of
element's [23264]size attribute, if it has one and parsing it is
successful. If applying those rules to the attribute's value is not
successful, or if the [23265]size attribute is absent, then the
element's [23266]display size is 4 if the element's [23267]multiple
content attribute is present, and 1 otherwise.
The list of options for a [23268]select element consists of all the
[23269]option element children of the [23270]select element, and all
the [23271]option element children of all the [23272]optgroup element
children of the [23273]select element, in [23274]tree order.
(BUTTON) ✔MDN
[23275]Attributes/required
Support in all current engines.
Firefox4+Safari5.1+Chrome10+
__________________________________________________________________
The required attribute is a [23276]boolean attribute. When specified,
the user will be required to select a value before submitting the form.
If a [23277]select element has a [23278]required attribute specified,
does not have a [23279]multiple attribute specified, and has a
[23280]display size of 1; and if the [23281]value of the first
[23282]option element in the [23283]select element's [23284]list of
options (if any) is the empty string, and that [23285]option element's
parent node is the [23286]select element (and not an [23287]optgroup
element), then that [23288]option is the [23289]select element's
placeholder label option.
If a [23290]select element has a [23291]required attribute specified,
does not have a [23292]multiple attribute specified, and has a
[23293]display size of 1, then the [23294]select element must have a
[23295]placeholder label option.
In practice, the requirement stated in the paragraph above can only
apply when a [23296]select element does not have a [23297]size
attribute with a value greater than 1.
Constraint validation: If the element has its [23298]required attribute
specified, and either none of the [23299]option elements in the
[23300]select element's [23301]list of options have their
[23302]selectedness set to true, or the only [23303]option element in
the [23304]select element's [23305]list of options with its
[23306]selectedness set to true is the [23307]placeholder label option,
then the element is [23308]suffering from being missing.
If the [23309]multiple attribute is absent, and the element is not
[23310]disabled, then the user agent should allow the user to pick an
[23311]option element in its [23312]list of options that is itself not
[23313]disabled. Upon this [23314]option element being picked (either
through a click, or through unfocusing the element after changing its
value, or through a [23315]menu command, or through any other
mechanism), and before the relevant user interaction event is queued
(e.g. before the [23316]click event), the user agent must set the
[23317]selectedness of the picked [23318]option element to true, set
its [23319]dirtiness to true, and then [23320]send select update
notifications.
If the [23321]multiple attribute is absent, whenever an [23322]option
element in the [23323]select element's [23324]list of options has its
[23325]selectedness set to true, and whenever an [23326]option element
with its [23327]selectedness set to true is added to the [23328]select
element's [23329]list of options, the user agent must set the
[23330]selectedness of all the other [23331]option elements in its
[23332]list of options to false.
If the [23333]multiple attribute is absent and the element's
[23334]display size is greater than 1, then the user agent should also
allow the user to request that the [23335]option whose
[23336]selectedness is true, if any, be unselected. Upon this request
being conveyed to the user agent, and before the relevant user
interaction event is queued (e.g. before the [23337]click event), the
user agent must set the [23338]selectedness of that [23339]option
element to false, set its [23340]dirtiness to true, and then
[23341]send select update notifications.
The selectedness setting algorithm, given a [23342]select element
element, is to run the following steps:
1. If element's [23343]multiple attribute is absent, and element's
[23344]display size is 1, and no [23345]option elements in the
element's [23346]list of options have their [23347]selectedness set
to true, then set the [23348]selectedness of the first
[23349]option element in the [23350]list of options in [23351]tree
order that is not [23352]disabled, if any, to true, and return.
2. If element's [23353]multiple attribute is absent, and two or more
[23354]option elements in element's [23355]list of options have
their [23356]selectedness set to true, then set the
[23357]selectedness of all but the last [23358]option element with
its [23359]selectedness set to true in the [23360]list of options
in [23361]tree order to false.
The [23362]option [23363]HTML element insertion steps, given
insertedNode, are:
1. If insertedNode's parent is a [23364]select element, or
insertedNode's parent is an [23365]optgroup element whose parent is
a [23366]select element, then run that [23367]select element's
[23368]selectedness setting algorithm.
The [23369]option [23370]HTML element removing steps, given removedNode
and oldParent, are:
1. If oldParent is a [23371]select element, or oldParent is an
[23372]optgroup element whose parent is a [23373]select element,
then run that [23374]select element's [23375]selectedness setting
algorithm.
The [23376]option [23377]HTML element moving steps, given movedNode and
oldParent, are:
1. Run the [23378]option [23379]HTML element removing steps given
movedNode and oldParent.
2. Run the [23380]option [23381]HTML element insertion steps given
movedNode.
The [23382]optgroup [23383]HTML element removing steps, given
removedNode and oldParent, are:
1. If oldParent is a [23384]select element and removedNode has an
[23385]option child, then run oldParent's [23386]selectedness
setting algorithm.
The [23387]optgroup [23388]HTML element moving steps, given movedNode
and oldParent, are:
1. Run the [23389]optgroup [23390]HTML element removing steps given
movedNode and oldParent.
If an [23391]option element in the [23392]list of options asks for a
reset, then run that [23393]select element's [23394]selectedness
setting algorithm.
If the [23395]multiple attribute is present, and the element is not
[23396]disabled, then the user agent should allow the user to toggle
the [23397]selectedness of the [23398]option elements in its
[23399]list of options that are themselves not [23400]disabled. Upon
such an element being [23401]toggled (either through a click, or
through a [23402]menu command, or any other mechanism), and before the
relevant user interaction event is queued (e.g. before a related
[23403]click event), the [23404]selectedness of the [23405]option
element must be changed (from true to false or false to true), the
[23406]dirtiness of the element must be set to true, and the user agent
must [23407]send select update notifications.
When the user agent is to send select update notifications,
[23408]queue an element task on the [23409]user interaction task source
given the [23410]select element to run these steps:
1. Set the [23411]select element's [23412]user validity to true.
2. [23413]Fire an event named [23414]input at the [23415]select
element, with the [23416]bubbles and [23417]composed attributes
initialized to true.
3. [23418]Fire an event named [23419]change at the [23420]select
element, with the [23421]bubbles attribute initialized to true.
The [23422]reset algorithm for a [23423]select element selectElement
is:
1. Set selectElement's [23424]user validity to false.
2. [23425]For each optionElement of selectElement's [23426]list of
options:
1. If optionElement has a [23427]selected attribute, then set
optionElement's [23428]selectedness to true; otherwise set it
to false.
2. Set optionElement's [23429]dirtiness to false.
3. Run the [23430]selectedness setting algorithm given selectElement.
The [23431]form attribute is used to explicitly associate the
[23432]select element with its [23433]form owner. The [23434]name
attribute represents the element's name. The [23435]disabled attribute
is used to make the control non-interactive and to prevent its value
from being submitted. The [23436]autocomplete attribute controls how
the user agent provides autofill behavior.
A [23437]select element that is not [23438]disabled is [23439]mutable.
Firefox Android?Safari iOS1+Chrome Android?WebView
Android?Samsung Internet?Opera Android10.1+
Returns "select-multiple" if the element has a [23442]multiple
attribute, and "select-one" otherwise.
Firefox Android?Safari iOS1+Chrome Android?WebView
Android?Samsung Internet?Opera Android12.1+
Returns an [23445]HTMLOptionsCollection of the [23446]list of
options.
select.[23447]length [ = value ]
Returns the number of elements in the [23448]list of options.
When set to a smaller number, truncates the number of
[23449]option elements in the [23450]select.
When set to a greater number, adds new blank [23451]option
elements to the [23452]select.
Firefox Android?Safari iOS1+Chrome Android?WebView
Android?Samsung Internet?Opera Android12.1+
Returns the first item with [23459]ID or [23460]name name from
the [23461]list of options.
Returns null if no element with that [23462]ID could be found.
Firefox Android?Safari iOS1+Chrome Android?WebView
Android?Samsung Internet?Opera Android12.1+
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 [23465]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 [23466]"HierarchyRequestError"
[23467]DOMException if element is an ancestor of the element
into which it is to be inserted.
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android10.1+
Returns an [23470]HTMLCollection of the [23471]list of options
that are selected.
Firefox Android?Safari iOS1+Chrome Android?WebView
Android?Samsung Internet?Opera Android12.1+
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.[23474]value [ = value ]
Returns the [23475]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.
select.[23476]showPicker()
Shows any applicable picker UI for select, so that the user can
select a value.
Throws an [23477]"InvalidStateError" [23478]DOMException if
select is not [23479]mutable.
Throws a [23480]"NotAllowedError" [23481]DOMException if called
without [23482]transient user activation.
Throws a [23483]"SecurityError" [23484]DOMException if select is
inside a cross-origin [23485]iframe.
Throws a [23486]"NotSupportedError" [23487]DOMException if
select is not [23488]being rendered.
The type IDL attribute, on getting, must return the string "select-one"
if the [23489]multiple attribute is absent, and the string
"select-multiple" if the [23490]multiple attribute is present.
The options IDL attribute must return an [23491]HTMLOptionsCollection
rooted at the [23492]select node, whose filter matches the elements in
the [23493]list of options.
The [23494]options collection is also mirrored on the
[23495]HTMLSelectElement object. The [23496]supported property indices
at any instant are the indices supported by the object returned by the
[23497]options attribute at that instant.
The length IDL attribute must return the number of nodes
[23498]represented by the [23499]options collection. On setting, it
must act like the attribute of the same name on the [23500]options
collection.
The item(index) method must return the value returned by [23501]the
method of the same name on the [23502]options collection, when invoked
with the same argument.
The namedItem(name) method must return the value returned by [23503]the
method of the same name on the [23504]options collection, when invoked
with the same argument.
When the user agent is to [23505]set the value of a new indexed
property or [23506]set the value of an existing indexed property for a
[23507]select element, it must instead run [23508]the corresponding
algorithm on the [23509]select element's [23510]options collection.
Similarly, the add(element, before) method must act like its namesake
method on that same [23511]options collection.
(BUTTON) ✔MDN
[23512]HTMLSelectElement/remove
Support in all current engines.
Firefox1+Safari3+Chrome1+
__________________________________________________________________
The remove() method must act like its namesake method on that same
[23513]options collection when it has arguments, and like its namesake
method on the [23514]ChildNode interface implemented by the
[23515]HTMLSelectElement ancestor interface [23516]Element when it has
no arguments.
The selectedOptions IDL attribute must return an [23517]HTMLCollection
rooted at the [23518]select node, whose filter matches the elements in
the [23519]list of options that have their [23520]selectedness set to
true.
The selectedIndex IDL attribute, on getting, must return the
[23521]index of the first [23522]option element in the [23523]list of
options in [23524]tree order that has its [23525]selectedness set to
true, if any. If there isn't one, then it must return −1.
On setting, the [23526]selectedIndex attribute must set the
[23527]selectedness of all the [23528]option elements in the
[23529]list of options to false, and then the [23530]option element in
the [23531]list of options whose [23532]index is the given new value,
if any, must have its [23533]selectedness set to true and its
[23534]dirtiness set to true.
This can result in no element having a [23535]selectedness set to true
even in the case of the [23536]select element having no [23537]multiple
attribute and a [23538]display size of 1.
The value IDL attribute, on getting, must return the [23539]value of
the first [23540]option element in the [23541]list of options in
[23542]tree order that has its [23543]selectedness set to true, if any.
If there isn't one, then it must return the empty string.
On setting, the [23544]value attribute must set the [23545]selectedness
of all the [23546]option elements in the [23547]list of options to
false, and then the first [23548]option element in the [23549]list of
options, in [23550]tree order, whose [23551]value is equal to the given
new value, if any, must have its [23552]selectedness set to true and
its [23553]dirtiness set to true.
This can result in no element having a [23554]selectedness set to true
even in the case of the [23555]select element having no [23556]multiple
attribute and a [23557]display size of 1.
The multiple, required, and size IDL attributes must [23558]reflect the
respective content attributes of the same name. The [23559]size IDL
attribute has a [23560]default value of 0.
For historical reasons, the default value of the [23561]size IDL
attribute does not return the actual size used, which, in the absence
of the [23562]size content attribute, is either 1 or 4 depending on the
presence of the [23563]multiple attribute.
The [23564]willValidate, [23565]validity, and [23566]validationMessage
IDL attributes, and the [23567]checkValidity(),
[23568]reportValidity(), and [23569]setCustomValidity() methods, are
part of the [23570]constraint validation API. The [23571]labels IDL
attribute provides a list of the element's [23572]labels. The
[23573]disabled, [23574]form, and [23575]name IDL attributes are part
of the element's forms API.
The following example shows how a [23576]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.
When there is no default option, a placeholder can be used instead:
Here, the user is offered a set of options from which they can select
any number. By default, all five options are selected.
Sometimes, a user has to select one or more items. This example shows
such an interface.
Occasionally it can be useful to have a separator:
The [23599]datalist element represents a set of [23600]option elements
that represent predefined options for other controls. In the rendering,
the [23601]datalist element [23602]represents nothing and it, along
with its children, should be hidden.
The [23603]datalist element can be used in two ways. In the simplest
case, the [23604]datalist element has just [23605]option element
children.
In the more elaborate case, the [23606]datalist element can be given
contents that are to be displayed for down-level clients that don't
support [23607]datalist. In this case, the [23608]option elements are
provided inside a [23609]select element inside the [23610]datalist
element.
The [23611]datalist element is hooked up to an [23612]input element
using the [23613]list attribute on the [23614]input element.
Each [23615]option element that is a descendant of the [23616]datalist
element, that is not [23617]disabled, and whose [23618]value is a
string that isn't the empty string, represents a suggestion. Each
suggestion has a [23619]value and a [23620]label.
datalist.[23621]options
Returns an [23622]HTMLCollection of the [23623]option elements
of the [23624]datalist element.
The options IDL attribute must return an [23625]HTMLCollection rooted
at the [23626]datalist node, whose filter matches [23627]option
elements.
Constraint validation: If an element has a [23628]datalist element
ancestor, it is [23629]barred from constraint validation.
4.10.9 The optgroup element
(BUTTON) ✔MDN
[23630]Element/optgroup
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
[23633]Contexts in which this element can be used:
As a child of a [23634]select element.
[23635]Content model:
Zero or more [23636]option and [23637]script-supporting
elements.
[23638]Tag omission in text/html:
An [23639]optgroup element's [23640]end tag can be omitted if
the [23641]optgroup element is immediately followed by another
[23642]optgroup element, if it is immediately followed by an
[23643]hr element, or if there is no more content in the parent
element.
[23644]Content attributes:
[23645]Global attributes
[23646]disabled — Whether the form control is disabled
[23647]label — User-visible label
The [23658]optgroup element [23659]represents a group of [23660]option
elements with a common label.
The element's group of [23661]option elements consists of the
[23662]option elements that are children of the [23663]optgroup
element.
When showing [23664]option elements in [23665]select elements, user
agents should show the [23666]option elements of such groups as being
related to each other and separate from other [23667]option elements.
(BUTTON) ✔MDN
[23668]Attributes/disabled
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
The disabled attribute is a [23669]boolean attribute and can be used to
[23670]disable a group of [23671]option elements together.
The label attribute must be specified. Its value gives the name of the
group, for the purposes of the user interface. User agents should use
this attribute's value when labeling the group of [23672]option
elements in a [23673]select element.
The disabled and label attributes must [23674]reflect the respective
content attributes of the same name.
There is no way to select an [23675]optgroup element. Only
[23676]option elements can be selected. An [23677]optgroup element
merely provides a label for a group of [23678]option elements.
The following snippet shows how a set of lessons from three courses
could be offered in a [23679]select drop-down widget:
4.10.10 The option element
(BUTTON) ✔MDN
[23680]Element/option
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
[23683]Contexts in which this element can be used:
As a child of a [23684]select element.
As a child of a [23685]datalist element.
As a child of an [23686]optgroup element.
[23687]Content model:
If the element has a [23688]label attribute and a [23689]value
attribute: [23690]Nothing.
If the element has a [23691]label attribute but no [23692]value
attribute: [23693]Text.
If the element has no [23694]label attribute and is not a child
of a [23695]datalist element: [23696]Text that is not
[23697]inter-element whitespace.
If the element has no [23698]label attribute and is a child of a
[23699]datalist element: [23700]Text.
[23701]Tag omission in text/html:
An [23702]option element's [23703]end tag can be omitted if the
[23704]option element is immediately followed by another
[23705]option element, if it is immediately followed by an
[23706]optgroup element, if it is immediately followed by an
[23707]hr element, or if there is no more content in the parent
element.
[23708]Content attributes:
[23709]Global attributes
[23710]disabled — Whether the form control is disabled
[23711]label — User-visible label
[23712]selected — Whether the option is selected by default
[23713]value — Value to be used for [23714]form submission
[[23734]CEReactions] attribute DOMString [23735]text;
readonly attribute long [23736]index;
};
The [23737]option element [23738]represents an option in a
[23739]select element or as part of a list of suggestions in a
[23740]datalist element.
In certain circumstances described in the definition of the
[23741]select element, an [23742]option element can be a [23743]select
element's [23744]placeholder label option. A [23745]placeholder label
option does not represent an actual option, but instead represents a
label for the [23746]select control.
(BUTTON) ✔MDN
[23747]Attributes/disabled
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
The disabled attribute is a [23748]boolean attribute. An [23749]option
element is disabled if its [23750]disabled attribute is present or if
it is a child of an [23751]optgroup element whose [23752]disabled
attribute is present.
An [23753]option element that is [23754]disabled must prevent any
[23755]click events that are [23756]queued on the [23757]user
interaction task source from being dispatched on the element.
The label attribute provides a label for element. The label of an
[23758]option element is the value of the [23759]label content
attribute, if there is one and its value is not the empty string, or,
otherwise, the value of the element's [23760]text IDL attribute.
The [23761]label content attribute, if specified, must not be empty.
The value attribute provides a value for element. The value of an
[23762]option element is the value of the [23763]value content
attribute, if there is one, or, if there is not, the value of the
element's [23764]text IDL attribute.
The selected attribute is a [23765]boolean attribute. It represents the
default [23766]selectedness of the element.
The dirtiness of an [23767]option element is a boolean state, initially
false. It controls whether adding or removing the [23768]selected
content attribute has any effect.
The selectedness of an [23769]option element is a boolean state,
initially false. Except where otherwise specified, when the element is
created, its [23770]selectedness must be set to true if the element has
a [23771]selected attribute. Whenever an [23772]option element's
[23773]selected attribute is added, if its [23774]dirtiness is false,
its [23775]selectedness must be set to true. Whenever an [23776]option
element's [23777]selected attribute is removed, if its [23778]dirtiness
is false, its [23779]selectedness must be set to false.
The [23780]Option() constructor, when called with three or fewer
arguments, overrides the initial state of the [23781]selectedness state
to always be false even if the third argument is true (implying that a
[23782]selected attribute is to be set). The fourth argument can be
used to explicitly set the initial [23783]selectedness state when using
the constructor.
A [23784]select element whose [23785]multiple attribute is not
specified must not have more than one descendant [23786]option element
with its [23787]selected attribute set.
An [23788]option element's index is the number of [23789]option
elements that are in the same [23790]list of options but that come
before it in [23791]tree order. If the [23792]option element is not in
a [23793]list of options, then the [23794]option element's [23795]index
is zero.
option.[23796]selected
Returns true if the element is selected, and false otherwise.
Can be set, to override the current state of the element.
option.[23797]index
Returns the index of the element in its [23798]select element's
[23799]options list.
option.[23800]form
Returns the element's [23801]form element, if any, or null
otherwise.
option.[23802]text
Same as [23803]textContent, except that spaces are collapsed and
[23804]script elements are skipped.
option = new [23805]Option([ text [, value [, defaultSelected [,
selected ] ] ] ])
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android12.1+
Returns a new [23807]option element.
The text argument sets the contents of the element.
The value argument sets the [23808]value attribute.
The defaultSelected argument sets the [23809]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 disabled IDL attribute must [23810]reflect the content attribute of
the same name. The defaultSelected IDL attribute must [23811]reflect
the [23812]selected content attribute.
The label IDL attribute, on getting, if there is a [23813]label content
attribute, must return that attribute's value; otherwise, it must
return the element's [23814]label. On setting, the element's
[23815]label content attribute must be set to the new value.
The value IDL attribute, on getting, must return the element's
[23816]value. On setting, the element's [23817]value content attribute
must be set to the new value.
The selected IDL attribute, on getting, must return true if the
element's [23818]selectedness is true, and false otherwise. On setting,
it must set the element's [23819]selectedness to the new value, set its
[23820]dirtiness to true, and then cause the element to [23821]ask for
a reset.
The index IDL attribute must return the element's [23822]index.
The text IDL attribute, on getting, must return the result of
[23823]stripping and collapsing ASCII whitespace from the concatenation
of [23824]data of all the [23825]Text node descendants of the
[23826]option element, in [23827]tree order, excluding any that are
descendants of descendants of the [23828]option element that are
themselves [23829]script or [23830]SVG script elements.
The [23831]text attribute's setter must [23832]string replace all with
the given value within this element.
The form IDL attribute's behavior depends on whether the [23833]option
element is in a [23834]select element or not. If the [23835]option has
a [23836]select element as its parent, or has an [23837]optgroup
element as its parent and that [23838]optgroup element has a
[23839]select element as its parent, then the [23840]form IDL attribute
must return the same value as the [23841]form IDL attribute on that
[23842]select element. Otherwise, it must return null.
A legacy factory function is provided for creating
[23843]HTMLOptionElement objects (in addition to the factory methods
from DOM such as [23844]createElement()): Option(text, value,
defaultSelected, selected). When invoked, the legacy factory function
must perform the following steps:
1. Let document be the [23845]current global object's
[23846]associated Document.
2. Let option be the result of [23847]creating an element given
document, "option", and the [23848]HTML namespace.
3. If text is not the empty string, then append to option a new
[23849]Text node whose data is text.
4. If value is given, then [23850]set an attribute value for option
using "[23851]value" and value.
5. If defaultSelected is true, then [23852]set an attribute value for
option using "[23853]selected" and the empty string.
6. If selected is true, then set option's [23854]selectedness to true;
otherwise set its [23855]selectedness to false (even if
defaultSelected is true).
7. Return option.
4.10.11 The textarea element
(BUTTON) ✔MDN
[23856]Element/textarea
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
[23869]Contexts in which this element can be used:
Where [23870]phrasing content is expected.
[23871]Content model:
[23872]Text.
[23873]Tag omission in text/html:
Neither tag is omissible.
[23874]Content attributes:
[23875]Global attributes
[23876]autocomplete — Hint for form autofill feature
[23877]cols — Maximum number of characters per line
[23878]dirname — Name of form control to use for sending the
element's [23879]directionality in [23880]form submission
[23881]disabled — Whether the form control is disabled
[23882]form — Associates the element with a [23883]form element
[23884]maxlength — Maximum [23885]length of value
[23886]minlength — Minimum [23887]length of value
[23888]name — Name of the element to use for [23889]form
submission and in the [23890]form.elements API
[23891]placeholder — User-visible label to be placed within the
form control
[23892]readonly — Whether to allow the value to be edited by the
user
[23893]required — Whether the control is required for
[23894]form submission
[23895]rows — Number of lines to show
[23896]wrap — How the value of the form control is to be wrapped
for [23897]form submission
undefined [23945]select();
attribute unsigned long [23946]selectionStart;
attribute unsigned long [23947]selectionEnd;
attribute DOMString [23948]selectionDirection;
undefined [23949]setRangeText(DOMString replacement);
undefined [23950]setRangeText(DOMString replacement, unsigned long start, unsi
gned long end, optional [23951]SelectionMode selectionMode = "preserve");
undefined [23952]setSelectionRange(unsigned long start, unsigned long end, opt
ional DOMString direction);
};
The [23953]textarea element [23954]represents a multiline plain text
edit control for the element's raw value. The contents of the control
represent the control's default value.
The [23955]raw value of a [23956]textarea control must be initially the
empty string.
This element [23957]has rendering requirements involving the
bidirectional algorithm.
The readonly attribute is a [23958]boolean attribute used to control
whether the text can be edited by the user or not.
In this example, a text control is marked read-only because it
represents a read-only file:
Filename: /etc/bash.bashrc
# 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" ] && return
...
Constraint validation: If the [23959]readonly attribute is specified on
a [23960]textarea element, the element is [23961]barred from constraint
validation.
A [23962]textarea element is [23963]mutable if it is neither
[23964]disabled nor has a [23965]readonly attribute specified.
When a [23966]textarea is [23967]mutable, its [23968]raw value should
be editable by the user: the user agent should allow the user to edit,
insert, and remove text, and to insert and remove line breaks in the
form of U+000A LINE FEED (LF) characters. Any time the user causes the
element's [23969]raw value to change, the user agent must [23970]queue
an element task on the [23971]user interaction task source given the
[23972]textarea element to [23973]fire an event named [23974]input at
the [23975]textarea element, with the [23976]bubbles and
[23977]composed attributes initialized to true. User agents may wait
for a suitable break in the user's interaction before queuing the task;
for example, a user agent could wait for the user to have not hit a key
for 100ms, so as to only fire the event when the user pauses, instead
of continuously for each keystroke.
A [23978]textarea element's [23979]dirty value flag must be set to true
whenever the user interacts with the control in a way that changes the
[23980]raw value.
The [23981]cloning steps for [23982]textarea elements given node, copy,
and subtree are to propagate the [23983]raw value and [23984]dirty
value flag from node to copy.
The [23985]children changed steps for [23986]textarea elements must, if
the element's [23987]dirty value flag is false, set the element's
[23988]raw value to its [23989]child text content.
The [23990]reset algorithm for [23991]textarea elements is to set the
[23992]user validity to false, [23993]dirty value flag back to false,
and set the [23994]raw value of element to its [23995]child text
content.
When a [23996]textarea element is popped off the [23997]stack of open
elements of an [23998]HTML parser or [23999]XML parser, then the user
agent must invoke the element's [24000]reset algorithm.
If the element is [24001]mutable, the user agent should allow the user
to change the writing direction of the element, setting it either to a
left-to-right writing direction or a right-to-left writing direction.
If the user does so, the user agent must then run the following steps:
1. Set the element's [24002]dir attribute to "[24003]ltr" if the user
selected a left-to-right writing direction, and "[24004]rtl" if the
user selected a right-to-left writing direction.
2. [24005]Queue an element task on the [24006]user interaction task
source given the [24007]textarea element to [24008]fire an event
named [24009]input at the [24010]textarea element, with the
[24011]bubbles and [24012]composed attributes initialized to true.
The cols attribute specifies the expected maximum number of characters
per line. If the [24013]cols attribute is specified, its value must be
a [24014]valid non-negative integer greater than zero. If applying the
[24015]rules for parsing non-negative integers to the attribute's value
results in a number greater than zero, then the element's character
width is that value; otherwise, it is 20.
The user agent may use the [24016]textarea element's [24017]character
width as a hint to the user as to how many characters the server
prefers per line (e.g. for visual user agents by making the width of
the control be that many characters). In visual renderings, the user
agent should wrap the user's input in the rendering so that each line
is no wider than this number of characters.
The rows attribute specifies the number of lines to show. If the
[24018]rows attribute is specified, its value must be a [24019]valid
non-negative integer greater than zero. If applying the [24020]rules
for parsing non-negative integers to the attribute's value results in a
number greater than zero, then the element's character height is that
value; otherwise, it is 2.
Visual user agents should set the height of the control to the number
of lines given by [24021]character height.
The wrap attribute is an [24022]enumerated attribute with the following
keywords and states:
Keyword State Brief description
soft Soft Text is not to be wrapped when submitted (though can still be
wrapped in the rendering).
hard Hard Text is to have newlines added by the user agent so that the
text is wrapped when it is submitted.
The attribute's [24023]missing value default and [24024]invalid value
default are both the [24025]Soft state.
If the element's [24026]wrap attribute is in the [24027]Hard state, the
[24028]cols attribute must be specified.
For historical reasons, the element's value is normalized in three
different ways for three different purposes. The [24029]raw value is
the value as it was originally set. It is not normalized. The
[24030]API value is the value used in the [24031]value IDL attribute,
[24032]textLength IDL attribute, and by the [24033]maxlength and
[24034]minlength content attributes. It is normalized so that line
breaks use U+000A LINE FEED (LF) characters. Finally, there is the
[24035]value, as used in form submission and other processing models in
this specification. It is normalized as for the [24036]API value, and
in addition, if necessary given the element's [24037]wrap attribute,
additional line breaks are inserted to wrap the text at the given
width.
The algorithm for obtaining the element's [24038]API value is to return
the element's [24039]raw value, with [24040]newlines normalized.
The element's [24041]value is defined to be the element's [24042]API
value with the [24043]textarea wrapping transformation applied. The
textarea wrapping transformation is the following algorithm, as applied
to a string:
1. If the element's [24044]wrap attribute is in the [24045]Hard state,
insert U+000A LINE FEED (LF) characters into the string using an
[24046]implementation-defined algorithm so that each line has no
more than [24047]character width characters. For the purposes of
this requirement, lines are delimited by the start of the string,
the end of the string, and U+000A LINE FEED (LF) characters.
The maxlength attribute is a [24048]form control maxlength attribute.
If the [24049]textarea element has a [24050]maximum allowed value
length, then the element's children must be such that the [24051]length
of the value of the element's [24052]descendant text content with
[24053]newlines normalized is less than or equal to the element's
[24054]maximum allowed value length.
The minlength attribute is a [24055]form control minlength attribute.
The required attribute is a [24056]boolean attribute. When specified,
the user will be required to enter a value before submitting the form.
Constraint validation: If the element has its [24057]required attribute
specified, and the element is [24058]mutable, and the element's
[24059]value is the empty string, then the element is [24060]suffering
from being missing.
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 [24061]placeholder attribute should not be used as an alternative
to a [24062]label. For a longer hint or other advisory text, the
[24063]title attribute is more appropriate.
These mechanisms are very similar but subtly different: the hint given
by the control's [24064]label is shown at all times; the short hint
given in the [24065]placeholder attribute is shown before the user
enters a value; and the hint in the [24066]title attribute is shown
when the user requests further help.
User agents should present this hint to the user when the element's
[24067]value is the empty string and the control is not [24068]focused
(e.g. by displaying it inside a blank unfocused control). All U+000D
CARRIAGE RETURN U+000A LINE FEED character pairs (CRLF) in the hint, as
well as all other U+000D CARRIAGE RETURN (CR) and U+000A LINE FEED (LF)
characters in the hint, must be treated as line breaks when rendering
the hint.
If a user agent normally doesn't show this hint to the user when the
control is [24069]focused, then the user agent should nonetheless show
the hint for the control if it was focused as a result of the
[24070]autofocus attribute, since in that case the user will not have
had an opportunity to examine the control before focusing it.
The [24071]name attribute represents the element's name. The
[24072]dirname attribute controls how the element's
[24073]directionality is submitted. The [24074]disabled attribute is
used to make the control non-interactive and to prevent its value from
being submitted. The [24075]form attribute is used to explicitly
associate the [24076]textarea element with its [24077]form owner. The
[24078]autocomplete attribute controls how the user agent provides
autofill behavior.
textarea.[24079]type
Returns the string "textarea".
textarea.[24080]value
Returns the current value of the element.
Can be set, to change the value.
The cols, placeholder, required, rows, and wrap IDL attributes must
[24081]reflect the respective content attributes of the same name. The
[24082]cols and [24083]rows attributes are [24084]limited to only
positive numbers with fallback. The [24085]cols IDL attribute's
[24086]default value is 20. The [24087]rows IDL attribute's
[24088]default value is 2. The dirName IDL attribute must
[24089]reflect the [24090]dirname content attribute. The maxLength IDL
attribute must [24091]reflect the [24092]maxlength content attribute,
[24093]limited to only non-negative numbers. The minLength IDL
attribute must [24094]reflect the [24095]minlength content attribute,
[24096]limited to only non-negative numbers. The readOnly IDL attribute
must [24097]reflect the [24098]readonly content attribute.
The type IDL attribute must return the value "textarea".
The defaultValue attribute's getter must return the element's
[24099]child text content.
The [24100]defaultValue attribute's setter must [24101]string replace
all with the given value within this element.
The value IDL attribute must, on getting, return the element's
[24102]API value. On setting, it must perform the following steps:
1. Let oldAPIValue be this element's [24103]API value.
2. Set this element's [24104]raw value to the new value.
3. Set this element's [24105]dirty value flag to true.
4. If the new [24106]API value is different from oldAPIValue, then
move the [24107]text entry cursor position to the end of the text
control, unselecting any selected text and [24108]resetting the
selection direction to "none".
The textLength IDL attribute must return the [24109]length of the
element's [24110]API value.
The [24111]willValidate, [24112]validity, and [24113]validationMessage
IDL attributes, and the [24114]checkValidity(),
[24115]reportValidity(), and [24116]setCustomValidity() methods, are
part of the [24117]constraint validation API. The [24118]labels IDL
attribute provides a list of the element's [24119]labels. The
[24120]select(), [24121]selectionStart, [24122]selectionEnd,
[24123]selectionDirection, [24124]setRangeText(), and
[24125]setSelectionRange() methods and IDL attributes expose the
element's text selection. The [24126]disabled, [24127]form, and
[24128]name IDL attributes are part of the element's forms API.
Here is an example of a [24129]textarea being used for unrestricted
free-form text input in a form:
If you have any comments, please let us know:
To specify a maximum length for the comments, one can use the
[24130]maxlength attribute:
If you have any short comments, please let us know:
To give a default value, text can be included inside the element:
If you have any comments, please let us know:
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:
Regarding your letter dated ...
...
Yours Sincerely,
...
A placeholder can be given as well, to suggest the basic form to the
user, without providing an explicit template:
To have the browser submit [24131]the directionality of the element
along with the value, the [24132]dirname attribute can be specified:
If you have any comments, please let us know (you may use either English or H
ebrew for your comments):
4.10.12 The output element
(BUTTON) ✔MDN
[24133]Element/output
Support in all current engines.
Firefox4+Safari7+Chrome10+
__________________________________________________________________
[24144]Contexts in which this element can be used:
Where [24145]phrasing content is expected.
[24146]Content model:
[24147]Phrasing content.
[24148]Tag omission in text/html:
Neither tag is omissible.
[24149]Content attributes:
[24150]Global attributes
[24151]for — Specifies controls from which the output was
calculated
[24152]form — Associates the element with a [24153]form element
[24154]name — Name of the element to use in the
[24155]form.elements API.
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 [24187]for attribute, if specified, must contain a
string consisting of an [24188]unordered set of unique space-separated
tokens, none of which are [24189]identical to another token and each of
which must have the value of an [24190]ID of an element in the same
[24191]tree.
The [24192]form attribute is used to explicitly associate the
[24193]output element with its [24194]form owner. The [24195]name
attribute represents the element's name. The [24196]output element is
associated with a form so that it can be easily [24197]referenced from
the event handlers of form controls; the element's value itself is not
submitted when the form is submitted.
The element has a default value override (null or a string). Initially
it must be null.
The element's default value is determined by the following steps:
1. If this element's [24198]default value override is non-null, then
return it.
2. Return this element's [24199]descendant text content.
The [24200]reset algorithm for [24201]output elements is to run these
steps:
1. [24202]String replace all with this element's [24203]default value
within this element.
2. Set this element's [24204]default value override to null.
output.[24205]value [ = value ]
Returns the element's current value.
Can be set, to change the value.
output.[24206]defaultValue [ = value ]
Returns the element's current default value.
Can be set, to change the default value.
output.[24207]type
Returns the string "output".
The value getter steps are to return [24208]this's [24209]descendant
text content.
The [24210]value setter steps are:
1. Set [24211]this's [24212]default value override to its
[24213]default value.
2. [24214]String replace all with the given value within [24215]this.
The defaultValue getter steps are to return the result of running
[24216]this's [24217]default value.
The [24218]defaultValue setter steps are:
1. If [24219]this's [24220]default value override is null, then
[24221]string replace all with the given value within [24222]this
and return.
2. Set [24223]this's [24224]default value override to the given value.
The type getter steps are to return "output".
The htmlFor IDL attribute must [24225]reflect the [24226]for content
attribute.
The [24227]willValidate, [24228]validity, and [24229]validationMessage
IDL attributes, and the [24230]checkValidity(),
[24231]reportValidity(), and [24232]setCustomValidity() methods, are
part of the [24233]constraint validation API. The [24234]labels IDL
attribute provides a list of the element's [24235]labels. The
[24236]form and [24237]name IDL attributes are part of the element's
forms API.
A simple calculator could use [24238]output for its display of
calculated results:
In this example, an [24239]output element is used to report the results
of a calculation performed by a remote server, as they come in:
4.10.13 The progress element
(BUTTON) ✔MDN
[24240]Element/progress
Support in all current engines.
Firefox6+Safari6+Chrome6+
__________________________________________________________________
The [24270]progress element [24271]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.
(BUTTON) ✔MDN
[24272]Attributes/max
Support in all current engines.
Firefox6+Safari6+Chrome6+
__________________________________________________________________
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 [24273]value attribute with
the current progress (either a number from 0.0 to 1.0, or, if the
[24274]max attribute is specified, a number from 0 to the value of the
[24275]max attribute). To make an indeterminate progress bar, remove
the [24276]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:
Task Progress
Progress:
(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 [24277]value and [24278]max attributes, when present, must have
values that are [24279]valid floating-point numbers. The [24280]value
attribute, if present, must have a value greater than or equal to zero,
and less than or equal to the value of the [24281]max attribute, if
present, or 1.0, otherwise. The [24282]max attribute, if present, must
have a value greater than zero.
The [24283]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 [24284]progress would be
inappropriate. Instead, the [24285]meter element is available for such
use cases.
User agent requirements: If the [24286]value attribute is omitted, then
the progress bar is an indeterminate progress bar. Otherwise, it is a
determinate progress bar.
If the progress bar is a determinate progress bar and the element has a
[24287]max attribute, the user agent must parse the [24288]max
attribute's value according to the [24289]rules for parsing
floating-point number values. If this does not result in an error, and
if the parsed value is greater than zero, then the maximum value of the
progress bar is that value. Otherwise, if the element has no [24290]max
attribute, or if it has one but parsing it resulted in an error, or if
the parsed value was less than or equal to zero, then the
[24291]maximum value of the progress bar is 1.0.
If the progress bar is a determinate progress bar, user agents must
parse the [24292]value attribute's value according to the [24293]rules
for parsing floating-point number values. If this does not result in an
error and the parsed value is greater than zero, then the value of the
progress bar is that parsed value. Otherwise, if parsing the
[24294]value attribute's value resulted in an error or a number less
than or equal to zero, then the [24295]value of the progress bar is
zero.
If the progress bar is a determinate progress bar, then the current
value is the [24296]maximum value, if [24297]value is greater than the
[24298]maximum value, and [24299]value otherwise.
UA requirements for showing the progress bar: When representing a
[24300]progress element to the user, the UA should indicate whether it
is a determinate or indeterminate progress bar, and in the former case,
should indicate the relative position of the [24301]current value
relative to the [24302]maximum value.
progress.[24303]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.
If the progress bar is an indeterminate progress bar, then the position
IDL attribute must return −1. Otherwise, it must return the result of
dividing the [24304]current value by the [24305]maximum value.
If the progress bar is an indeterminate progress bar, then the value
IDL attribute, on getting, must return 0. Otherwise, it must return the
[24306]current value. On setting, the given value must be converted to
the [24307]best representation of the number as a floating-point number
and then the [24308]value content attribute must be set to that string.
Setting the [24309]value IDL attribute to itself when the corresponding
content attribute is absent would change the progress bar from an
indeterminate progress bar to a determinate progress bar with no
progress.
The max IDL attribute must [24310]reflect the content attribute of the
same name, [24311]limited to only positive numbers. The [24312]default
value for [24313]max is 1.0.
The [24314]labels IDL attribute provides a list of the element's
[24315]labels.
4.10.14 The meter element
(BUTTON) ✔MDN
[24316]Element/meter
Support in all current engines.
Firefox16+Safari6+Chrome6+
__________________________________________________________________
[24323]Contexts in which this element can be used:
Where [24324]phrasing content is expected.
[24325]Content model:
[24326]Phrasing content, but there must be no [24327]meter
element descendants.
[24328]Tag omission in text/html:
Neither tag is omissible.
[24329]Content attributes:
[24330]Global attributes
[24331]value — Current value of the element
[24332]min — Lower bound of range
[24333]max — Upper bound of range
[24334]low — High limit of low range
[24335]high — Low limit of high range
[24336]optimum — Optimum value in gauge
The [24357]meter element [24358]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 [24359]meter element should not be used to indicate progress (as in
a progress bar). For that role, HTML provides a separate
[24360]progress element.
The [24361]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.
(BUTTON) ✔MDN
[24362]Attributes/max
Support in all current engines.
Firefox16+Safari6+Chrome6+
__________________________________________________________________
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.
Authoring requirements: The [24364]value attribute must be specified.
The [24365]value, [24366]min, [24367]low, [24368]high, [24369]max, and
[24370]optimum attributes, when present, must have values that are
[24371]valid floating-point numbers.
In addition, the attributes' values are further constrained:
Let value be the [24372]value attribute's number.
If the [24373]min attribute is specified, then let minimum be that
attribute's value; otherwise, let it be zero.
If the [24374]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 ≤ [24375]low ≤ maximum (if [24376]low is specified)
* minimum ≤ [24377]high ≤ maximum (if [24378]high is specified)
* minimum ≤ [24379]optimum ≤ maximum (if [24380]optimum is specified)
* [24381]low ≤ [24382]high (if both [24383]low and [24384]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 [24385]meter element.
When used with [24386]microdata, the [24387]meter element's
[24388]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: 6 blocks used (out of 8 total)
Voter turnout:
Tickets sold:
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):
The grapefruit pie had a radius of 12cm
and a height of 2cm.
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:
The grapefruit pie had a radius of 12cm and a height of
2cm.
Radius:
12cm
Height:
2cm
There is no explicit way to specify units in the [24389]meter element,
but the units may be specified in the [24390]title attribute in
free-form text.
The example above could be extended to mention the units:
Radius:
12cm
Height:
2cm
User agent requirements: User agents must parse the [24391]min,
[24392]max, [24393]value, [24394]low, [24395]high, and [24396]optimum
attributes using the [24397]rules for parsing floating-point number
values.
User agents must then use all these numbers to obtain values for six
points on the gauge, as follows. (The order in which these are
evaluated is important, as some of the values refer to earlier ones.)
The minimum value
If the [24398]min attribute is specified and a value could be
parsed out of it, then the minimum value is that value.
Otherwise, the minimum value is zero.
The maximum value
If the [24399]max attribute is specified and a value could be
parsed out of it, then the candidate maximum value is that
value. Otherwise, the candidate maximum value is 1.0.
If the candidate maximum value is greater than or equal to the
minimum value, then the maximum value is the candidate maximum
value. Otherwise, the maximum value is the same as the minimum
value.
The actual value
If the [24400]value attribute is specified and a value could be
parsed out of it, then that value is the candidate actual value.
Otherwise, the candidate actual value is zero.
If the candidate actual value is less than the minimum value,
then the actual value is the minimum value.
Otherwise, if the candidate actual value is greater than the
maximum value, then the actual value is the maximum value.
Otherwise, the actual value is the candidate actual value.
The low boundary
If the [24401]low attribute is specified and a value could be
parsed out of it, then the candidate low boundary is that value.
Otherwise, the candidate low boundary is the same as the minimum
value.
If the candidate low boundary is less than the minimum value,
then the low boundary is the minimum value.
Otherwise, if the candidate low boundary is greater than the
maximum value, then the low boundary is the maximum value.
Otherwise, the low boundary is the candidate low boundary.
The high boundary
If the [24402]high attribute is specified and a value could be
parsed out of it, then the candidate high boundary is that
value. Otherwise, the candidate high boundary is the same as the
maximum value.
If the candidate high boundary is less than the low boundary,
then the high boundary is the low boundary.
Otherwise, if the candidate high boundary is greater than the
maximum value, then the high boundary is the maximum value.
Otherwise, the high boundary is the candidate high boundary.
The optimum point
If the [24403]optimum attribute is specified and a value could
be parsed out of it, then the candidate optimum point is that
value. Otherwise, the candidate optimum point is the midpoint
between the minimum value and the maximum value.
If the candidate optimum point is less than the minimum value,
then the optimum point is the minimum value.
Otherwise, if the candidate optimum point is greater than the
maximum value, then the optimum point is the maximum value.
Otherwise, the optimum point is the candidate optimum point.
All of which will result in the following inequalities all being true:
* minimum value ≤ actual value ≤ maximum value
* minimum value ≤ low boundary ≤ high boundary ≤ maximum value
* minimum value ≤ optimum point ≤ maximum value
UA requirements for regions of the gauge: If the optimum point is equal
to the low boundary or the high boundary, or anywhere in between them,
then the region between the low and high boundaries of the gauge must
be treated as the optimum region, and the low and high parts, if any,
must be treated as suboptimal. Otherwise, if the optimum point is less
than the low boundary, then the region between the minimum value and
the low boundary must be treated as the optimum region, the region from
the low boundary up to the high boundary must be treated as a
suboptimal region, and the remaining region must be treated as an even
less good region. Finally, if the optimum point is higher than the high
boundary, then the situation is reversed; the region between the high
boundary and the maximum value must be treated as the optimum region,
the region from the high boundary down to the low boundary must be
treated as a suboptimal region, and the remaining region must be
treated as an even less good region.
UA requirements for showing the gauge: When representing a [24404]meter
element to the user, the UA should indicate the relative position of
the actual value to the minimum and maximum values, and the
relationship between the actual value and the three regions of the
gauge.
With the elements rendered as inline green bars of varying
lengths.
User agents may combine the value of the [24405]title attribute and the
other attributes to provide context-sensitive help or inline text
detailing the actual values.
For example, the following snippet:
...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 value IDL attribute, on getting, must return the [24406]actual
value. On setting, the given value must be converted to the [24407]best
representation of the number as a floating-point number and then the
[24408]value content attribute must be set to that string.
The min IDL attribute, on getting, must return the [24409]minimum
value. On setting, the given value must be converted to the [24410]best
representation of the number as a floating-point number and then the
[24411]min content attribute must be set to that string.
The max IDL attribute, on getting, must return the [24412]maximum
value. On setting, the given value must be converted to the [24413]best
representation of the number as a floating-point number and then the
[24414]max content attribute must be set to that string.
The low IDL attribute, on getting, must return the [24415]low boundary.
On setting, the given value must be converted to the [24416]best
representation of the number as a floating-point number and then the
[24417]low content attribute must be set to that string.
The high IDL attribute, on getting, must return the [24418]high
boundary. On setting, the given value must be converted to the
[24419]best representation of the number as a floating-point number and
then the [24420]high content attribute must be set to that string.
The optimum IDL attribute, on getting, must return the [24421]optimum
value. On setting, the given value must be converted to the [24422]best
representation of the number as a floating-point number and then the
[24423]optimum content attribute must be set to that string.
The [24424]labels IDL attribute provides a list of the element's
[24425]labels.
The following example shows how a gauge could fall back to localized or
pretty-printed text.
Disk usage: 170 261 928 bytes used
out of 233 257 824 bytes available
4.10.15 The fieldset element
(BUTTON) ✔MDN
[24426]Element/fieldset
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
[24434]Contexts in which this element can be used:
Where [24435]flow content is expected.
[24436]Content model:
Optionally, a [24437]legend element, followed by [24438]flow
content.
[24439]Tag omission in text/html:
Neither tag is omissible.
[24440]Content attributes:
[24441]Global attributes
[24442]disabled — Whether the descendant form controls, except
any inside [24443]legend, are disabled
[24444]form — Associates the element with a [24445]form element
[24446]name — Name of the element to use in the
[24447]form.elements API.
The [24470]fieldset element [24471]represents a set of form controls
(or other content) grouped together, optionally with a caption. The
caption is given by the first [24472]legend element that is a child of
the [24473]fieldset element, if any. The remainder of the descendants
form the group.
(BUTTON) ✔MDN
[24474]Element/fieldset#attr-disabled
Support in all current engines.
Firefox4+Safari6+Chrome20+
__________________________________________________________________
The disabled attribute, when specified, causes all the form control
descendants of the [24475]fieldset element, excluding those that are
descendants of the [24476]fieldset element's first [24477]legend
element child, if any, to be [24478]disabled.
A [24479]fieldset element is a disabled fieldset if it matches any of
the following conditions:
* Its [24480]disabled attribute is specified
* It is a descendant of another [24481]fieldset element whose
[24482]disabled attribute is specified, and is not a descendant of
that [24483]fieldset element's first [24484]legend element child,
if any.
The [24485]form attribute is used to explicitly associate the
[24486]fieldset element with its [24487]form owner. The [24488]name
attribute represents the element's name.
fieldset.[24489]type
Returns the string "fieldset".
fieldset.[24490]elements
Returns an [24491]HTMLCollection of the form controls in the
element.
The disabled IDL attribute must [24492]reflect the content attribute of
the same name.
The type IDL attribute must return the string "fieldset".
The elements IDL attribute must return an [24493]HTMLCollection rooted
at the [24494]fieldset element, whose filter matches [24495]listed
elements.
The [24496]willValidate, [24497]validity, and [24498]validationMessage
attributes, and the [24499]checkValidity(), [24500]reportValidity(),
and [24501]setCustomValidity() methods, are part of the
[24502]constraint validation API. The [24503]form and [24504]name IDL
attributes are part of the element's forms API.
This example shows a [24505]fieldset element being used to group a set
of related controls:
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 controls and an optional
year/month control.
You can also nest [24506]fieldset elements. Here is an example
expanding on the previous one that does so:
In this example, if the outer "Use Club Card" checkbox is not checked,
everything inside the outer [24507]fieldset, including the two radio
buttons in the legends of the two nested [24508]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
[24509]fieldsets is to be enabled.
This example shows a grouping of controls where the [24510]legend
element both labels the grouping, and the nested heading element
surfaces the grouping in the document outline:
4.10.16 The legend element
(BUTTON) ✔MDN
[24511]Element/legend
Support in all current engines.
Firefox1+Safari3+Chrome1+
__________________________________________________________________
The [24532]legend element [24533]represents a caption for the rest of
the contents of the [24534]legend element's parent [24535]fieldset
element, if any.
legend.[24536]form
Returns the element's [24537]form element, if any, or null
otherwise.
The form IDL attribute's behavior depends on whether the [24538]legend
element is in a [24539]fieldset element or not. If the [24540]legend
has a [24541]fieldset element as its parent, then the [24542]form IDL
attribute must return the same value as the [24543]form IDL attribute
on that [24544]fieldset element. Otherwise, it must return null.
4.10.17 Form control infrastructure
4.10.17.1 A form control's value
Most form controls have a value and a checkedness. (The latter is only
used by [24545]input elements.) These are used to describe how the user
interacts with the control.
A control's [24546]value is its internal state. As such, it might not
match the user's current input.
For instance, if a user enters the word "three" into [24547]a numeric
field that expects digits, the user's input would be the string "three"
but the control's [24548]value would remain unchanged. Or, if a user
enters the email address " awesome@example.com" (with leading
whitespace) into [24549]an email field, the user's input would be the
string " awesome@example.com" but the browser's UI for email fields
might translate that into a [24550]value of "awesome@example.com"
(without the leading whitespace).
[24551]input and [24552]textarea elements have a dirty value flag. This
is used to track the interaction between the [24553]value and default
value. If it is false, [24554]value mirrors the default value. If it is
true, the default value is ignored.
[24555]input, [24556]textarea, and [24557]select elements have a user
validity boolean. It is initially set to false.
To define the behavior of constraint validation in the face of the
[24558]input element's [24559]multiple attribute, [24560]input elements
can also have separately defined values.
To define the behavior of the [24561]maxlength and [24562]minlength
attributes, as well as other APIs specific to the [24563]textarea
element, all form control with a [24564]value also have an algorithm
for obtaining an API value. By default this algorithm is to simply
return the control's [24565]value.
The [24566]select element does not have a [24567]value; the
[24568]selectedness of its [24569]option elements is what is used
instead.
4.10.17.2 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 [24570]value or [24571]checkedness of a
form control, or whether or not a control can be automatically
prefilled.
4.10.17.3 Association of controls and forms
A [24572]form-associated element can have a relationship with a
[24573]form element, which is called the element's form owner. If a
[24574]form-associated element is not associated with a [24575]form
element, its [24576]form owner is said to be null.
A [24577]form-associated element has an associated parser inserted
flag.
(BUTTON) ✔MDN
[24578]Element/input#form
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
A [24580]form-associated element is, by default, associated with its
nearest ancestor [24581]form element (as described below), but, if it
is [24582]listed, may have a form attribute specified to override this.
This feature allows authors to work around the lack of support for
nested [24583]form elements.
If a [24584]listed [24585]form-associated element has a [24586]form
attribute specified, then that attribute's value must be the [24587]ID
of a [24588]form element in the element's [24589]tree.
The rules in this section are complicated by the fact that although
conforming documents or [24590]trees will never contain nested
[24591]form elements, it is quite possible (e.g., using a script that
performs DOM manipulation) to generate [24592]trees that have such
nested elements. They are also complicated by rules in the HTML parser
that, for historical reasons, can result in a [24593]form-associated
element being associated with a [24594]form element that is not its
ancestor.
When a [24595]form-associated element is created, its [24596]form owner
must be initialized to null (no owner).
When a [24597]form-associated element is to be associated with a form,
its [24598]form owner must be set to that form.
When a [24599]listed [24600]form-associated element's [24601]form
attribute is set, changed, or removed, then the user agent must
[24602]reset the form owner of that element.
When a [24603]listed [24604]form-associated element has a [24605]form
attribute and the [24606]ID of any of the elements in the [24607]tree
changes, then the user agent must [24608]reset the form owner of that
[24609]form-associated element.
When a [24610]listed [24611]form-associated element has a [24612]form
attribute and an element with an [24613]ID is [24614]inserted into or
[24615]removed from the [24616]Document, or its [24617]HTML element
moving steps are run, then the user agent must [24618]reset the form
owner of that [24619]form-associated element.
The form owner is also reset by the [24620]HTML element insertion
steps, [24621]HTML element removing steps, and [24622]HTML element
moving steps.
To reset the form owner of a [24623]form-associated element element:
1. Unset element's [24624]parser inserted flag.
2. If all of the following are true:
+ element's [24625]form owner is not null;
+ element is not [24626]listed or its [24627]form content
attribute is not present; and
+ element's [24628]form owner is its nearest [24629]form element
ancestor after the change to the ancestor chain,
then return.
3. Set element's [24630]form owner to null.
4. If element is [24631]listed, has a [24632]form content attribute,
and is [24633]connected, then:
1. If the first element in element's [24634]tree, in [24635]tree
order, to have an [24636]ID that is [24637]identical to
element's [24638]form content attribute's value, is a
[24639]form element, then [24640]associate the element with
that [24641]form element.
5. Otherwise, if element has an ancestor [24642]form element, then
[24643]associate element with the nearest such ancestor [24644]form
element.
In the following non-conforming snippet
...
...
the [24645]form owner of "d" would be the inner nested form "c", while
the [24646]form owner of "e" would be the outer form "a".
This happens as follows: First, the "e" node gets associated with "c"
in the [24647]HTML parser. Then, the [24648]innerHTML algorithm moves
the nodes from the temporary document to the "b" element. At this
point, the nodes see their ancestor chain change, and thus all the
"magic" associations done by the parser are reset to normal ancestor
associations.
This example is a non-conforming document, though, as it is a violation
of the content models to nest [24649]form elements, and there is a
[24650]parse error for the tag.
[24655]Listed [24656]form-associated elements except for
[24657]form-associated custom elements have a form IDL attribute,
which, on getting, must return the element's [24658]form owner, or null
if there isn't one.
(BUTTON) ✔MDN
[24659]ElementInternals/form
Support in all current engines.
Firefox98+Safari16.4+Chrome77+
__________________________________________________________________
[24660]Form-associated custom elements don't have [24661]form IDL
attribute. Instead, their [24662]ElementInternals object has a form IDL
attribute. On getting, it must throw a [24663]"NotSupportedError"
[24664]DOMException if the [24665]target element is not a
[24666]form-associated custom element. Otherwise, it must return the
element's [24667]form owner, or null if there isn't one.
4.10.18 Attributes common to form controls
4.10.18.1 Naming form controls: the [24668]name attribute
(BUTTON) ✔MDN
[24669]Element/input#name
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
The name content attribute gives the name of the form control, as used
in [24670]form submission and in the [24671]form element's
[24672]elements object. If the attribute is specified, its value must
not be the empty string or isindex.
A number of user agents historically implemented special support for
first-in-form text controls with the name isindex, and this
specification previously defined related user agent requirements for
it. However, some user agents subsequently dropped that special
support, and the related requirements were removed from this
specification. So, to avoid problematic reinterpretations in legacy
user agents, the name isindex is no longer allowed.
Other than isindex, any non-empty value for [24673]name is allowed. An
[24674]ASCII case-insensitive match for the name _charset_ is special:
if used as the name of a [24675]Hidden control with no [24676]value
attribute, then during submission the [24677]value attribute is
automatically given a value consisting of the submission character
encoding.
The name IDL attribute must [24678]reflect the [24679]name content
attribute.
DOM clobbering is a common cause of security issues. Avoid using the
names of built-in form properties with the [24680]name content
attribute.
In this example, the [24681]input element overrides the built-in
[24682]method property:
let form = document.createElement("form");
let input = document.createElement("input");
form.appendChild(input);
form.method; // => "get"
input.name = "method"; // DOM clobbering occurs here
form.method === input; // => true
Since the input name takes precedence over built-in form properties,
the JavaScript reference form.method will point to the [24683]input
element named "method" instead of the built-in [24684]method property.
4.10.18.2 Submitting element directionality: the [24685]dirname
attribute
(BUTTON) ✔MDN
[24686]Element/input#dirname
Support in all current engines.
Firefox116+Safari6+Chrome17+
__________________________________________________________________
The dirname attribute on a form control element enables the submission
of [24687]the directionality of the element, and gives the name of the
control that contains this value during [24688]form submission. If such
an attribute is specified, its value must not be the empty string.
In this example, a form contains a text control and a submission
button:
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=add
4.10.18.3 Limiting user input length: the [24689]maxlength
attribute
A form control maxlength attribute, controlled by the [24690]dirty
value flag, declares a limit on the number of characters a user can
input. The number of characters is measured using [24691]length and, in
the case of [24692]textarea elements, with all newlines normalized to a
single character (as opposed to CRLF pairs).
If an element has its [24693]form control maxlength attribute
specified, the attribute's value must be a [24694]valid non-negative
integer. If the attribute is specified and applying the [24695]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 [24696]maximum allowed value length.
Constraint validation: If an element has a [24697]maximum allowed value
length, its [24698]dirty value flag is true, its [24699]value was last
changed by a user edit (as opposed to a change made by a script), and
the [24700]length of the element's [24701]API value is greater than the
element's [24702]maximum allowed value length, then the element is
[24703]suffering from being too long.
User agents may prevent the user from causing the element's [24704]API
value to be set to a value whose [24705]length is greater than the
element's [24706]maximum allowed value length.
In the case of [24707]textarea elements, the [24708]API value and
[24709]value differ. In particular, [24710]newline normalization is
applied before the [24711]maximum allowed value length is checked
(whereas the [24712]textarea wrapping transformation is not applied).
4.10.18.4 Setting minimum input length requirements: the [24713]minlength
attribute
A form control minlength attribute, controlled by the [24714]dirty
value flag, declares a lower bound on the number of characters a user
can input. The "number of characters" is measured using [24715]length
and, in the case of [24716]textarea elements, with all newlines
normalized to a single character (as opposed to CRLF pairs).
The [24717]minlength attribute does not imply the required attribute.
If the form control has no required attribute, then the value can still
be omitted; the [24718]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 [24719]form control minlength attribute
specified, the attribute's value must be a [24720]valid non-negative
integer. If the attribute is specified and applying the [24721]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 [24722]minimum allowed value length.
If an element has both a [24723]maximum allowed value length and a
[24724]minimum allowed value length, the [24725]minimum allowed value
length must be smaller than or equal to the [24726]maximum allowed
value length.
Constraint validation: If an element has a [24727]minimum allowed value
length, its [24728]dirty value flag is true, its [24729]value was last
changed by a user edit (as opposed to a change made by a script), its
[24730]value is not the empty string, and the [24731]length of the
element's [24732]API value is less than the element's [24733]minimum
allowed value length, then the element is [24734]suffering from being
too short.
In this example, there are four text controls. 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.
4.10.18.5 Enabling and disabling form controls: the [24735]disabled
attribute
(BUTTON) ✔MDN
[24736]Attributes/disabled
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
The disabled content attribute is a [24741]boolean attribute.
The [24742]disabled attribute for [24743]option elements and the
[24744]disabled attribute for [24745]optgroup elements are defined
separately.
A form control is disabled if any of the following are true:
* the element is a [24746]button, [24747]input, [24748]select,
[24749]textarea, or [24750]form-associated custom element, and the
[24751]disabled attribute is specified on this element (regardless
of its value); or
* the element is a descendant of a [24752]fieldset element whose
[24753]disabled attribute is specified, and is not a descendant of
that [24754]fieldset element's first [24755]legend element child,
if any.
A form control that is [24756]disabled must prevent any [24757]click
events that are [24758]queued on the [24759]user interaction task
source from being dispatched on the element.
Constraint validation: If an element is [24760]disabled, it is
[24761]barred from constraint validation.
(BUTTON) ✔MDN
[24762]HTMLButtonElement/disabled
Support in all current engines.
Firefox1+Safari3+Chrome1+
__________________________________________________________________
Attributes for form submission can be specified both on [24767]form
elements and on [24768]submit buttons (elements that represent buttons
that submit forms, e.g. an [24769]input element whose [24770]type
attribute is in the [24771]Submit Button state).
The [24772]attributes for form submission that may be specified on
[24773]form elements are [24774]action, [24775]enctype, [24776]method,
[24777]novalidate, and [24778]target.
The corresponding [24779]attributes for form submission that may be
specified on [24780]submit buttons are [24781]formaction,
[24782]formenctype, [24783]formmethod, [24784]formnovalidate, and
[24785]formtarget. When omitted, they default to the values given on
the corresponding attributes on the [24786]form element.
__________________________________________________________________
(BUTTON) ✔MDN
[24787]Element/input#formaction
Support in all current engines.
Firefox4+Safari5+Chrome9+
__________________________________________________________________
The action and formaction content attributes, if specified, must have a
value that is a [24788]valid non-empty URL potentially surrounded by
spaces.
The action of an element is the value of the element's
[24789]formaction attribute, if the element is a [24790]submit button
and has such an attribute, or the value of its [24791]form owner's
[24792]action attribute, if it has one, or else the empty string.
__________________________________________________________________
(BUTTON) ✔MDN
[24793]Element/input#formmethod
Support in all current engines.
Firefox4+Safari5+Chrome9+
__________________________________________________________________
The method and formmethod content attributes are [24794]enumerated
attributes with the following keywords and states:
Keyword State Brief description
get GET Indicates the [24795]form will use the HTTP GET method.
post POST Indicates the [24796]form will use the HTTP POST method.
dialog Dialog Indicates the [24797]form is intended to close the
[24798]dialog box in which the form finds itself, if any, and otherwise
not submit.
The [24799]method attribute's [24800]missing value default and
[24801]invalid value default are both the [24802]GET state.
The [24803]formmethod attribute has no [24804]missing value default,
and its [24805]invalid value default is the [24806]GET state.
The method of an element is one of those states. If the element is a
[24807]submit button and has a [24808]formmethod attribute, then the
element's [24809]method is that attribute's state; otherwise, it is the
[24810]form owner's [24811]method attribute's state.
Here the [24812]method attribute is used to explicitly specify the
default value, "[24813]get", so that the search query is submitted in
the URL:
On the other hand, here the [24814]method attribute is used to specify
the value "[24815]post", so that the user's message is submitted in the
HTTP request's body:
In this example, a [24816]form is used with a [24817]dialog. The
[24818]method attribute's "[24819]dialog" keyword is used to have the
dialog automatically close when the form is submitted.
__________________________________________________________________
(BUTTON) ✔MDN
[24820]Element/input#formenctype
Support in all current engines.
Firefox4+Safari5+Chrome9+
__________________________________________________________________
The enctype and formenctype content attributes are [24821]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 attribute's [24822]missing value default and [24823]invalid value
default are both the [24824]application/x-www-form-urlencoded state.
The [24825]formenctype attribute has no [24826]missing value default,
and its [24827]invalid value default is the
[24828]application/x-www-form-urlencoded state.
The enctype of an element is one of those three states. If the element
is a [24829]submit button and has a [24830]formenctype attribute, then
the element's [24831]enctype is that attribute's state; otherwise, it
is the [24832]form owner's [24833]enctype attribute's state.
__________________________________________________________________
(BUTTON) ✔MDN
[24834]Element/input#formtarget
Support in all current engines.
Firefox4+Safari5+Chrome9+
__________________________________________________________________
The target and formtarget content attributes, if specified, must have
values that are [24835]valid navigable target names or keywords.
__________________________________________________________________
(BUTTON) ✔MDN
[24836]Element/input#formnovalidate
Support in all current engines.
Firefox4+Safari5+Chrome4+
__________________________________________________________________
The novalidate and formnovalidate content attributes are [24837]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
[24838]submit button and the element's [24839]formnovalidate attribute
is present, or if the element's [24840]form owner's [24841]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.
The action IDL attribute must [24847]reflect the content attribute of
the same name, except that on getting, when the content attribute is
missing or its value is the empty string, the element's [24848]node
document's [24849]URL must be returned instead. The target IDL
attribute must [24850]reflect the content attribute of the same name.
The method and enctype IDL attributes must [24851]reflect the
respective content attributes of the same name, [24852]limited to only
known values. The encoding IDL attribute must [24853]reflect the
[24854]enctype content attribute, [24855]limited to only known values.
The noValidate IDL attribute must [24856]reflect the [24857]novalidate
content attribute. The formAction IDL attribute must [24858]reflect the
[24859]formaction content attribute, except that on getting, when the
content attribute is missing or its value is the empty string, the
element's [24860]node document's [24861]URL must be returned instead.
The formEnctype IDL attribute must [24862]reflect the
[24863]formenctype content attribute, [24864]limited to only known
values. The formMethod IDL attribute must [24865]reflect the
[24866]formmethod content attribute, [24867]limited to only known
values. The formNoValidate IDL attribute must [24868]reflect the
[24869]formnovalidate content attribute. The formTarget IDL attribute
must [24870]reflect the [24871]formtarget content attribute.
4.10.18.7 Autofill
4.10.18.7.1 Autofilling form controls: the [24872]autocomplete
attribute
(BUTTON) ✔MDN
[24873]Attributes/autocomplete
Support in all current engines.
Firefox4+Safari6+Chrome14+
__________________________________________________________________
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.
There are two ways this attribute is used. When wearing the autofill
expectation mantle, the [24874]autocomplete attribute describes what
input is expected from users. When wearing the autofill anchor mantle,
the [24875]autocomplete attribute describes the meaning of the given
value.
On an [24876]input element whose [24877]type attribute is in the
[24878]Hidden state, the [24879]autocomplete attribute wears the
[24880]autofill anchor mantle. In all other cases, it wears the
[24881]autofill expectation mantle.
When wearing the [24882]autofill expectation mantle, the
[24883]autocomplete attribute, if specified, must have a value that is
an ordered [24884]set of space-separated tokens consisting of either a
single token that is an [24885]ASCII case-insensitive match for the
string "[24886]off", or a single token that is an [24887]ASCII
case-insensitive match for the string "[24888]on", or [24889]autofill
detail tokens.
When wearing the [24890]autofill anchor mantle, the [24891]autocomplete
attribute, if specified, must have a value that is an ordered
[24892]set of space-separated tokens consisting of just [24893]autofill
detail tokens (i.e. the "[24894]on" and "[24895]off" keywords are not
allowed).
Autofill detail tokens are the following, in the order given below:
1. Optionally, a token whose first eight characters are an
[24896]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:
2. Optionally, a token that is an [24897]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 [24898]ASCII case-insensitive match for one
of the following [24899]autofill field names, excluding those
that are [24900]inappropriate for the control:
o "[24901]name"
o "[24902]honorific-prefix"
o "[24903]given-name"
o "[24904]additional-name"
o "[24905]family-name"
o "[24906]honorific-suffix"
o "[24907]nickname"
o "[24908]username"
o "[24909]new-password"
o "[24910]current-password"
o "[24911]one-time-code"
o "[24912]organization-title"
o "[24913]organization"
o "[24914]street-address"
o "[24915]address-line1"
o "[24916]address-line2"
o "[24917]address-line3"
o "[24918]address-level4"
o "[24919]address-level3"
o "[24920]address-level2"
o "[24921]address-level1"
o "[24922]country"
o "[24923]country-name"
o "[24924]postal-code"
o "[24925]cc-name"
o "[24926]cc-given-name"
o "[24927]cc-additional-name"
o "[24928]cc-family-name"
o "[24929]cc-number"
o "[24930]cc-exp"
o "[24931]cc-exp-month"
o "[24932]cc-exp-year"
o "[24933]cc-csc"
o "[24934]cc-type"
o "[24935]transaction-currency"
o "[24936]transaction-amount"
o "[24937]language"
o "[24938]bday"
o "[24939]bday-day"
o "[24940]bday-month"
o "[24941]bday-year"
o "[24942]sex"
o "[24943]url"
o "[24944]photo"
(See the table below for descriptions of these values.)
+ The following, in the given order:
1. Optionally, a token that is an [24945]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
2. A token that is an [24946]ASCII case-insensitive match
for one of the following [24947]autofill field names,
excluding those that are [24948]inappropriate for the
control:
# "[24949]tel"
# "[24950]tel-country-code"
# "[24951]tel-national"
# "[24952]tel-area-code"
# "[24953]tel-local"
# "[24954]tel-local-prefix"
# "[24955]tel-local-suffix"
# "[24956]tel-extension"
# "[24957]email"
# "[24958]impp"
(See the table below for descriptions of these values.)
4. Optionally, a token that is an [24959]ASCII case-insensitive match
for the string "webauthn", meaning the user agent should show
[24960]public key credentials available via [24961]conditional
mediation when the user interacts with the form control.
[24962]webauthn is only valid for [24963]input and [24964]textarea
elements.
As noted earlier, the meaning of the attribute and its keywords depends
on the mantle that the attribute is wearing.
When wearing the [24965]autofill expectation mantle...
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 them;
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 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 [24966]autofill field 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 meaning of
each such keyword is described in the table below.
If the [24967]autocomplete attribute is omitted, the default
value corresponding to the state of the element's [24968]form
owner's [24969]autocomplete attribute is used instead (either
"[24970]on" or "[24971]off"). If there is no [24972]form owner,
then the value "[24973]on" is used.
When wearing the [24974]autofill anchor mantle...
The [24975]autofill field listed above indicate that the value
of the particular kind of value specified is that value provided
for this element. The meaning of each such keyword is described
in the table below.
In this example the page has explicitly specified the currency
and amount of the transaction. The form requests a credit card
and other billing details. The user agent could use this
information to suggest a credit card that it knows has
sufficient balance and that supports the relevant currency.
The autofill field 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 ("[24976]cc-exp"), or as two fields,
one giving the month ("[24977]cc-exp-month") and one the year
("[24978]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.
Some fields are only appropriate for certain form controls. An
[24979]autofill field name is inappropriate for a control if the
control does not belong to the group listed for that [24980]autofill
field in the fifth column of the first row describing that
[24981]autofill field in the table below. What controls fall into each
group is described below the table.
Field name Meaning Canonical Format Canonical Format Example Control
group
"name" Full name Free-form text, no newlines Sir Timothy John
Berners-Lee, OM, KBE, FRS, FREng, FRSA [24982]Text
"honorific-prefix" Prefix or title (e.g. "Mr.", "Ms.", "Dr.", "M^lle")
Free-form text, no newlines Sir [24983]Text
"given-name" Given name (in some Western cultures, also known as the
first name) Free-form text, no newlines Timothy [24984]Text
"additional-name" Additional names (in some Western cultures, also
known as middle names, forenames other than the first name) Free-form
text, no newlines John [24985]Text
"family-name" Family name (in some Western cultures, also known as the
last name or surname) Free-form text, no newlines Berners-Lee
[24986]Text
"honorific-suffix" Suffix (e.g. "Jr.", "B.Sc.", "MBASW", "II")
Free-form text, no newlines OM, KBE, FRS, FREng, FRSA [24987]Text
"nickname" Nickname, screen name, handle: a typically short name used
instead of the full name Free-form text, no newlines Tim [24988]Text
"organization-title" Job title (e.g. "Software Engineer", "Senior Vice
President", "Deputy Managing Director") Free-form text, no newlines
Professor [24989]Text
"username" A username Free-form text, no newlines timbl [24990]Username
"new-password" A new password (e.g. when creating an account or
changing a password) Free-form text, no newlines GUMFXbadyrS3
[24991]Password
"current-password" The current password for the account identified by
the [24992]username field (e.g. when logging in) Free-form text, no
newlines qwerty [24993]Password
"one-time-code" One-time code used for verifying user identity
Free-form text, no newlines 123456 [24994]Password
"organization" Company name corresponding to the person, address, or
contact information in the other fields associated with this field
Free-form text, no newlines World Wide Web Consortium [24995]Text
"street-address" Street address (multiple lines, newlines preserved)
Free-form text 32 Vassar Street
MIT Room 32-G524 [24996]Multiline
"address-line1" Street address (one line per field) Free-form text, no
newlines 32 Vassar Street [24997]Text
"address-line2" Free-form text, no newlines MIT Room 32-G524
[24998]Text
"address-line3" Free-form text, no newlines [24999]Text
"address-level4" The most fine-grained [25000]administrative level, in
addresses with four administrative levels Free-form text, no newlines
[25001]Text
"address-level3" The [25002]third administrative level, in addresses
with three or more administrative levels Free-form text, no newlines
[25003]Text
"address-level2" The [25004]second administrative level, in addresses
with two or more administrative levels; in the countries with two
administrative levels, this would typically be the city, town, village,
or other locality within which the relevant street address is found
Free-form text, no newlines Cambridge [25005]Text
"address-level1" The broadest [25006]administrative level in the
address, i.e. the province within which the locality is found; for
example, in the US, this would be the state; in Switzerland it would be
the canton; in the UK, the post town Free-form text, no newlines MA
[25007]Text
"country" Country code Valid [25008]ISO 3166-1-alpha-2 country code
[25009][ISO3166] US [25010]Text
"country-name" Country name Free-form text, no newlines; [25011]derived
from country in some cases US [25012]Text
"postal-code" Postal code, post code, ZIP code, CEDEX code (if CEDEX,
append "CEDEX", and the arrondissement, if relevant, to the
[25013]address-level2 field) Free-form text, no newlines 02139
[25014]Text
"cc-name" Full name as given on the payment instrument Free-form text,
no newlines Tim Berners-Lee [25015]Text
"cc-given-name" Given name as given on the payment instrument (in some
Western cultures, also known as the first name) Free-form text, no
newlines Tim [25016]Text
"cc-additional-name" 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 [25017]Text
"cc-family-name" Family name given on the payment instrument (in some
Western cultures, also known as the last name or surname) Free-form
text, no newlines Berners-Lee [25018]Text
"cc-number" Code identifying the payment instrument (e.g. the credit
card number) [25019]ASCII digits 4114360123456785 [25020]Text
"cc-exp" Expiration date of the payment instrument [25021]Valid month
string 2014-12 [25022]Month
"cc-exp-month" Month component of the expiration date of the payment
instrument [25023]Valid integer in the range 1..12 12 [25024]Numeric
"cc-exp-year" Year component of the expiration date of the payment
instrument [25025]Valid integer greater than zero 2014 [25026]Numeric
"cc-csc" 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.)
[25027]ASCII digits 419 [25028]Text
"cc-type" Type of payment instrument Free-form text, no newlines Visa
[25029]Text
"transaction-currency" The currency that the user would prefer the
transaction to use ISO 4217 currency code [25030][ISO4217] GBP
[25031]Text
"transaction-amount" The amount that the user would like for the
transaction (e.g. when entering a bid or sale price) [25032]Valid
floating-point number 401.00 [25033]Numeric
"language" Preferred language Valid BCP 47 language tag [25034][BCP47]
en [25035]Text
"bday" Birthday [25036]Valid date string 1955-06-08 [25037]Date
"bday-day" Day component of birthday [25038]Valid integer in the range
1..31 8 [25039]Numeric
"bday-month" Month component of birthday [25040]Valid integer in the
range 1..12 6 [25041]Numeric
"bday-year" Year component of birthday [25042]Valid integer greater
than zero 1955 [25043]Numeric
"sex" Gender identity (e.g. Female, Fa'afafine) Free-form text, no
newlines Male [25044]Text
"url" Home page or other web page corresponding to the company, person,
address, or contact information in the other fields associated with
this field [25045]Valid URL string
https://www.w3.org/People/Berners-Lee/ [25046]URL
"photo" Photograph, icon, or other image corresponding to the company,
person, address, or contact information in the other fields associated
with this field [25047]Valid URL string
https://www.w3.org/Press/Stock/Berners-Lee/2001-europaeum-eighth.jpg
[25048]URL
"tel" Full telephone number, including country code [25049]ASCII digits
and U+0020 SPACE characters, prefixed by a U+002B PLUS SIGN character
(+) +1 617 253 5702 [25050]Tel
"tel-country-code" Country code component of the telephone number
[25051]ASCII digits prefixed by a U+002B PLUS SIGN character (+) +1
[25052]Text
"tel-national" Telephone number without the county code component, with
a country-internal prefix applied if applicable [25053]ASCII digits and
U+0020 SPACE characters 617 253 5702 [25054]Text
"tel-area-code" Area code component of the telephone number, with a
country-internal prefix applied if applicable [25055]ASCII digits 617
[25056]Text
"tel-local" Telephone number without the country code and area code
components [25057]ASCII digits 2535702 [25058]Text
"tel-local-prefix" First part of the component of the telephone number
that follows the area code, when that component is split into two
components [25059]ASCII digits 253 [25060]Text
"tel-local-suffix" Second part of the component of the telephone number
that follows the area code, when that component is split into two
components [25061]ASCII digits 5702 [25062]Text
"tel-extension" Telephone number internal extension code [25063]ASCII
digits 1000 [25064]Text
"email" Email address [25065]Valid email address timbl@w3.org
[25066]Username
"impp" URL representing an instant messaging protocol endpoint (for
example, "aim:goim?screenname=example" or "xmpp:fred@example.net")
[25067]Valid URL string irc://example.org/timbl,isuser [25068]URL
The groups correspond to controls as follows:
Text
[25069]input elements with a [25070]type attribute in the
[25071]Hidden state
[25072]input elements with a [25073]type attribute in the
[25074]Text state
[25075]input elements with a [25076]type attribute in the
[25077]Search state
[25078]textarea elements
[25079]select elements
Multiline
[25080]input elements with a [25081]type attribute in the
[25082]Hidden state
[25083]textarea elements
[25084]select elements
Password
[25085]input elements with a [25086]type attribute in the
[25087]Hidden state
[25088]input elements with a [25089]type attribute in the
[25090]Text state
[25091]input elements with a [25092]type attribute in the
[25093]Search state
[25094]input elements with a [25095]type attribute in the
[25096]Password state
[25097]textarea elements
[25098]select elements
URL
[25099]input elements with a [25100]type attribute in the
[25101]Hidden state
[25102]input elements with a [25103]type attribute in the
[25104]Text state
[25105]input elements with a [25106]type attribute in the
[25107]Search state
[25108]input elements with a [25109]type attribute in the
[25110]URL state
[25111]textarea elements
[25112]select elements
Username
[25113]input elements with a [25114]type attribute in the
[25115]Hidden state
[25116]input elements with a [25117]type attribute in the
[25118]Text state
[25119]input elements with a [25120]type attribute in the
[25121]Search state
[25122]input elements with a [25123]type attribute in the
[25124]Email state
[25125]textarea elements
[25126]select elements
Tel
[25127]input elements with a [25128]type attribute in the
[25129]Hidden state
[25130]input elements with a [25131]type attribute in the
[25132]Text state
[25133]input elements with a [25134]type attribute in the
[25135]Search state
[25136]input elements with a [25137]type attribute in the
[25138]Telephone state
[25139]textarea elements
[25140]select elements
Numeric
[25141]input elements with a [25142]type attribute in the
[25143]Hidden state
[25144]input elements with a [25145]type attribute in the
[25146]Text state
[25147]input elements with a [25148]type attribute in the
[25149]Search state
[25150]input elements with a [25151]type attribute in the
[25152]Number state
[25153]textarea elements
[25154]select elements
Month
[25155]input elements with a [25156]type attribute in the
[25157]Hidden state
[25158]input elements with a [25159]type attribute in the
[25160]Text state
[25161]input elements with a [25162]type attribute in the
[25163]Search state
[25164]input elements with a [25165]type attribute in the
[25166]Month state
[25167]textarea elements
[25168]select elements
Date
[25169]input elements with a [25170]type attribute in the
[25171]Hidden state
[25172]input elements with a [25173]type attribute in the
[25174]Text state
[25175]input elements with a [25176]type attribute in the
[25177]Search state
[25178]input elements with a [25179]type attribute in the
[25180]Date state
[25181]textarea elements
[25182]select elements
Address levels: The "[25183]address-level1" – "[25184]address-level4"
fields are used to describe the locality of the street address.
Different locales have different numbers of levels. For example, the US
uses two levels (state and town), the UK uses one or two depending on
the address (the post town, and in some cases the locality), and China
can use three (province, city, district). The "[25185]address-level1"
field represents the widest administrative division. Different locales
order the fields in different ways; for example, in the US the town
(level 2) precedes the state (level 1); while in Japan the prefecture
(level 1) precedes the city (level 2) which precedes the district
(level 3). Authors are encouraged to provide forms that are presented
in a way that matches the country's conventions (hiding, showing, and
rearranging fields accordingly as the user changes the country).
4.10.18.7.2 Processing model
Each [25186]input element to which the [25187]autocomplete attribute
[25188]applies, each [25189]select element, and each [25190]textarea
element, has an autofill hint set, an autofill scope, an autofill field
name, a non-autofill credential type, and an IDL-exposed autofill
value.
The [25191]autofill field name specifies the specific kind of data
expected in the field, e.g. "[25192]street-address" or "[25193]cc-exp".
The [25194]autofill hint set identifies what address or contact
information type the user agent is to look at, e.g. "[25195]shipping
[25196]fax" or "[25197]billing".
The [25198]non-autofill credential type identifies a type of
[25199]credential that may be offered by the user agent when the user
interacts with the field alongside other [25200]autofill field values.
If this value is "webauthn" instead of null, selecting a credential of
that type will resolve a pending [25201]conditional mediation
[25202]navigator.credentials.get() request, instead of autofilling the
field.
For example, a sign-in page could instruct the user agent to either
autofill a saved password, or show a [25203]public key credential that
will resolve a pending [25204]navigator.credentials.get() request. A
user can select either to sign-in.
The [25205]autofill scope identifies the group of fields whose
information concerns the same subject, and consists of the
[25206]autofill hint set with, if applicable, the "section-*" prefix,
e.g. "billing", "section-parent shipping", or "section-child shipping
home".
These values are defined as the result of running the following
algorithm:
1. If the element has no [25207]autocomplete attribute, then jump to
the step labeled default.
2. Let tokens be the result of [25208]splitting the attribute's value
on ASCII whitespace.
3. If tokens is empty, then jump to the step labeled default.
4. Let index be the index of the last token in tokens.
5. Let field be the indexth token in tokens.
6. Set the category, maximum tokens pair to the result of
[25209]determining a field's category given field.
7. If category is null, then jump to the step labeled default.
8. If the number of tokens in tokens is greater than maximum tokens,
then jump to the step labeled default.
9. If category is Off or Automatic but the element's
[25210]autocomplete attribute is wearing the [25211]autofill anchor
mantle, then jump to the step labeled default.
10. If category is Off, let the element's [25212]autofill field name be
the string "off", let its [25213]autofill hint set be empty, and
let its [25214]IDL-exposed autofill value be the string "off".
Then, return.
11. If category is Automatic, let the element's [25215]autofill field
name be the string "on", let its [25216]autofill hint set be empty,
and let its [25217]IDL-exposed autofill value be the string "on".
Then, return.
12. Let scope tokens be an empty list.
13. Let hint tokens be an empty set.
14. Let credential type be null.
15. Let IDL value have the same value as field.
16. If category is Credential and the indexth token in tokens is an
[25218]ASCII case-insensitive match for "[25219]webauthn", then run
the substeps that follow:
1. Set credential type to "webauthn".
2. If the indexth token in tokens is the first entry, then skip
to the step labeled done.
3. Decrement index by one.
4. Set the category, maximum tokens pair to the result of
[25220]determining a field's category given the indexth token
in tokens.
5. If category is not Normal and category is not Contact, then
jump to the step labeled default.
6. If index is greater than maximum tokens minus one (i.e. if the
number of remaining tokens is greater than maximum tokens),
then jump to the step labeled default.
7. Set IDL value to the concatenation of the indexth token in
tokens, a U+0020 SPACE character, and the previous value of
IDL value.
17. If the indexth token in tokens is the first entry, then skip to the
step labeled done.
18. Decrement index by one.
19. If category is Contact and the indexth token in tokens is an
[25221]ASCII case-insensitive match for one of the strings in the
following list, then run the substeps that follow:
+ "[25222]home"
+ "[25223]work"
+ "[25224]mobile"
+ "[25225]fax"
+ "[25226]pager"
The substeps are:
1. Let contact be the matching string from the list above.
2. Insert contact at the start of scope tokens.
3. Add contact to hint tokens.
4. Let IDL value be the concatenation of contact, a U+0020 SPACE
character, and the previous value of IDL value.
5. If the indexth entry in tokens is the first entry, then skip
to the step labeled done.
6. Decrement index by one.
20. If the indexth token in tokens is an [25227]ASCII case-insensitive
match for one of the strings in the following list, then run the
substeps that follow:
+ "[25228]shipping"
+ "[25229]billing"
The substeps are:
1. Let mode be the matching string from the list above.
2. Insert mode at the start of scope tokens.
3. Add mode to hint tokens.
4. Let IDL value be the concatenation of mode, a U+0020 SPACE
character, and the previous value of IDL value.
5. If the indexth entry in tokens is the first entry, then skip
to the step labeled done.
6. Decrement index by one.
21. If the indexth entry in tokens is not the first entry, then jump to
the step labeled default.
22. If the first eight characters of the indexth token in tokens are
not an [25230]ASCII case-insensitive match for the string
"[25231]section-", then jump to the step labeled default.
23. Let section be the indexth token in tokens, [25232]converted to
ASCII lowercase.
24. Insert section at the start of scope tokens.
25. Let IDL value be the concatenation of section, a U+0020 SPACE
character, and the previous value of IDL value.
26. Done: Let the element's [25233]autofill hint set be hint tokens.
27. Let the element's [25234]non-autofill credential type be credential
type.
28. Let the element's [25235]autofill scope be scope tokens.
29. Let the element's [25236]autofill field name be field.
30. Let the element's [25237]IDL-exposed autofill value be IDL value.
31. Return.
32. Default: Let the element's [25238]IDL-exposed autofill value be the
empty string, and its [25239]autofill hint set and [25240]autofill
scope be empty.
33. If the element's [25241]autocomplete attribute is wearing the
[25242]autofill anchor mantle, then let the element's
[25243]autofill field name be the empty string and return.
34. Let form be the element's [25244]form owner, if any, or null
otherwise.
35. If form is not null and form's [25245]autocomplete attribute is in
the [25246]off state, then let the element's [25247]autofill field
name be "[25248]off".
Otherwise, let the element's [25249]autofill field name be
"[25250]on".
To determine a field's category, given field:
1. If the field is not an [25251]ASCII case-insensitive match for one
of the tokens given in the first column of the following table,
return the pair (null, null).
Token Maximum number of tokens Category
"[25252]off" 1 Off
"[25253]on" 1 Automatic
"[25254]name" 3 Normal
"[25255]honorific-prefix" 3 Normal
"[25256]given-name" 3 Normal
"[25257]additional-name" 3 Normal
"[25258]family-name" 3 Normal
"[25259]honorific-suffix" 3 Normal
"[25260]nickname" 3 Normal
"[25261]organization-title" 3 Normal
"[25262]username" 3 Normal
"[25263]new-password" 3 Normal
"[25264]current-password" 3 Normal
"[25265]one-time-code" 3 Normal
"[25266]organization" 3 Normal
"[25267]street-address" 3 Normal
"[25268]address-line1" 3 Normal
"[25269]address-line2" 3 Normal
"[25270]address-line3" 3 Normal
"[25271]address-level4" 3 Normal
"[25272]address-level3" 3 Normal
"[25273]address-level2" 3 Normal
"[25274]address-level1" 3 Normal
"[25275]country" 3 Normal
"[25276]country-name" 3 Normal
"[25277]postal-code" 3 Normal
"[25278]cc-name" 3 Normal
"[25279]cc-given-name" 3 Normal
"[25280]cc-additional-name" 3 Normal
"[25281]cc-family-name" 3 Normal
"[25282]cc-number" 3 Normal
"[25283]cc-exp" 3 Normal
"[25284]cc-exp-month" 3 Normal
"[25285]cc-exp-year" 3 Normal
"[25286]cc-csc" 3 Normal
"[25287]cc-type" 3 Normal
"[25288]transaction-currency" 3 Normal
"[25289]transaction-amount" 3 Normal
"[25290]language" 3 Normal
"[25291]bday" 3 Normal
"[25292]bday-day" 3 Normal
"[25293]bday-month" 3 Normal
"[25294]bday-year" 3 Normal
"[25295]sex" 3 Normal
"[25296]url" 3 Normal
"[25297]photo" 3 Normal
"[25298]tel" 4 Contact
"[25299]tel-country-code" 4 Contact
"[25300]tel-national" 4 Contact
"[25301]tel-area-code" 4 Contact
"[25302]tel-local" 4 Contact
"[25303]tel-local-prefix" 4 Contact
"[25304]tel-local-suffix" 4 Contact
"[25305]tel-extension" 4 Contact
"[25306]email" 4 Contact
"[25307]impp" 4 Contact
"[25308]webauthn" 5 Credential
2. Otherwise, let maximum tokens and category be the values of the
cells in the second and third columns of that row respectively.
3. Return the pair (category, maximum tokens).
__________________________________________________________________
For the purposes of autofill, a control's data depends on the kind of
control:
An [25309]input element with its [25310]type attribute in the
[25311]Email state and with the [25312]multiple attribute
specified
The element's [25313]values.
Any other [25314]input element
A [25315]textarea element
The element's [25316]value.
A [25317]select element with its [25318]multiple attribute specified
The [25319]option elements in the [25320]select element's
[25321]list of options that have their [25322]selectedness set
to true.
Any other [25323]select element
The [25324]option element in the [25325]select element's
[25326]list of options that has its [25327]selectedness set to
true.
__________________________________________________________________
How to process the [25328]autofill hint set, [25329]autofill scope, and
[25330]autofill field name depends on the mantle that the
[25331]autocomplete attribute is wearing.
When wearing the [25332]autofill expectation mantle...
When an element's [25333]autofill field name is "[25334]off",
the user agent should not remember the [25335]control's data,
and should not offer past values to the user.
In addition, when an element's [25336]autofill field name is
"[25337]off", [25338]values are reset when [25339]reactivating a
document.
Banks frequently do not want UAs to prefill login information:
When an element's [25340]autofill field name is not
"[25341]off", the user agent may store the [25342]control's
data, and may offer previously stored values to the user.
For example, suppose a user visits a page with this control:
This might render as follows:
A drop-down control with a long alphabetical list of countries.
Suppose that on the first visit to this page, the user selects
"Zambia". On the second visit, the user agent could duplicate
the entry for Zambia at the top of the list, so that the
interface instead looks like this:
The same drop-down control with the alphabetical list of
countries, but with Zambia as an entry at the top.
When the [25343]autofill field name is "[25344]on", the user
agent should attempt to use heuristics to determine the most
appropriate values to offer the user, e.g. based on the
element's [25345]name value, the position of the element in its
[25346]tree, what other fields exist in the form, and so forth.
When the [25347]autofill field name is one of the names of the
[25348]autofill fields described above, the user agent should
provide suggestions that match the meaning of the field name as
given in the table earlier in this section. The [25349]autofill
hint set should be used to select amongst multiple possible
suggestions.
For example, if a user once entered one address into fields that
used the "[25350]shipping" keyword, and another address into
fields that used the "[25351]billing" keyword, then in
subsequent forms only the first address would be suggested for
form controls whose [25352]autofill hint set contains the
keyword "[25353]shipping". Both addresses might be suggested,
however, for address-related form controls whose [25354]autofill
hint set does not contain either keyword.
When wearing the [25355]autofill anchor mantle...
When the [25356]autofill field name is not the empty string,
then the user agent must act as if the user had specified the
[25357]control's data for the given [25358]autofill hint set,
[25359]autofill scope, and [25360]autofill field name
combination.
When the user agent autofills form controls, elements with the same
[25361]form owner and the same [25362]autofill scope must use data
relating to the same person, address, payment instrument, and contact
details. When a user agent autofills "[25363]country" and
"[25364]country-name" fields with the same [25365]form owner and
[25366]autofill scope, and the user agent has a value for the
[25367]country" field(s), then the "[25368]country-name" field(s) must
be filled using a human-readable name for the same country. When a user
agent fills in multiple fields at once, all fields with the same
[25369]autofill field name, [25370]form owner, and [25371]autofill
scope must be filled with the same value.
Suppose a user agent knows of two phone numbers, +1 555 123 1234 and +1
555 666 7777. It would not be conforming for the user agent to fill a
field with autocomplete="shipping tel-local-prefix" with the value
"123" and another field in the same form with autocomplete="shipping
tel-local-suffix" with the value "7777". The only valid prefilled
values given the aforementioned information would be "123" and "1234",
or "666" and "7777", respectively.
Similarly, if a form for some reason contained both a "[25372]cc-exp"
field and a "[25373]cc-exp-month" field, and the user agent prefilled
the form, then the month component of the former would have to match
the latter.
This requirement interacts with the [25374]autofill anchor mantle also.
Consider the following markup snippet:
The only value that a conforming user agent could suggest in the text
control is "TreePlate", the value given by the hidden [25375]input
element.
The "section-*" tokens in the [25376]autofill scope are opaque; user
agents must not attempt to derive meaning from the precise values of
these tokens.
For example, it would not be conforming if the user agent decided that
it should offer the address it knows to be the user's daughter's
address for "section-child" and the addresses it knows to be the user's
spouses' addresses for "section-spouse".
The autocompletion mechanism must be implemented by the user agent
acting as if the user had modified the [25377]control's data, and must
be done at a time where the element is [25378]mutable (e.g. just after
the element has been inserted into the document, or when the user agent
[25379]stops parsing). User agents must only prefill controls using
values that the user could have entered.
For example, if a [25380]select element only has [25381]option elements
with values "Steve" and "Rebecca", "Jay", and "Bob", and has an
[25382]autofill field name "[25383]given-name", but the user agent's
only idea for what to prefill the field with is "Evan", then the user
agent cannot prefill the field. It would not be conforming to somehow
set the [25384]select element to the value "Evan", since the user could
not have done so themselves.
A user agent prefilling a form control must not discriminate between
form controls that are [25385]in a document tree and those that are
[25386]connected; that is, it is not conforming to make the decision on
whether or not to autofill based on whether the element's [25387]root
is a [25388]shadow root versus a [25389]Document.
A user agent prefilling a form control's [25390]value must not cause
that control to [25391]suffer from a type mismatch, [25392]suffer from
being too long, [25393]suffer from being too short, [25394]suffer from
an underflow, [25395]suffer from an overflow, or [25396]suffer from a
step mismatch. A user agent prefilling a form control's [25397]value
must not cause that control to [25398]suffer from a pattern mismatch
either. Where possible given the control's constraints, user agents
must use the format given as canonical in the aforementioned table.
Where it's not possible for the canonical format to be used, user
agents should use heuristics to attempt to convert values so that they
can be used.
For example, if the user agent knows that the user's middle name is
"Ines", and attempts to prefill a form control that looks like this:
...then the user agent could convert "Ines" to "I" and prefill it that
way.
A more elaborate example would be with month values. If the user agent
knows that the user's birthday is the 27th of July 2012, then it might
try to prefill all of the following controls with slightly different
values, all driven from this information:
2012-07 The day is dropped since the [25399]Month state only accepts a
month/year combination. (Note that this example is non-conforming,
because the [25400]autofill field name [25401]bday is not allowed with
the [25402]Month state.)
July The user agent picks the month from the listed options, either by
noticing there are twelve options and picking the 7th, or by
recognizing that one of the strings (three characters "Jul" followed by
a newline and a space) is a close match for the name of the month
(July) in one of the user agent's supported languages, or through some
other similar mechanism.
7 User agent converts "July" to a month number in the range 1..12, like
the field.
6 User agent converts "July" to a month number in the range 0..11, like
the field.
User agent doesn't fill in the field, since it can't make a good guess
as to what the form expects.
A user agent may allow the user to override an element's
[25403]autofill field name, e.g. to change it from "[25404]off" to
"[25405]on" to allow values to be remembered and prefilled despite the
page author's objections, or to always "[25406]off", never remembering
values.
More specifically, user agents may in particular consider replacing the
[25407]autofill field name of form controls that match the description
given in the first column of the following table, when their
[25408]autofill field name is either "[25409]on" or "[25410]off", with
the value given in the second cell of that row. If this table is used,
the replacements must be done in [25411]tree order, since all but the
first row references the [25412]autofill field name of earlier
elements. When the descriptions below refer to form controls being
preceded or followed by others, they mean in the list of [25413]listed
elements that share the same [25414]form owner.
Form control New [25415]autofill field name
an [25416]input element whose [25417]type attribute is in the
[25418]Text state that is followed by an [25419]input element whose
[25420]type attribute is in the [25421]Password state "[25422]username"
an [25423]input element whose [25424]type attribute is in the
[25425]Password state that is preceded by an [25426]input element whose
[25427]autofill field name is "[25428]username"
"[25429]current-password"
an [25430]input element whose [25431]type attribute is in the
[25432]Password state that is preceded by an [25433]input element whose
[25434]autofill field name is "[25435]current-password"
"[25436]new-password"
an [25437]input element whose [25438]type attribute is in the
[25439]Password state that is preceded by an [25440]input element whose
[25441]autofill field name is "[25442]new-password"
"[25443]new-password"
The autocomplete IDL attribute, on getting, must return the element's
[25444]IDL-exposed autofill value, and on setting, must [25445]reflect
the content attribute of the same name.
4.10.19 APIs for the text control selections
The [25446]input and [25447]textarea elements define several attributes
and methods for handling their selection. Their shared algorithms are
defined here.
element.[25448]select()
Selects everything in the text control.
element.[25449]selectionStart [ = value ]
Returns the offset to the start of the selection.
Can be set, to change the start of the selection.
element.[25450]selectionEnd [ = value ]
Returns the offset to the end of the selection.
Can be set, to change the end of the selection.
element.[25451]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.[25452]setSelectionRange(start, end [, direction])
Firefox Android?Safari iOS1+Chrome Android?WebView
Android?Samsung Internet?Opera Android10.1+
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.[25454]setRangeText(replacement [, start, end [, selectionMode
] ])
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
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 will be set
after the text has been replaced. The possible values are:
"[25456]select"
Selects the newly inserted text.
"[25457]start"
Moves the selection to just before the inserted text.
"[25458]end"
Moves the selection to just after the selected text.
"[25459]preserve"
Attempts to preserve the selection. This is the default.
All [25460]input elements to which these APIs [25461]apply, and all
[25462]textarea elements, have either a selection or a text entry
cursor position at all times (even for elements that are not
[25463]being rendered), measured in offsets into the [25464]code units
of the control's [25465]relevant value. The initial state must consist
of a [25466]text entry cursor at the beginning of the control.
For [25467]input elements, these APIs must operate on the element's
[25468]value. For [25469]textarea elements, these APIs must operate on
the element's [25470]API value. In the below algorithms, we call the
value string being operated on the relevant value.
The use of [25471]API value instead of [25472]raw value for
[25473]textarea elements means that U+000D (CR) characters are
normalized away. For example,
If we had operated on the [25474]raw value of "A\r\nB", then we would
have replaced the characters "A\r", ending up with a result of
"replaced\nB". But since we used the [25475]API value of "A\nB", we
replaced the characters "A\n", giving "replacedB".
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.
Whenever the [25476]relevant value changes for an element to which
these APIs apply, run these steps:
1. If the element has a [25477]selection:
1. If the start of the selection is now past the end of the
[25478]relevant value, set it to the end of the
[25479]relevant value.
2. If the end of the selection is now past the end of the
[25480]relevant value, set it to the end of the
[25481]relevant value.
3. If the user agent does not support empty selection, and both
the start and end of the selection are now pointing to the end
of the [25482]relevant value, then instead set the element's
[25483]text entry cursor position to the end of the
[25484]relevant value, removing any selection.
2. Otherwise, the element must have a [25485]text entry cursor
position position. If it is now past the end of the [25486]relevant
value, set it to the end of the [25487]relevant value.
In some cases where the [25488]relevant value changes, other parts of
the specification will also modify the [25489]text entry cursor
position, beyond just the clamping steps above. For example, see the
[25490]value setter for [25491]textarea.
Where possible, user interface features for changing the [25492]text
selection in [25493]input and [25494]textarea elements must be
implemented using the [25495]set the selection range algorithm so that,
e.g., all the same events fire.
The [25496]selections of [25497]input and [25498]textarea elements have
a selection direction, which is either "forward", "backward", or
"none". The exact meaning of the selection direction depends on the
platform. This direction is set when the user manipulates the
selection. The initial [25499]selection direction must be "none" if the
platform supports that direction, or "forward" otherwise.
To set the selection direction of an element to a given direction,
update the element's [25500]selection direction to the given direction,
unless the direction is "none" and the platform does not support that
direction; in that case, update the element's [25501]selection
direction to "forward".
On Windows, the direction indicates the position of the caret relative
to the selection: a "forward" selection has the caret at the end of the
selection and a "backward" selection has the caret at the start of the
selection. Windows has no "none" direction.
On Mac, the direction indicates which end of the selection is affected
when the user adjusts the size of the selection using the arrow keys
with the Shift modifier: the "forward" direction means the end of the
selection is modified, and the "backward" direction means the start of
the selection is modified. The "none" direction is the default on Mac,
it indicates that no particular direction has yet been selected. The
user sets the direction implicitly when first adjusting the selection,
based on which directional arrow key was used.
(BUTTON) ✔MDN
[25502]HTMLInputElement/select
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
The select() method, when invoked, must run the following steps:
1. If this element is an [25504]input element, and either
[25505]select() [25506]does not apply to this element or the
corresponding control has no selectable text, return.
For instance, in a user agent where [25507] is
rendered as a color well with a picker, as opposed to a text
control accepting a hexadecimal color code, there would be no
selectable text, and thus calls to the method are ignored.
2. [25508]Set the selection range with 0 and infinity.
The selectionStart attribute's getter must run the following steps:
1. If this element is an [25509]input element, and
[25510]selectionStart [25511]does not apply to this element, return
null.
2. If there is no [25512]selection, return the [25513]code unit offset
within the [25514]relevant value to the character that immediately
follows the [25515]text entry cursor.
3. Return the [25516]code unit offset within the [25517]relevant value
to the character that immediately follows the start of the
[25518]selection.
The [25519]selectionStart attribute's setter must run the following
steps:
1. If this element is an [25520]input element, and
[25521]selectionStart [25522]does not apply to this element, throw
an [25523]"InvalidStateError" [25524]DOMException.
2. Let end be the value of this element's [25525]selectionEnd
attribute.
3. If end is less than the given value, set end to the given value.
4. [25526]Set the selection range with the given value, end, and the
value of this element's [25527]selectionDirection attribute.
The selectionEnd attribute's getter must run the following steps:
1. If this element is an [25528]input element, and [25529]selectionEnd
[25530]does not apply to this element, return null.
2. If there is no [25531]selection, return the [25532]code unit offset
within the [25533]relevant value to the character that immediately
follows the [25534]text entry cursor.
3. Return the [25535]code unit offset within the [25536]relevant value
to the character that immediately follows the end of the
[25537]selection.
The [25538]selectionEnd attribute's setter must run the following
steps:
1. If this element is an [25539]input element, and [25540]selectionEnd
[25541]does not apply to this element, throw an
[25542]"InvalidStateError" [25543]DOMException.
2. [25544]Set the selection range with the value of this element's
[25545]selectionStart attribute, the given value, and the value of
this element's [25546]selectionDirection attribute.
The selectionDirection attribute's getter must run the following steps:
1. If this element is an [25547]input element, and
[25548]selectionDirection [25549]does not apply to this element,
return null.
2. Return this element's [25550]selection direction.
The [25551]selectionDirection attribute's setter must run the following
steps:
1. If this element is an [25552]input element, and
[25553]selectionDirection [25554]does not apply to this element,
throw an [25555]"InvalidStateError" [25556]DOMException.
2. [25557]Set the selection range with the value of this element's
[25558]selectionStart attribute, the value of this element's
[25559]selectionEnd attribute, and the given value.
The setSelectionRange(start, end, direction) method, when invoked, must
run the following steps:
1. If this element is an [25560]input element, and
[25561]setSelectionRange() [25562]does not apply to this element,
throw an [25563]"InvalidStateError" [25564]DOMException.
2. [25565]Set the selection range with start, end, and direction.
To set the selection range with an integer or null start, an integer or
null or the special value infinity end, and optionally a string
direction, run the following steps:
1. If start is null, let start be zero.
2. If end is null, let end be zero.
3. Set the [25566]selection of the text control to the sequence of
[25567]code units within the [25568]relevant value starting with
the code unit at the startth position (in logical order) and ending
with the code unit at the (end-1)th position. Arguments greater
than the [25569]length of the [25570]relevant value of the text
control (including the special value infinity) must be treated as
pointing at the end of the text control. If end is less than or
equal to start then the start of the selection and the end of the
selection must both be placed immediately before the character with
offset end. In UAs where there is no concept of an empty selection,
this must set the cursor to be just before the character with
offset end.
4. If direction is not [25571]identical to either "backward" or
"forward", or if the direction argument was not given, set
direction to "none".
5. [25572]Set the selection direction of the text control to
direction.
6. If the previous steps caused the [25573]selection of the text
control to be modified (in either extent or [25574]direction), then
[25575]queue an element task on the [25576]user interaction task
source given the element to [25577]fire an event named
[25578]select at the element, with the [25579]bubbles attribute
initialized to true.
The setRangeText(replacement, start, end, selectMode) method, when
invoked, must run the following steps:
1. If this element is an [25580]input element, and
[25581]setRangeText() [25582]does not apply to this element, throw
an [25583]"InvalidStateError" [25584]DOMException.
2. Set this element's [25585]dirty value flag to true.
3. If the method has only one argument, then let start and end have
the values of the [25586]selectionStart attribute and the
[25587]selectionEnd attribute respectively.
Otherwise, let start, end have the values of the second and third
arguments respectively.
4. If start is greater than end, then throw an [25588]"IndexSizeError"
[25589]DOMException.
5. If start is greater than the [25590]length of the [25591]relevant
value of the text control, then set it to the [25592]length of the
[25593]relevant value of the text control.
6. If end is greater than the [25594]length of the [25595]relevant
value of the text control, then set it to the [25596]length of the
[25597]relevant value of the text control.
7. Let selection start be the current value of the
[25598]selectionStart attribute.
8. Let selection end be the current value of the [25599]selectionEnd
attribute.
9. If start is less than end, delete the sequence of [25600]code units
within the element's [25601]relevant value starting with the code
unit at the startth position and ending with the code unit at the
(end-1)th position.
10. Insert the value of the first argument into the text of the
[25602]relevant value of the text control, immediately before the
startth [25603]code unit.
11. Let new length be the [25604]length of the value of the first
argument.
12. Let new end be the sum of start and new length.
13. Run the appropriate set of substeps from the following list:
If the fourth argument's value is "select"
Let selection start be start.
Let selection end be new end.
If the fourth argument's value is "start"
Let selection start and selection end be start.
If the fourth argument's value is "end"
Let selection start and selection end be new end.
If the fourth argument's value is "preserve"
If the method has only one argument
1. Let old length be end minus start.
2. Let delta be new length minus old length.
3. If selection start is greater than end, then increment it
by delta. (If delta is negative, i.e. the new text is
shorter than the old text, then this will decrease the
value of selection start.)
Otherwise: if selection start is greater than start, then
set it to start. (This snaps the start of the selection
to the start of the new text if it was in the middle of
the text that it replaced.)
4. If selection end is greater than end, then increment it
by delta in the same way.
Otherwise: if selection end is greater than start, then
set it to new end. (This snaps the end of the selection
to the end of the new text if it was in the middle of the
text that it replaced.)
14. [25605]Set the selection range with selection start and selection
end.
The [25606]setRangeText() method uses the following enumeration:
enum SelectionMode {
"[25607]select",
"[25608]start",
"[25609]end",
"[25610]preserve" // default
};
__________________________________________________________________
To obtain the currently selected text, the following JavaScript
suffices:
var selectionText = control.value.substring(control.selectionStart, control.sele
ctionEnd);
...where control is the [25611]input or [25612]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, oldD
irection);
...where control is the [25613]input or [25614]textarea element.
4.10.20 Constraints
4.10.20.1 Definitions
A [25615]submittable element is a candidate for constraint validation
except when a condition has barred the element from constraint
validation. (For example, an element is [25616]barred from constraint
validation if it has a [25617]datalist element ancestor.)
An element can have a custom validity error message defined. Initially,
an element must have its [25618]custom validity error message set to
the empty string. When its value is not the empty string, the element
is [25619]suffering from a custom error. It can be set using the
[25620]setCustomValidity() method, except for [25621]form-associated
custom elements. [25622]Form-associated custom elements can have a
[25623]custom validity error message set via their
[25624]ElementInternals object's [25625]setValidity() method. The user
agent should use the [25626]custom validity error message when alerting
the user to the problem with the control.
An element can be constrained in various ways. The following is the
list of validity states that a form control can be in, making the
control invalid for the purposes of constraint validation. (The
definitions below are non-normative; other parts of this specification
define more precisely when each state applies or does not.)
Suffering from being missing
When a control has no [25627]value but has a required attribute
([25628]input [25629]required, [25630]textarea [25631]required);
or, more complicated rules for [25632]select elements and
controls in [25633]radio button groups, as specified in their
sections.
When the [25634]setValidity() method sets valueMissing flag to
true for a [25635]form-associated custom element.
Suffering from a type mismatch
When a control that allows arbitrary user input has a
[25636]value that is not in the correct syntax ([25637]Email,
[25638]URL).
When the [25639]setValidity() method sets typeMismatch flag to
true for a [25640]form-associated custom element.
Suffering from a pattern mismatch
When a control has a [25641]value that doesn't satisfy the
[25642]pattern attribute.
When the [25643]setValidity() method sets patternMismatch flag
to true for a [25644]form-associated custom element.
Suffering from being too long
When a control has a [25645]value that is too long for the
[25646]form control maxlength attribute ([25647]input
[25648]maxlength, [25649]textarea [25650]maxlength).
When the [25651]setValidity() method sets tooLong flag to true
for a [25652]form-associated custom element.
Suffering from being too short
When a control has a [25653]value that is too short for the
[25654]form control minlength attribute ([25655]input
[25656]minlength, [25657]textarea [25658]minlength).
When the [25659]setValidity() method sets tooShort flag to true
for a [25660]form-associated custom element.
Suffering from an underflow
When a control has a [25661]value that is not the empty string
and is too low for the [25662]min attribute.
When the [25663]setValidity() method sets rangeUnderflow flag to
true for a [25664]form-associated custom element.
Suffering from an overflow
When a control has a [25665]value that is not the empty string
and is too high for the [25666]max attribute.
When the [25667]setValidity() method sets rangeOverflow flag to
true for a [25668]form-associated custom element.
Suffering from a step mismatch
When a control has a [25669]value that doesn't fit the rules
given by the [25670]step attribute.
When the [25671]setValidity() method sets stepMismatch flag to
true for a [25672]form-associated custom element.
Suffering from bad input
When a control has incomplete input and the user agent does not
think the user ought to be able to submit the form in its
current state.
When the [25673]setValidity() method sets badInput flag to true
for a [25674]form-associated custom element.
Suffering from a custom error
When a control's [25675]custom validity error message (as set by
the element's [25676]setCustomValidity() method or
[25677]ElementInternals's [25678]setValidity() method) is not
the empty string.
An element can still suffer from these states even when the element is
[25679]disabled; thus these states can be represented in the DOM even
if validating the form during submission wouldn't indicate a problem to
the user.
An element satisfies its constraints if it is not suffering from any of
the above [25680]validity states.
4.10.20.2 Constraint validation
When the user agent is required to statically validate the constraints
of [25681]form element form, it must run the following steps, which
return either a positive result (all the controls in the form are
valid) or a negative result (there are invalid controls) along with a
(possibly empty) list of elements that are invalid and for which no
script has claimed responsibility:
1. Let controls be a list of all the [25682]submittable elements whose
[25683]form owner is form, in [25684]tree order.
2. Let invalid controls be an initially empty list of elements.
3. For each element field in controls, in [25685]tree order:
1. If field is not a [25686]candidate for constraint validation,
then move on to the next element.
2. Otherwise, if field [25687]satisfies its constraints, then
move on to the next element.
3. Otherwise, add field to invalid controls.
4. If invalid controls is empty, then return a positive result.
5. Let unhandled invalid controls be an initially empty list of
elements.
6. For each element field in invalid controls, if any, in [25688]tree
order:
1. Let notCanceled be the result of [25689]firing an event named
[25690]invalid at field, with the [25691]cancelable attribute
initialized to true.
2. If notCanceled is true, then add field to unhandled invalid
controls.
7. Return a negative result with the list of elements in the unhandled
invalid controls list.
If a user agent is to interactively validate the constraints of
[25692]form element form, then the user agent must run the following
steps:
1. [25693]Statically validate the constraints of form, and let
unhandled invalid controls be the list of elements returned if the
result was negative.
2. If the result was positive, then return that result.
3. Report the problems with the constraints of at least one of the
elements given in unhandled invalid controls to the user.
+ User agents may focus one of those elements in the process, by
running the [25694]focusing steps for that element, and may
change the scrolling position of the document, or perform some
other action that brings the element to the user's attention.
For elements that are [25695]form-associated custom elements,
user agents should use their [25696]validation anchor instead,
for the purposes of these actions.
+ User agents may report more than one constraint violation.
+ User agents may coalesce related constraint violation reports
if appropriate (e.g. if multiple radio buttons in a
[25697]group are marked as required, only one error need be
reported).
+ If one of the controls is not [25698]being rendered (e.g. it
has the [25699]hidden attribute set) then user agents may
report a script error.
4. Return a negative result.
Firefox Android?Safari iOS4+Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
Returns true if the element will be validated when the form is
submitted; false otherwise.
Firefox Android?Safari iOS4+Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
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.
Firefox Android?Safari iOS5+Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
Returns true if the element has no value but is a required
field; false otherwise.
element.[25708]validity.[25709]typeMismatch
Returns true if the element's value is not in the correct
syntax; false otherwise.
element.[25710]validity.[25711]patternMismatch
Returns true if the element's value doesn't match the provided
pattern; false otherwise.
Firefox Android64+Safari iOS5+Chrome Android?WebView
Android4+Samsung Internet?Opera Android12.1+
Returns true if the element's value is longer than the provided
maximum length; false otherwise.
Firefox Android64+Safari iOS?Chrome Android?WebView
Android67+Samsung Internet?Opera Android?
Returns true if the element's value, if it is not the empty
string, is shorter than the provided minimum length; false
otherwise.
element.[25718]validity.[25719]rangeUnderflow
Returns true if the element's value is lower than the provided
minimum; false otherwise.
element.[25720]validity.[25721]rangeOverflow
Returns true if the element's value is higher than the provided
maximum; false otherwise.
element.[25722]validity.[25723]stepMismatch
Returns true if the element's value doesn't fit the rules given
by the [25724]step attribute; false otherwise.
Firefox Android64+Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
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.[25728]validity.[25729]customError
Returns true if the element has a custom error; false otherwise.
element.[25730]validity.[25731]valid
Returns true if the element's value has no validity problems;
false otherwise.
Firefox Android?Safari iOS4+Chrome Android?WebView
Android37+Samsung Internet?Opera Android10.1+
Returns true if the element's value has no validity problems;
false otherwise. Fires an [25736]invalid event at the element in
the latter case.
Firefox Android64+Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
Returns true if the element's value has no validity problems;
otherwise, returns false, fires an [25740]invalid event at the
element, and (if the event isn't canceled) reports the problem
to the user.
Firefox Android?Safari iOS?Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
Returns the error message that would be shown to the user if the
element was to be checked for validity.
The willValidate attribute's getter must return true, if this element
is a [25743]candidate for constraint validation, and false otherwise
(i.e., false if any conditions are [25744]barring it from constraint
validation).
(BUTTON) ✔MDN
[25745]ElementInternals/willValidate
Support in all current engines.
Firefox98+Safari16.4+Chrome77+
__________________________________________________________________
The willValidate attribute of [25746]ElementInternals interface, on
getting, must throw a [25747]"NotSupportedError" [25748]DOMException if
the [25749]target element is not a [25750]form-associated custom
element. Otherwise, it must return true if the [25751]target element is
a [25752]candidate for constraint validation, and false otherwise.
(BUTTON) ✔MDN
[25753]HTMLInputElement/setCustomValidity
Support in all current engines.
Firefox4+Safari5+Chrome4+
__________________________________________________________________
The setCustomValidity(error) method steps are:
1. Set error to the result of [25754]normalizing newlines given error.
2. Set the [25755]custom validity error message to error.
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
[25756]setCustomValidity() method to set an appropriate message.
(BUTTON) ✔MDN
[25757]HTMLObjectElement/validity
Support in all current engines.
Firefox4+Safari5.1+Chrome10+
__________________________________________________________________
The validity attribute's getter must return a [25758]ValidityState
object that represents the [25759]validity states of this element. This
object is [25760]live.
(BUTTON) ✔MDN
[25761]ElementInternals/validity
Support in all current engines.
Firefox98+Safari16.4+Chrome77+
__________________________________________________________________
The validity attribute of [25762]ElementInternals interface, on
getting, must throw a [25763]"NotSupportedError" [25764]DOMException if
the [25765]target element is not a [25766]form-associated custom
element. Otherwise, it must return a [25767]ValidityState object that
represents the [25768]validity states of the [25769]target element.
This object is [25770]live.
[Exposed=Window]
interface ValidityState {
readonly attribute boolean [25771]valueMissing;
readonly attribute boolean [25772]typeMismatch;
readonly attribute boolean [25773]patternMismatch;
readonly attribute boolean [25774]tooLong;
readonly attribute boolean [25775]tooShort;
readonly attribute boolean [25776]rangeUnderflow;
readonly attribute boolean [25777]rangeOverflow;
readonly attribute boolean [25778]stepMismatch;
readonly attribute boolean [25779]badInput;
readonly attribute boolean [25780]customError;
readonly attribute boolean [25781]valid;
};
A [25782]ValidityState object has the following attributes. On getting,
they must return true if the corresponding condition given in the
following list is true, and false otherwise.
valueMissing
The control is [25783]suffering from being missing.
Firefox Android?Safari iOS5+Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
The control is [25787]suffering from a pattern mismatch.
tooLong
The control is [25788]suffering from being too long.
tooShort
The control is [25789]suffering from being too short.
Firefox Android?Safari iOS5+Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
The control is [25795]suffering from a step mismatch.
badInput
The control is [25796]suffering from bad input.
customError
The control is [25797]suffering from a custom error.
valid
None of the other conditions are true.
The check validity steps for an element element are:
1. If element is a [25798]candidate for constraint validation and does
not [25799]satisfy its constraints, then:
1. [25800]Fire an event named [25801]invalid at element, with the
[25802]cancelable attribute initialized to true (though
canceling has no effect).
2. Return false.
2. Return true.
The checkValidity() method, when invoked, must run the [25803]check
validity steps on this element.
(BUTTON) ✔MDN
[25804]ElementInternals/checkValidity
Support in all current engines.
Firefox98+Safari16.4+Chrome77+
__________________________________________________________________
The checkValidity() method of the [25805]ElementInternals interface
must run these steps:
1. Let element be this [25806]ElementInternals's [25807]target
element.
2. If element is not a [25808]form-associated custom element, then
throw a [25809]"NotSupportedError" [25810]DOMException.
3. Run the [25811]check validity steps on element.
The report validity steps for an element element are:
1. If element is a [25812]candidate for constraint validation and does
not [25813]satisfy its constraints, then:
1. Let report be the result of [25814]firing an event named
[25815]invalid at element, with the [25816]cancelable
attribute initialized to true.
2. If report is true, then report the problems with the
constraints of this element to the user. When reporting the
problem with the constraints to the user, the user agent may
run the [25817]focusing steps for element, and may change the
scrolling position of the document, or perform some other
action that brings element to the user's attention. User
agents may report more than one constraint violation, if
element suffers from multiple problems at once.
3. Return false.
2. Return true.
The reportValidity() method, when invoked, must run the [25818]report
validity steps on this element.
(BUTTON) ✔MDN
[25819]ElementInternals/reportValidity
Support in all current engines.
Firefox98+Safari16.4+Chrome77+
__________________________________________________________________
The reportValidity() method of the [25820]ElementInternals interface
must run these steps:
1. Let element be this [25821]ElementInternals's [25822]target
element.
2. If element is not a [25823]form-associated custom element, then
throw a [25824]"NotSupportedError" [25825]DOMException.
3. Run the [25826]report validity steps on element.
The validationMessage attribute's getter must run these steps:
1. If this element is not a [25827]candidate for constraint validation
or if this element [25828]satisfies its constraints, then return
the empty string.
2. Return a suitably localized message that the user agent would show
the user if this were the only form control with a validity
constraint problem. If the user agent would not actually show a
textual message in such a situation (e.g., it would show a
graphical cue instead), then return a suitably localized message
that expresses (one or more of) the validity constraint(s) that the
control does not satisfy. If the element is a [25829]candidate for
constraint validation and is [25830]suffering from a custom error,
then the [25831]custom validity error message should be present in
the return value.
4.10.20.4 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.
4.10.21 Form submission
4.10.21.1 Introduction
This section is non-normative.
When a form is submitted, the data in the form is converted into the
structure specified by the [25832]enctype, and then sent to the
destination specified by the [25833]action using the given
[25834]method.
For example, take the following form:
If the user types in "cats" in the first field and "fur" in the second,
and then hits the submit button, then the user agent will load
/find.cgi?t=cats&q=fur.
On the other hand, consider this 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"
A [25835]form element's default button is the first [25836]submit
button in [25837]tree order whose [25838]form owner is that [25839]form
element.
If the user agent supports letting the user submit a form implicitly
(for example, on some platforms hitting the "enter" key while a text
control is [25840]focused implicitly submits the form), then doing so
for a form, whose [25841]default button has [25842]activation behavior
and is not [25843]disabled, must cause the user agent to [25844]fire a
click event at that [25845]default button.
There are pages on the web that are only usable if there is a way to
implicitly submit forms, so user agents are strongly encouraged to
support this.
If the form has no [25846]submit button, then the implicit submission
mechanism must perform the following steps:
1. If the form has more than one [25847]field that blocks implicit
submission, then return.
2. [25848]Submit the [25849]form element from the [25850]form element
itself with [25851]userInvolvement set to "[25852]activation".
For the purpose of the previous paragraph, an element is a field that
blocks implicit submission of a [25853]form element if it is an
[25854]input element whose [25855]form owner is that [25856]form
element and whose [25857]type attribute is in one of the following
states: [25858]Text, [25859]Search, [25860]Telephone, [25861]URL,
[25862]Email, [25863]Password, [25864]Date, [25865]Month, [25866]Week,
[25867]Time, [25868]Local Date and Time, [25869]Number
4.10.21.3 Form submission algorithm
Each [25870]form element has a constructing entry list boolean,
initially false.
Each [25871]form element has a firing submission events boolean,
initially false.
To submit a [25872]form element form from an element submitter
(typically a button), given an optional boolean submitted from submit()
method (default false) and an optional [25873]user navigation
involvement userInvolvement (default "[25874]none"):
1. If form [25875]cannot navigate, then return.
2. If form's [25876]constructing entry list is true, then return.
3. Let form document be form's [25877]node document.
4. If form document's [25878]active sandboxing flag set has its
[25879]sandboxed forms browsing context flag set, then return.
5. If submitted from [25880]submit() method is false, then:
1. If form's [25881]firing submission events is true, then
return.
2. Set form's [25882]firing submission events to true.
3. For each element field in the list of [25883]submittable
elements whose [25884]form owner is form, set field's
[25885]user validity to true.
4. If the submitter element's [25886]no-validate state is false,
then [25887]interactively validate the constraints of form and
examine the result. If the result is negative (i.e., the
constraint validation concluded that there were invalid fields
and probably informed the user of this), then:
1. Set form's [25888]firing submission events to false.
2. Return.
5. Let submitterButton be null if submitter is form. Otherwise,
let submitterButton be submitter.
6. Let shouldContinue be the result of [25889]firing an event
named [25890]submit at form using [25891]SubmitEvent, with the
[25892]submitter attribute initialized to submitterButton, the
[25893]bubbles attribute initialized to true, and the
[25894]cancelable attribute initialized to true.
7. Set form's [25895]firing submission events to false.
8. If shouldContinue is false, then return.
9. If form [25896]cannot navigate, then return.
[25897]Cannot navigate is run again as dispatching the
[25898]submit event could have changed the outcome.
6. Let encoding be the result of [25899]picking an encoding for the
form.
7. Let entry list be the result of [25900]constructing the entry list
with form, submitter, and encoding.
8. [25901]Assert: entry list is not null.
9. If form [25902]cannot navigate, then return.
[25903]Cannot navigate is run again as dispatching the
[25904]formdata event in [25905]constructing the entry list could
have changed the outcome.
10. Let method be the submitter element's [25906]method.
11. If method is [25907]dialog, then:
1. If form does not have an ancestor [25908]dialog element, then
return.
2. Let subject be form's nearest ancestor [25909]dialog element.
3. Let result be null.
4. If submitter is an [25910]input element whose [25911]type
attribute is in the [25912]Image Button state, then:
1. Let (x, y) be the [25913]selected coordinate.
2. Set result to the concatenation of x, ",", and y.
5. Otherwise, if submitter has a [25914]value, then set result to
that [25915]value.
6. [25916]Close the dialog subject with result.
7. Return.
12. Let action be the submitter element's [25917]action.
13. If action is the empty string, let action be the [25918]URL of the
form document.
14. Let parsed action be the result of [25919]encoding-parsing a URL
given action, relative to submitter's [25920]node document.
15. If parsed action is failure, then return.
16. Let scheme be the [25921]scheme of parsed action.
17. Let enctype be the submitter element's [25922]enctype.
18. Let formTarget be null.
19. If the submitter element is a [25923]submit button and it has a
[25924]formtarget attribute, then set formTarget to the
[25925]formtarget attribute value.
20. Let target be the result of [25926]getting an element's target
given submitter's [25927]form owner and formTarget.
21. Let noopener be the result of [25928]getting an element's noopener
with form, parsed action, and target.
22. Let targetNavigable be the first return value of applying
[25929]the rules for choosing a navigable given target, form's
[25930]node navigable, and noopener.
23. If targetNavigable is null, then return.
24. Let historyHandling be "[25931]auto".
25. If form document equals targetNavigable's [25932]active document,
and form document has not yet [25933]completely loaded, then set
historyHandling to "[25934]replace".
26. Select the appropriate row in the table below based on scheme as
given by the first cell of each row. Then, select the appropriate
cell on that row based on method as given in the first cell of each
column. Then, jump to the steps named in that cell and defined
below the table.
[25935]GET [25936]POST
http [25937]Mutate action URL [25938]Submit as entity body
https [25939]Mutate action URL [25940]Submit as entity body
ftp [25941]Get action URL [25942]Get action URL
javascript [25943]Get action URL [25944]Get action URL
data [25945]Mutate action URL [25946]Get action URL
mailto [25947]Mail with headers [25948]Mail as body
If scheme is not one of those listed in this table, then the
behavior is not defined by this specification. User agents should,
in the absence of another specification defining this, act in a
manner analogous to that defined in this specification for similar
schemes.
Each [25949]form element has a planned navigation, which is either
null or a [25950]task; when the [25951]form is first created, its
[25952]planned navigation must be set to null. In the behaviors
described below, when the user agent is required to plan to
navigate to a [25953]URL url given an optional [25954]POST
resource-or-null postResource (default null), it must run the
following steps:
1. Let referrerPolicy be the empty string.
2. If the [25955]form element's [25956]link types include the
[25957]noreferrer keyword, then set referrerPolicy to
"no-referrer".
3. If the [25958]form has a non-null [25959]planned navigation,
remove it from its [25960]task queue.
4. [25961]Queue an element task on the [25962]DOM manipulation
task source given the [25963]form element and the following
steps:
1. Set the [25964]form's [25965]planned navigation to null.
2. [25966]Navigate targetNavigable to url using the
[25967]form element's [25968]node document, with
[25969]historyHandling set to historyHandling,
[25970]userInvolvement set to userInvolvement,
[25971]sourceElement set to submitter,
[25972]referrerPolicy set to referrerPolicy,
[25973]documentResource set to postResource, and
[25974]formDataEntryList set to entry list.
5. Set the [25975]form's [25976]planned navigation to the
just-queued [25977]task.
The behaviors are as follows:
Mutate action URL
Let pairs be the result of [25978]converting to a list of
name-value pairs with entry list.
Let query be the result of running the
[25979]application/x-www-form-urlencoded serializer with
pairs and encoding.
Set parsed action's [25980]query component to query.
[25981]Plan to navigate to parsed action.
Submit as entity body
[25982]Assert: method is [25983]POST.
Switch on enctype:
[25984]application/x-www-form-urlencoded
Let pairs be the result of [25985]converting to a
list of name-value pairs with entry list.
Let body be the result of running the
[25986]application/x-www-form-urlencoded serializer
with pairs and encoding.
Set body to the result of [25987]encoding body.
Let mimeType be
`[25988]application/x-www-form-urlencoded`.
[25989]multipart/form-data
Let body be the result of running the
[25990]multipart/form-data encoding algorithm with
entry list and encoding.
Let mimeType be the [25991]isomorphic encoding of
the concatenation of "multipart/form-data;
boundary=" and the [25992]multipart/form-data
boundary string generated by the
[25993]multipart/form-data encoding algorithm.
[25994]text/plain
Let pairs be the result of [25995]converting to a
list of name-value pairs with entry list.
Let body be the result of running the
[25996]text/plain encoding algorithm with pairs.
Set body to the result of [25997]encoding body using
encoding.
Let mimeType be `[25998]text/plain`.
[25999]Plan to navigate to parsed action given a
[26000]POST resource whose [26001]request body is body and
[26002]request content-type is mimeType.
Get action URL
[26003]Plan to navigate to parsed action.
entry list is discarded.
Mail with headers
Let pairs be the result of [26004]converting to a list of
name-value pairs with entry list.
Let headers be the result of running the
[26005]application/x-www-form-urlencoded serializer with
pairs and encoding.
Replace occurrences of U+002B PLUS SIGN characters (+) in
headers with the string "%20".
Set parsed action's [26006]query to headers.
[26007]Plan to navigate to parsed action.
Mail as body
Let pairs be the result of [26008]converting to a list of
name-value pairs with entry list.
Switch on enctype:
[26009]text/plain
Let body be the result of running the
[26010]text/plain encoding algorithm with pairs.
Set body to the result of running [26011]UTF-8
percent-encode on body using the [26012]default
encode set. [26013][URL]
Otherwise
Let body be the result of running the
[26014]application/x-www-form-urlencoded serializer
with pairs and encoding.
If parsed action's [26015]query is null, then set it to
the empty string.
If parsed action's [26016]query is not the empty string,
then append a single U+0026 AMPERSAND character (&) to it.
Append "body=" to parsed action's [26017]query.
Append body to parsed action's [26018]query.
[26019]Plan to navigate to parsed action.
4.10.21.4 Constructing the entry list
An entry list is a [26020]list of [26021]entries, typically
representing the contents of a form. An entry is a tuple consisting of
a name (a [26022]scalar value string) and a value (either a
[26023]scalar value string or a [26024]File object).
To create an entry given a string name, a string or [26025]Blob object
value, and optionally a [26026]scalar value string filename:
1. Set name to the result of [26027]converting name into a
[26028]scalar value string.
2. If value is a string, then set value to the result of
[26029]converting value into a [26030]scalar value string.
3. Otherwise:
1. If value is not a [26031]File object, then set value to a new
[26032]File object, representing the same bytes, whose
[26033]name attribute value is "blob".
2. If filename is given, then set value to a new [26034]File
object, representing the same bytes, whose [26035]name
attribute is filename.
These operations will create a new [26036]File object if either
filename is given or the passed [26037]Blob is not a [26038]File
object. In those cases, the identity of the passed [26039]Blob
object is not kept.
4. Return an [26040]entry whose [26041]name is name and whose
[26042]value is value.
To construct the entry list given a form, an optional submitter
(default null), and an optional encoding (default [26043]UTF-8):
1. If form's [26044]constructing entry list is true, then return null.
2. Set form's [26045]constructing entry list to true.
3. Let controls be a list of all the [26046]submittable elements whose
[26047]form owner is form, in [26048]tree order.
4. Let entry list be a new empty [26049]entry list.
5. For each element field in controls, in [26050]tree order:
1. If any of the following are true:
o field has a [26051]datalist element ancestor;
o field is [26052]disabled;
o field is a [26053]button but it is not submitter;
o field is an [26054]input element whose [26055]type
attribute is in the [26056]Checkbox state and whose
[26057]checkedness is false; or
o field is an [26058]input element whose [26059]type
attribute is in the [26060]Radio Button state and whose
[26061]checkedness is false,
then [26062]continue.
2. If the field element is an [26063]input element whose
[26064]type attribute is in the [26065]Image Button state,
then:
1. If the field element is not submitter, then
[26066]continue.
2. If the field element has a [26067]name attribute
specified and its value is not the empty string, let name
be that value followed by U+002E (.). Otherwise, let name
be the empty string.
3. Let name[x] be the concatenation of name and U+0078 (x).
4. Let name[y] be the concatenation of name and U+0079 (y).
5. Let (x, y) be the [26068]selected coordinate.
6. [26069]Create an entry with name[x] and x, and
[26070]append it to entry list.
7. [26071]Create an entry with name[y] and y, and
[26072]append it to entry list.
8. [26073]Continue.
3. If the field is a [26074]form-associated custom element, then
perform the [26075]entry construction algorithm given field
and entry list, then [26076]continue.
4. If either the field element does not have a [26077]name
attribute specified, or its [26078]name attribute's value is
the empty string, then [26079]continue.
5. Let name be the value of the field element's [26080]name
attribute.
6. If the field element is a [26081]select element, then for each
[26082]option element in the [26083]select element's
[26084]list of options whose [26085]selectedness is true and
that is not [26086]disabled, [26087]create an entry with name
and the [26088]value of the [26089]option element, and
[26090]append it to entry list.
7. Otherwise, if the field element is an [26091]input element
whose [26092]type attribute is in the [26093]Checkbox state or
the [26094]Radio Button state, then:
1. If the field element has a [26095]value attribute
specified, then let value be the value of that attribute;
otherwise, let value be the string "on".
2. [26096]Create an entry with name and value, and
[26097]append it to entry list.
8. Otherwise, if the field element is an [26098]input element
whose [26099]type attribute is in the [26100]File Upload
state, then:
1. If there are no [26101]selected files, then [26102]create
an entry with name and a new [26103]File object with an
empty name, [26104]application/octet-stream as type, and
an empty body, and [26105]append it to entry list.
2. Otherwise, for each file in [26106]selected files,
[26107]create an entry with name and a [26108]File object
representing the file, and [26109]append it to entry
list.
9. Otherwise, if the field element is an [26110]input element
whose [26111]type attribute is in the [26112]Hidden state and
name is an [26113]ASCII case-insensitive match for
"[26114]_charset_":
1. Let charset be the [26115]name of encoding.
2. [26116]Create an entry with name and charset, and
[26117]append it to entry list.
10. Otherwise, [26118]create an entry with name and the
[26119]value of the field element, and [26120]append it to
entry list.
11. If the element has a [26121]dirname attribute, that
attribute's value is not the empty string, and the element is
an [26122]auto-directionality form-associated element:
1. Let dirname be the value of the element's [26123]dirname
attribute.
2. Let dir be the string "ltr" if [26124]the directionality
of the element is '[26125]ltr', and "rtl" otherwise
(i.e., when [26126]the directionality of the element is
'[26127]rtl').
3. [26128]Create an entry with dirname and dir, and
[26129]append it to entry list.
6. Let form data be a new [26130]FormData object associated with entry
list.
7. [26131]Fire an event named [26132]formdata at form using
[26133]FormDataEvent, with the [26134]formData attribute
initialized to form data and the [26135]bubbles attribute
initialized to true.
8. Set form's [26136]constructing entry list to false.
9. Return a [26137]clone of entry list.
4.10.21.5 Selecting a form submission encoding
If the user agent is to pick an encoding for a form, it must run the
following steps:
1. Let encoding be the [26138]document's character encoding.
2. If the [26139]form element has an [26140]accept-charset attribute,
set encoding to the return value of running these substeps:
1. Let input be the value of the [26141]form element's
[26142]accept-charset attribute.
2. Let candidate encoding labels be the result of
[26143]splitting input on ASCII whitespace.
3. Let candidate encodings be an empty list of [26144]character
encodings.
4. For each token in candidate encoding labels in turn (in the
order in which they were found in input), [26145]get an
encoding for the token and, if this does not result in
failure, append the [26146]encoding to candidate encodings.
5. If candidate encodings is empty, return [26147]UTF-8.
6. Return the first encoding in candidate encodings.
3. Return the result of [26148]getting an output encoding from
encoding.
4.10.21.6 Converting an entry list to a list of name-value pairs
The [26149]application/x-www-form-urlencoded and [26150]text/plain
encoding algorithms take a list of name-value pairs, where the values
must be strings, rather than an [26151]entry list where the value can
be a [26152]File. The following algorithm performs the conversion.
To convert to a list of name-value pairs an [26153]entry list entry
list, run these steps:
1. Let list be an empty [26154]list of name-value pairs.
2. [26155]For each entry of entry list:
1. Let name be entry's [26156]name, with every occurrence of
U+000D (CR) not followed by U+000A (LF), and every occurrence
of U+000A (LF) not preceded by U+000D (CR), replaced by a
string consisting of U+000D (CR) and U+000A (LF).
2. If entry's [26157]value is a [26158]File object, then let
value be entry's [26159]value's [26160]name. Otherwise, let
value be entry's [26161]value.
3. Replace every occurrence of U+000D (CR) not followed by U+000A
(LF), and every occurrence of U+000A (LF) not preceded by
U+000D (CR), in value, by a string consisting of U+000D (CR)
and U+000A (LF).
4. [26162]Append to list a new name-value pair whose name is name
and whose value is value.
3. Return list.
4.10.21.7 URL-encoded form data
See URL for details on [26163]application/x-www-form-urlencoded.
[26164][URL]
4.10.21.8 Multipart form data
The multipart/form-data encoding algorithm, given an [26165]entry list
entry list and an [26166]encoding encoding, is as follows:
1. [26167]For each entry of entry list:
1. Replace every occurrence of U+000D (CR) not followed by U+000A
(LF), and every occurrence of U+000A (LF) not preceded by
U+000D (CR), in entry's [26168]name, by a string consisting of
a U+000D (CR) and U+000A (LF).
2. If entry's [26169]value is not a [26170]File object, then
replace every occurrence of U+000D (CR) not followed by U+000A
(LF), and every occurrence of U+000A (LF) not preceded by
U+000D (CR), in entry's [26171]value, by a string consisting
of a U+000D (CR) and U+000A (LF).
2. Return the byte sequence resulting from encoding the entry list
using the rules described by RFC 7578, Returning Values from Forms:
multipart/form-data, given the following conditions:
[26172][RFC7578]
+ Each [26173]entry in entry list is a field, the [26174]name of
the entry is the field name and the [26175]value of the entry
is the field value.
+ The order of parts must be the same as the order of fields in
entry list. Multiple entries with the same name must be
treated as distinct fields.
+ Field names, field values for non-file fields, and filenames
for file fields, in the generated [26176]multipart/form-data
resource must be set to the result of [26177]encoding the
corresponding entry's name or value with encoding, converted
to a byte sequence.
+ For field names and filenames for file fields, the result of
the encoding in the previous bullet point must be escaped by
replacing any 0x0A (LF) bytes with the byte sequence `%0A`,
0x0D (CR) with `%0D` and 0x22 (") with `%22`. The user agent
must not perform any other escapes.
+ The parts of the generated [26178]multipart/form-data resource
that correspond to non-file fields must not have a
`[26179]Content-Type` header specified.
+ The boundary used by the user agent in generating the return
value of this algorithm is the multipart/form-data boundary
string. (This value is used to generate the MIME type of the
form submission payload generated by this algorithm.)
For details on how to interpret [26180]multipart/form-data payloads,
see RFC 7578. [26181][RFC7578]
4.10.21.9 Plain text form data
The text/plain encoding algorithm, given a list of name-value pairs
pairs, is as follows:
1. Let result be the empty string.
2. For each pair in pairs:
1. Append pair's name to result.
2. Append a single U+003D EQUALS SIGN character (=) to result.
3. Append pair's value to result.
4. Append a U+000D CARRIAGE RETURN (CR) U+000A LINE FEED (LF)
character pair to result.
3. Return result.
Payloads using the [26182]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).
4.10.21.10 The [26183]SubmitEvent interface
(BUTTON) ✔MDN
[26184]SubmitEvent
Support in all current engines.
Firefox75+Safari15+Chrome81+
__________________________________________________________________
event.[26192]submitter
Returns the element representing the [26193]submit button that
triggered the [26194]form submission, or null if the submission
was not triggered by a button.
The submitter attribute must return the value it was initialized to.
4.10.21.11 The [26195]FormDataEvent interface
(BUTTON) ✔MDN
[26196]FormDataEvent/FormDataEvent
Support in all current engines.
Firefox72+Safari15+Chrome77+
__________________________________________________________________
event.[26204]formData
Returns a [26205]FormData object representing names and values
of elements associated to the target [26206]form. Operations on
the [26207]FormData object will affect form data to be
submitted.
The formData attribute must return the value it was initialized to. It
represents a [26208]FormData object associated to the [26209]entry list
that is [26210]constructed when the [26211]form is submitted.
4.10.22 Resetting a form
When a [26212]form element form is reset, run these steps:
1. Let reset be the result of [26213]firing an event named
[26214]reset at form, with the [26215]bubbles and [26216]cancelable
attributes initialized to true.
2. If reset is true, then invoke the [26217]reset algorithm of each
[26218]resettable element whose [26219]form owner is form.
Each [26220]resettable element defines its own reset algorithm. Changes
made to form controls as part of these algorithms do not count as
changes caused by the user (and thus, e.g., do not cause [26221]input
events to fire).
4.11 Interactive elements
4.11.1 The details element
(BUTTON) ✔MDN
[26222]Element/details
Support in all current engines.
Firefox49+Safari6+Chrome12+
__________________________________________________________________
[26228]Contexts in which this element can be used:
Where [26229]flow content is expected.
[26230]Content model:
One [26231]summary element followed by [26232]flow content.
[26233]Tag omission in text/html:
Neither tag is omissible.
[26234]Content attributes:
[26235]Global attributes
[26236]name — Name of group of mutually-exclusive [26237]details
elements
[26238]open — Whether the details are visible
The [26249]details element [26250]represents a disclosure widget from
which the user can obtain additional information or controls.
As with all HTML elements, it is not conforming to use the
[26251]details element when attempting to represent another type of
control. For example, tab widgets and menu widgets are not disclosure
widgets, so abusing the [26252]details element to implement these
patterns is incorrect.
The [26253]details element is not appropriate for footnotes. Please see
[26254]the section on footnotes for details on how to mark up
footnotes.
The first [26255]summary element child of the element, if any,
[26256]represents the summary or legend of the details. If there is no
child [26257]summary element, the user agent should provide its own
legend (e.g. "Details").
The rest of the element's contents [26258]represents the additional
information or controls.
The name content attribute gives the name of the group of related
[26259]details elements that the element is a member of. Opening one
member of this group causes other members of the group to close. If the
attribute is specified, its value must not be the empty string.
Before using this feature, authors should consider whether this
grouping of related [26260]details elements into an exclusive accordion
is helpful or harmful to users. While using an exclusive accordion can
reduce the maximum amount of space that a set of content can occupy, it
can also frustrate users who have to open many items to find what they
want or users who want to look at the contents of multiple items at the
same time.
A document must not contain more than one [26261]details element in the
same [26262]details name group that has the [26263]open attribute
present. Authors must not use script to add [26264]details elements to
a document in a way that would cause a [26265]details name group to
have more than one [26266]details element with the [26267]open
attribute present.
The group of elements that is created by a common [26268]name attribute
is exclusive, meaning that at most one of the [26269]details elements
can be open at once. While this exclusivity is enforced by user agents,
the resulting enforcement immediately changes the [26270]open
attributes in the markup. This requirement on authors forbids such
misleading markup.
A document must not contain a [26271]details element that is a
descendant of another [26272]details element in the same [26273]details
name group.
Documents that use the [26274]name attribute to group multiple related
[26275]details elements should keep those related elements together in
a containing element (such as a [26276]section element or
[26277]article element). When it makes sense for the group to be
introduced with a heading, authors should put that heading in a
[26278]heading element at the start of the containing element.
Visually and programmatically grouping related elements together can be
important for accessible user experiences. This can help users
understand the relationship between such elements. When related
elements are in disparate sections of a web page rather than being
grouped, the elements' relationships to each other can be less
discoverable or understandable.
The open content attribute is a [26279]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.
When the element is created, if the attribute is absent, the additional
information should be hidden; if the attribute is present, that
information should be shown. Subsequently, if the attribute is removed,
then the information should be hidden; if the attribute is added, the
information should be shown.
The user agent should allow the user to request that the additional
information be shown or hidden. To honor a request for the details to
be shown, the user agent must [26280]set the [26281]open attribute on
the element to the empty string. To honor a request for the information
to be hidden, the user agent must [26282]remove the [26283]open
attribute from the element.
This ability to request that additional information be shown or hidden
may simply be the [26284]activation behavior of the appropriate
[26285]summary element, in the case such an element exists. However, if
no such element exists, user agents can still provide this ability
through some other user interface affordance.
The details name group that contains a [26286]details element a also
contains all the other [26287]details elements b that fulfill all of
the following conditions:
* Both a and b are in the same [26288]tree.
* They both have a [26289]name attribute, their [26290]name
attributes are not the empty string, and the value of a's
[26291]name attribute equals the value of b's [26292]name
attribute.
Every [26293]details element has a details toggle task tracker, which
is a [26294]toggle task tracker or null, initially null.
The following [26295]attribute change steps, given element, localName,
oldValue, value, and namespace, are used for all [26296]details
elements:
1. If namespace is not null, then return.
2. If localName is [26297]name, then [26298]ensure details exclusivity
by closing the given element if needed given element.
3. If localName is [26299]open, then:
1. If one of oldValue or value is null and the other is not null,
run the following steps, which are known as the details
notification task steps, for this [26300]details element:
When the [26301]open attribute is toggled several times in
succession, the resulting tasks essentially get coalesced so
that only one event is fired.
1. If oldValue is null, [26302]queue a details toggle event
task given the [26303]details element, "closed", and
"open".
2. Otherwise, [26304]queue a details toggle event task given
the [26305]details element, "open", and "closed".
2. If oldValue is null and value is not null, then [26306]ensure
details exclusivity by closing other elements if needed given
element.
The [26307]details [26308]HTML element insertion steps, given
insertedNode, are:
1. [26309]Ensure details exclusivity by closing the given element if
needed given insertedNode.
To be clear, these attribute change and insertion steps also run when
an attribute or element is inserted via the parser.
To queue a details toggle event task given a [26310]details element
element, a string oldState, and a string newState:
1. If element's [26311]details toggle task tracker is not null, then:
1. Set oldState to element's [26312]details toggle task tracker's
[26313]old state.
2. Remove element's [26314]details toggle task tracker's
[26315]task from its [26316]task queue.
3. Set element's [26317]details toggle task tracker to null.
2. [26318]Queue an element task given the [26319]DOM manipulation task
source and element to run the following steps:
1. [26320]Fire an event named [26321]toggle at element, using
[26322]ToggleEvent, with the [26323]oldState attribute
initialized to oldState and the [26324]newState attribute
initialized to newState.
2. Set element's [26325]details toggle task tracker to null.
3. Set element's [26326]details toggle task tracker to a struct with
[26327]task set to the just-queued [26328]task and [26329]old state
set to oldState.
To ensure details exclusivity by closing other elements if needed given
a [26330]details element element:
1. [26331]Assert: element has an [26332]open attribute.
2. If element does not have a [26333]name attribute, or its
[26334]name attribute is the empty string, then return.
3. Let groupMembers be a list of elements, containing all elements in
element's [26335]details name group except for element, in
[26336]tree order.
4. [26337]For each element otherElement of groupMembers:
1. If the [26338]open attribute is set on otherElement, then:
1. [26339]Assert: otherElement is the only element in
groupMembers that has the [26340]open attribute set.
2. [26341]Remove the [26342]open attribute on otherElement.
3. [26343]Break.
To ensure details exclusivity by closing the given element if needed
given a [26344]details element element:
1. If element does not have an [26345]open attribute, then return.
2. If element does not have a [26346]name attribute, or its
[26347]name attribute is the empty string, then return.
3. Let groupMembers be a list of elements, containing all elements in
element's [26348]details name group except for element, in
[26349]tree order.
4. [26350]For each element otherElement of groupMembers:
1. If the [26351]open attribute is set on otherElement, then:
1. [26352]Remove the [26353]open attribute on element.
2. [26354]Break.
(BUTTON) ✔MDN
[26355]HTMLDetailsElement/open
Support in all current engines.
Firefox49+Safari6+Chrome10+
__________________________________________________________________
The name and open IDL attributes must [26356]reflect the respective
content attributes of the same name.
The ancestor details revealing algorithm is to run the following steps
on currentNode:
1. While currentNode has a parent node within the [26357]flat tree:
1. If currentNode is slotted into the second slot of a
[26358]details element:
1. Set currentNode to the [26359]details element which
currentNode is slotted into.
2. If the [26360]open attribute is not set on currentNode,
then [26361]set the [26362]open attribute on currentNode
to the empty string.
2. Otherwise, set currentNode to the parent node of currentNode
within the [26363]flat tree.
The following example shows the [26364]details element being used to
hide technical details in a progress report.
Copying "Really Achieving Your Childhood Dreams"
Copying... 25%
Transfer rate:
452KB/s
Local filename:
/home/rpausch/raycd.m4v
Remote filename:
/var/www/lectures/raycd.m4v
Duration:
01:16:27
Color profile:
SD (6-1-6)
Dimensions:
320×240
The following shows how a [26365]details element can be used to hide
some controls by default:
One could use this in conjunction with other [26366]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.
In these examples, the summary really just summarizes what the controls
can change, and not the actual values, which is less than ideal.
The following example shows the [26367]name attribute of the
[26368]details element being used to create an exclusive accordion, a
set of [26369]details elements where a user action to open one
[26370]details element causes any open [26371]details to close.
Material
The picture frame is made of solid oak wood.
Size
The picture frame fits a photo 40cm tall and 30cm wide.
The frame is 45cm tall, 35cm wide, and 2cm thick.
Color
The picture frame is available in its natural wood
color, or with black stain.
The following example shows what happens when the [26372]open attribute
is set on a [26373]details element that is part of a set of elements
using the [26374]name attribute to create an exclusive accordion.
Given the initial markup:
.........
and the script:
document.getElementById("d2").setAttribute("open", "");
then the resulting tree after the script executes will be equivalent to
the markup:
.........
because setting the [26375]open attribute on d2 removes it from d1.
The same happens when the user activates the [26376]summary element
inside of d2.
Because the [26377]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 style sheet is used to
animate the color of the summary when the element is opened or closed:
Automated Status: Operational
Velocity: 12m/s
Direction: North
4.11.2 The summary element
(BUTTON) ✔MDN
[26378]Element/summary
Support in all current engines.
Firefox49+Safari6+Chrome12+
__________________________________________________________________
The [26394]summary element [26395]represents a summary, caption, or
legend for the rest of the contents of the [26396]summary element's
parent [26397]details element, if any.
A [26398]summary element is a summary for its parent details if the
following algorithm returns true:
1. If this [26399]summary element has no parent, then return false.
2. Let parent be this [26400]summary element's parent.
3. If parent is not a [26401]details element, then return false.
4. If parent's first [26402]summary element child is not this
[26403]summary element, then return false.
5. Return true.
The [26404]activation behavior of [26405]summary elements is to run the
following steps:
1. If this [26406]summary element is not the [26407]summary for its
parent details, then return.
2. Let parent be this [26408]summary element's parent.
3. If the [26409]open attribute is present on parent, then
[26410]remove it. Otherwise, [26411]set parent's [26412]open
attribute to the empty string.
This will then run the [26413]details notification task steps.
4.11.3 Commands
4.11.3.1 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 [26414]Disabled State.
Commands are defined to have the following facets:
Label
The name of the command as seen by the user.
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.
Action
The actual effect that triggering the command will have. This
could be a scripted event handler, a [26415]URL to which to
[26416]navigate, or a form submission.
User agents may expose the [26417]commands that match the following
criteria:
* The [26418]Hidden State facet is false (visible)
* The element is [26419]in a document with a non-null [26420]browsing
context.
* Neither the element nor any of its ancestors has a [26421]hidden
attribute specified.
User agents are encouraged to do this especially for commands that have
[26422]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.
4.11.3.2 Using the a element to define a command
An [26423]a element with an [26424]href attribute [26425]defines a
command.
The [26426]Label of the command is the element's [26427]descendant text
content.
The [26428]Access Key of the command is the element's [26429]assigned
access key, if any.
The [26430]Hidden State of the command is true (hidden) if the element
has a [26431]hidden attribute, and false otherwise.
The [26432]Disabled State facet of the command is true if the element
or one of its ancestors is [26433]inert, and false otherwise.
The [26434]Action of the command is to [26435]fire a click event at the
element.
4.11.3.3 Using the button element to define a command
A [26436]button element always [26437]defines a command.
The [26438]Label, [26439]Access Key, [26440]Hidden State, and
[26441]Action facets of the command are determined [26442]as for a
elements (see the previous section).
The [26443]Disabled State of the command is true if the element or one
of its ancestors is [26444]inert, or if the element's [26445]disabled
state is set, and false otherwise.
4.11.3.4 Using the input element to define a command
An [26446]input element whose [26447]type attribute is in one of the
[26448]Submit Button, [26449]Reset Button, [26450]Image Button,
[26451]Button, [26452]Radio Button, or [26453]Checkbox states
[26454]defines a command.
The [26455]Label of the command is determined as follows:
* If the [26456]type attribute is in one of the [26457]Submit Button,
[26458]Reset Button, [26459]Image Button, or [26460]Button states,
then the [26461]Label is the string given by the [26462]value
attribute, if any, and a UA-dependent, locale-dependent value that
the UA uses to label the button itself if the attribute is absent.
* Otherwise, if the element is a [26463]labeled control, then the
[26464]Label is the [26465]descendant text content of the first
[26466]label element in [26467]tree order whose [26468]labeled
control is the element in question. (In JavaScript terms, this is
given by element.labels[0].textContent.)
* Otherwise, if the [26469]value attribute is present, then the
[26470]Label is the value of that attribute.
* Otherwise, the [26471]Label is the empty string.
Even though the [26472]value attribute on [26473]input elements in the
[26474]Image Button state is non-conformant, the attribute can still
contribute to the [26475]Label determination, if it is present and the
Image Button's [26476]alt attribute is missing.
The [26477]Access Key of the command is the element's [26478]assigned
access key, if any.
The [26479]Hidden State of the command is true (hidden) if the element
has a [26480]hidden attribute, and false otherwise.
The [26481]Disabled State of the command is true if the element or one
of its ancestors is [26482]inert, or if the element's [26483]disabled
state is set, and false otherwise.
The [26484]Action of the command is to [26485]fire a click event at the
element.
4.11.3.5 Using the option element to define a command
An [26486]option element with an ancestor [26487]select element and
either no [26488]value attribute or a [26489]value attribute that is
not the empty string [26490]defines a command.
The [26491]Label of the command is the value of the [26492]option
element's [26493]label attribute, if there is one, or else the
[26494]option element's [26495]descendant text content, with
[26496]ASCII whitespace stripped and collapsed.
The [26497]Access Key of the command is the element's [26498]assigned
access key, if any.
The [26499]Hidden State of the command is true (hidden) if the element
has a [26500]hidden attribute, and false otherwise.
The [26501]Disabled State of the command is true if the element is
[26502]disabled, or if its nearest ancestor [26503]select element is
[26504]disabled, or if it or one of its ancestors is [26505]inert, and
false otherwise.
If the [26506]option's nearest ancestor [26507]select element has a
[26508]multiple attribute, the [26509]Action of the command is to
[26510]toggle the [26511]option element. Otherwise, the [26512]Action
is to [26513]pick the [26514]option element.
4.11.3.6 Using the accesskey attribute on a legend element to define a
command
A [26515]legend element [26516]defines a command if all of the
following are true:
* It has an [26517]assigned access key.
* It is a child of a [26518]fieldset element.
* Its parent has a descendant that [26519]defines a command that is
neither a [26520]label element nor a [26521]legend element. This
element, if it exists, is the legend element's accesskey delegatee.
The [26522]Label of the command is the element's [26523]descendant text
content.
The [26524]Access Key of the command is the element's [26525]assigned
access key.
The [26526]Hidden State, [26527]Disabled State, and [26528]Action
facets of the command are the same as the respective facets of
[26529]the legend element's accesskey delegatee.
In this example, the [26530]legend element specifies an
[26531]accesskey, which, when activated, will delegate to the
[26532]input element inside the [26533]legend element.
4.11.3.7 Using the accesskey attribute to define a command on other
elements
An element that has an [26534]assigned access key [26535]defines a
command.
If one of the earlier sections that define elements that [26536]define
commands define that this element [26537]defines a command, then that
section applies to this element, and this section does not. Otherwise,
this section applies to that element.
The [26538]Label of the command depends on the element. If the element
is a [26539]labeled control, the [26540]descendant text content of the
first [26541]label element in [26542]tree order whose [26543]labeled
control is the element in question is the [26544]Label (in JavaScript
terms, this is given by element.labels[0].textContent). Otherwise, the
[26545]Label is the element's [26546]descendant text content.
The [26547]Access Key of the command is the element's [26548]assigned
access key.
The [26549]Hidden State of the command is true (hidden) if the element
has a [26550]hidden attribute, and false otherwise.
The [26551]Disabled State of the command is true if the element or one
of its ancestors is [26552]inert, and false otherwise.
The [26553]Action of the command is to run the following steps:
1. Run the [26554]focusing steps for the element.
2. [26555]Fire a click event at the element.
4.11.4 The dialog element
(BUTTON) ✔MDN
[26556]Element/dialog
Support in all current engines.
Firefox98+Safari15.4+Chrome37+
__________________________________________________________________
[26560]Contexts in which this element can be used:
Where [26561]flow content is expected.
[26562]Content model:
[26563]Flow content.
[26564]Tag omission in text/html:
Neither tag is omissible.
[26565]Content attributes:
[26566]Global attributes
[26567]closedby — Which user actions will close the dialog
[26568]open — Whether the dialog box is showing
The [26588]dialog element represents a transitory part of an
application, in the form of a small window ("dialog box"), which the
user interacts with to perform a task or gather information. Once the
user is done, the dialog can be automatically closed by the
application, or manually closed by the user.
Especially for modal dialogs, which are a familiar pattern across all
types of applications, authors should work to ensure that dialogs in
their web applications behave in a way that is familiar to users of
non-web applications.
As with all HTML elements, it is not conforming to use the
[26589]dialog element when attempting to represent another type of
control. For example, context menus, tooltips, and popup listboxes are
not dialog boxes, so abusing the [26590]dialog element to implement
these patterns is incorrect.
An important part of user-facing dialog behavior is the placement of
initial focus. The [26591]dialog focusing steps attempt to pick a good
candidate for initial focus when a dialog is shown, but might not be a
substitute for authors carefully thinking through the correct choice to
match user expectations for a specific dialog. As such, authors should
use the [26592]autofocus attribute on the descendant element of the
dialog that the user is expected to immediately interact with after the
dialog opens. If there is no such element, then authors should use the
[26593]autofocus attribute on the [26594]dialog element itself.
In the following example, a dialog is used for editing the details of a
product in an inventory management web application.
If the [26595]autofocus attribute was not present, the Product Number
field would have been focused by the dialog focusing steps. Although
that is reasonable behavior, the author determined that the more
relevant field to focus was the Product Name field, as the Product
Number field is readonly and expects no user input. So, the author used
autofocus to override the default.
Even if the author wants to focus the Product Number field by default,
they are best off explicitly specifying that by using autofocus on that
[26596]input element. This makes the intent obvious to future readers
of the code, and ensures the code stays robust in the face of future
updates. (For example, if another developer added a close button, and
positioned it in the node tree before the Product Number field).
Another important aspect of user behavior is whether dialogs are
scrollable or not. In some cases, overflow (and thus scrollability)
cannot be avoided, e.g., when it is caused by the user's high text zoom
settings. But in general, scrollable dialogs are not expected by users.
Adding large text nodes directly to dialog elements is particularly bad
as this is likely to cause the dialog element itself to overflow.
Authors are best off avoiding them.
The following terms of service dialog respects the above suggestions.
Note how the [26597]dialog focusing steps would have picked the
scrollable [26598]div element by default, but similarly to the previous
example, we have placed [26599]autofocus on the [26600]div so as to be
more explicit and robust against future changes.
In contrast, if the [26601]p elements expressing the terms of service
did not have such a wrapper [26602]div element, then the [26603]dialog
itself would become scrollable, violating the above advice.
Furthermore, in the absence of any [26604]autofocus attribute, such a
markup pattern would have violated the above advice and tripped up the
[26605]dialog focusing steps's default behavior, and caused focus to
jump to the Agree [26606]button, which is a bad user experience.
This dialog box has some small print. The [26607]strong element is used
to draw the user's attention to the more important part.
__________________________________________________________________
The open attribute is a [26608]boolean attribute. When specified, it
indicates that the [26609]dialog element is active and that the user
can interact with it.
The closedby content attribute is an [26610]enumerated attribute with
the following keywords and states:
Keyword State Brief description
any Any [26611]Close requests or clicks outside close the dialog.
closerequest Close Request [26612]Close requests close the dialog.
none None No user actions automatically close the dialog.
The [26613]closedby attribute's [26614]invalid value default and
[26615]missing value default are both the Auto state.
The [26616]Auto state behaves as [26617]Close Request state when the
[26618]dialog was shown using its [26619]showModal() method; otherwise
the [26620]None state.
A [26621]dialog element without an [26622]open attribute specified
should not be shown to the user. This requirement may be implemented
indirectly through the style layer. For example, user agents that
[26623]support the suggested default rendering implement this
requirement using the CSS rules described in the [26624]Rendering
section.
Removing the [26625]open attribute will usually hide the dialog.
However, doing so has a number of strange additional consequences:
* The [26626]close event will not be fired.
* The [26627]close() method, and any [26628]close requests, will no
longer be able to close the dialog.
* If the dialog was shown using its [26629]showModal() method, the
[26630]Document will still be [26631]blocked.
For these reasons, it is generally better to never remove the
[26632]open attribute manually. Instead, use the [26633]requestClose()
or [26634]close() methods to close the dialog, or the [26635]hidden
attribute to hide it.
The [26636]tabindex attribute must not be specified on [26637]dialog
elements.
__________________________________________________________________
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
Displays the [26643]dialog element and makes it the top-most
modal dialog.
This method honors the [26644]autofocus attribute.
The argument, if provided, provides a return value.
dialog.[26648]requestClose([ result ])
Acts as if a [26649]close request was sent targeting dialog, by
first firing a [26650]cancel event, and if that event is not
canceled with [26651]preventDefault(), proceeding to close the
dialog in the same way as the [26652]close() method (including
firing a [26653]close event).
This is a helper utility that can be used to consolidate
cancelation and closing logic into the [26654]cancel and
[26655]close event handlers, by having all non-[26656]close
request closing affordances call this method.
Note that this method ignores the [26657]closedby attribute:
that is, even if [26658]closedby is set to "[26659]none", the
same behavior will apply.
The argument, if provided, provides a return value.
The show() method steps are:
1. If [26663]this has an [26664]open attribute and [26665]is modal of
[26666]this is false, then return.
2. If [26667]this has an [26668]open attribute, then throw an
[26669]"InvalidStateError" [26670]DOMException.
3. If the result of [26671]firing an event named [26672]beforetoggle,
using [26673]ToggleEvent, with the [26674]cancelable attribute
initialized to true, the [26675]oldState attribute initialized to
"closed", and the [26676]newState attribute initialized to "open"
at [26677]this is false, then return.
4. If [26678]this has an [26679]open attribute, then return.
5. [26680]Queue a dialog toggle event task given [26681]this,
"closed", and "open".
6. Add an [26682]open attribute to [26683]this, whose value is the
empty string.
7. [26684]Assert: [26685]this's [26686]node document's [26687]open
dialogs list does not [26688]contain [26689]this.
8. Add [26690]this to [26691]this's [26692]node document's [26693]open
dialogs list.
9. [26694]Set the dialog close watcher with [26695]this.
10. Set [26696]this's [26697]previously focused element to the
[26698]focused element.
11. Let document be [26699]this's [26700]node document.
12. Let hideUntil be the result of running [26701]topmost popover
ancestor given [26702]this, document's [26703]showing hint popover
list, null, and false.
13. If hideUntil is null, then set hideUntil to the result of running
[26704]topmost popover ancestor given [26705]this, document's
[26706]showing auto popover list, null, and false.
14. If hideUntil is null, then set hideUntil to document.
15. Run [26707]hide all popovers until given hideUntil, false, and
true.
16. Run the [26708]dialog focusing steps given [26709]this.
The showModal() method steps are to [26710]show a modal dialog given
[26711]this.
The close(returnValue) method steps are:
1. If returnValue is not given, then set it to null.
2. [26712]Close the dialog [26713]this with returnValue.
The requestClose(returnValue) method steps are:
1. If [26714]this does not have an [26715]open attribute, then return.
2. [26716]Assert: [26717]this's [26718]close watcher is not null.
3. Set dialog's [26719]enable close watcher for requestClose() to
true.
4. If returnValue is not given, then set it to null.
5. Set [26720]this's [26721]request close return value to returnValue.
6. [26722]Request to close dialog's [26723]close watcher with false.
7. Set dialog's [26724]enable close watcher for requestClose() to
false.
We use show/close as the verbs for [26725]dialog elements, as opposed
to verb pairs that are more commonly thought of as antonyms such as
show/hide or open/close, due to the following constraints:
* Hiding a dialog is different from closing one. Closing a dialog
gives it a return value, fires an event, unblocks the page for
other dialogs, and so on. Whereas hiding a dialog is a purely
visual property, and is something you can already do with the
[26726]hidden attribute or by removing the [26727]open attribute.
(See also the [26728]note above about removing the [26729]open
attribute, and how hiding the dialog in that way is generally not
desired.)
* Showing a dialog is different from opening one. Opening a dialog
consists of creating and showing that dialog (similar to how
[26730]window.open() both creates and shows a new window). Whereas
showing the dialog is the process of taking a [26731]dialog element
that is already in the DOM, and making it interactive and visible
to the user.
* If we were to have a dialog.open() method despite the above, it
would conflict with the [26732]dialog.open property.
Furthermore, a [26733]survey of many other UI frameworks contemporary
to the original design of the [26734]dialog element made it clear that
the show/close verb pair was reasonably common.
In summary, it turns out that the implications of certain verbs, and
how they are used in technology contexts, mean that paired actions such
as showing and closing a dialog are not always expressible as antonyms.
The returnValue IDL attribute, on getting, must return the last value
to which it was set. On setting, it must be set to the new value. When
the element is created, it must be set to the empty string.
The closedBy getter steps are to return the keyword corresponding to
the [26735]computed closed-by state given [26736]this.
The [26737]closedBy setter steps are to set the [26738]closedby content
attribute to the given value.
(BUTTON) ✔MDN
[26739]HTMLDialogElement/open
Support in all current engines.
Firefox98+Safari15.4+Chrome37+
__________________________________________________________________
The open IDL attribute must [26740]reflect the [26741]open content
attribute.
__________________________________________________________________
Each [26742]Document has a dialog pointerdown target, which is an
[26743]HTML dialog element or null, initially null.
Each [26744]HTML element has a previously focused element which is null
or an element, and it is initially null. When [26745]showModal() and
[26746]show() are called, this element is set to the currently
[26747]focused element before running the [26748]dialog focusing steps.
Elements with the [26749]popover attribute set this element to the
currently [26750]focused element during the [26751]show popover
algorithm.
Each [26752]dialog element has a dialog toggle task tracker, which is a
[26753]toggle task tracker or null, initially null.
Each [26754]dialog element has a close watcher, which is a [26755]close
watcher or null, initially null.
Each [26756]dialog element has a request close return value, which is a
string, initially null.
Each [26757]dialog element has an enable close watcher for
requestClose() boolean, initially false.
Each [26758]dialog element has an is modal boolean, initially false.
__________________________________________________________________
The [26759]dialog [26760]HTML element removing steps, given removedNode
and oldParent, are:
1. If removedNode's [26761]close watcher is not null, then:
1. [26762]Destroy removedNode's [26763]close watcher.
2. Set removedNode's [26764]close watcher to null.
2. If removedNode's [26765]node document's [26766]top layer
[26767]contains removedNode, then [26768]remove an element from the
top layer immediately given removedNode.
3. Set [26769]is modal of removedNode to false.
4. [26770]Remove removedNode from removedNode's [26771]node document's
[26772]open dialogs list.
To show a modal dialog given a [26773]dialog element subject:
1. If subject has an [26774]open attribute and [26775]is modal of
subject is true, then return.
2. If subject has an [26776]open attribute, then throw an
[26777]"InvalidStateError" [26778]DOMException.
3. If subject's [26779]node document is not [26780]fully active, then
throw an [26781]"InvalidStateError" [26782]DOMException.
4. If subject is not [26783]connected, then throw an
[26784]"InvalidStateError" [26785]DOMException.
5. If subject is in the [26786]popover showing state, then throw an
[26787]"InvalidStateError" [26788]DOMException.
6. If the result of [26789]firing an event named [26790]beforetoggle,
using [26791]ToggleEvent, with the [26792]cancelable attribute
initialized to true, the [26793]oldState attribute initialized to
"closed", and the [26794]newState attribute initialized to "open"
at subject is false, then return.
7. If subject has an [26795]open attribute, then return.
8. If subject is not [26796]connected, then return.
9. If subject is in the [26797]popover showing state, then return.
10. [26798]Queue a dialog toggle event task given subject, "closed",
and "open".
11. Add an [26799]open attribute to subject, whose value is the empty
string.
12. Set [26800]is modal of subject to true.
13. [26801]Assert: subject's [26802]node document's [26803]open dialogs
list does not [26804]contain subject.
14. Add subject to subject's [26805]node document's [26806]open dialogs
list.
15. Let subject's [26807]node document be [26808]blocked by the modal
dialog subject.
This will cause the [26809]focused area of the document to become
[26810]inert (unless that currently focused area is a
[26811]shadow-including descendant of subject). In such cases, the
[26812]focused area of the document will soon be [26813]reset to
the [26814]viewport. In a couple steps we will attempt to find a
better candidate to focus.
16. If subject's [26815]node document's [26816]top layer does not
already [26817]contain subject, then [26818]add an element to the
top layer given subject.
17. [26819]Set the dialog close watcher with subject.
18. Set subject's [26820]previously focused element to the
[26821]focused element.
19. Let document be subject's [26822]node document.
20. Let hideUntil be the result of running [26823]topmost popover
ancestor given subject, document's [26824]showing hint popover
list, null, and false.
21. If hideUntil is null, then set hideUntil to the result of running
[26825]topmost popover ancestor given subject, document's
[26826]showing auto popover list, null, and false.
22. If hideUntil is null, then set hideUntil to document.
23. Run [26827]hide all popovers until given hideUntil, false, and
true.
24. Run the [26828]dialog focusing steps given subject.
To set the dialog close watcher, given a [26829]dialog element dialog:
1. Set dialog's [26830]close watcher to the result of
[26831]establishing a close watcher given dialog's [26832]relevant
global object, with:
+ [26833]cancelAction given canPreventClose being to return the
result of [26834]firing an event named [26835]cancel at
dialog, with the [26836]cancelable attribute initialized to
canPreventClose.
+ [26837]closeAction being to [26838]close the dialog given
dialog and dialog's [26839]request close return value.
+ [26840]getEnabledState being to return true if dialog's
[26841]enable close watcher for requestClose() is true or
dialog's [26842]computed closed-by state is not [26843]None;
otherwise false.
The [26844]is valid invoker command steps for [26845]dialog elements,
given a [26846]command attribute command, are:
1. If command is in the [26847]Close state or in the [26848]Show Modal
state, then return true.
2. Return false.
The [26849]invoker command steps for [26850]dialog elements, given an
element element, an element invoker, and a [26851]command attribute
command, are:
1. If element is in the [26852]popover showing state, then return.
2. If command is in the [26853]Close state and element has an
[26854]open attribute:
1. Let value be invoker's [26855]value.
2. [26856]Close the dialog element with value.
3. If command is the [26857]Show Modal state and element does not have
an [26858]open attribute, then [26859]show a modal dialog given
element.
The following buttons use [26860]commandfor to open and close a
"confirm" [26861]dialog as modal when activated:
When a [26862]dialog element subject is to be closed, with null or a
string result, run these steps:
1. If subject does not have an [26863]open attribute, then return.
2. [26864]Fire an event named [26865]beforetoggle, using
[26866]ToggleEvent, with the [26867]oldState attribute initialized
to "open" and the [26868]newState attribute initialized to "closed"
at subject.
3. If subject does not have an [26869]open attribute, then return.
4. [26870]Queue a dialog toggle event task given subject, "open", and
"closed".
5. Remove subject's [26871]open attribute.
6. If [26872]is modal of subject is true, then [26873]request an
element to be removed from the top layer given subject.
7. Let wasModal be the value of subject's [26874]is modal flag.
8. Set [26875]is modal of subject to false.
9. [26876]Remove subject from subject's [26877]node document's
[26878]open dialogs list.
10. If result is not null, then set the [26879]returnValue attribute to
result.
11. Set the [26880]request close return value to null.
12. If subject's [26881]previously focused element is not null, then:
1. Let element be subject's [26882]previously focused element.
2. Set subject's [26883]previously focused element to null.
3. If subject's [26884]node document's [26885]focused area of the
document's [26886]DOM anchor is a [26887]shadow-including
inclusive descendant of subject, or wasModal is true, then run
the [26888]focusing steps for element; the viewport should not
be scrolled by doing this step.
13. [26889]Queue an element task on the [26890]user interaction task
source given the subject element to [26891]fire an event named
[26892]close at subject.
14. If subject's [26893]close watcher is not null, then:
1. [26894]Destroy subject's [26895]close watcher.
2. Set subject's [26896]close watcher to null.
To queue a dialog toggle event task given a [26897]dialog element
element, a string oldState, and a string newState:
1. If element's [26898]dialog toggle task tracker is not null, then:
1. Set oldState to element's [26899]dialog toggle task tracker's
[26900]old state.
2. Remove element's [26901]dialog toggle task tracker's
[26902]task from its [26903]task queue.
3. Set element's [26904]dialog toggle task tracker to null.
2. [26905]Queue an element task given the [26906]DOM manipulation task
source and element to run the following steps:
1. [26907]Fire an event named [26908]toggle at element, using
[26909]ToggleEvent, with the [26910]oldState attribute
initialized to oldState and the [26911]newState attribute
initialized to newState.
2. Set element's [26912]dialog toggle task tracker to null.
3. Set element's [26913]dialog toggle task tracker to a struct with
[26914]task set to the just-queued [26915]task and [26916]old state
set to oldState.
To retrieve a dialog's computed closed-by state, given a [26917]dialog
dialog:
1. If the state of dialog's [26918]closedby attribute is [26919]Auto:
1. If dialog's [26920]is modal is true, then return [26921]Close
Request.
2. Return [26922]None.
2. Return the state of dialog's [26923]closedby attribute.
The dialog focusing steps, given a [26924]dialog element subject, are
as follows:
1. If the [26925]allow focus steps given subject's [26926]node
document return false, then return.
2. Let control be null.
3. If subject has the [26927]autofocus attribute, then set control to
subject.
4. If control is null, then set control to the [26928]focus delegate
of subject.
5. If control is null, then set control to subject.
6. Run the [26929]focusing steps for control.
If control is not [26930]focusable, this will do nothing. This
would only happen if subject had no focus delegate, and the user
agent decided that [26931]dialog elements were not generally
focusable. In that case, any [26932]earlier modifications to the
[26933]focused area of the document will apply.
7. Let topDocument be control's [26934]node navigable's
[26935]top-level traversable's [26936]active document.
8. If control's [26937]node document's [26938]origin is not the
[26939]same as the [26940]origin of topDocument, then return.
9. [26941]Empty topDocument's [26942]autofocus candidates.
10. Set topDocument's [26943]autofocus processed flag to true.
4.11.5 Dialog light dismiss
"Light dismiss" means that clicking outside of a [26944]dialog element
whose [26945]closedby attribute is in the [26946]Any state will close
the [26947]dialog element. This is in addition to how such
[26948]dialogs respond to [26949]close requests.
To light dismiss open dialogs, given a [26950]PointerEvent event:
1. [26951]Assert: event's [26952]isTrusted attribute is true.
2. Let document be event's [26953]target's [26954]node document.
3. If document's [26955]open dialogs list is [26956]empty, then
return.
4. Let ancestor be the result of running [26957]nearest clicked dialog
given event.
5. If event's [26958]type is "[26959]pointerdown", then set document's
[26960]dialog pointerdown target to ancestor.
6. If event's [26961]type is "[26962]pointerup", then:
1. Let sameTarget be true if ancestor is document's [26963]dialog
pointerdown target.
2. Set document's [26964]dialog pointerdown target to null.
3. If sameTarget is false, then return.
4. Let topmostDialog be the last element of document's
[26965]open dialogs list.
5. If ancestor is topmostDialog, then return.
6. If topmostDialog's [26966]computed closed-by state is not
[26967]Any, then return.
7. [26968]Assert: topmostDialog's [26969]close watcher is not
null.
8. [26970]Request to close topmostDialog's [26971]close watcher
with false.
To run light dismiss activities, given a [26972]PointerEvent event:
1. Run [26973]light dismiss open popovers with event.
2. Run [26974]light dismiss open dialogs with event.
[26975]Run light dismiss activities will be called by the
[26976]Pointer Events spec when the user clicks or touches anywhere on
the page.
To find the nearest clicked dialog, given a [26977]PointerEvent event:
1. Let target be event's [26978]target.
2. If target is a [26979]dialog element, target has an [26980]open
attribute, target's [26981]is modal is true, and event's
[26982]clientX and [26983]clientY are outside the bounds of target,
then return null.
The check for [26984]clientX and [26985]clientY is because a
pointer event that hits the ::backdrop pseudo element of a dialog
will result in event having a target of the dialog element itself.
3. Let currentNode be target.
4. While currentNode is not null:
1. If currentNode is a [26986]dialog element and currentNode has
an [26987]open attribute, then return currentNode.
2. Set currentNode to currentNode's parent in the [26988]flat
tree.
5. Return null.
4.12 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 a script to show or hide a section to
show more details, the [26989]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.
4.12.1 The script element
(BUTTON) ✔MDN
[26990]Element/script
Support in all current engines.
Firefox1+Safari3+Chrome1+
__________________________________________________________________
[26997]Contexts in which this element can be used:
Where [26998]metadata content is expected.
Where [26999]phrasing content is expected.
Where [27000]script-supporting elements are expected.
[27001]Content model:
If there is no [27002]src attribute, depends on the value of the
[27003]type attribute, but must match [27004]script content
restrictions.
If there is a [27005]src attribute, the element must be either
empty or contain only [27006]script documentation that also
matches [27007]script content restrictions.
[27008]Tag omission in text/html:
Neither tag is omissible.
[27009]Content attributes:
[27010]Global attributes
[27011]src — Address of the resource
[27012]type — Type of script
[27013]nomodule — Prevents execution in user agents that support
[27014]module scripts
[27015]async — Execute script when available, without blocking
while fetching
[27016]defer — Defer script execution
[27017]crossorigin — How the element handles crossorigin
requests
[27018]integrity — Integrity metadata used in Subresource
Integrity checks [27019][SRI]
[27020]referrerpolicy — [27021]Referrer policy for
[27022]fetches initiated by the element
[27023]blocking — Whether the element is [27024]potentially
render-blocking
[27025]fetchpriority — Sets the [27026]priority for
[27027]fetches initiated by the element
The [27059]script element allows authors to include dynamic script and
data blocks in their documents. The element does not [27060]represent
content for the user.
(BUTTON) ✔MDN
[27061]Element/script#attr-type
Support in all current engines.
Firefox1+Safari≤4+Chrome1+
__________________________________________________________________
The type attribute allows customization of the type of script
represented:
* Omitting the attribute, setting it to the empty string, or setting
it to a [27062]JavaScript MIME type essence match, means that the
script is a [27063]classic script, to be interpreted according to
the JavaScript [27064]Script top-level production. Classic scripts
are affected by the [27065]async and [27066]defer attributes, but
only when the [27067]src attribute is set. Authors should omit the
[27068]type attribute instead of redundantly setting it.
* Setting the attribute to an [27069]ASCII case-insensitive match for
"module" means that the script is a [27070]JavaScript module
script, to be interpreted according to the JavaScript [27071]Module
top-level production. Module scripts are not affected by the
[27072]defer attribute, but are affected by the [27073]async
attribute (regardless of the state of the [27074]src attribute).
* Setting the attribute to an [27075]ASCII case-insensitive match for
"importmap" means that the script is an [27076]import map,
containing JSON that will be used to control the behavior of
[27077]module specifier resolution. Import maps can only be inline,
i.e., the [27078]src attribute and most other attributes are
meaningless and not to be used with them.
* Setting the attribute to any other value means that the script is a
data block, which is not processed. None of the [27079]script
attributes (except [27080]type itself) have any effect on data
blocks. Authors must use a [27081]valid MIME type string that is
not a [27082]JavaScript MIME type essence match to denote data
blocks.
The requirement that [27083]data blocks must be denoted using a
[27084]valid MIME type string is in place to avoid potential future
collisions. If this specification ever adds additional types of
[27085]script, they will be triggered by setting the [27086]type
attribute to something which is not a MIME type, like how the "module"
value denotes [27087]module scripts. By using a valid MIME type string
now, you ensure that your data block will not ever be reinterpreted as
a different script type, even in future user agents.
[27088]Classic scripts and [27089]JavaScript module scripts can be
embedded inline, or be imported from an external file using the src
attribute, which if specified gives the [27090]URL of the external
script resource to use. If [27091]src is specified, it must be a
[27092]valid non-empty URL potentially surrounded by spaces.
The contents of inline [27093]script elements, or the external script
resource, must conform with the requirements of the JavaScript
specification's [27094]Script or [27095]Module productions, for
[27096]classic scripts and [27097]JavaScript module scripts
respectively. [27098][JAVASCRIPT]
The contents of the external script resource for [27099]CSS module
scripts must conform to the requirements of the CSS specification.
[27100][CSS]
The contents of the external script resource for [27101]JSON module
scripts must conform to the requirements of the JSON specification.
[27102][JSON]
The contents of inline [27103]script elements for [27104]import maps
must conform with the [27105]import map authoring requirements.
For [27106]import map [27107]script elements, the [27108]src,
[27109]async, [27110]nomodule, [27111]defer, [27112]crossorigin,
[27113]integrity, and [27114]referrerpolicy attributes must not be
specified.
A document must not have more than one [27115]import map [27116]script
element.
When used to include [27117]data blocks, the data must be embedded
inline, the format of the data must be given using the [27118]type
attribute, and the contents of the [27119]script element must conform
to the requirements defined for the format used. The [27120]src,
[27121]async, [27122]nomodule, [27123]defer, [27124]crossorigin,
[27125]integrity, [27126]referrerpolicy, and [27127]fetchpriority
attributes must not be specified.
The nomodule attribute is a [27128]boolean attribute that prevents a
script from being executed in user agents that support [27129]module
scripts. This allows selective execution of [27130]module scripts in
modern user agents and [27131]classic scripts in older user agents,
[27132]as shown below. The [27133]nomodule attribute must not be
specified on [27134]module scripts (and will be ignored if it is).
(BUTTON) ✔MDN
[27135]Element/script#attr-async
Support in all current engines.
Firefox1+Safari≤4+Chrome1+
__________________________________________________________________
The async and defer attributes are [27137]boolean attributes that
indicate how the script should be evaluated. [27138]Classic scripts may
specify [27139]defer or [27140]async, but must not specify either
unless the [27141]src attribute is present. [27142]Module scripts may
specify the [27143]async attribute, but must not specify the
[27144]defer attribute.
There are several possible modes that can be selected using these
attributes, and depending on the script's type.
For [27145]classic scripts, if the [27146]async attribute is present,
then the classic script will be fetched [27147]in parallel to parsing
and evaluated as soon as it is available (potentially before parsing
completes). If the [27148]async attribute is not present but the
[27149]defer attribute is present, then the classic script will be
fetched [27150]in parallel and evaluated when the page has finished
parsing. If neither attribute is present, then the script is fetched
and evaluated immediately, blocking parsing until these are both
complete.
For [27151]module scripts, if the [27152]async attribute is present,
then the module script and all its dependencies will be fetched
[27153]in parallel to parsing, and the module script will be evaluated
as soon as it is available (potentially before parsing completes).
Otherwise, the module script and its dependencies will be fetched
[27154]in parallel to parsing and evaluated when the page has finished
parsing. (The [27155]defer attribute has no effect on module scripts.)
This is all summarized in the following schematic diagram:
With
The blocking attribute is a [27190]blocking attribute.
The fetchpriority attribute is a [27191]fetch priority attribute. Its
purpose is to set the [27192]priority used when [27193]fetching the
script.
Changing the [27194]src, [27195]type, [27196]nomodule, [27197]async,
[27198]defer, [27199]crossorigin, [27200]integrity,
[27201]referrerpolicy, and [27202]fetchpriority attributes dynamically
has no direct effect; these attributes are only used at specific times
described below.
The IDL attributes src, type, defer, integrity, and blocking, must each
[27203]reflect the respective content attributes of the same name.
(BUTTON) ✔MDN
[27204]HTMLScriptElement/referrerPolicy
Support in all current engines.
Firefox65+Safari14+Chrome70+
__________________________________________________________________
The referrerPolicy IDL attribute must [27205]reflect the
[27206]referrerpolicy content attribute, [27207]limited to only known
values.
The fetchPriority IDL attribute must [27208]reflect the
[27209]fetchpriority content attribute, [27210]limited to only known
values.
The crossOrigin IDL attribute must [27211]reflect the
[27212]crossorigin content attribute, [27213]limited to only known
values.
The noModule IDL attribute must [27214]reflect the [27215]nomodule
content attribute.
The async getter steps are:
1. If [27216]this's [27217]force async is true, then return true.
2. If [27218]this's [27219]async content attribute is present, then
return true.
3. Return false.
The [27220]async setter steps are:
1. Set [27221]this's [27222]force async to false.
2. If the given value is true, then set [27223]this's [27224]async
content attribute to the empty string.
3. Otherwise, remove [27225]this's [27226]async content attribute.
script.[27227]text [ = value ]
Returns the [27228]child text content of the element.
Can be set, to replace the element's children with the given
value.
[27229]HTMLScriptElement.[27230]supports(type)
Returns true if the given type is a script type supported by the
user agent. The possible script types in this specification are
"classic", "module", and "importmap", but others might be added
in the future.
The text attribute's getter must return this [27231]script element's
[27232]child text content.
The [27233]text attribute's setter must [27234]string replace all with
the given value within this [27235]script element.
(BUTTON) ✔MDN
[27236]HTMLScriptElement/supports_static
Support in all current engines.
Firefox94+Safari16+Chrome96+
__________________________________________________________________
The supports(type) method steps are:
1. If type [27237]is "classic", then return true.
2. If type [27238]is "module", then return true.
3. If type [27239]is "importmap", then return true.
4. Return false.
The type argument has to exactly match these values; we do not perform
an [27240]ASCII case-insensitive match. This is different from how
[27241]type content attribute values are treated, and how
[27242]DOMTokenList's [27243]supports() method works, but it aligns
with the [27244]WorkerType enumeration used in the [27245]Worker()
constructor.
In this example, two [27246]script elements are used. One embeds an
external [27247]classic script, and the other includes some data as a
[27248]data block.
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 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 [27249]script element can be used to
define a function that is then used by other parts of the document, as
part of a [27250]classic script. It also shows how a [27251]script
element can be used to invoke script while the document is being
parsed, in this case to initialize the form's output.
The following sample shows how a [27252]script element can be used to
include an external [27253]JavaScript module script.
This module, and all its dependencies (expressed through JavaScript
import statements in the source file), will be fetched. Once the entire
resulting module graph has been imported, and the document has finished
parsing, the contents of app.mjs will be evaluated.
Additionally, if code from another [27254]script element in the same
[27255]Window imports the module from app.mjs (e.g. via import
"./app.mjs";), then the same [27256]JavaScript module script created by
the former [27257]script element will be imported.
This example shows how to include a [27258]JavaScript module script for
modern user agents, and a [27259]classic script for older user agents:
In modern user agents that support [27260]JavaScript module scripts,
the [27261]script element with the [27262]nomodule attribute will be
ignored, and the [27263]script element with a [27264]type of "module"
will be fetched and evaluated (as a [27265]JavaScript module script).
Conversely, older user agents will ignore the [27266]script element
with a [27267]type of "module", as that is an unknown script type for
them — but they will have no problem fetching and evaluating the other
[27268]script element (as a [27269]classic script), since they do not
implement the [27270]nomodule attribute.
The following sample shows how a [27271]script element can be used to
write an inline [27272]JavaScript module script that performs a number
of substitutions on the document's text, in order to make for a more
interesting reading experience (e.g. on a news site): [27273][XKCD1288]
Some notable features gained by using a JavaScript module script
include the ability to import functions from other JavaScript modules,
strict mode by default, and how top-level declarations do not introduce
new properties onto the [27274]global object. Also note that no matter
where this [27275]script element appears in the document, it will not
be evaluated until both document parsing has complete and its
dependency (dom-utils.mjs) has been fetched and evaluated.
The following sample shows how a [27276]JSON module script can be
imported from inside a [27277]JavaScript module script:
MIME type checking for module scripts is strict. In order for the fetch
of the [27278]JSON module script to succeed, the HTTP response must
have a [27279]JSON MIME type, for example Content-Type: text/json. On
the other hand, if the with { type: "json" } part of the statement is
omitted, it is assumed that the intent is to import a [27280]JavaScript
module script, and the fetch will fail if the HTTP response has a MIME
type that is not a [27281]JavaScript MIME type.
4.12.1.1 Processing model
A [27282]script element has several associated pieces of state.
A [27283]script element has a parser document, which is either null or
a [27284]Document, initially null. It is set by the [27285]HTML parser
and the [27286]XML parser on [27287]script elements they insert, and
affects the processing of those elements. [27288]script elements with
non-null [27289]parser documents are known as parser-inserted.
A [27290]script element has a preparation-time document, which is
either null or a [27291]Document, initially null. It is used to prevent
scripts that move between documents during [27292]preparation from
[27293]executing.
A [27294]script element has a force async boolean, initially true. It
is set to false by the [27295]HTML parser and the [27296]XML parser on
[27297]script elements they insert, and when the element gets an
[27298]async content attribute added.
A [27299]script element has a from an external file boolean, initially
false. It is determined when the script is [27300]prepared, based on
the [27301]src attribute of the element at that time.
A [27302]script element has a ready to be parser-executed boolean,
initially false. This is used only used for elements that are also
[27303]parser-inserted, to let the parser know when to execute the
script.
A [27304]script element has an already started boolean, initially
false.
A [27305]script element has a delaying the load event boolean,
initially false.
A [27306]script element has a type, which is either null, "classic",
"module", or "importmap", initially null. It is determined when the
element is [27307]prepared, based on the [27308]type attribute of the
element at that time.
A [27309]script element has a result, which is either "uninitialized",
null (representing an error), a [27310]script, or an [27311]import map
parse result. It is initially "uninitialized".
A [27312]script element has steps to run when the result is ready,
which are a series of steps or null, initially null. To mark as ready a
[27313]script element el given a [27314]script, [27315]import map parse
result, or null result:
1. Set el's [27316]result to result.
2. If el's [27317]steps to run when the result is ready are not null,
then run them.
3. Set el's [27318]steps to run when the result is ready to null.
4. Set el's [27319]delaying the load event to false.
__________________________________________________________________
A [27320]script element el is [27321]implicitly potentially
render-blocking if el's [27322]type is "classic", el is
[27323]parser-inserted, and el does not have an [27324]async or
[27325]defer attribute.
The [27326]cloning steps for [27327]script elements given node, copy,
and subtree are to set copy's [27328]already started to node's
[27329]already started.
When an [27330]async attribute is added to a [27331]script element el,
the user agent must set el's [27332]force async to false.
Whenever a [27333]script element el's [27334]delaying the load event is
true, the user agent must [27335]delay the load event of el's
[27336]preparation-time document.
__________________________________________________________________
The [27337]script [27338]HTML element post-connection steps, given
insertedNode, are:
1. If insertedNode is not [27339]connected, then return.
This can happen in the case where an earlier-inserted [27340]script
removes a later-inserted [27341]script. For instance:
Nothing is printed to the console in this example. By the time the
[27342]HTML element post-connection steps run for the first
[27343]script that was atomically inserted by [27344]append(), it
can observe that the second [27345]script is already
[27346]connected to the DOM. It removes the second [27347]script,
so that by the time its [27348]HTML element post-connection steps
run, it is no longer [27349]connected, and does not get
[27350]prepared.
2. If insertedNode is [27351]parser-inserted, then return.
3. [27352]Prepare the script element given insertedNode.
The [27353]script [27354]children changed steps are:
1. Run the [27355]script [27356]HTML element post-connection steps,
given the [27357]script element.
This has an interesting implication on the execution order of a
[27358]script element and any newly-inserted child [27359]script
elements. Consider the following snippet:
By the time the second script block executes, the outer-script has
already been [27360]prepared, but because it is empty, it did not
execute and therefore is not marked as [27361]already started. The
atomic insertion of the [27362]Text nodes and nested [27363]script
element have the following effects:
1. All three child nodes get atomically inserted as children of
outer-script; all of their [27364]insertion steps run, which have
no observable consequences in this case.
2. The outer-script's [27365]children changed steps run, which
[27366]prepares that script; because its body is now non-empty,
this executes the contents of the two [27367]Text nodes, in order.
3. The [27368]script [27369]HTML element post-connection steps finally
run for innerScript, causing its body to execute.
The following [27370]attribute change steps, given element, localName,
oldValue, value, and namespace, are used for all [27371]script
elements:
1. If namespace is not null, then return.
2. If localName is [27372]src, then run the [27373]script [27374]HTML
element post-connection steps, given element.
To prepare the script element given a [27375]script element el:
1. If el's [27376]already started is true, then return.
2. Let parser document be el's [27377]parser document.
3. Set el's [27378]parser document to null.
This is done so that if parser-inserted [27379]script elements fail
to run when the parser tries to run them, e.g. because they are
empty or specify an unsupported scripting language, another script
can later mutate them and cause them to run again.
4. If parser document is non-null and el does not have an [27380]async
attribute, then set el's [27381]force async to true.
This is done so that if a parser-inserted [27382]script element
fails to run when the parser tries to run it, but it is later
executed after a script dynamically updates it, it will execute in
an async fashion even if the [27383]async attribute isn't set.
5. Let source text be el's [27384]child text content.
6. If el has no [27385]src attribute, and source text is the empty
string, then return.
7. If el is not [27386]connected, then return.
8. If any of the following are true:
+ el has a [27387]type attribute whose value is the empty
string;
+ el has no [27388]type attribute but it has a [27389]language
attribute and that attribute's value is the empty string; or
+ el has neither a [27390]type attribute nor a [27391]language
attribute,
then let the script block's type string for this [27392]script
element be "text/javascript".
Otherwise, if el has a [27393]type attribute, then let the script
block's type string be the value of that attribute with
[27394]leading and trailing ASCII whitespace stripped.
Otherwise, el has a non-empty [27395]language attribute; let the
script block's type string be the concatenation of "text/" and the
value of el's [27396]language attribute.
The [27397]language attribute is never conforming, and is always
ignored if there is a [27398]type attribute present.
9. If the script block's type string is a [27399]JavaScript MIME type
essence match, then set el's [27400]type to "classic".
10. Otherwise, if the script block's type string is an [27401]ASCII
case-insensitive match for the string "module", then set el's
[27402]type to "module".
11. Otherwise, if the script block's type string is an [27403]ASCII
case-insensitive match for the string "importmap", then set el's
[27404]type to "importmap".
12. Otherwise, return. (No script is executed, and el's [27405]type is
left as null.)
13. If parser document is non-null, then set el's [27406]parser
document back to parser document and set el's [27407]force async to
false.
14. Set el's [27408]already started to true.
15. Set el's [27409]preparation-time document to its [27410]node
document.
16. If parser document is non-null, and parser document is not equal to
el's [27411]preparation-time document, then return.
17. If [27412]scripting is disabled for el, then return.
The definition of [27413]scripting is disabled means that, amongst
others, the following scripts will not execute: scripts in
[27414]XMLHttpRequest's [27415]responseXML documents, scripts in
[27416]DOMParser-created documents, scripts in documents created by
[27417]XSLTProcessor's [27418]transformToDocument feature, and
scripts that are first inserted by a script into a [27419]Document
that was created using the [27420]createDocument() API.
[27421][XHR] [27422][DOMPARSING] [27423][XSLTP] [27424][DOM]
18. If el has a [27425]nomodule content attribute and its [27426]type
is "classic", then return.
This means specifying [27427]nomodule on a [27428]module script has
no effect; the algorithm continues onward.
19. If el does not have a [27429]src content attribute, and the
[27430]Should element's inline behavior be blocked by Content
Security Policy? algorithm returns "Blocked" when given el,
"script", and source text, then return. [27431][CSP]
20. If el has an [27432]event attribute and a [27433]for attribute, and
el's [27434]type is "classic", then:
1. Let for be the value of el's [27435]for attribute.
2. Let event be the value of el's [27436]event attribute.
3. [27437]Strip leading and trailing ASCII whitespace from event
and for.
4. If for is not an [27438]ASCII case-insensitive match for the
string "window", then return.
5. If event is not an [27439]ASCII case-insensitive match for
either the string "onload" or the string "onload()", then
return.
21. If el has a [27440]charset attribute, then let encoding be the
result of [27441]getting an encoding from the value of the
[27442]charset attribute.
If el does not have a [27443]charset attribute, or if
[27444]getting an encoding failed, then let encoding be el's
[27445]node document's [27446]the encoding.
If el's [27447]type is "module", this encoding will be ignored.
22. Let classic script CORS setting be the current state of el's
[27448]crossorigin content attribute.
23. Let module script credentials mode be the [27449]CORS settings
attribute credentials mode for el's [27450]crossorigin content
attribute.
24. Let cryptographic nonce be el's [27451][[CryptographicNonce]]
internal slot's value.
25. If el has an [27452]integrity attribute, then let integrity
metadata be that attribute's value.
Otherwise, let integrity metadata be the empty string.
26. Let referrer policy be the current state of el's
[27453]referrerpolicy content attribute.
27. Let fetch priority be the current state of el's
[27454]fetchpriority content attribute.
28. Let parser metadata be "parser-inserted" if el is
[27455]parser-inserted, and "not-parser-inserted" otherwise.
29. Let options be a [27456]script fetch options whose
[27457]cryptographic nonce is cryptographic nonce, [27458]integrity
metadata is integrity metadata, [27459]parser metadata is parser
metadata, [27460]credentials mode is module script credentials
mode, [27461]referrer policy is referrer policy, and [27462]fetch
priority is fetch priority.
30. Let settings object be el's [27463]node document's [27464]relevant
settings object.
31. If el has a [27465]src content attribute, then:
1. If el's [27466]type is "importmap", then [27467]queue an
element task on the [27468]DOM manipulation task source given
el to [27469]fire an event named [27470]error at el, and
return.
External import map scripts are not currently supported. See
[27471]WICG/import-maps issue #235 for discussions on adding
support.
2. Let src be the value of el's [27472]src attribute.
3. If src is the empty string, then [27473]queue an element task
on the [27474]DOM manipulation task source given el to
[27475]fire an event named [27476]error at el, and return.
4. Set el's [27477]from an external file to true.
5. Let url be the result of [27478]encoding-parsing a URL given
src, relative to el's [27479]node document.
6. If url is failure, then [27480]queue an element task on the
[27481]DOM manipulation task source given el to [27482]fire an
event named [27483]error at el, and return.
7. If el is [27484]potentially render-blocking, then [27485]block
rendering on el.
8. Set el's [27486]delaying the load event to true.
9. If el is currently [27487]render-blocking, then set options's
[27488]render-blocking to true.
10. Let onComplete given result be the following steps:
1. [27489]Mark as ready el given result.
11. Switch on el's [27490]type:
"classic"
[27491]Fetch a classic script given url, settings
object, options, classic script CORS setting,
encoding, and onComplete.
"module"
If el does not have an [27492]integrity attribute,
then set options's [27493]integrity metadata to the
result of [27494]resolving a module integrity
metadata with url and settings object.
[27495]Fetch an external module script graph given
url, settings object, options, and onComplete.
For performance reasons, user agents may start fetching the
classic script or module graph (as defined above) as soon as
the [27496]src attribute is set, instead, in the hope that el
will become connected (and that the [27497]crossorigin
attribute won't change value in the meantime). Either way,
once el [27498]becomes connected, the load must have started
as described in this step. If the UA performs such
prefetching, but el never becomes connected, or the [27499]src
attribute is dynamically changed, or the [27500]crossorigin
attribute is dynamically changed, then the user agent will not
execute the script so obtained, and the fetching process will
have been effectively wasted.
32. If el does not have a [27501]src content attribute:
1. Let base URL be el's [27502]node document's [27503]document
base URL.
2. Switch on el's [27504]type:
"classic"
1. Let script be the result of [27505]creating a
classic script using source text, settings object,
base URL, and options.
2. [27506]Mark as ready el given script.
"module"
1. Set el's [27507]delaying the load event to true.
2. If el is [27508]potentially render-blocking, then:
1. [27509]Block rendering on el.
2. Set options's [27510]render-blocking to true.
3. [27511]Fetch an inline module script graph, given
source text, base URL, settings object, options, and
with the following steps given result:
1. [27512]Queue an element task on the
[27513]networking task source given el to
perform the following steps:
1. [27514]Mark as ready el given result.
Queueing a task here means that, even if the
inline module script has no dependencies or
synchronously results in a parse error, we
won't proceed to [27515]execute the script
element synchronously.
"importmap"
1. Let result be the result of [27516]creating an
import map parse result given source text and base
URL.
2. [27517]Mark as ready el given result.
33. If el's [27518]type is "classic" and el has a [27519]src attribute,
or el's [27520]type is "module":
1. [27521]Assert: el's [27522]result is "uninitialized".
2. If el has an [27523]async attribute or el's [27524]force async
is true:
1. Let scripts be el's [27525]preparation-time document's
[27526]set of scripts that will execute as soon as
possible.
2. [27527]Append el to scripts.
3. Set el's [27528]steps to run when the result is ready to
the following:
1. [27529]Execute the script element el.
2. [27530]Remove el from scripts.
3. Otherwise, if el is not [27531]parser-inserted:
1. Let scripts be el's [27532]preparation-time document's
[27533]list of scripts that will execute in order as soon
as possible.
2. [27534]Append el to scripts.
3. Set el's [27535]steps to run when the result is ready to
the following:
1. If scripts[0] is not el, then abort these steps.
2. While scripts is not empty, and scripts[0]'s
[27536]result is not "uninitialized":
1. [27537]Execute the script element scripts[0].
2. [27538]Remove scripts[0].
4. Otherwise, if el has a [27539]defer attribute or el's
[27540]type is "module":
1. [27541]Append el to its [27542]parser document's
[27543]list of scripts that will execute when the
document has finished parsing.
2. Set el's [27544]steps to run when the result is ready to
the following: set el's [27545]ready to be
parser-executed to true. (The parser will handle
executing the script.)
5. Otherwise:
1. Set el's [27546]parser document's [27547]pending
parsing-blocking script to el.
2. [27548]Block rendering on el.
3. Set el's [27549]steps to run when the result is ready to
the following: set el's [27550]ready to be
parser-executed to true. (The parser will handle
executing the script.)
34. Otherwise:
1. [27551]Assert: el's [27552]result is not "uninitialized".
2. If all of the following are true:
o el's [27553]type is "classic";
o el is [27554]parser-inserted;
o el's [27555]parser document [27556]has a style sheet that
is blocking scripts; and
o either the parser that created el is an [27557]XML
parser, or it's an [27558]HTML parser whose [27559]script
nesting level is not greater than one,
then:
1. Set el's [27560]parser document's [27561]pending
parsing-blocking script to el.
2. Set el's [27562]ready to be parser-executed to true. (The
parser will handle executing the script.)
3. Otherwise, [27563]immediately [27564]execute the script
element el, even if other scripts are already executing.
Each [27565]Document has a pending parsing-blocking script, which is a
[27566]script element or null, initially null.
Each [27567]Document has a set of scripts that will execute as soon as
possible, which is a [27568]set of [27569]script elements, initially
empty.
Each [27570]Document has a list of scripts that will execute in order
as soon as possible, which is a [27571]list of [27572]script elements,
initially empty.
Each [27573]Document has a list of scripts that will execute when the
document has finished parsing, which is a [27574]list of [27575]script
elements, initially empty.
If a [27576]script element that blocks a parser gets moved to another
[27577]Document before it would normally have stopped blocking that
parser, it nonetheless continues blocking that parser until the
condition that causes it to be blocking the parser no longer applies
(e.g., if the script is a [27578]pending parsing-blocking script
because the original [27579]Document [27580]has a style sheet that is
blocking scripts when it was parsed, but then the script is moved to
another [27581]Document before the blocking style sheet(s) loaded, the
script still blocks the parser until the style sheets are all loaded,
at which time the script executes and the parser is unblocked).
To execute the script element given a [27582]script element el:
1. Let document be el's [27583]node document.
2. If el's [27584]preparation-time document is not equal to document,
then return.
3. [27585]Unblock rendering on el.
4. If el's [27586]result is null, then [27587]fire an event named
[27588]error at el, and return.
5. If el's [27589]from an external file is true, or el's [27590]type
is "module", then increment document's
[27591]ignore-destructive-writes counter.
6. Switch on el's [27592]type:
"classic"
1. Let oldCurrentScript be the value to which document's
[27593]currentScript object was most recently set.
2. If el's [27594]root is not a [27595]shadow root, then set
document's [27596]currentScript attribute to el.
Otherwise, set it to null.
This does not use the [27597]in a document tree check, as
el could have been removed from the document prior to
execution, and in that scenario [27598]currentScript
still needs to point to it.
3. [27599]Run the classic script given by el's
[27600]result.
4. Set document's [27601]currentScript attribute to
oldCurrentScript.
"module"
1. [27602]Assert: document's [27603]currentScript attribute
is null.
2. [27604]Run the module script given by el's [27605]result.
"importmap"
1. [27606]Register an import map given el's [27607]relevant
global object and el's [27608]result.
7. Decrement the [27609]ignore-destructive-writes counter of document,
if it was incremented in the earlier step.
8. If el's [27610]from an external file is true, then [27611]fire an
event named [27612]load at el.
4.12.1.2 Scripting languages
User agents are not required to support JavaScript. This standard needs
to be updated if a language other than JavaScript comes along and gets
similar wide adoption by web browsers. Until such a time, implementing
other languages is in conflict with this standard, given the processing
model defined for the [27613]script element.
Servers should use [27614]text/javascript for JavaScript resources, in
accordance with Updates to ECMAScript Media Types. Servers should not
use other [27615]JavaScript MIME types for JavaScript resources, and
must not use non-[27616]JavaScript MIME types. [27617][RFC9239]
For external JavaScript resources, MIME type parameters in
`[27618]Content-Type` headers are generally ignored. (In some cases the
`charset` parameter has an effect.) However, for the [27619]script
element's [27620]type attribute they are significant; it uses the
[27621]JavaScript MIME type essence match concept.
For example, scripts with their [27622]type attribute set to
"text/javascript; charset=utf-8" will not be evaluated, even though
that is a valid [27623]JavaScript MIME type when parsed.
Furthermore, again for external JavaScript resources, special
considerations apply around `[27624]Content-Type` header processing as
detailed in the [27625]prepare the script element algorithm and Fetch.
[27626][FETCH]
4.12.1.3 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 an ASCII case-insensitive
match for ""
script-open = "<" s c r i p t tag-end
s = %x0053 ; U+0053 LATIN CAPITAL LETTER S
s =/ %x0073 ; U+0073 LATIN SMALL LETTER S
c = %x0043 ; U+0043 LATIN CAPITAL LETTER C
c =/ %x0063 ; U+0063 LATIN SMALL LETTER C
r = %x0052 ; U+0052 LATIN CAPITAL LETTER R
r =/ %x0072 ; U+0072 LATIN SMALL LETTER R
i = %x0049 ; U+0049 LATIN CAPITAL LETTER I
i =/ %x0069 ; U+0069 LATIN SMALL LETTER I
p = %x0050 ; U+0050 LATIN CAPITAL LETTER P
p =/ %x0070 ; U+0070 LATIN SMALL LETTER P
t = %x0054 ; U+0054 LATIN CAPITAL LETTER T
t =/ %x0074 ; U+0074 LATIN SMALL LETTER T
When a [27631]script element contains [27632]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:
const example = ʼConsider this string:
What is going on here is that for legacy reasons, "
It is possible for these sequences to naturally occur in script
expressions, as in the following examples:
if (x
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
If element is [29831]focused, draws a focus ring around the
[29832]current default path, following the platform conventions
for focus rings.
context.[29833]drawFocusIfNeeded(path, element)
If element is [29834]focused, draws a focus ring around path,
following the platform conventions for focus rings.
Objects that implement the [29835]CanvasUserInterface interface provide
the following methods to draw focus rings.
The drawFocusIfNeeded(element) method steps are to [29836]draw focus if
needed given [29837]this, element, and [29838]this's [29839]current
default path.
The drawFocusIfNeeded(path, element) method steps are to [29840]draw
focus if needed given [29841]this, element, and path.
To draw focus if needed, given an object implementing
[29842]CanvasUserInterface context, an element element, and a
[29843]path path:
1. If element is not [29844]focused or is not a descendant of
context's [29845]canvas element, then return.
2. Draw a focus ring of the appropriate style along path, following
platform conventions.
Some platforms only draw focus rings around elements that have been
focused from the keyboard, and not those focused from the mouse.
Other platforms simply don't draw focus rings around some elements
at all unless relevant accessibility features are enabled. This API
is intended to follow these conventions. User agents that implement
distinctions based on the manner in which the element was focused
are encouraged to classify focus driven by the [29846]focus()
method based on the kind of user interaction event from which the
call was triggered (if any).
The focus ring should not be subject to the [29847]shadow effects,
the [29848]global alpha, the [29849]current compositing and
blending operator, the [29850]fill style, the [29851]stroke style,
or any of the members in the [29852]CanvasPathDrawingStyles,
[29853]CanvasTextDrawingStyles interfaces, but should be subject to
the [29854]clipping region. (The effect of transformations is
described above and varies based on which path is being used.)
3. [29855]Inform the user that the focus is at the location given by
the intended path. User agents may wait until the next time the
[29856]event loop reaches its [29857]update the rendering step to
optionally inform the user.
User agents should not implicitly close open subpaths in the intended
path when drawing the focus ring.
This might be a moot point, however. For example, if the focus ring is
drawn as an axis-aligned bounding rectangle around the points in the
intended path, then whether the subpaths are closed or not has no
effect. This specification intentionally does not specify precisely how
focus rings are to be drawn: user agents are expected to honor their
platform's native conventions.
"Inform the user", as used in this section, does not imply any
persistent state change. It could mean, for instance, calling a system
accessibility API to notify assistive technologies such as
magnification tools so that the user's magnifier moves to the given
area of the canvas. However, it does not associate the path with the
element, or provide a region for tactile feedback, etc.
4.12.5.1.15 Drawing images
Objects that implement the [29858]CanvasDrawImage interface have the
drawImage() method to draw images.
This method can be invoked with three different sets of arguments:
* drawImage(image, dx, dy)
* drawImage(image, dx, dy, dw, dh)
* drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)
context.[29861]drawImage(image, dx, dy, dw, dh)
context.[29862]drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)
Draws the given image onto the canvas. The arguments are
interpreted as follows:
The sx and sy parameters give the x and y coordinates of the
source rectangle; the sw and sh arguments give the width and
height of the source rectangle; the dx and dy give the x and y
coordinates of the destination rectangle; and the dw and dh
arguments give the width and height of the destination
rectangle.
If the image isn't yet fully decoded, then nothing is drawn. If
the image is a canvas with no data, throws an
[29863]"InvalidStateError" [29864]DOMException.
When the [29865]drawImage() method is invoked, the user agent must run
these steps:
1. If any of the arguments are infinite or NaN, then return.
2. Let usability be the result of [29866]checking the usability of
image.
3. If usability is bad, then return (without drawing anything).
4. Establish the source and destination rectangles as follows:
If not specified, the dw and dh arguments must default to the
values of sw and sh, interpreted such that one [29867]CSS pixel in
the image is treated as one unit in the [29868]output bitmap's
coordinate space. If the sx, sy, sw, and sh arguments are omitted,
then they must default to 0, 0, the image's [29869]natural width in
image pixels, and the image's [29870]natural height in image
pixels, respectively. If the image has no [29871]natural
dimensions, then the concrete object size must be used instead, as
determined using the CSS "[29872]Concrete Object Size Resolution"
algorithm, with the specified size having neither a definite width
nor height, nor any additional constraints, the object's natural
properties being those of the image argument, and the
[29873]default object size being the size of the [29874]output
bitmap. [29875][CSSIMAGES]
The source rectangle is the rectangle whose corners are the four
points (sx, sy), (sx+sw, sy), (sx+sw, sy+sh), (sx, sy+sh).
The destination rectangle is the rectangle whose corners are the
four points (dx, dy), (dx+dw, dy), (dx+dw, dy+dh), (dx, dy+dh).
When the source rectangle is outside the source image, the source
rectangle must be clipped to the source image and the destination
rectangle must be clipped in the same proportion.
When the destination rectangle is outside the destination image
(the [29876]output bitmap), the pixels that land outside the
[29877]output bitmap are discarded, as if the destination was an
infinite canvas whose rendering was clipped to the dimensions of
the [29878]output bitmap.
5. If one of the sw or sh arguments is zero, then return. Nothing is
painted.
6. Paint the region of the image argument specified by the source
rectangle on the region of the rendering context's [29879]output
bitmap specified by the destination rectangle, after applying the
[29880]current transformation matrix to the destination rectangle.
The image data must be processed in the original direction, even if
the dimensions given are negative.
When scaling up, if the [29881]imageSmoothingEnabled attribute is
set to true, the user agent should attempt to apply a smoothing
algorithm to the image data when it is scaled. User agents which
support multiple filtering algorithms may use the value of the
[29882]imageSmoothingQuality attribute to guide the choice of
filtering algorithm when the [29883]imageSmoothingEnabled attribute
is set to true. Otherwise, the image must be rendered using
nearest-neighbor interpolation.
This specification does not define the precise algorithm to use
when scaling an image down, or when scaling an image up when the
[29884]imageSmoothingEnabled attribute is set to true.
When a [29885]canvas element is drawn onto itself, the
[29886]drawing model requires the source to be copied before the
image is drawn, so it is possible to copy parts of a [29887]canvas
element onto overlapping parts of itself.
If the original image data is a bitmap image, then the value
painted at a point in the destination rectangle is computed by
filtering the original image data. The user agent may use any
filtering algorithm (for example bilinear interpolation or
nearest-neighbor). When the filtering algorithm requires a pixel
value from outside the original image data, it must instead use the
value from the nearest edge pixel. (That is, the filter uses
'clamp-to-edge' behavior.) When the filtering algorithm requires a
pixel value from outside the source rectangle but inside the
original image data, then the value from the original image data
must be used.
Thus, scaling an image in parts or in whole will have the same
effect. This does mean that when sprites coming from a single
sprite sheet are to be scaled, adjacent images in the sprite sheet
can interfere. This can be avoided by ensuring each sprite in the
sheet is surrounded by a border of [29888]transparent black, or by
copying sprites to be scaled into temporary [29889]canvas elements
and drawing the scaled sprites from there.
Images are painted without affecting the current path, and are
subject to [29890]shadow effects, [29891]global alpha, the
[29892]clipping region, and the [29893]current compositing and
blending operator.
7. If image [29894]is not origin-clean, then set the
[29895]CanvasRenderingContext2D's [29896]origin-clean flag to
false.
4.12.5.1.16 Pixel manipulation
imageData = new [29897]ImageData(sw, sh [, settings])
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
Returns an [29899]ImageData object with the given dimensions and
the color space indicated by settings. All the pixels in the
returned object are [29900]transparent black.
Throws an [29901]"IndexSizeError" [29902]DOMException if either
of the width or height arguments are zero.
imageData = new [29903]ImageData(data, sw [, sh [, settings ] ])
Returns an [29904]ImageData object using the data provided in
the [29905]ImageDataArray argument, interpreted using the given
dimensions and the color space indicated by settings.
The byte length of the data needs to be a multiple of the number
of bytes per pixel times the given width. If the height is
provided as well, then the length needs to be exactly the number
of bytes per pixel times the width times the height.
Throws an [29906]"IndexSizeError" [29907]DOMException if the
given data and dimensions can't be interpreted consistently, or
if either dimension is zero.
imageData = context.[29908]createImageData(imageData)
Returns an [29909]ImageData object with the same dimensions and
color space as the argument. All the pixels in the returned
object are [29910]transparent black.
imageData = context.[29911]createImageData(sw, sh [, settings])
Firefox Android?Safari iOS?Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
Returns an [29913]ImageData object with the given dimensions.
The color space of the returned object is the [29914]color space
of context unless overridden by settings. All the pixels in the
returned object are [29915]transparent black.
Throws an [29916]"IndexSizeError" [29917]DOMException if either
of the width or height arguments are zero.
imageData = context.[29918]getImageData(sx, sy, sw, sh [, settings])
Firefox Android?Safari iOS?Chrome Android?WebView
Android37+Samsung Internet?Opera Android10.1+
Returns an [29920]ImageData object containing the image data for
the given rectangle of the bitmap. The color space of the
returned object is the [29921]color space of context unless
overridden by settings.
Throws an [29922]"IndexSizeError" [29923]DOMException if the
either of the width or height arguments are zero.
Firefox Android?Safari iOS?Chrome Android?WebView
Android37+Samsung Internet?Opera Android10.1+
Returns the actual dimensions of the data in the
[29928]ImageData object, in pixels.
Firefox Android?Safari iOS?Chrome Android?WebView
Android37+Samsung Internet?Opera Android10.1+
Returns the one-dimensional array containing the data in RGBA
order, as integers in the range 0 to 255.
imageData.[29931]colorSpace
Returns the color space of the pixels.
context.[29932]putImageData(imageData, dx, dy [, dirtyX, dirtyY,
dirtyWidth, dirtyHeight ])
Firefox Android?Safari iOS?Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
Paints the data from the given [29934]ImageData object onto the
bitmap. If a dirty rectangle is provided, only the pixels from
that rectangle are painted.
The [29935]globalAlpha and [29936]globalCompositeOperation
properties, as well as the [29937]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 an [29938]"InvalidStateError" [29939]DOMException if the
imageData object's [29940]data attribute value's
[[ViewedArrayBuffer]] internal slot is detached.
Objects that implement the [29941]CanvasImageData interface provide the
following methods for reading and writing pixel data to the bitmap.
The new ImageData(sw, sh, settings) constructor steps are:
1. If one or both of sw and sh are zero, then throw an
[29942]"IndexSizeError" [29943]DOMException.
2. [29944]Initialize [29945]this given sw, sh, and settings.
3. Initialize the image data of [29946]this to [29947]transparent
black.
The new ImageData(data, sw, sh, settings) constructor steps are:
1. Let bytesPerPixel be 4 if settings["[29948]pixelFormat"] is
"[29949]rgba-unorm8"; otherwise 8.
2. Let length be the [29950]buffer source byte length of data.
3. If length is not a nonzero integral multiple of bytesPerPixel, then
throw an [29951]"InvalidStateError" [29952]DOMException.
4. Let length be length divided by bytesPerPixel.
5. If length is not an integral multiple of sw, then throw an
[29953]"IndexSizeError" [29954]DOMException.
At this step, the length is guaranteed to be greater than zero
(otherwise the second step above would have aborted the steps), so
if sw is zero, this step will throw the exception and return.
6. Let height be length divided by sw.
7. If sh was given and its value is not equal to height, then throw an
[29955]"IndexSizeError" [29956]DOMException.
8. [29957]Initialize [29958]this given sw, sh, settings, and
[29959]source set to data.
This step does not set [29960]this's data to a copy of data. It
sets it to the actual [29961]ImageDataArray object passed as data.
The createImageData(sw, sh, settings) method steps are:
1. If one or both of sw and sh are zero, then throw an
[29962]"IndexSizeError" [29963]DOMException.
2. Let newImageData be a [29964]new [29965]ImageData object.
3. [29966]Initialize newImageData given the absolute magnitude of sw,
the absolute magnitude of sh, settings, and
[29967]defaultColorSpace set to [29968]this's [29969]color space.
4. Initialize the image data of newImageData to [29970]transparent
black.
5. Return newImageData.
The createImageData(imageData) method steps are:
1. Let newImageData be a [29971]new [29972]ImageData object.
2. Let settings be the [29973]ImageDataSettings object «[
"[29974]colorSpace" → [29975]this's [29976]colorSpace,
"[29977]pixelFormat" → [29978]this's [29979]pixelFormat ]».
3. [29980]Initialize newImageData given the value of imageData's
[29981]width attribute, the value of imageData's [29982]height
attribute, and settings.
4. Initialize the image data of newImageData to [29983]transparent
black.
5. Return newImageData.
The getImageData(sx, sy, sw, sh, settings) method steps are:
1. If either the sw or sh arguments are zero, then throw an
[29984]"IndexSizeError" [29985]DOMException.
2. If the [29986]CanvasRenderingContext2D's [29987]origin-clean flag
is set to false, then throw a [29988]"SecurityError"
[29989]DOMException.
3. Let imageData be a [29990]new [29991]ImageData object.
4. [29992]Initialize imageData given sw, sh, settings, and
[29993]defaultColorSpace set to [29994]this's [29995]color space.
5. Let the source rectangle be the rectangle whose corners are the
four points (sx, sy), (sx+sw, sy), (sx+sw, sy+sh), (sx, sy+sh).
6. Set the pixel values of imageData to be the pixels of [29996]this's
[29997]output bitmap in the area specified by the source rectangle
in the bitmap's coordinate space units, converted from
[29998]this's [29999]color space to imageData's [30000]colorSpace
using [30001]'relative-colorimetric' rendering intent.
7. Set the pixels values of imageData for areas of the source
rectangle that are outside of the [30002]output bitmap to
[30003]transparent black.
8. Return imageData.
To initialize an ImageData object imageData, given a positive integer
number of pixels per row pixelsPerRow, a positive integer number of
rows rows, an [30004]ImageDataSettings settings, an optional
[30005]ImageDataArray source, and an optional
[30006]PredefinedColorSpace defaultColorSpace:
1. If source was given:
1. If settings["[30008]pixelFormat"] equals "[30009]rgba-unorm8"
and source is not a [30010]Uint8ClampedArray, then throw an
[30011]"InvalidStateError" [30012]DOMException.
2. If settings["[30013]pixelFormat"] is "[30014]rgba-float16" and
source is not a [30015]Float16Array, then throw an
[30016]"InvalidStateError" [30017]DOMException.
3. Initialize the data attribute of imageData to source.
2. Otherwise (source was not given):
1. If settings["[30018]pixelFormat"] is "[30019]rgba-unorm8",
then initialize the [30020]data attribute of imageData to a
new [30021]Uint8ClampedArray object. The
[30022]Uint8ClampedArray object must use a new
[30023]ArrayBuffer for its storage, and must have a zero byte
offset and byte length equal to the length of its storage, in
bytes. The storage [30024]ArrayBuffer must have a length of 4
× rows × pixelsPerRow bytes.
2. Otherwise, if settings["[30025]pixelFormat"] is
"[30026]rgba-float16", then initialize the [30027]data
attribute of imageData to a new [30028]Float16Array object.
The [30029]Float16Array object must use a new
[30030]ArrayBuffer for its storage, and must have a zero byte
offset and byte length equal to the length of its storage, in
bytes. The storage [30031]ArrayBuffer must have a length of 8
× rows × pixelsPerRow bytes.
3. If the storage [30032]ArrayBuffer could not be allocated, then
rethrow the [30033]RangeError thrown by JavaScript, and
return.
3. Initialize the width attribute of imageData to pixelsPerRow.
4. Initialize the height attribute of imageData to rows.
5. Initialize the pixelFormat attribute of imageData to
settings["pixelFormat"].
6. If settings["[30034]colorSpace"] [30035]exists, then initialize the
colorSpace attribute of imageData to settings["colorSpace"].
7. Otherwise, if defaultColorSpace was given, then initialize the
[30036]colorSpace attribute of imageData to defaultColorSpace.
8. Otherwise, initialize the [30037]colorSpace attribute of imageData
to "[30038]srgb".
[30039]ImageData objects are [30040]serializable objects. Their
[30041]serialization steps, given value and serialized, are:
1. Set serialized.[[Data]] to the [30042]sub-serialization of the
value of value's [30043]data attribute.
2. Set serialized.[[Width]] to the value of value's [30044]width
attribute.
3. Set serialized.[[Height]] to the value of value's [30045]height
attribute.
4. Set serialized.[[ColorSpace]] to the value of value's
[30046]colorSpace attribute.
5. Set serialized.[[PixelFormat]] to the value of value's
[30047]pixelFormat attribute.
Their [30048]deserialization steps, given serialized, value, and
targetRealm, are:
1. Initialize value's [30049]data attribute to the
[30050]sub-deserialization of serialized.[[Data]].
2. Initialize value's [30051]width attribute to serialized.[[Width]].
3. Initialize value's [30052]height attribute to
serialized.[[Height]].
4. Initialize value's [30053]colorSpace attribute to
serialized.[[ColorSpace]].
5. Initialize value's [30054]pixelFormat attribute to
serialized.[[PixelFormat]].
The [30055]ImageDataPixelFormat enumeration is used to specify type of
the [30056]data attribute of an [30057]ImageData and the arrangement
and numerical representation of the color components for each pixel.
The "rgba-unorm8" value indicates that the [30058]data attribute of an
[30059]ImageData must be of type [30060]Uint8ClampedArray. The color
components of each pixel must be stored in four sequential elements in
the order of red, green, blue, and then alpha. Each element represents
the 8-bit unsigned normalized value for that component.
The "rgba-float16" value indicates that the [30061]data attribute of an
[30062]ImageData must be of type [30063]Float16Array. The color
components of each pixel must be stored in four sequential elements in
the order of red, green, blue, and then alpha. Each element represents
the value for that component.
An [30064]ImageData object represents a rectanglar bitmap with width
equal to the [30065]width attribute and height equal to the
[30066]height attribute. The pixel values of this bitmap are stored in
the [30067]data attribute in left-to-right order, row by row from top
to bottom, starting with 0 for the top left pixel, with the order and
numerical representation of the color components of each pixel
determined by the [30068]pixelFormat attribute. The color space of the
pixel values of the bitmap is determined by the [30069]colorSpace
attribute.
The putImageData(imageData, dx, dy) method steps are to [30070]put
pixels from an ImageData onto a bitmap, given imageData, [30071]this's
[30072]output bitmap, dx, dy, 0, 0, imageData's [30073]width, and
imageData's [30074]height.
The putImageData(imageData, dx, dy, dirtyX, dirtyY, dirtyWidth,
dirtyHeight) method steps are to [30075]put pixels from an ImageData
onto a bitmap, given imageData, [30076]this's [30077]output bitmap, dx,
dy, dirtyX, dirtyY, dirtyWidth, and dirtyHeight.
To put pixels from an ImageData onto a bitmap, given an
[30078]ImageData imageData, an [30079]output bitmap bitmap, and numbers
dx, dy, dirtyX, dirtyY, dirtyWidth, and dirtyHeight:
1. Let buffer be imageData's [30080]data attribute value's
[[ViewedArrayBuffer]] internal slot.
2. If [30081]IsDetachedBuffer(buffer) is true, then throw an
[30082]"InvalidStateError" [30083]DOMException.
3. If dirtyWidth is negative, then let dirtyX be dirtyX+dirtyWidth,
and let dirtyWidth be equal to the absolute magnitude of
dirtyWidth.
If dirtyHeight is negative, then let dirtyY be dirtyY+dirtyHeight,
and let dirtyHeight be equal to the absolute magnitude of
dirtyHeight.
4. If dirtyX is negative, then let dirtyWidth be dirtyWidth+dirtyX,
and let dirtyX be zero.
If dirtyY is negative, then let dirtyHeight be dirtyHeight+dirtyY,
and let dirtyY be zero.
5. If dirtyX+dirtyWidth is greater than the [30084]width attribute of
the imageData argument, then let dirtyWidth be the value of that
[30085]width attribute, minus the value of dirtyX.
If dirtyY+dirtyHeight is greater than the [30086]height attribute
of the imageData argument, then let dirtyHeight be the value of
that [30087]height attribute, minus the value of dirtyY.
6. If, after those changes, either dirtyWidth or dirtyHeight are
negative or zero, then return without affecting any bitmaps.
7. For all integer values of x and y where
dirtyX ≤ x < dirtyX+dirtyWidth and dirtyY ≤ y < dirtyY+dirtyHeight,
set the pixel with coordinate (dx+x, dy+y) in bitmap to the color
of the pixel at coordinate (x, y) in the imageData data structure's
[30088]bitmap, converted from imageData's [30089]colorSpace to the
[30090]color space of bitmap using [30091]'relative-colorimetric'
rendering intent.
Due to the lossy nature of converting between color spaces and
converting to and from [30092]premultiplied alpha color values, pixels
that have just been set using [30093]putImageData(), and are not
completely opaque, might be returned to an equivalent
[30094]getImageData() as different values.
The current path, [30095]transformation matrix, [30096]shadow
attributes, [30097]global alpha, the [30098]clipping region, and
[30099]current compositing and blending operator must not affect the
methods described in this section.
In the following example, the script generates an [30100]ImageData
object so that it can draw onto it.
// canvas is a reference to a
// create a blank slate
var data = context.createImageData(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.putImageData(data, 0, 0);
// support methods
function FillPlasma(data, color) { ... }
function AddCloud(data, x, y) { ... }
Here is an example of using [30101]getImageData() and
[30102]putImageData() to implement an edge detection filter.
Edge detection demo
Here is an example of color space conversion applied when drawing a
solid color and reading the result back using and
[30103]getImageData().
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android12.1+
Returns the current [30106]global alpha value applied to
rendering operations.
Can be set, to change the [30107]global alpha value. Values
outside of the range 0.0 .. 1.0 are ignored.
context.[30108]globalCompositeOperation [ = value ]
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android10.1+
Returns the [30110]current compositing and blending operator,
from the values defined in Compositing and Blending.
[30111][COMPOSITE]
Can be set, to change the [30112]current compositing and
blending operator. Unknown values are ignored.
Objects that implement the [30113]CanvasCompositing interface have a
[30114]global alpha value and a [30115]current compositing and blending
operator value that both affect all the drawing operations on this
object.
The global alpha value gives an alpha value that is applied to shapes
and images before they are composited onto the [30116]output bitmap.
The value ranges from 0.0 (fully transparent) to 1.0 (no additional
transparency). It must initially have the value 1.0.
The globalAlpha getter steps are to return [30117]this's [30118]global
alpha.
The [30119]globalAlpha setter steps are:
1. If the given value is either infinite, NaN, or not in the range 0.0
to 1.0, then return.
2. Otherwise, set [30120]this's [30121]global alpha to the given
value.
The current compositing and blending operator value controls how shapes
and images are drawn onto the [30122]output bitmap, once they have had
the [30123]global alpha and the [30124]current transformation matrix
applied. Initially, it must be set to "[30125]source-over".
The globalCompositeOperation getter steps are to return [30126]this's
[30127]current compositing and blending operator.
The [30128]globalCompositeOperation setter steps are:
1. If the given value is not [30129]identical to any of the values
that the [30130] or the [30131]
properties are defined to take, then return. [30132][COMPOSITE]
2. Otherwise, set [30133]this's [30134]current compositing and
blending operator to the given value.
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
Returns whether pattern fills and the [30137]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).
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
Returns the current image-smoothing-quality preference.
Can be set, to change the preferred quality of image smoothing.
The possible values are "[30140]low", "[30141]medium" and
"[30142]high". Unknown values are ignored.
Objects that implement the [30143]CanvasImageSmoothing interface have
attributes that control how image smoothing is performed.
The imageSmoothingEnabled attribute, on getting, must return the last
value it was set to. On setting, it must be set to the new value. When
the object implementing the [30144]CanvasImageSmoothing interface is
created, the attribute must be set to true.
The imageSmoothingQuality attribute, on getting, must return the last
value it was set to. On setting, it must be set to the new value. When
the object implementing the [30145]CanvasImageSmoothing interface is
created, the attribute must be set to "[30146]low".
4.12.5.1.19 Shadows
All drawing operations on an object which implements the
[30147]CanvasShadowStyles interface are affected by the four global
shadow attributes.
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android12.1+
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.
Objects which implement the [30156]CanvasShadowStyles interface have an
associated shadow color, which is a CSS color. Initially, it must be
[30157]transparent black.
The shadowColor getter steps are to return the [30158]serialization of
[30159]this's [30160]shadow color with [30161]HTML-compatible
serialization requested.
The [30162]shadowColor setter steps are:
1. Let context be [30163]this's [30164]canvas attribute's value, if
that is an element; otherwise null.
2. Let parsedValue be the result of [30165]parsing the given value
with context if non-null.
3. If parsedValue is failure, then return.
4. Set [30166]this's [30167]shadow color to parsedValue.
The shadowOffsetX and shadowOffsetY attributes specify the distance
that the shadow will be offset in the positive horizontal and positive
vertical distance respectively. Their values are in coordinate space
units. They are not affected by the current transformation matrix.
When the context is created, the shadow offset attributes must
initially have the value 0.
On getting, they must return their current value. On setting, the
attribute being set must be set to the new value, except if the value
is infinite or NaN, in which case the new value must be ignored.
The shadowBlur attribute specifies the level of the blurring effect.
(The units do not map to coordinate space units, and are not affected
by the current transformation matrix.)
When the context is created, the [30168]shadowBlur attribute must
initially have the value 0.
On getting, the attribute must return its current value. On setting,
the attribute must be set to the new value, except if the value is
negative, infinite or NaN, in which case the new value must be ignored.
Shadows are only drawn if the opacity component of the alpha component
of the [30169]shadow color is nonzero and either the [30170]shadowBlur
is nonzero, or the [30171]shadowOffsetX is nonzero, or the
[30172]shadowOffsetY is nonzero.
[30173]When shadows are drawn, they must be rendered as follows:
1. Let A be an infinite [30174]transparent black bitmap on which the
source image for which a shadow is being created has been rendered.
2. Let B be an infinite [30175]transparent black bitmap, with a
coordinate space and an origin identical to A.
3. Copy the alpha component of A to B, offset by [30176]shadowOffsetX
in the positive x direction, and [30177]shadowOffsetY in the
positive y direction.
4. If [30178]shadowBlur is greater than 0:
1. Let σ be half the value of [30179]shadowBlur.
2. Perform a 2D Gaussian Blur on B, using σ as the standard
deviation.
User agents may limit values of σ to an implementation-specific
maximum value to avoid exceeding hardware limitations during the
Gaussian blur operation.
5. Set the red, green, and blue components of every pixel in B to the
red, green, and blue components (respectively) of the [30180]shadow
color.
6. Multiply the alpha component of every pixel in B by the alpha
component of the [30181]shadow color.
7. The shadow is in the bitmap B, and is rendered as part of the
[30182]drawing model described below.
If the [30183]current compositing and blending operator is
"[30184]copy", then shadows effectively won't render (since the shape
will overwrite the shadow).
4.12.5.1.20 Filters
All drawing operations on an object which implements the
[30185]CanvasFilters interface are affected by the global filter
attribute.
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
Returns the current filter.
Can be set, to change the filter. Values can either be the
string "none" or a string parseable as a
[30188]. Other values are ignored.
Such objects have an associated current filter, which is a string.
Initially the [30189]current filter is set to the string "none".
Whenever the value of the [30190]current filter is the string "none"
filters will be disabled for the context.
The [30191]filter getter steps are to return [30192]this's
[30193]current filter.
The [30194]filter setter steps are:
1. If the given value is "none", then set [30195]this's [30196]current
filter to "none" and return.
2. Let parsedValue be the result of [30197]parsing the given values as
a [30198]. If any property-independent style
sheet syntax like 'inherit' or 'initial' is present, then this
parsing must return failure.
3. If parsedValue is failure, then return.
4. Set [30199]this's [30200]current filter to the given value.
Though context.[30201]filter = "none" will disable filters for the
context, context.[30202]filter = "", context.[30203]filter = null, and
context.[30204]filter = undefined are all treated as unparseable inputs
and the value of the [30205]current filter is left unchanged.
Coordinates used in the value of the [30206]current filter are
interpreted such that one pixel is equivalent to one SVG user space
unit and to one canvas coordinate space unit. Filter coordinates are
not affected by the [30207]current transformation matrix. The current
transformation matrix affects only the input to the filter. Filters are
applied in the [30208]output bitmap's coordinate space.
When the value of the [30209]current filter is a string parsable as a
[30210] which defines lengths using percentages or
using [30211]'em' or [30212]'ex' units, these must be interpreted
relative to the [30213]computed value of the [30214]'font-size'
property of the [30215]font style source object at the time that the
attribute is set. If the [30216]computed values are undefined for a
particular case (e.g. because the [30217]font style source object is
not an element or is not [30218]being rendered), then the relative
keywords must be interpreted relative to the default value of the
[30219]font attribute. The 'larger' and 'smaller' keywords are not
supported.
If the value of the [30220]current filter is a string parseable as a
[30221] with a reference to an SVG filter in the
same document, and this SVG filter changes, then the changed filter is
used for the next draw operation.
If the value of the [30222]current filter is a string parseable as a
[30223] with a reference to an SVG filter in an
external resource document and that document is not loaded when a
drawing operation is invoked, then the drawing operation must proceed
with no filtering.
4.12.5.1.21 Working with externally-defined SVG filters
This section is non-normative.
Since drawing is performed using filter value "none" until an
externally-defined filter has finished loading, authors might wish to
determine whether such a filter has finished loading before proceeding
with a drawing operation. One way to accomplish this is to load the
externally-defined filter elsewhere within the same page in some
element that sends a load event (for example, an [30224]SVG use
element), and wait for the load event to be dispatched.
4.12.5.1.22 Drawing model
When a shape or image is painted, user agents must follow these steps,
in the order given (or act as if they do):
1. Render the shape or image onto an infinite [30225]transparent black
bitmap, creating image A, as described in the previous sections.
For shapes, the current fill, stroke, and line styles must be
honored, and the stroke must itself also be subjected to the
current transformation matrix.
2. Multiply the alpha component of every pixel in A by [30226]global
alpha.
3. When the [30227]current filter is set to a value other than "none"
and all the externally-defined filters it references, if any, are
in documents that are currently loaded, then use image A as the
input to the [30228]current filter, creating image B. If the
[30229]current filter is a string parseable as a
[30230], then draw using the [30231]current
filter in the same manner as SVG.
Otherwise, let B be an alias for A.
4. [30232]When shadows are drawn, render the shadow from image B,
using the current shadow styles, creating image C.
5. [30233]When shadows are drawn, composite C within the
[30234]clipping region over the current [30235]output bitmap using
the [30236]current compositing and blending operator.
6. Composite B within the [30237]clipping region over the current
[30238]output bitmap using the [30239]current compositing and
blending operator.
When compositing onto the [30240]output bitmap, pixels that would fall
outside of the [30241]output bitmap must be discarded.
4.12.5.1.23 Best practices
When a canvas is interactive, authors should include [30242]focusable
elements in the element's fallback content corresponding to each
[30243]focusable part of the canvas, as in the [30244]example above.
When rendering focus rings, to ensure that focus rings have the
appearance of native focus rings, authors should use the
[30245]drawFocusIfNeeded() method, passing it the element for which a
ring is being drawn. This method only draws the focus ring if the
element is [30246]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
[30247]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 control 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 [30248]input element, the
[30249]textarea element, or the [30250]contenteditable attribute.
4.12.5.1.24 Examples
This section is non-normative.
Here is an example of a script that uses canvas to draw [30251]pretty
glowing lines.
The 2D rendering context for [30252]canvas is often used for
sprite-based games. The following example demonstrates this:
[30255]ImageBitmapRenderingContext is a performance-oriented interface
that provides a low overhead method for displaying the contents of
[30256]ImageBitmap objects. It uses transfer semantics to reduce
overall memory consumption. It also streamlines performance by avoiding
intermediate compositing, unlike the [30257]drawImage() method of
[30258]CanvasRenderingContext2D.
Using an [30259]img element as an intermediate for getting an image
resource into a canvas, for example, would result in two copies of the
decoded image existing in memory at the same time: the [30260]img
element's copy, and the one in the canvas's backing store. This memory
cost can be prohibitive when dealing with extremely large images. This
can be avoided by using [30261]ImageBitmapRenderingContext.
Using [30262]ImageBitmapRenderingContext, here is how to transcode an
image to the JPEG format in a memory- and CPU-efficient way:
createImageBitmap(inputImageBlob).then(image => {
const canvas = document.createElement(ʼcanvasʼ);
const context = canvas.getContext(ʼbitmaprendererʼ);
context.transferFromImageBitmap(image);
canvas.toBlob(outputJPEGBlob => {
// Do something with outputJPEGBlob.
}, ʼimage/jpegʼ);
});
4.12.5.2.2 The [30263]ImageBitmapRenderingContext interface
(BUTTON) ✔MDN
[30264]ImageBitmapRenderingContext
Support in all current engines.
Firefox46+Safari11.1+Chrome66+
__________________________________________________________________
context = canvas.[30271]getContext('bitmaprenderer' [, { [
[30272]alpha: false ] } ])
Returns an [30273]ImageBitmapRenderingContext object that is
permanently bound to a particular [30274]canvas element.
If the [30275]alpha setting is provided and set to false, then
the canvas is forced to always be opaque.
context.[30276]canvas
Returns the [30277]canvas element that the context is bound to.
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
Transfers the underlying [30280]bitmap data from imageBitmap to
context, and the bitmap becomes the contents of the
[30281]canvas element to which context is bound.
context.[30282]transferFromImageBitmap(null)
Replaces contents of the [30283]canvas element to which context
is bound with a [30284]transparent black bitmap whose size
corresponds to the [30285]width and [30286]height content
attributes of the [30287]canvas element.
The canvas attribute must return the value it was initialized to when
the object was created.
An [30288]ImageBitmapRenderingContext object has an output bitmap,
which is a reference to [30289]bitmap data.
An [30290]ImageBitmapRenderingContext object has a bitmap mode, which
can be set to valid or blank. A value of [30291]valid indicates that
the context's [30292]output bitmap refers to [30293]bitmap data that
was acquired via [30294]transferFromImageBitmap(). A value [30295]blank
indicates that the context's [30296]output bitmap is a default
transparent bitmap.
An [30297]ImageBitmapRenderingContext object also has an alpha flag,
which can be set to true or false. When an
[30298]ImageBitmapRenderingContext object has its [30299]alpha flag set
to false, the contents of the [30300]canvas element to which the
context is bound are obtained by compositing the context's
[30301]output bitmap onto an [30302]opaque black bitmap of the same
size using the [30303]source-over compositing operator. If the
[30304]alpha flag is set to true, then the [30305]output bitmap is used
as the contents of the [30306]canvas element to which the context is
bound. [30307][COMPOSITE]
The step of compositing over an [30308]opaque black bitmap ought to be
elided whenever equivalent results can be obtained more efficiently by
other means.
__________________________________________________________________
When a user agent is required to set an ImageBitmapRenderingContext's
output bitmap, with a context argument that is an
[30309]ImageBitmapRenderingContext object and an optional argument
bitmap that refers to [30310]bitmap data, it must run these steps:
1. If a bitmap argument was not provided, then:
1. Set context's [30311]bitmap mode to [30312]blank.
2. Let canvas be the [30313]canvas element to which context is
bound.
3. Set context's [30314]output bitmap to be [30315]transparent
black with a [30316]natural width equal to [30317]the numeric
value of canvas's [30318]width attribute and a [30319]natural
height equal to [30320]the numeric value of canvas's
[30321]height attribute, those values being interpreted in
[30322]CSS pixels.
4. Set the [30323]output bitmap's [30324]origin-clean flag to
true.
2. If a bitmap argument was provided, then:
1. Set context's [30325]bitmap mode to [30326]valid.
2. Set context's [30327]output bitmap to refer to the same
underlying bitmap data as bitmap, without making a copy.
The [30328]origin-clean flag of bitmap is included in the
bitmap data to be referenced by context's [30329]output
bitmap.
__________________________________________________________________
The ImageBitmapRenderingContext creation algorithm, which is passed a
target and options, consists of running these steps:
1. Let settings be the result of [30330]converting options to the
dictionary type [30331]ImageBitmapRenderingContextSettings. (This
can throw an exception.)
2. Let context be a new [30332]ImageBitmapRenderingContext object.
3. Initialize context's [30333]canvas attribute to point to target.
4. Set context's [30334]output bitmap to the same bitmap as target's
bitmap (so that they are shared).
5. Run the steps to [30335]set an ImageBitmapRenderingContext's output
bitmap with context.
6. Initialize context's [30336]alpha flag to true.
7. Process each of the members of settings as follows:
alpha
If false, then set context's [30337]alpha flag to false.
The transferFromImageBitmap(bitmap) method, when invoked, must run
these steps:
1. Let bitmapContext be the [30338]ImageBitmapRenderingContext object
on which the [30339]transferFromImageBitmap() method was called.
2. If bitmap is null, then run the steps to [30340]set an
ImageBitmapRenderingContext's output bitmap, with bitmapContext as
the context argument and no bitmap argument, then return.
3. If the value of bitmap's [30341][[Detached]] internal slot is set
to true, then throw an [30342]"InvalidStateError"
[30343]DOMException.
4. Run the steps to [30344]set an ImageBitmapRenderingContext's output
bitmap, with the context argument equal to bitmapContext, and the
bitmap argument referring to bitmap's underlying [30345]bitmap
data.
5. Set the value of bitmap's [30346][[Detached]] internal slot to
true.
6. Unset bitmap's [30347]bitmap data.
4.12.5.3 The [30348]OffscreenCanvas interface
(BUTTON) ✔MDN
[30349]OffscreenCanvas
Support in all current engines.
Firefox105+Safari16.4+Chrome69+
__________________________________________________________________
typedef ([30350]OffscreenCanvasRenderingContext2D or [30351]ImageBitmapRendering
Context or [30352]WebGLRenderingContext or [30353]WebGL2RenderingContext or [303
54]GPUCanvasContext) OffscreenRenderingContext;
[Exposed=(Window,Worker), [30362]Transferable]
interface OffscreenCanvas : [30363]EventTarget {
[30364]constructor([EnforceRange] unsigned long long width, [EnforceRange] uns
igned long long height);
attribute [EnforceRange] unsigned long long [30365]width;
attribute [EnforceRange] unsigned long long [30366]height;
[30380]OffscreenCanvas is an [30381]EventTarget, so both
[30382]OffscreenCanvasRenderingContext2D and WebGL can fire events at
it. [30383]OffscreenCanvasRenderingContext2D can fire
[30384]contextlost and [30385]contextrestored, and WebGL can fire
webglcontextlost and webglcontextrestored. [30386][WEBGL]
[30387]OffscreenCanvas objects are used to create rendering contexts,
much like an [30388]HTMLCanvasElement, but with no connection to the
DOM. This makes it possible to use canvas rendering contexts in
[30389]workers.
An [30390]OffscreenCanvas object may hold a weak reference to a
placeholder canvas element, which is typically in the DOM, whose
embedded content is provided by the [30391]OffscreenCanvas object. The
bitmap of the [30392]OffscreenCanvas object is pushed to the
[30393]placeholder canvas element as part of the
[30394]OffscreenCanvas's [30395]relevant agent's [30396]event loop's
[30397]update the rendering steps.
offscreenCanvas = new [30398]OffscreenCanvas(width, height)
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
Returns a new [30400]OffscreenCanvas object that is not linked
to a [30401]placeholder canvas element, and whose bitmap's size
is determined by the width and height arguments.
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
Returns an object that exposes an API for drawing on the
[30404]OffscreenCanvas object. contextId specifies the desired
API: "[30405]2d", "[30406]bitmaprenderer", "[30407]webgl",
"[30408]webgl2", or "[30409]webgpu". options is handled by that
API.
This specification defines the "[30410]2d" context below, which
is similar but distinct from the "[30411]2d" context that is
created from a [30412]canvas element. The WebGL specifications
define the "[30413]webgl" and "[30414]webgl2" contexts. WebGPU
defines the "[30415]webgpu" context. [30416][WEBGL]
[30417][WEBGPU]
Returns null if the canvas has already been initialized with
another context type (e.g., trying to get a "[30418]2d" context
after getting a "[30419]webgl" context).
An [30420]OffscreenCanvas object has an internal bitmap that is
initialized when the object is created. The width and height of the
[30421]bitmap are equal to the values of the [30422]width and
[30423]height attributes of the [30424]OffscreenCanvas object.
Initially, all the bitmap's pixels are [30425]transparent black.
An [30426]OffscreenCanvas object has an internal inherited language and
inherited direction set when the [30427]OffscreenCanvas is created.
An [30428]OffscreenCanvas object can have a rendering context bound to
it. Initially, it does not have a bound rendering context. To keep
track of whether it has a rendering context or not, and what kind of
rendering context it is, an [30429]OffscreenCanvas object also has a
context mode, which is initially none but can be changed to either 2d,
bitmaprenderer, webgl, webgl2, webgpu, or detached by algorithms
defined in this specification.
The new OffscreenCanvas(width, height) constructor steps are:
1. Initialize the [30430]bitmap of [30431]this to a rectangular array
of [30432]transparent black pixels of the dimensions specified by
width and height.
2. Initialize the [30433]width of [30434]this to width.
3. Initialize the [30435]height of [30436]this to height.
4. Set [30437]this's [30438]inherited language to [30439]explicitly
unknown.
5. Set [30440]this's [30441]inherited direction to "ltr".
6. Let global be the [30442]relevant global object of [30443]this.
7. If global is a [30444]Window object:
1. Let element be the [30445]document element of global's
[30446]associated Document.
2. If element is not null:
1. Set the [30447]inherited language of [30448]this to
element's [30449]language.
2. Set the [30450]inherited direction of [30451]this to
element's [30452]directionality.
[30453]OffscreenCanvas objects are [30454]transferable. Their
[30455]transfer steps, given value and dataHolder, are as follows:
1. If value's [30456]context mode is not equal to [30457]none, then
throw an [30458]"InvalidStateError" [30459]DOMException.
2. Set value's [30460]context mode to [30461]detached.
3. Let width and height be the dimensions of value's [30462]bitmap.
4. Let language and direction be the values of value's
[30463]inherited language and [30464]inherited direction.
5. Unset value's [30465]bitmap.
6. Set dataHolder.[[Width]] to width and dataHolder.[[Height]] to
height.
7. Set dataHolder.[[Language]] to language and
dataHolder.[[Direction]] to direction.
8. Set dataHolder.[[PlaceholderCanvas]] to be a weak reference to
value's [30466]placeholder canvas element, if value has one, or
null if it does not.
Their [30467]transfer-receiving steps, given dataHolder and value, are:
1. Initialize value's [30468]bitmap to a rectangular array of
[30469]transparent black pixels with width given by
dataHolder.[[Width]] and height given by dataHolder.[[Height]].
2. Set value's [30470]inherited language to dataHolder.[[Language]]
and [30471]inherited direction to dataHolder.[[Direction]].
3. If dataHolder.[[PlaceholderCanvas]] is not null, set value's
[30472]placeholder canvas element to
dataHolder.[[PlaceholderCanvas]] (while maintaining the weak
reference semantics).
__________________________________________________________________
The getContext(contextId, options) method of an [30473]OffscreenCanvas
object, when invoked, must run these steps:
1. If options is not an [30474]object, then set options to null.
2. Set options to the result of [30475]converting options to a
JavaScript value.
3. Run the steps in the cell of the following table whose column
header matches this [30476]OffscreenCanvas object's [30477]context
mode and whose row header matches contextId:
[30478]none [30479]2d [30480]bitmaprenderer [30481]webgl or
[30482]webgl2 [30483]webgpu [30484]detached
"2d"
1. Let context be the result of running the [30485]offscreen 2D
context creation algorithm given [30486]this and options.
2. Set [30487]this's [30488]context mode to [30489]2d.
3. Return context.
Return the same object as was returned the last time the method was
invoked with this same first argument. Return null. Return null. Return
null. Throw an [30490]"InvalidStateError" [30491]DOMException.
"bitmaprenderer"
1. Let context be the result of running the
[30492]ImageBitmapRenderingContext creation algorithm given
[30493]this and options.
2. Set [30494]this's [30495]context mode to
[30496]bitmaprenderer.
3. Return context.
Return null. Return the same object as was returned the last time the
method was invoked with this same first argument. Return null. Return
null. Throw an [30497]"InvalidStateError" [30498]DOMException.
"webgl" or "webgl2"
1. Let context be the result of following the instructions given
in the WebGL specifications' Context Creation sections.
[30499][WEBGL]
2. If context is null, then return null; otherwise set
[30500]this's [30501]context mode to [30502]webgl or
[30503]webgl2.
3. Return context.
Return null. Return null. Return the same value as was returned the
last time the method was invoked with this same first argument. Return
null. Throw an [30504]"InvalidStateError" [30505]DOMException.
"webgpu"
1. Let context be the result of following the instructions given
in WebGPU's [30506]Canvas Rendering section. [30507][WEBGPU]
2. If context is null, then return null; otherwise set
[30508]this's [30509]context mode to [30510]webgpu.
3. Return context.
Return null. Return null. Return null. Return the same value as was
returned the last time the method was invoked with this same first
argument. Throw an [30511]"InvalidStateError" [30512]DOMException.
__________________________________________________________________
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
These attributes return the dimensions of the
[30517]OffscreenCanvas object's [30518]bitmap.
They can be set, to replace the [30519]bitmap with a new,
[30520]transparent black bitmap of the specified dimensions
(effectively resizing it).
If either the width or height attributes of an [30521]OffscreenCanvas
object are set (to a new value or to the same value as before) and the
[30522]OffscreenCanvas object's [30523]context mode is [30524]2d, then
[30525]reset the rendering context to its default state and resize the
[30526]OffscreenCanvas object's [30527]bitmap to the new values of the
[30528]width and [30529]height attributes.
The resizing behavior for "[30530]webgl" and "[30531]webgl2" contexts
is defined in the WebGL specifications. [30532][WEBGL]
The resizing behavior for "[30533]webgpu" context is defined in WebGPU.
[30534][WEBGPU]
If an [30535]OffscreenCanvas object whose dimensions were changed has a
[30536]placeholder canvas element, then the [30537]placeholder canvas
element's [30538]natural size will only be updated during the
[30539]OffscreenCanvas's [30540]relevant agent's [30541]event loop's
[30542]update the rendering steps.
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
Returns a promise that will fulfill with a new [30545]Blob
object representing a file containing the image in the
[30546]OffscreenCanvas object.
The argument, if provided, is a dictionary that controls the
encoding options of the image file to be created. The
[30547]type field specifies the file format and has a default
value of "[30548]image/png"; that type is also used if the
requested type isn't supported. If the image format supports
variable quality (such as "[30549]image/jpeg"), then the
[30550]quality field is a number in the range 0.0 to 1.0
inclusive indicating the desired quality level for the resulting
image.
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
Returns a newly created [30553]ImageBitmap object with the image
in the [30554]OffscreenCanvas object. The image in the
[30555]OffscreenCanvas object is replaced with a new blank
image.
The convertToBlob(options) method steps are:
1. If the value of [30556]this's [30557][[Detached]] internal slot is
true, then return [30558]a promise rejected with an
[30559]"InvalidStateError" [30560]DOMException.
2. If [30561]this's [30562]context mode is [30563]2d and the rendering
context's [30564]output bitmap's [30565]origin-clean flag is set to
false, then return [30566]a promise rejected with a
[30567]"SecurityError" [30568]DOMException.
3. If [30569]this's [30570]bitmap has no pixels (i.e., either its
horizontal dimension or its vertical dimension is zero), then
return [30571]a promise rejected with an [30572]"IndexSizeError"
[30573]DOMException.
4. Let bitmap be a copy of [30574]this's [30575]bitmap.
5. Let result be a new promise object.
6. Let global be [30576]this's [30577]relevant global object.
7. Run these steps [30578]in parallel:
1. Let file be [30579]a serialization of bitmap as a file, with
options's type and quality if present.
2. [30580]Queue a global task on the [30581]canvas blob
serialization task source given global to run these steps:
1. If file is null, then reject result with an
[30582]"EncodingError" [30583]DOMException.
2. Otherwise, resolve result with a new [30584]Blob object,
created in global's [30585]relevant realm, representing
file. [30586][FILEAPI]
8. Return result.
The transferToImageBitmap() method, when invoked, must run the
following steps:
1. If the value of this [30587]OffscreenCanvas object's
[30588][[Detached]] internal slot is set to true, then throw an
[30589]"InvalidStateError" [30590]DOMException.
2. If this [30591]OffscreenCanvas object's [30592]context mode is set
to [30593]none, then throw an [30594]"InvalidStateError"
[30595]DOMException.
3. Let image be a newly created [30596]ImageBitmap object that
references the same underlying bitmap data as this
[30597]OffscreenCanvas object's [30598]bitmap.
4. Set this [30599]OffscreenCanvas object's [30600]bitmap to reference
a newly created bitmap of the same dimensions and color space as
the previous bitmap, and with its pixels initialized to
[30601]transparent black, or [30602]opaque black if the rendering
context's [30603]alpha is false.
This means that if the rendering context of this
[30604]OffscreenCanvas is a [30605]WebGLRenderingContext, the value
of [30606]preserveDrawingBuffer will have no effect. [30607][WEBGL]
5. Return image.
The following are the [30608]event handlers (and their corresponding
[30609]event handler event types) that must be supported, as
[30610]event handler IDL attributes, by all objects implementing the
[30611]OffscreenCanvas interface:
[30612]Event handler [30613]Event handler event type
oncontextlost [30614]contextlost
oncontextrestored [30615]contextrestored
4.12.5.3.1 The offscreen 2D rendering context
(BUTTON) ✔MDN
[30616]OffscreenCanvasRenderingContext2D
Support in all current engines.
Firefox105+Safari16.4+Chrome69+
__________________________________________________________________
[30619]OffscreenCanvasRenderingContext2D includes [30620]CanvasSettings;
[30621]OffscreenCanvasRenderingContext2D includes [30622]CanvasState;
[30623]OffscreenCanvasRenderingContext2D includes [30624]CanvasTransform;
[30625]OffscreenCanvasRenderingContext2D includes [30626]CanvasCompositing;
[30627]OffscreenCanvasRenderingContext2D includes [30628]CanvasImageSmoothing;
[30629]OffscreenCanvasRenderingContext2D includes [30630]CanvasFillStrokeStyles;
[30631]OffscreenCanvasRenderingContext2D includes [30632]CanvasShadowStyles;
[30633]OffscreenCanvasRenderingContext2D includes [30634]CanvasFilters;
[30635]OffscreenCanvasRenderingContext2D includes [30636]CanvasRect;
[30637]OffscreenCanvasRenderingContext2D includes [30638]CanvasDrawPath;
[30639]OffscreenCanvasRenderingContext2D includes [30640]CanvasText;
[30641]OffscreenCanvasRenderingContext2D includes [30642]CanvasDrawImage;
[30643]OffscreenCanvasRenderingContext2D includes [30644]CanvasImageData;
[30645]OffscreenCanvasRenderingContext2D includes [30646]CanvasPathDrawingStyles
;
[30647]OffscreenCanvasRenderingContext2D includes [30648]CanvasTextDrawingStyles
;
[30649]OffscreenCanvasRenderingContext2D includes [30650]CanvasPath;
The [30651]OffscreenCanvasRenderingContext2D object is a rendering
context for drawing to the [30652]bitmap of an [30653]OffscreenCanvas
object. It is similar to the [30654]CanvasRenderingContext2D object,
with the following differences:
* there is no support for [30655]user interface features;
* its [30656]canvas attribute refers to an [30657]OffscreenCanvas
object rather than a [30658]canvas element;
An [30659]OffscreenCanvasRenderingContext2D object has an associated
OffscreenCanvas object, which is the [30660]OffscreenCanvas object from
which the [30661]OffscreenCanvasRenderingContext2D object was created.
offscreenCanvas = offscreenCanvasRenderingContext2D.[30662]canvas
Returns the [30663]associated OffscreenCanvas object.
The offscreen 2D context creation algorithm, which is passed a target
(an [30664]OffscreenCanvas object) and optionally some arguments,
consists of running the following steps:
1. If the algorithm was passed some arguments, let arg be the first
such argument. Otherwise, let arg be undefined.
2. Let settings be the result of [30665]converting arg to the
dictionary type [30666]CanvasRenderingContext2DSettings. (This can
throw an exception.)
3. Let context be a new [30667]OffscreenCanvasRenderingContext2D
object.
4. Set context's [30668]associated OffscreenCanvas object to target.
5. Run the [30669]canvas settings output bitmap initialization
algorithm, given context and settings.
6. Set context's [30670]output bitmap to a newly created bitmap with
the dimensions specified by the [30671]width and [30672]height
attributes of target, and set target's bitmap to the same bitmap
(so that they are shared).
7. If context's [30673]alpha flag is set to true, initialize all the
pixels of context's [30674]output bitmap to [30675]transparent
black. Otherwise, initialize the pixels to [30676]opaque black.
8. Return context.
Implementations are encouraged to short-circuit the graphics update
steps of the [30677]window event loop for the purposes of updating the
contents of a [30678]placeholder canvas element to the display. This
could mean, for example, that the bitmap contents are copied directly
to a graphics buffer that is mapped to the physical display location of
the [30679]placeholder canvas element. This or similar short-circuiting
approaches can significantly reduce display latency, especially in
cases where the [30680]OffscreenCanvas is updated from a [30681]worker
event loop and the [30682]window event loop of the [30683]placeholder
canvas element is busy. However, such shortcuts cannot have any
script-observable side-effects. This means that the committed bitmap
still needs to be sent to the [30684]placeholder canvas element, in
case the element is used as a [30685]CanvasImageSource, as an
[30686]ImageBitmapSource, or in case [30687]toDataURL() or
[30688]toBlob() are called on it.
The canvas attribute, on getting, must return this
[30689]OffscreenCanvasRenderingContext2D's [30690]associated
OffscreenCanvas object.
4.12.5.4 Color spaces and color space conversion
The [30691]canvas APIs provide mechanisms for specifying the color
space of the canvas's backing store. The default backing store color
space for all canvas APIs is [30692]'srgb'.
[30693]Color space conversion must be applied to the canvas's backing
store when rendering the canvas to the output device. This color space
conversion must be identical to the color space conversion that would
be applied to an [30694]img element with a color profile that specifies
the same [30695]color space as the canvas's backing store.
When drawing content to a 2D context, all inputs must be
[30696]converted to the [30697]context's color space before drawing.
Interpolation of gradient color stops must be performed on color values
after conversion to the [30698]context's color space. Alpha blending
must be performed on values after conversion to the [30699]context's
color space.
There do not exist any inputs to a 2D context for which the color space
is undefined. The color space for CSS colors is defined in CSS Color.
The color space for images that specify no color profile information is
assumed to be [30700]'srgb', as specified in the [30701]Color Spaces of
Untagged Colors section of CSS Color. [30702][CSSCOLOR]
4.12.5.5 Serializing bitmaps to a file
When a user agent is to create a serialization of the bitmap as a file,
given a type and an optional quality, it must create an image file in
the format given by type. If an error occurs during the creation of the
image file (e.g. an internal encoder error), then the result of the
serialization is null. [30703][PNG]
The image file's pixel data must be the bitmap's pixel data scaled to
one image pixel per coordinate space unit, and if the file format used
supports encoding resolution metadata, the resolution must be given as
96dpi (one image pixel per [30704]CSS pixel).
If type is supplied, then it must be interpreted as a [30705]MIME type
giving the format to use. If the type has any parameters, then it must
be treated as not supported.
For example, the value "[30706]image/png" would mean to generate a PNG
image, the value "[30707]image/jpeg" would mean to generate a JPEG
image, and the value "[30708]image/svg+xml" would mean to generate an
SVG image (which would require that the user agent track how the bitmap
was generated, an unlikely, though potentially awesome, feature).
User agents must support PNG ("[30709]image/png"). User agents may
support other types. If the user agent does not support the requested
type, then it must create the file using the PNG format. [30710][PNG]
User agents must [30711]convert the provided type to ASCII lowercase
before establishing if they support that type.
For image types that do not support an alpha component, the serialized
image must be the bitmap image composited onto an [30712]opaque black
background using the [30713]source-over compositing operator.
For image types that support color profiles, the serialized image must
include a color profile indicating the color space of the underlying
bitmap. For image types that do not support color profiles, the
serialized image must be [30714]converted to the [30715]'srgb' color
space using [30716]'relative-colorimetric' rendering intent.
Thus, in the 2D context, calling the [30717]drawImage() method to
render the output of the [30718]toDataURL() or [30719]toBlob() method
to the canvas, given the appropriate dimensions, has no visible effect
beyond, at most, clipping colors of the canvas to a more narrow gamut.
For image types that support multiple bit depths, the serialized image
must use the bit depth that best preserves content of the underlying
bitmap.
For example, when serializing a 2D context that has [30720]color type
of [30721]float16 to type "[30722]image/png", the resulting image would
have 16 bits per sample. This serialization will still lose significant
detail (all values less than 0.5/65535 would be clamped to 0, and all
values greater than 1 would be clamped to 1).
If type is an image format that supports variable quality (such as
"[30723]image/jpeg"), quality is given, and type is not
"[30724]image/png", then, if quality [30725]is a Number in the range
0.0 to 1.0 inclusive, the user agent must treat quality as the desired
quality level. Otherwise, the user agent must use its default quality
value, as if the quality argument had not been given.
The use of type-testing here, instead of simply declaring quality as a
Web IDL double, is a historical artifact.
Different implementations can have slightly different interpretations
of "quality". When the quality is not specified, an
implementation-specific default is used that represents a reasonable
compromise between compression ratio, image quality, and encoding time.
4.12.5.6 Security with [30726]canvas elements
This section is non-normative.
Information leakage can occur if scripts from one [30727]origin can
access information (e.g. read pixels) from images from another origin
(one that isn't the [30728]same).
To mitigate this, bitmaps used with [30729]canvas elements,
[30730]OffscreenCanvas objects, and [30731]ImageBitmap objects are
defined to have a flag indicating whether they are [30732]origin-clean.
All bitmaps start with their [30733]origin-clean set to true. The flag
is set to false when cross-origin images are used.
The [30734]toDataURL(), [30735]toBlob(), and [30736]getImageData()
methods check the flag and will throw a [30737]"SecurityError"
[30738]DOMException rather than leak cross-origin data.
The value of the [30739]origin-clean flag is propagated from a source's
bitmap to a new [30740]ImageBitmap object by
[30741]createImageBitmap(). Conversely, a destination [30742]canvas
element's bitmap will have its [30743]origin-clean flags set to false
by [30744]drawImage if the source image is an [30745]ImageBitmap object
whose bitmap has its [30746]origin-clean flag set to false.
The flag can be reset in certain situations; for example, when changing
the value of the [30747]width or the [30748]height content attribute of
the [30749]canvas element to which a [30750]CanvasRenderingContext2D is
bound, the bitmap is cleared and its [30751]origin-clean flag is reset.
When using an [30752]ImageBitmapRenderingContext, the value of the
[30753]origin-clean flag is propagated from [30754]ImageBitmap objects
when they are transferred to the [30755]canvas via
[30756]transferFromImageBitmap().
4.12.5.7 Premultiplied alpha and the 2D rendering context
Premultiplied alpha refers to one way of representing transparency in
an image, the other being non-premultiplied alpha.
Under non-premultiplied alpha, the red, green, and blue components of a
pixel represent that pixel's color, and its alpha component represents
that pixel's opacity.
Under premultiplied alpha, however, the red, green, and blue components
of a pixel represent the amounts of color that the pixel adds to the
image, and its alpha component represents the amount that the pixel
obscures whatever is behind it.
For instance, assuming the color components range from 0 (off) to 255
(full intensity), these example colors are represented in the following
ways:
CSS color representation Premultiplied representation Non-premultiplied
representation Description of color Image of color blended above other
content
rgba(255, 127, 0, 1) 255, 127, 0, 255 255, 127, 0, 255
Completely-opaque orange An opaque orange circle sits atop a background
rgba(255, 255, 0, 0.5) 127, 127, 0, 127 255, 255, 0, 127 Halfway-opaque
yellow A yellow circle, halfway transparent, sits atop a background
Unrepresentable 255, 127, 0, 127 Unrepresentable Additive
halfway-opaque orange An orange circle somewhat brightens the
background that it sits atop
Unrepresentable 255, 127, 0, 0 Unrepresentable Additive
fully-transparent orange An orange circle completely brightens the
background that it sits atop
rgba(255, 127, 0, 0) 0, 0, 0, 0 255, 127, 0, 0 Fully-transparent
("invisible") orange An empty background with nothing atop it
rgba(0, 127, 255, 0) 0, 0, 0, 0 255, 127, 0, 0 Fully-transparent
("invisible") turquoise An empty background with nothing atop it
Converting a color value from a non-premultiplied representation to a
premultiplied one involves multiplying the color's red, green, and blue
components by its alpha component (remapping the range of the alpha
component such that "fully transparent" is 0, and "fully opaque" is 1).
Converting a color value from a premultiplied representation to a
non-premultiplied one involves the inverse: dividing the color's red,
green, and blue components by its alpha component.
As certain colors can only be represented under premultiplied alpha
(for instance, additive colors), and others can only be represented
under non-premultiplied alpha (for instance, "invisible" colors which
hold certain red, green, and blue values even with no opacity); and
division and multiplication using finite precision entails a loss of
accuracy, converting between premultiplied and non-premultiplied alpha
is a lossy operation on colors that are not fully opaque.
A [30757]CanvasRenderingContext2D's [30758]output bitmap and an
[30759]OffscreenCanvasRenderingContext2D's [30760]output bitmap must
use premultiplied alpha to represent transparent colors.
It is important for canvas bitmaps to represent colors using
premultiplied alpha because it affects the range of representable
colors. While additive colors cannot currently be drawn onto canvases
directly because CSS colors are non-premultiplied and cannot represent
them, it is still possible to, for instance, draw additive colors onto
a WebGL canvas and then draw that WebGL canvas onto a 2D canvas via
[30761]drawImage().
4.13 Custom elements
(BUTTON) ✔MDN
[30762]Using_custom_elements
Support in all current engines.
Firefox63+Safari10.1+Chrome54+
__________________________________________________________________
[30763]Custom elements provide a way for authors to build their own
fully-featured DOM elements. Although authors could always use
non-standard elements in their documents, with application-specific
behavior added after the fact by scripting or similar, such elements
have historically been non-conforming and not very functional. By
[30764]defining a custom element, authors can inform the parser how to
properly construct an element and how elements of that class should
react to changes.
Custom elements are part of a larger effort to "rationalise the
platform", by explaining existing platform features (like the elements
of HTML) in terms of lower-level author-exposed extensibility points
(like custom element definition). Although today there are many
limitations on the capabilities of custom elements—both functionally
and semantically—that prevent them from fully explaining the behaviors
of HTML's existing elements, we hope to shrink this gap over time.
4.13.1.1 Creating an autonomous custom element
This section is non-normative.
For the purposes of illustrating how to create an [30765]autonomous
custom element, let's define a custom element that encapsulates
rendering a small icon for a country flag. Our goal is to be able to
use it like so:
To do this, we first declare a class for the custom element, extending
[30766]HTMLElement:
class FlagIcon extends HTMLElement {
constructor() {
super();
this._countryCode = null;
}
static observedAttributes = ["country"];
attributeChangedCallback(name, oldValue, newValue) {
// name will always be "country" due to observedAttributes
this._countryCode = newValue;
this._updateRendering();
}
connectedCallback() {
this._updateRendering();
}
get country() {
return this._countryCode;
}
set country(v) {
this.setAttribute("country", v);
}
_updateRendering() {
// Left as an exercise for the reader. But, youʼll probably want to
// check this.ownerDocument.defaultView to see if weʼve been
// inserted into a document with a browsing context, and avoid
// doing any work if not.
}
}
We then need to use this class to define the element:
customElements.define("flag-icon", FlagIcon);
At this point, our above code will work! The parser, whenever it sees
the flag-icon tag, will construct a new instance of our FlagIcon class,
and tell our code about its new country attribute, which we then use to
set the element's internal state and update its rendering (when
appropriate).
You can also create flag-icon elements using the DOM API:
const flagIcon = document.createElement("flag-icon")
flagIcon.country = "jp"
document.body.appendChild(flagIcon)
Finally, we can also use the [30767]custom element constructor itself.
That is, the above code is equivalent to:
const flagIcon = new FlagIcon()
flagIcon.country = "jp"
document.body.appendChild(flagIcon)
4.13.1.2 Creating a form-associated custom element
This section is non-normative.
Adding a static formAssociated property, with a true value, makes an
[30768]autonomous custom element a [30769]form-associated custom
element. The [30770]ElementInternals interface helps you to implement
functions and properties common to form control elements.
class MyCheckbox extends HTMLElement {
static formAssociated = true;
static observedAttributes = [ʼcheckedʼ];
get form() { return this._internals.form; }
get name() { return this.getAttribute(ʼnameʼ); }
get type() { return this.localName; }
get checked() { return this.hasAttribute(ʼcheckedʼ); }
set checked(flag) { this.toggleAttribute(ʼcheckedʼ, Boolean(flag)); }
attributeChangedCallback(name, oldValue, newValue) {
// name will always be "checked" due to observedAttributes
this._internals.setFormValue(this.checked ? ʼonʼ : null);
}
You can use the custom element my-checkbox like a built-in
form-associated element. For example, putting it in [30771]form or
[30772]label associates the my-checkbox element with them, and
submitting the [30773]form will send data provided by my-checkbox
implementation.
4.13.1.3 Creating a custom element with default accessible roles, states,
and properties
This section is non-normative.
By using the appropriate properties of [30774]ElementInternals, your
custom element can have default accessibility semantics. The following
code expands our form-associated checkbox from the previous section to
properly set its default role and checkedness, as viewed by
accessibility technology:
class MyCheckbox extends HTMLElement {
static formAssociated = true;
static observedAttributes = [ʼcheckedʼ];
get form() { return this._internals.form; }
get name() { return this.getAttribute(ʼnameʼ); }
get type() { return this.localName; }
get checked() { return this.hasAttribute(ʼcheckedʼ); }
set checked(flag) { this.toggleAttribute(ʼcheckedʼ, Boolean(flag)); }
attributeChangedCallback(name, oldValue, newValue) {
// name will always be "checked" due to observedAttributes
this._internals.setFormValue(this.checked ? ʼonʼ : null);
this._internals.ariaChecked = this.checked;
}
Note that, like for built-in elements, these are only defaults, and can
be overridden by the page author using the [30775]role and
[30776]aria-* attributes:
Custom element authors are encouraged to state what aspects of their
accessibility semantics are strong native semantics, i.e., should not
be overridden by users of the custom element. In our example, the
author of the my-checkbox element would state that its [30777]role and
[30778]aria-checked values are strong native semantics, thus
discouraging code such as the above.
4.13.1.4 Creating a customized built-in element
This section is non-normative.
[30779]Customized built-in elements are a distinct kind of
[30780]custom element, which are defined slightly differently and used
very differently compared to [30781]autonomous custom elements. They
exist to allow reuse of behaviors from the existing elements of HTML,
by extending those elements with new custom functionality. This is
important since many of the existing behaviors of HTML elements can
unfortunately not be duplicated by using purely [30782]autonomous
custom elements. Instead, [30783]customized built-in elements allow the
installation of custom construction behavior, lifecycle hooks, and
prototype chain onto existing elements, essentially "mixing in" these
capabilities on top of the already-existing element.
[30784]Customized built-in elements require a distinct syntax from
[30785]autonomous custom elements because user agents and other
software key off an element's local name in order to identify the
element's semantics and behavior. That is, the concept of
[30786]customized built-in elements building on top of existing
behavior depends crucially on the extended elements retaining their
original local name.
In this example, we'll be creating a [30787]customized built-in element
named plastic-button, which behaves like a normal button but gets fancy
animation effects added whenever you click on it. We start by defining
a class, just like before, although this time we extend
[30788]HTMLButtonElement instead of [30789]HTMLElement:
class PlasticButton extends HTMLButtonElement {
constructor() {
super();
When defining our custom element, we have to also specify the
[30790]extends option:
customElements.define("plastic-button", PlasticButton, { extends: "button" });
In general, the name of the element being extended cannot be determined
simply by looking at what element interface it extends, as many
elements share the same interface (such as [30791]q and
[30792]blockquote both sharing [30793]HTMLQuoteElement).
To construct our [30794]customized built-in element from parsed HTML
source text, we use the [30795]is attribute on a [30796]button element:
Trying to use a [30797]customized built-in element as an
[30798]autonomous custom element will not work; that is,
Click me? will simply create an
[30799]HTMLElement with no special behavior.
If you need to create a customized built-in element programmatically,
you can use the following form of [30800]createElement():
const plasticButton = document.createElement("button", { is: "plastic-button" })
;
plasticButton.textContent = "Click me!";
And as before, the constructor will also work:
const plasticButton2 = new PlasticButton();
console.log(plasticButton2.localName); // will output "button"
console.assert(plasticButton2 instanceof PlasticButton);
console.assert(plasticButton2 instanceof HTMLButtonElement);
Note that when creating a customized built-in element programmatically,
the [30801]is attribute will not be present in the DOM, since it was
not explicitly set. However, [30802]it will be added to the output when
serializing:
console.assert(!plasticButton.hasAttribute("is"));
console.log(plasticButton.outerHTML); // will output ʼʼ
Regardless of how it is created, all of the ways in which [30803]button
is special apply to such "plastic buttons" as well: their focus
behavior, ability to participate in [30804]form submission, the
[30805]disabled attribute, and so on.
[30806]Customized built-in elements are designed to allow extension of
existing HTML elements that have useful user-agent supplied behavior or
APIs. As such, they can only extend existing HTML elements defined in
this specification, and cannot extend legacy elements such as
[30807]bgsound, [30808]blink, [30809]isindex, [30810]keygen,
[30811]multicol, [30812]nextid, or [30813]spacer that have been defined
to use [30814]HTMLUnknownElement as their [30815]element interface.
One reason for this requirement is future-compatibility: if a
[30816]customized built-in element was defined that extended a
currently-unknown element, for example combobox, this would prevent
this specification from defining a combobox element in the future, as
consumers of the derived [30817]customized built-in element would have
come to depend on their base element having no interesting
user-agent-supplied behavior.
4.13.1.5 Drawbacks of autonomous custom elements
This section is non-normative.
As specified below, and alluded to above, simply defining and using an
element called taco-button does not mean that such elements
[30818]represent buttons. That is, tools such as web browsers, search
engines, or accessibility technology will not automatically treat the
resulting element as a button just based on its defined name.
To convey the desired button semantics to a variety of users, while
still using an [30819]autonomous custom element, a number of techniques
would need to be employed:
* The addition of the [30820]tabindex attribute would make the
taco-button [30821]focusable. Note that if the taco-button were to
become logically disabled, the [30822]tabindex attribute would need
to be removed.
* The addition of an ARIA role and various ARIA states and properties
helps convey semantics to accessibility technology. For example,
setting the [30823]role to "[30824]button" will convey the
semantics that this is a button, enabling users to successfully
interact with the control using usual button-like interactions in
their accessibility technology. Setting the [30825]aria-label
property is necessary to give the button an [30826]accessible name,
instead of having accessibility technology traverse its child text
nodes and announce them. And setting the [30827]aria-disabled state
to "true" when the button is logically disabled conveys to
accessibility technology the button's disabled state.
* The addition of event handlers to handle commonly-expected button
behaviors helps convey the semantics of the button to web browser
users. In this case, the most relevant event handler would be one
that proxies appropriate [30828]keydown events to become
[30829]click events, so that you can activate the button both with
keyboard and by clicking.
* In addition to any default visual styling provided for taco-button
elements, the visual styling will also need to be updated to
reflect changes in logical state, such as becoming disabled; that
is, whatever style sheet has rules for taco-button will also need
to have rules for taco-button[disabled].
With these points in mind, a full-featured taco-button that took on the
responsibility of conveying button semantics (including the ability to
be disabled) might look something like this:
class TacoButton extends HTMLElement {
static observedAttributes = ["disabled"];
get disabled() {
return this.hasAttribute("disabled");
}
set disabled(flag) {
this.toggleAttribute("disabled", Boolean(flag));
}
attributeChangedCallback(name, oldValue, newValue) {
// name will always be "disabled" due to observedAttributes
if (this.disabled) {
this.removeAttribute("tabindex");
this._internals.ariaDisabled = "true";
} else {
this.setAttribute("tabindex", "0");
this._internals.ariaDisabled = "false";
}
}
}
Even with this rather-complicated element definition, the element is
not a pleasure to use for consumers: it will be continually "sprouting"
[30830]tabindex attributes of its own volition, and its choice of
tabindex="0" focusability behavior may not match the [30831]button
behavior on the current platform. This is because as of now there is no
way to specify default focus behavior for custom elements, forcing the
use of the [30832]tabindex attribute to do so (even though it is
usually reserved for allowing the consumer to override default
behavior).
In contrast, a simple [30833]customized built-in element, as shown in
the previous section, would automatically inherit the semantics and
behavior of the [30834]button element, with no need to implement these
behaviors manually. In general, for any elements with nontrivial
behavior and semantics that build on top of existing elements of HTML,
[30835]customized built-in elements will be easier to develop,
maintain, and consume.
4.13.1.6 Upgrading elements after their creation
This section is non-normative.
Because [30836]element definition can occur at any time, a non-custom
element could be [30837]created, and then later become a [30838]custom
element after an appropriate [30839]definition is registered. We call
this process "upgrading" the element, from a normal element into a
custom element.
[30840]Upgrades enable scenarios where it may be preferable for
[30841]custom element definitions to be registered after relevant
elements have been initially created, such as by the parser. They allow
progressive enhancement of the content in the custom element. For
example, in the following HTML document the element definition for
img-viewer is loaded asynchronously:
Image viewer example
The definition for the img-viewer element here is loaded using a
[30842]script element marked with the [30843]async attribute, placed
after the tag in the markup. While the script is loading,
the img-viewer element will be treated as an undefined element, similar
to a [30844]span. Once the script loads, it will define the img-viewer
element, and the existing img-viewer element on the page will be
upgraded, applying the custom element's definition (which presumably
includes applying an image filter identified by the string "Kelvin",
enhancing the image's visual appearance).
__________________________________________________________________
Note that [30845]upgrades only apply to elements in the document tree.
(Formally, elements that are [30846]connected.) An element that is not
inserted into a document will stay un-upgraded. An example illustrates
this point:
Upgrade edge-cases example
4.13.1.7 Exposing custom element states
Built-in elements provided by user agents have certain states that can
change over time depending on user interaction and other factors, and
are exposed to web authors through [30847]pseudo-classes. For example,
some form controls have the "invalid" state, which is exposed through
the [30848]:invalid [30849]pseudo-class.
Like built-in elements, [30850]custom elements can have various states
to be in too, and [30851]custom element authors want to expose these
states in a similar fashion as the built-in elements.
This is done via the [30852]:state() pseudo-class. A custom element
author can use the [30853]states property of [30854]ElementInternals to
add and remove such custom states, which are then exposed as arguments
to the [30855]:state() pseudo-class.
The following shows how [30856]:state() can be used to style a custom
checkbox element. Assume that LabeledCheckbox doesn't expose its
"checked" state via a content attribute.
You need to check this
Custom pseudo-classes can even target shadow parts. An extension of the
above example shows this:
Continue?
4.13.2 Requirements for custom element constructors and reactions
When authoring [30857]custom element constructors, authors are bound by
the following conformance requirements:
* A parameter-less call to super() must be the first statement in the
constructor body, to establish the correct prototype chain and this
value before any further code is run.
* A return statement must not appear anywhere inside the constructor
body, unless it is a simple early-return (return or return this).
* The constructor must not use the [30858]document.write() or
[30859]document.open() methods.
* The element's attributes and children must not be inspected, as in
the non-[30860]upgrade case none will be present, and relying on
upgrades makes the element less usable.
* The element must not gain any attributes or children, as this
violates the expectations of consumers who use the
[30861]createElement or [30862]createElementNS methods.
* In general, work should be deferred to connectedCallback as much as
possible—especially work involving fetching resources or rendering.
However, note that connectedCallback can be called more than once,
so any initialization work that is truly one-time will need a guard
to prevent it from running twice.
* In general, the constructor should be used to set up initial state
and default values, and to set up event listeners and possibly a
[30863]shadow root.
Several of these requirements are checked during [30864]element
creation, either directly or indirectly, and failing to follow them
will result in a custom element that cannot be instantiated by the
parser or DOM APIs. This is true even if the work is done inside a
constructor-initiated [30865]microtask, as a [30866]microtask
checkpoint can occur immediately after construction.
When authoring [30867]custom element reactions, authors should avoid
manipulating the node tree as this can lead to unexpected results.
An element's connectedCallback can be queued before the element is
disconnected, but as the callback queue is still processed, it results
in a connectedCallback for an element that is no longer connected:
class CParent extends HTMLElement {
connectedCallback() {
this.firstChild.remove();
}
}
customElements.define("c-parent", CParent);
4.13.2.1 Preserving custom element state when moved
This section is non-normative.
When manipulating the DOM tree, an element can be [30868]moved in the
tree while connected. This applies to custom elements as well. By
default, the "disconnectedCallback" and "connectedCallback" would be
called on the element, one after the other. This is done to maintain
compatibility with existing custom elements that predate the
[30869]moveBefore() method. This means that by default, custom elements
reset their state as if they were removed and re-inserted. In the
example [30870]above, the impact would be that the observer would be
disconnected and re-connected, and the tab index would be reset.
To opt in to a state-preserving behavior while [30871]moving, the
author can implement a "connectedMoveCallback". The existence of this
callback, even if empty, would supercede the default behavior of
calling "disconnectedCallback" and "connectedCallback".
"connectedMoveCallback" can also be an appropriate place to execute
logic that depends on the element's ancestors. For example:
class TacoButton extends HTMLElement {
static observedAttributes = ["disabled"];
// Implementing this function would avoid resetting the tab index or re-regist
ering the
// mutation observer when this element is moved inside the DOM without being d
isconnected.
connectedMoveCallback() {
// The parent can change during a state-preserving move.
this._notifyMain();
}
}
4.13.3 Core concepts
A custom element is an element that is [30872]custom. Informally, this
means that its constructor and prototype are defined by the author,
instead of by the user agent. This author-supplied constructor function
is called the custom element constructor.
Two distinct types of [30873]custom elements can be defined:
1. An autonomous custom element, which is defined with no
[30875]extends option. These types of custom elements have a local
name equal to their [30876]defined name.
2. A customized built-in element, which is defined with an
[30877]extends option. These types of custom elements have a local
name equal to the value passed in their [30878]extends option, and
their [30879]defined name is used as the value of the is attribute,
which therefore must be a [30880]valid custom element name.
After a [30881]custom element is [30882]created, changing the value of
the [30883]is attribute does not change the element's behavior, as it
is saved on the element as its [30884]is value.
[30885]Autonomous custom elements have the following element
definition:
[30886]Categories:
[30887]Flow content.
[30888]Phrasing content.
[30889]Palpable content.
For [30890]form-associated custom elements: [30891]Listed,
[30892]labelable, [30893]submittable, and [30894]resettable
[30895]form-associated element.
[30896]Contexts in which this element can be used:
Where [30897]phrasing content is expected.
[30898]Content model:
[30899]Transparent.
[30900]Content attributes:
[30901]Global attributes, except the [30902]is attribute
[30903]form, for [30904]form-associated custom elements —
Associates the element with a [30905]form element
[30906]disabled, for [30907]form-associated custom elements —
Whether the form control is disabled
[30908]readonly, for [30909]form-associated custom elements —
Affects [30910]willValidate, plus any behavior added by the
custom element author
[30911]name, for [30912]form-associated custom elements — Name
of the element to use for [30913]form submission and in the
[30914]form.elements API
Any other attribute that has no namespace (see prose).
[30921]DOM interface:
Supplied by the element's author (inherits from
[30922]HTMLElement)
An [30923]autonomous custom element does not have any special meaning:
it [30924]represents its children. A [30925]customized built-in element
inherits the semantics of the element that it extends.
Any namespace-less attribute that is relevant to the element's
functioning, as determined by the element's author, may be specified on
an [30926]autonomous custom element, so long as the attribute name is
[30927]XML-compatible and contains no [30928]ASCII upper alphas. The
exception is the [30929]is attribute, which must not be specified on an
[30930]autonomous custom element (and which will have no effect if it
is).
[30931]Customized built-in elements follow the normal requirements for
attributes, based on the elements they extend. To add custom
attribute-based behavior, use [30932]data-* attributes.
__________________________________________________________________
An [30933]autonomous custom element is called a form-associated custom
element if the element is associated with a [30934]custom element
definition whose [30935]form-associated field is set to true.
The [30936]name attribute represents the [30937]form-associated custom
element's name. The [30938]disabled attribute is used to make the
[30939]form-associated custom element non-interactive and to prevent
its [30940]submission value from being submitted. The [30941]form
attribute is used to explicitly associate the [30942]form-associated
custom element with its [30943]form owner.
The readonly attribute of [30944]form-associated custom elements
specifies that the element is [30945]barred from constraint validation.
User agents don't provide any other behavior for the attribute, but
custom element authors should, where possible, use its presence to make
their control non-editable in some appropriate fashion, similar to the
behavior for the [30946]readonly attribute on built-in form controls.
Constraint validation: If the [30947]readonly attribute is specified on
a [30948]form-associated custom element, the element is [30949]barred
from constraint validation.
The [30950]reset algorithm for [30951]form-associated custom elements
is to [30952]enqueue a custom element callback reaction with the
element, callback name "formResetCallback", and « ».
__________________________________________________________________
A valid custom element name is a sequence of characters name that meets
all of the following requirements:
* name must match the [30953]PotentialCustomElementName production:
This uses the [30956]EBNF notation from the XML specification.
[30957][XML]
* name must not be any of the following:
+ annotation-xml
+ color-profile
+ font-face
+ font-face-src
+ font-face-uri
+ font-face-format
+ font-face-name
+ missing-glyph
The list of names above is the summary of all hyphen-containing
element names from the [30958]applicable specifications, namely SVG
2 and MathML. [30959][SVG] [30960][MATHML]
These requirements ensure a number of goals for [30961]valid custom
element names:
* They start with an [30962]ASCII lower alpha, ensuring that the HTML
parser will treat them as tags instead of as text.
* They do not contain any [30963]ASCII upper alphas, ensuring that
the user agent can always treat HTML elements
ASCII-case-insensitively.
* They contain a hyphen, used for namespacing and to ensure forward
compatibility (since no elements will be added to HTML, SVG, or
MathML with hyphen-containing local names in the future).
* They can always be created with [30964]createElement() and
[30965]createElementNS(), which have restrictions that go beyond
the parser's.
Apart from these restrictions, a large variety of names is allowed, to
give maximum flexibility for use cases like or .
A custom element definition describes a [30966]custom element and
consists of:
A name
A [30967]valid custom element name
A local name
A local name
A constructor
A Web IDL [30968]CustomElementConstructor callback function type
value wrapping the [30969]custom element constructor
A list of observed attributes
A sequence
A collection of lifecycle callbacks
A map, whose keys are the strings "connectedCallback",
"disconnectedCallback", "adoptedCallback",
"connectedMoveCallback", "attributeChangedCallback",
"formAssociatedCallback", "formDisabledCallback",
"formResetCallback", and "formStateRestoreCallback". The
corresponding values are either a Web IDL [30970]Function
callback function type value, or null. By default the value of
each entry is null.
A construction stack
A list, initially empty, that is manipulated by the
[30971]upgrade an element algorithm and the [30972]HTML element
constructors. Each entry in the list will be either an element
or an already constructed marker.
A form-associated boolean
If this is true, user agent treats elements associated to this
[30973]custom element definition as [30974]form-associated
custom elements.
A disable internals boolean
Controls [30975]attachInternals().
A disable shadow boolean
Controls [30976]attachShadow().
To look up a custom element definition, given null or a
[30977]CustomElementRegistry object registry, string-or-null namespace,
string localName, and string-or-null is, perform the following steps.
They will return either a [30978]custom element definition or null:
1. If registry is null, then return null.
2. If namespace is not the [30979]HTML namespace, then return null.
3. If registry's [30980]custom element definition set [30981]contains
an item with [30982]name and [30983]local name both equal to
localName, then return that item.
4. If registry's [30984]custom element definition set [30985]contains
an item with [30986]name equal to is and [30987]local name equal to
localName, then return that item.
5. Return null.
4.13.4 The [30988]CustomElementRegistry interface
(BUTTON) ✔MDN
[30989]CustomElementRegistry
Support in all current engines.
Firefox63+Safari10.1+Chrome54+
__________________________________________________________________
Each [30990]similar-origin window agent has an associated active custom
element constructor map, which is a [30991]map of constructors to
[30992]CustomElementRegistry objects.
(BUTTON) ✔MDN
[30993]Window/customElements
Support in all current engines.
Firefox63+Safari10.1+Chrome54+
__________________________________________________________________
The [30994]Window customElements getter steps are:
1. [30995]Assert: [30996]this's [30997]associated Document's
[30998]custom element registry is a [30999]CustomElementRegistry
object.
A [31000]Window's [31001]associated Document is always created with
a new [31002]CustomElementRegistry object.
2. Return [31003]this's [31004]associated Document's [31005]custom
element registry.
Every [31023]CustomElementRegistry has an is scoped, a boolean,
initially false.
Every [31024]CustomElementRegistry has a scoped document set, a
[31025]set of [31026]Document objects, initially « ».
Every [31027]CustomElementRegistry has a custom element definition set,
a [31028]set of [31029]custom element definitions, initially « ».
Lookup of items in this [31030]set uses their [31031]name, [31032]local
name, or [31033]constructor.
Every [31034]CustomElementRegistry also has an element definition is
running boolean which is used to prevent reentrant invocations of
[31035]element definition. It is initially false.
Every [31036]CustomElementRegistry also has a when-defined promise map,
a [31037]map of [31038]valid custom element names to promises. It is
used to implement the [31039]whenDefined() method.
To look up a custom element registry, given a [31040]Node object node:
1. If node is an [31041]Element object, then return node's
[31042]custom element registry.
2. If node is a [31043]ShadowRoot object, then return node's
[31044]custom element registry.
3. If node is a [31045]Document object, then return node's
[31046]custom element registry.
4. Return null.
registry = window.[31047]customElements
Returns the global's associated [31048]Document's
[31049]CustomElementRegistry object.
registry = new [31050]CustomElementRegistry()
Constructs a new [31051]CustomElementRegistry object, for scoped
usage.
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
Defines a new [31054]custom element, mapping the given name to
the given constructor as an [31055]autonomous custom element.
registry.[31056]define(name, constructor, { extends: baseLocalName })
Defines a new [31057]custom element, mapping the given name to
the given constructor as a [31058]customized built-in element
for the [31059]element type identified by the supplied
baseLocalName. A [31060]"NotSupportedError" [31061]DOMException
will be thrown upon trying to extend a [31062]custom element or
an unknown element, or when registry is not a global
[31063]CustomElementRegistry object.
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
Retrieves the [31066]custom element constructor defined for the
given [31067]name. Returns undefined if there is no
[31068]custom element definition with the given [31069]name.
registry.[31070]getName(constructor)
Retrieves the given name for a [31071]custom element defined for
the given [31072]constructor. Returns null if there is no
[31073]custom element definition with the given
[31074]constructor.
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
Returns a promise that will be fulfilled with the [31077]custom
element's constructor when a [31078]custom element becomes
defined with the given name. (If such a [31079]custom element is
already defined, the returned promise will be immediately
fulfilled.) Returns a promise rejected with a
[31080]"SyntaxError" [31081]DOMException if not given a
[31082]valid custom element name.
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
[31085]Tries to upgrade all [31086]shadow-including inclusive
descendant elements of root, even if they are not
[31087]connected.
registry.[31088]initialize(root)
Each [31089]inclusive descendant of root with a null registry
will have it updated to this [31090]CustomElementRegistry
object.
The new CustomElementRegistry() constructor steps are to set
[31091]this's [31092]is scoped to true.
Element definition is a process of adding a [31093]custom element
definition to the [31094]CustomElementRegistry. This is accomplished by
the [31095]define() method. The define(name, constructor, options)
method steps are:
1. If [31096]IsConstructor(constructor) is false, then throw a
[31097]TypeError.
2. If name is not a [31098]valid custom element name, then throw a
[31099]"SyntaxError" [31100]DOMException.
3. If [31101]this's [31102]custom element definition set
[31103]contains an item with [31104]name name, then throw a
[31105]"NotSupportedError" [31106]DOMException.
4. If [31107]this's [31108]custom element definition set
[31109]contains an item with [31110]constructor constructor, then
throw a [31111]"NotSupportedError" [31112]DOMException.
5. Let localName be name.
6. Let extends be options["[31113]extends"] if it [31114]exists;
otherwise null.
7. If extends is not null:
1. If [31115]this's [31116]is scoped is true, then throw a
[31117]"NotSupportedError" [31118]DOMException.
2. If extends is a [31119]valid custom element name, then throw a
[31120]"NotSupportedError" [31121]DOMException.
3. If the [31122]element interface for extends and the
[31123]HTML namespace is [31124]HTMLUnknownElement (e.g., if
extends does not indicate an element definition in this
specification), then throw a [31125]"NotSupportedError"
[31126]DOMException.
4. Set localName to extends.
8. If [31127]this's [31128]element definition is running is true, then
throw a [31129]"NotSupportedError" [31130]DOMException.
9. Set [31131]this's [31132]element definition is running to true.
10. Let formAssociated be false.
11. Let disableInternals be false.
12. Let disableShadow be false.
13. Let observedAttributes be an empty sequence.
14. Run the following steps while catching any exceptions:
1. Let prototype be ? [31133]Get(constructor, "prototype").
2. If prototype [31134]is not an Object, then throw a
[31135]TypeError exception.
3. Let lifecycleCallbacks be the [31136]ordered map «[
"connectedCallback" → null, "disconnectedCallback" → null,
"adoptedCallback" → null, "connectedMoveCallback" → null,
"attributeChangedCallback" → null ]».
4. For each callbackName of [31137]the keys of
lifecycleCallbacks:
1. Let callbackValue be ? [31138]Get(prototype,
callbackName).
2. If callbackValue is not undefined, then [31139]set
lifecycleCallbacks[callbackName] to the result of
[31140]converting callbackValue to the Web IDL
[31141]Function callback type.
5. If lifecycleCallbacks["attributeChangedCallback"] is not null:
1. Let observedAttributesIterable be ?
[31142]Get(constructor, "observedAttributes").
2. If observedAttributesIterable is not undefined, then set
observedAttributes to the result of [31143]converting
observedAttributesIterable to a sequence.
Rethrow any exceptions from the conversion.
6. Let disabledFeatures be an empty sequence.
7. Let disabledFeaturesIterable be ? [31144]Get(constructor,
"disabledFeatures").
8. If disabledFeaturesIterable is not undefined, then set
disabledFeatures to the result of [31145]converting
disabledFeaturesIterable to a sequence. Rethrow any
exceptions from the conversion.
9. If disabledFeatures [31146]contains "internals", then set
disableInternals to true.
10. If disabledFeatures [31147]contains "shadow", then set
disableShadow to true.
11. Let formAssociatedValue be ? [31148]Get( constructor,
"formAssociated").
12. Set formAssociated to the result of [31149]converting
formAssociatedValue to a boolean.
13. If formAssociated is true, then for each callbackName of «
"formAssociatedCallback", "formResetCallback",
"formDisabledCallback", "formStateRestoreCallback" »:
1. Let callbackValue be ? [31150]Get(prototype,
callbackName).
2. If callbackValue is not undefined, then [31151]set
lifecycleCallbacks[callbackName] to the result of
[31152]converting callbackValue to the Web IDL
[31153]Function callback type.
Then, regardless of whether the above steps threw an exception or
not: set [31154]this's [31155]element definition is running to
false.
Finally, if the steps threw an exception, rethrow that exception.
15. Let definition be a new [31156]custom element definition with
[31157]name name, [31158]local name localName, [31159]constructor
constructor, [31160]observed attributes observedAttributes,
[31161]lifecycle callbacks lifecycleCallbacks,
[31162]form-associated formAssociated, [31163]disable internals
disableInternals, and [31164]disable shadow disableShadow.
16. [31165]Append definition to [31166]this's [31167]custom element
definition set.
17. If [31168]this's [31169]is scoped is true, then for each document
of [31170]this's [31171]scoped document set: [31172]upgrade
particular elements within a document given document, definition,
and localName.
18. Otherwise, [31173]upgrade particular elements within a document
given [31174]this's [31175]relevant global object's
[31176]associated Document, definition, localName, and name.
19. If [31177]this's [31178]when-defined promise map[name]
[31179]exists:
1. Resolve [31180]this's [31181]when-defined promise map[name]
with constructor.
2. [31182]Remove [31183]this's [31184]when-defined promise
map[name].
To upgrade particular elements within a document given a
[31185]Document object document, a [31186]custom element definition
definition, a string localName, and optionally a string name (default
localName):
1. Let upgradeCandidates be all elements that are
[31187]shadow-including descendants of document, whose namespace is
the [31188]HTML namespace and whose local name is localName, in
[31189]shadow-including tree order. Additionally, if name is not
localName, only include elements whose [31190]is value is equal to
name.
2. For each element element of upgradeCandidates: [31191]enqueue a
custom element upgrade reaction given element and definition.
The get(name) method steps are:
1. If [31192]this's [31193]custom element definition set
[31194]contains an item with [31195]name name, then return that
item's [31196]constructor.
2. Return undefined.
The getName(constructor) method steps are:
1. If [31198]this's [31199]custom element definition set
[31200]contains an item with [31201]constructor constructor, then
return that item's [31202]name.
2. Return null.
The whenDefined(name) method steps are:
1. If name is not a [31203]valid custom element name, then return
[31204]a promise rejected with a [31205]"SyntaxError"
[31206]DOMException.
2. If [31207]this's [31208]custom element definition set
[31209]contains an item with [31210]name name, then return [31211]a
promise resolved with that item's [31212]constructor.
3. If [31213]this's [31214]when-defined promise map[name] does not
[31215]exist, then [31216]set [31217]this's [31218]when-defined
promise map[name] to a new promise.
4. Return [31219]this's [31220]when-defined promise map[name].
The [31221]whenDefined() method can be used to avoid performing an
action until all appropriate [31222]custom elements are [31223]defined.
In this example, we combine it with the [31224]:defined pseudo-class to
hide a dynamically-loaded article's contents until we're sure that all
of the [31225]autonomous custom elements it uses are defined.
articleContainer.hidden = true;
The upgrade(root) method steps are:
1. Let candidates be a [31226]list of all of root's
[31227]shadow-including inclusive descendant elements, in
[31228]shadow-including tree order.
2. [31229]For each candidate of candidates, [31230]try to upgrade
candidate.
The [31231]upgrade() method allows upgrading of elements at will.
Normally elements are automatically upgraded when they become
[31232]connected, but this method can be used if you need to upgrade
before you're ready to connect the element.
const el = document.createElement("spider-man");
class SpiderMan extends HTMLElement {}
customElements.define("spider-man", SpiderMan);
console.assert(!(el instanceof SpiderMan)); // not yet upgraded
The initialize(root) method steps are:
1. If root is a [31233]Document node whose [31234]custom element
registry is null, then set root's [31235]custom element registry to
[31236]this.
2. Otherwise, if root is a [31237]ShadowRoot node whose [31238]custom
element registry is null, then set root's [31239]custom element
registry to [31240]this.
3. For each [31241]inclusive descendant inclusiveDescendant of root:
if inclusiveDescendant is an [31242]Element node whose
[31243]custom element registry is null:
1. Set inclusiveDescendant's [31244]custom element registry to
[31245]this.
2. If [31246]this's [31247]is scoped is true, then [31248]append
inclusiveDescendant's [31249]node document to [31250]this's
[31251]scoped document set.
Once the custom element registry of a node is initialized to a
[31252]CustomElementRegistry object, it intentionally cannot be changed
any further. This simplifies reasoning about code and allows
implementations to optimize.
4.13.5 Upgrades
To upgrade an element, given as input a [31253]custom element
definition definition and an element element, run the following steps:
1. If element's [31254]custom element state is not "undefined" or
"uncustomized", then return.
One scenario where this can occur due to reentrant invocation of
this algorithm, as in the following example:
This step will thus bail out the algorithm early when
[31255]upgrade an element is invoked with "b" a second time.
2. Set element's [31256]custom element definition to definition.
3. Set element's [31257]custom element state to "failed".
It will be set to "custom" [31258]after the upgrade succeeds. For
now, we set it to "failed" so that any reentrant invocations will
hit [31259]the above early-exit step.
4. For each attribute in element's [31260]attribute list, in order,
[31261]enqueue a custom element callback reaction with element,
callback name "attributeChangedCallback", and « attribute's local
name, null, attribute's value, attribute's namespace ».
5. If element is [31262]connected, then [31263]enqueue a custom
element callback reaction with element, callback name
"connectedCallback", and « ».
6. Add element to the end of definition's [31264]construction stack.
7. Let C be definition's [31265]constructor.
8. [31266]Set the [31267]surrounding agent's [31268]active custom
element constructor map[C] to element's [31269]custom element
registry.
9. Run the following steps while catching any exceptions:
1. If definition's [31270]disable shadow is true and element's
[31271]shadow root is non-null, then throw a
[31272]"NotSupportedError" [31273]DOMException.
This is needed as [31274]attachShadow() does not use
[31275]look up a custom element definition while
[31276]attachInternals() does.
2. Set element's [31277]custom element state to "precustomized".
3. Let constructResult be the result of [31278]constructing C,
with no arguments.
If C [31279]non-conformantly uses an API decorated with the
[31280][CEReactions] extended attribute, then the reactions
enqueued at the beginning of this algorithm will execute
during this step, before C finishes and control returns to
this algorithm. Otherwise, they will execute after C and the
rest of the upgrade process finishes.
4. If [31281]SameValue(constructResult, element) is false, then
throw a [31282]TypeError.
This can occur if C constructs another instance of the same
custom element before calling super(), or if C uses
JavaScript's return-override feature to return an arbitrary
[31283]HTMLElement object from the constructor.
Then, perform the following steps, regardless of whether the above
steps threw an exception or not:
1. [31284]Remove the [31285]surrounding agent's [31286]active
custom element constructor map[C].
This is a no-op if C immediately calls super() as it ought to
do.
2. Remove the last entry from the end of definition's
[31287]construction stack.
Assuming C calls super() (as it will if it is
[31288]conformant), and that the call succeeds, this will be
the [31289]already constructed marker that replaced the
element we pushed at the beginning of this algorithm. (The
[31290]HTML element constructor carries out this replacement.)
If C does not call super() (i.e. it is not [31291]conformant),
or if any step in the [31292]HTML element constructor throws,
then this entry will still be element.
Finally, if the above steps threw an exception, then:
1. Set element's [31293]custom element definition to null.
2. Empty element's [31294]custom element reaction queue.
3. Rethrow the exception (thus terminating this algorithm).
If the above steps threw an exception, then element's [31295]custom
element state will remain "failed" or "precustomized".
10. If element is a [31296]form-associated custom element, then:
1. [31297]Reset the form owner of element. If element is
associated with a [31298]form element, then [31299]enqueue a
custom element callback reaction with element, callback name
"formAssociatedCallback", and « the associated [31300]form ».
2. If element is [31301]disabled, then [31302]enqueue a custom
element callback reaction with element, callback name
"formDisabledCallback", and « true ».
11. Set element's [31303]custom element state to "custom".
To try to upgrade an element given an element element:
1. Let definition be the result of [31304]looking up a custom element
definition given element's [31305]custom element registry,
element's [31306]namespace, element's [31307]local name, and
element's [31308]is value.
2. If definition is not null, then [31309]enqueue a custom element
upgrade reaction given element and definition.
4.13.6 Custom element reactions
A [31310]custom element possesses the ability to respond to certain
occurrences by running author code:
* When [31311]upgraded, its [31312]constructor is run, with no
arguments.
* When it [31313]becomes connected, its connectedCallback is called,
with no arguments.
* When it [31314]becomes disconnected, its disconnectedCallback is
called, with no arguments.
* When it is [31315]moved, its connectedMoveCallback is called, with
no arguments.
* When it is [31316]adopted into a new document, its adoptedCallback
is called, given the old document and new document as arguments.
* When any of its attributes are [31317]changed, [31318]appended,
[31319]removed, or [31320]replaced, its attributeChangedCallback is
called, given the attribute's local name, old value, new value, and
namespace as arguments. (An attribute's old or new value is
considered to be null when the attribute is added or removed,
respectively.)
* When the user agent [31321]resets the form owner of a
[31322]form-associated custom element and doing so changes the form
owner, its formAssociatedCallback is called, given the new form
owner (or null if no owner) as an argument.
* When the form owner of a [31323]form-associated custom element is
[31324]reset, its formResetCallback is called.
* When the [31325]disabled state of a [31326]form-associated custom
element is changed, its formDisabledCallback is called, given the
new state as an argument.
* When user agent updates a [31327]form-associated custom element's
value on behalf of a user or [31328]as part of navigation, its
formStateRestoreCallback is called, given the new state and a
string indicating a reason, "autocomplete" or "restore", as
arguments.
We call these reactions collectively custom element reactions.
The way in which [31329]custom element reactions are invoked is done
with special care, to avoid running author code during the middle of
delicate operations. Effectively, they are delayed until "just before
returning to user script". This means that for most purposes they
appear to execute synchronously, but in the case of complicated
composite operations (like [31330]cloning, or [31331]range
manipulation), they will instead be delayed until after all the
relevant user agent processing steps have completed, and then run
together as a batch.
Additionally, the precise ordering of these reactions is managed via a
somewhat-complicated stack-of-queues system, described below. The
intention behind this system is to guarantee that [31332]custom element
reactions always are invoked in the same order as their triggering
actions, at least within the local context of a single [31333]custom
element. (Because [31334]custom element reaction code can perform its
own mutations, it is not possible to give a global ordering guarantee
across multiple elements.)
__________________________________________________________________
Each [31335]similar-origin window agent has a custom element reactions
stack, which is initially empty. A [31336]similar-origin window agent's
current element queue is the [31337]element queue at the top of its
[31338]custom element reactions stack. Each item in the stack is an
element queue, which is initially empty as well. Each item in an
[31339]element queue is an element. (The elements are not necessarily
[31340]custom yet, since this queue is used for [31341]upgrades as
well.)
Each [31342]custom element reactions stack has an associated backup
element queue, which is an initially-empty [31343]element queue.
Elements are pushed onto the [31344]backup element queue during
operations that affect the DOM without going through an API decorated
with [31345][CEReactions], or through the parser's [31346]create an
element for the token algorithm. An example of this is a user-initiated
editing operation which modifies the descendants or attributes of an
[31347]editable element. To prevent reentrancy when processing the
[31348]backup element queue, each [31349]custom element reactions stack
also has a processing the backup element queue flag, initially unset.
All elements have an associated custom element reaction queue,
initially empty. Each item in the [31350]custom element reaction queue
is of one of two types:
* An upgrade reaction, which will [31351]upgrade the custom element
and contains a [31352]custom element definition; or
* A callback reaction, which will call a lifecycle callback, and
contains a callback function as well as a list of arguments.
This is all summarized in the following schematic diagram:
A custom element reactions stack consists of a stack of element queues.
Zooming in on a particular queue, we see that it contains a number of
elements (in our example, , then , then ). Any
particular element in the queue then has a custom element reaction
queue. Zooming in on the custom element reaction queue, we see that it
contains a variety of queued-up reactions (in our example, upgrade,
then attribute changed, then another attribute changed, then
connected).
To enqueue an element on the appropriate element queue, given an
element element, run the following steps:
1. Let reactionsStack be element's [31353]relevant agent's
[31354]custom element reactions stack.
2. If reactionsStack is empty, then:
1. Add element to reactionsStack's [31355]backup element queue.
2. If reactionsStack's [31356]processing the backup element queue
flag is set, then return.
3. Set reactionsStack's [31357]processing the backup element
queue flag.
4. [31358]Queue a microtask to perform the following steps:
1. [31359]Invoke custom element reactions in
reactionsStack's [31360]backup element queue.
2. Unset reactionsStack's [31361]processing the backup
element queue flag.
3. Otherwise, add element to element's [31362]relevant agent's
[31363]current element queue.
To enqueue a custom element callback reaction, given a [31364]custom
element element, a callback name callbackName, and a list of arguments
args, run the following steps:
1. Let definition be element's [31365]custom element definition.
2. Let callback be the value of the entry in definition's
[31366]lifecycle callbacks with key callbackName.
3. If callbackName is "connectedMoveCallback" and callback is null:
1. Let disconnectedCallback be the value of the entry in
definition's [31367]lifecycle callbacks with key
"disconnectedCallback".
2. Let connectedCallback be the value of the entry in
definition's [31368]lifecycle callbacks with key
"connectedCallback".
3. If connectedCallback and disconnectedCallback are null, then
return.
4. Set callback to the following steps:
1. If disconnectedCallback is not null, then call
disconnectedCallback with no arguments.
2. If connectedCallback is not null, then call
connectedCallback with no arguments.
4. If callback is null, then return.
5. If callbackName is "attributeChangedCallback":
1. Let attributeName be the first element of args.
2. If definition's [31369]observed attributes does not contain
attributeName, then return.
6. Add a new [31370]callback reaction to element's [31371]custom
element reaction queue, with callback function callback and
arguments args.
7. [31372]Enqueue an element on the appropriate element queue given
element.
To enqueue a custom element upgrade reaction, given an element element
and [31373]custom element definition definition, run the following
steps:
1. Add a new [31374]upgrade reaction to element's [31375]custom
element reaction queue, with [31376]custom element definition
definition.
2. [31377]Enqueue an element on the appropriate element queue given
element.
To invoke custom element reactions in an [31378]element queue queue,
run the following steps:
1. While queue is not [31379]empty:
1. Let element be the result of [31380]dequeuing from queue.
2. Let reactions be element's [31381]custom element reaction
queue.
3. Repeat until reactions is empty:
1. Remove the first element of reactions, and let reaction
be that element. Switch on reaction's type:
[31382]upgrade reaction
[31383]Upgrade element using reaction's
[31384]custom element definition.
If this throws an exception, catch it, and
[31385]report it for reaction's [31386]custom
element definition's [31387]constructor's
corresponding JavaScript object's
[31388]associated realm's [31389]global
object.
[31390]callback reaction
[31391]Invoke reaction's callback function
with reaction's arguments and "report", and
[31392]callback this value set to element.
__________________________________________________________________
To ensure [31393]custom element reactions are triggered appropriately,
we introduce the [CEReactions] IDL [31394]extended attribute. It
indicates that the relevant algorithm is to be supplemented with
additional steps in order to appropriately track and invoke
[31395]custom element reactions.
The [31396][CEReactions] extended attribute must take no arguments, and
must not appear on anything other than an operation, attribute, setter,
or deleter. Additionally, it must not appear on readonly attributes.
Operations, attributes, setters, or deleters annotated with the
[31397][CEReactions] extended attribute must run the following steps in
place of the ones specified in their description:
1. [31398]Push a new [31399]element queue onto this object's
[31400]relevant agent's [31401]custom element reactions stack.
2. Run the originally-specified steps for this construct, catching any
exceptions. If the steps return a value, let value be the returned
value. If they throw an exception, let exception be the thrown
exception.
3. Let queue be the result of [31402]popping from this object's
[31403]relevant agent's [31404]custom element reactions stack.
4. [31405]Invoke custom element reactions in queue.
5. If an exception exception was thrown by the original steps, rethrow
exception.
6. If a value value was returned from the original steps, return
value.
The intent behind this extended attribute is somewhat subtle. One way
of accomplishing its goals would be to say that every operation,
attribute, setter, and deleter on the platform must have these steps
inserted, and to allow implementers to optimize away unnecessary cases
(where no DOM mutation is possible that could cause [31406]custom
element reactions to occur).
However, in practice this imprecision could lead to non-interoperable
implementations of [31407]custom element reactions, as some
implementations might forget to invoke these steps in some cases.
Instead, we settled on the approach of explicitly annotating all
relevant IDL constructs, as a way of ensuring interoperable behavior
and helping implementations easily pinpoint all cases where these steps
are necessary.
Any nonstandard APIs introduced by the user agent that could modify the
DOM in such a way as to cause [31408]enqueuing a custom element
callback reaction or [31409]enqueuing a custom element upgrade
reaction, for example by modifying any attributes or child elements,
must also be decorated with the [31410][CEReactions] attribute.
As of the time of this writing, the following nonstandard or
not-yet-standardized APIs are known to fall into this category:
* [31411]HTMLInputElement's webkitdirectory and incremental IDL
attributes
* [31412]HTMLLinkElement's scope IDL attribute
4.13.7 Element internals
Certain capabilities are meant to be available to a custom element
author, but not to a custom element consumer. These are provided by the
[31413]element.attachInternals() method, which returns an instance of
[31414]ElementInternals. The properties and methods of
[31415]ElementInternals allow control over internal features which the
user agent provides to all elements.
element.[31416]attachInternals()
Returns an [31417]ElementInternals object targeting the
[31418]custom element element. Throws an exception if element is
not a [31419]custom element, if the "internals" feature was
disabled as part of the element definition, or if it is called
twice on the same element.
Each [31420]HTMLElement has an attached internals (null or an
[31421]ElementInternals object), initially null.
(BUTTON) ✔MDN
[31422]HTMLElement/attachInternals
Support in all current engines.
Firefox93+Safari16.4+Chrome77+
__________________________________________________________________
The attachInternals() method steps are:
1. If [31423]this's [31424]is value is not null, then throw a
[31425]"NotSupportedError" [31426]DOMException.
2. Let definition be the result of [31427]looking up a custom element
definition given [31428]this's [31429]custom element registry,
[31430]this's [31431]namespace, [31432]this's [31433]local name,
and null.
3. If definition is null, then throw an [31434]"NotSupportedError"
[31435]DOMException.
4. If definition's [31436]disable internals is true, then throw a
[31437]"NotSupportedError" [31438]DOMException.
5. If [31439]this's [31440]attached internals is non-null, then throw
an [31441]"NotSupportedError" [31442]DOMException.
6. If [31443]this's [31444]custom element state is not "precustomized"
or "custom", then throw a [31445]"NotSupportedError"
[31446]DOMException.
7. Set [31447]this's [31448]attached internals to a new
[31449]ElementInternals instance whose [31450]target element is
[31451]this.
8. Return [31452]this's [31453]attached internals.
4.13.7.1 The [31454]ElementInternals interface
(BUTTON) ✔MDN
[31455]ElementInternals
Support in all current engines.
Firefox93+Safari16.4+Chrome77+
__________________________________________________________________
The IDL for the [31456]ElementInternals interface is as follows, with
the various operations and attributes defined in the following
sections:
[Exposed=Window]
interface ElementInternals {
// [31457]Shadow root access
readonly attribute [31458]ShadowRoot? [31459]shadowRoot;
// [31460]Form-associated custom elements
undefined [31461]setFormValue(([31462]File or [31463]USVString or [31464]FormD
ata)? value,
optional ([31465]File or [31466]USVString or [31467]For
mData)? state);
Each [31487]ElementInternals has a target element, which is a
[31488]custom element.
4.13.7.2 Shadow root access
internals.[31489]shadowRoot
Returns the [31490]ShadowRoot for internals's [31491]target
element, if the [31492]target element is a [31493]shadow host,
or null otherwise.
(BUTTON) ✔MDN
[31494]ElementInternals/shadowRoot
Support in all current engines.
Firefox93+Safari16.4+Chrome88+
__________________________________________________________________
The shadowRoot getter steps are:
1. Let target be [31495]this's [31496]target element.
2. If target is not a [31497]shadow host, then return null.
3. Let shadow be target's [31498]shadow root.
4. If shadow's [31499]available to element internals is false, then
return null.
5. Return shadow.
4.13.7.3 Form-associated custom elements
internals.[31500]setFormValue(value)
Sets both the [31501]state and [31502]submission value of
internals's [31503]target element to value.
If value is null, the element won't participate in form
submission.
internals.[31504]setFormValue(value, state)
Sets the [31505]submission value of internals's [31506]target
element to value, and its [31507]state to state.
If value is null, the element won't participate in form
submission.
internals.[31508]form
Returns the [31509]form owner of internals's [31510]target
element.
internals.[31511]setValidity(flags, message [, anchor ])
Marks internals's [31512]target element as suffering from the
constraints indicated by the flags argument, and sets the
element's validation message to message. If anchor is specified,
the user agent might use it to indicate problems with the
constraints of internals's [31513]target element when the
[31514]form owner is validated interactively or
[31515]reportValidity() is called.
internals.[31516]setValidity({})
Marks internals's [31517]target element as [31518]satisfying its
constraints.
internals.[31519]willValidate
Returns true if internals's [31520]target element will be
validated when the form is submitted; false otherwise.
internals.[31521]validity
Returns the [31522]ValidityState object for internals's
[31523]target element.
internals.[31524]validationMessage
Returns the error message that would be shown to the user if
internals's [31525]target element was to be checked for
validity.
valid = internals.[31526]checkValidity()
Returns true if internals's [31527]target element has no
validity problems; false otherwise. Fires an [31528]invalid
event at the element in the latter case.
valid = internals.[31529]reportValidity()
Returns true if internals's [31530]target element has no
validity problems; otherwise, returns false, fires an
[31531]invalid event at the element, and (if the event isn't
canceled) reports the problem to the user.
internals.[31532]labels
Returns a [31533]NodeList of all the [31534]label elements that
internals's [31535]target element is associated with.
Each [31536]form-associated custom element has submission value. It is
used to provide one or more [31537]entries on form submission. The
initial value of [31538]submission value is null, and [31539]submission
value can be null, a string, a [31540]File, or a [31541]list of
[31542]entries.
Each [31543]form-associated custom element has state. It is information
with which the user agent can restore a user's input for the element.
The initial value of [31544]state is null, and [31545]state can be
null, a string, a [31546]File, or a [31547]list of [31548]entries.
The [31549]setFormValue() method is used by the custom element author
to set the element's [31550]submission value and [31551]state, thus
communicating these to the user agent.
When the user agent believes it is a good idea to restore a
[31552]form-associated custom element's [31553]state, for example
[31554]after navigation or restarting the user agent, they may
[31555]enqueue a custom element callback reaction with that element,
callback name "formStateRestoreCallback", and « the state to be
restored, "restore" ».
If the user agent has a form-filling assist feature, then when the
feature is invoked, it may [31556]enqueue a custom element callback
reaction with a [31557]form-associated custom element, callback name
"formStateRestoreCallback", and « the state value determined by history
of state value and some heuristics, "autocomplete" ».
In general, the [31558]state is information specified by a user, and
the [31559]submission value is a value after canonicalization or
sanitization, suitable for submission to the server. The following
examples makes this concrete:
Suppose that we have a [31560]form-associated custom element which asks
a user to specify a date. The user specifies "3/15/2019", but the
control wishes to submit "2019-03-15" to the server. "3/15/2019" would
be a [31561]state of the element, and "2019-03-15" would be a
[31562]submission value.
Suppose you develop a custom element emulating a the behavior of the
existing [31563]checkbox [31564]input type. Its [31565]submission value
would be the value of its value content attribute, or the string "on".
Its [31566]state would be one of "checked", "unchecked",
"checked/indeterminate", or "unchecked/indeterminate".
(BUTTON) ✔MDN
[31567]ElementInternals/setFormValue
Support in all current engines.
Firefox98+Safari16.4+Chrome77+
__________________________________________________________________
The setFormValue(value, state) method steps are:
1. Let element be [31568]this's [31569]target element.
2. If element is not a [31570]form-associated custom element, then
throw a [31571]"NotSupportedError" [31572]DOMException.
3. Set [31573]target element's [31574]submission value to value if
value is not a [31575]FormData object, or to a [31576]clone of
value's [31577]entry list otherwise.
4. If the state argument of the function is omitted, set element's
[31578]state to its [31579]submission value.
5. Otherwise, if state is a [31580]FormData object, set element's
[31581]state to a [31582]clone of state's [31583]entry list.
6. Otherwise, set element's [31584]state to state.
__________________________________________________________________
Each [31585]form-associated custom element has validity flags named
valueMissing, typeMismatch, patternMismatch, tooLong, tooShort,
rangeUnderflow, rangeOverflow, stepMismatch, and customError. They are
false initially.
Each [31586]form-associated custom element has a validation message
string. It is the empty string initially.
Each [31587]form-associated custom element has a validation anchor
element. It is null initially.
(BUTTON) ✔MDN
[31588]ElementInternals/setValidity
Support in all current engines.
Firefox98+Safari16.4+Chrome77+
__________________________________________________________________
The setValidity(flags, message, anchor) method steps are:
1. Let element be [31589]this's [31590]target element.
2. If element is not a [31591]form-associated custom element, then
throw a [31592]"NotSupportedError" [31593]DOMException.
3. If flags contains one or more true values and message is not given
or is the empty string, then throw a [31594]TypeError.
4. For each entry flag → value of flags, set element's validity flag
with the name flag to value.
5. Set element's [31595]validation message to the empty string if
message is not given or all of element's validity flags are false,
or to message otherwise.
6. If element's customError validity flag is true, then set element's
[31596]custom validity error message to element's [31597]validation
message. Otherwise, set element's [31598]custom validity error
message to the empty string.
7. Set element's [31599]validation anchor to null if anchor is not
given. Otherwise, if anchor is not a [31600]shadow-including
descendant of element, then throw a [31601]"NotFoundError"
[31602]DOMException. Otherwise, set element's [31603]validation
anchor to anchor.
(BUTTON) ✔MDN
[31604]ElementInternals/validationMessage
Support in all current engines.
Firefox98+Safari16.4+Chrome77+
__________________________________________________________________
The validationMessage getter steps are:
1. Let element be [31605]this's [31606]target element.
2. If element is not a [31607]form-associated custom element, then
throw a [31608]"NotSupportedError" [31609]DOMException.
3. Return element's [31610]validation message.
The entry construction algorithm for a [31611]form-associated custom
element, given an element element and an [31612]entry list entry list,
consists of the following steps:
1. If element's [31613]submission value is a [31614]list of
[31615]entries, then [31616]append each item of element's
[31617]submission value to entry list, and return.
In this case, user agent does not refer to the [31618]name content
attribute value. An implementation of [31619]form-associated custom
element is responsible to decide names of [31620]entries. They can
be the [31621]name content attribute value, they can be strings
based on the [31622]name content attribute value, or they can be
unrelated to the [31623]name content attribute.
2. If the element does not have a [31624]name attribute specified, or
its [31625]name attribute's value is the empty string, then return.
3. If the element's [31626]submission value is not null, [31627]create
an entry with the [31628]name attribute value and the
[31629]submission value, and [31630]append it to entry list.
4.13.7.4 Accessibility semantics
internals.[31631]role [ = value ]
Sets or retrieves the default ARIA role for internals's
[31632]target element, which will be used unless the page author
overrides it using the [31633]role attribute.
internals.[31634]aria* [ = value ]
Sets or retrieves various default ARIA states or property values
for internals's [31635]target element, which will be used unless
the page author overrides them using the [31636]aria-*
attributes.
Each [31637]custom element has an internal content attribute map, which
is a [31638]map, initially empty. See the [31639]Requirements related
to ARIA and to platform accessibility APIs section for information on
how this impacts platform accessibility APIs.
4.13.7.5 Custom state pseudo-class
internals.[31640]states.add(value)
Adds the string value to the element's [31641]states set to be
exposed as a pseudo-class.
internals.[31642]states.has(value)
Returns true if value is in the element's [31643]states set,
otherwise false.
internals.[31644]states.delete(value)
If the element's [31645]states set has value, then it will be
removed and true will be returned. Otherwise, false will be
returned.
internals.[31646]states.clear()
Removes all values from the element's [31647]states set.
for (const stateName of internals.[31648]states)
for (const stateName of internals.[31649]states.entries())
for (const stateName of internals.[31650]states.keys())
for (const stateName of internals.[31651]states.values())
Iterates over all values in the element's [31652]states set.
internals.[31653]states.forEach(callback)
Iterates over all values in the element's [31654]states set by
calling callback once for each value.
internals.[31655]states.size
Returns the number of values in the element's [31656]states set.
Each [31657]custom element has a states set, which is a
[31658]CustomStateSet, initially empty.
[Exposed=Window]
interface CustomStateSet {
setlike;
};
The states getter steps are to return [31659]this's [31660]target
element's [31661]states set.
The [31662]states set can expose boolean states represented by
existence/non-existence of string values. If an author wants to expose
a state which can have three values, it can be converted to three
exclusive boolean states. For example, a state called readyState with
"loading", "interactive", and "complete" values can be mapped to three
exclusive boolean states, "loading", "interactive", and "complete":
// Change the readyState from anything to "complete".
this._readyState = "complete";
this._internals.states.delete("loading");
this._internals.states.delete("interactive");
this._internals.states.add("complete");
4.14 Common idioms without dedicated elements
4.14.1 Breadcrumb navigation
This specification does not provide a machine-readable way of
describing breadcrumb navigation menus. Authors are encouraged to just
use a series of links in a paragraph. The [31663]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.
4.14.2 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 [31664]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:
...
The actual frequency of each tag is given using the [31665]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 [31666]ul element is used (rather than [31667]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 [31668]tag [31669]rel-keyword is not used on these [31670]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.
4.14.3 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 in discourse.
Instead, authors are encouraged to mark up conversations using [31671]p
elements and punctuation. Authors who need to mark the speaker for
styling purposes are encouraged to use [31672]span or [31673]b.
Paragraphs with their text wrapped in the [31674]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:
Costello: Look, you gotta first baseman?
Abbott: Certainly.
Costello: Whoʼs playing first?
Abbott: Thatʼs right.
Costello becomes exasperated.
Costello: When you pay off the first baseman every month, who gets the money
?
Abbott: Every dollar of it.
The following extract shows how an IM conversation log could be marked
up, using the [31675]data element to provide Unix timestamps for each
line. Note that the timestamps are provided in a format that the
[31676]time element does not support, so the [31677]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 [31678]time element, that element could have been used instead of
[31679]data. This could be advantageous as it would allow data analysis
tools to detect the timestamps unambiguously, without coordination with
the page author.
14:22 egof Iʼm not that nerdy, Iʼve o
nly seen 30% of the star trek episodes
14:23 kaj if you know what percentage
of the star trek episodes you have seen, you are inarguably nerdy
14:23 egof itʼs unarguably
14:23 * kaj blinks
14:24 kaj you are not helping your ca
se
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 example shows one possible convention using [31680]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. [31681][DOT]
Next, you meet a fisher. You can say one of several greetings:
"Hello there!"
She responds with "Hello, how may I help you?"; you can respond with:
"I would like to buy a fish."
She sells you a fish and the conversation finishes.
"Can I borrow your boat?"
She is surprised and asks "What are you offering in return?".
"Five gold." (if you have enough)
"Ten gold." (if you have enough)
"Fifteen gold." (if you have enough)
She lends you her boat. The conversation ends.
"A fish." (if you have one)
"A newspaper." (if you have one)
"A pebble." (if you have one)
"No thanks", she replies. Your conversation options
at this point are the same as they were after asking to borrow
her boat, minus any options youʼve suggested before.
"Vote for me in the next election!"
She turns away. The conversation finishes.
"Madam, are you aware that your fish are running away?"
She looks at you skeptically and says "Fish cannot run, miss".
"You got me!"
The fisher sighs and the conversation ends.
"Only kidding."
"Good one!" she retorts. Your conversation options at this
point are the same as those following "Hello there!" above.
"Oh, then what are they doing?"
She looks at her fish, giving you an opportunity to steal
her boat, which you do. The conversation ends.
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:
Dialogue
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.
The Shopkeeper
How may I help you?
Fresh apples!
A loaf of bread for madam?
The pilot
Before the accident:
Iʼm about to fly out, sorry!
Sorry, Iʼm just waiting for flight clearance and then Iʼll be off!
After the accident:
Iʼm about to fly out, sorry!
Ok, Iʼm not leaving right now, my plane is being cleaned.
Ok, itʼs not being cleaned, it needs a minor repair first.
Ok, ok, stop bothering me! Truth is, I had a crash.
Clan Leader
During the first clan meeting:
Hey, have you seen my daughter? I bet sheʼs up to something nefarious agai
n...
Nice weather weʼre having today, eh?
The name is Bailey, Jeff Bailey. How can I help you today?
A glass of water? Fresh from the well!
After the earthquake:
Everyone is safe in the shelter, we just have to put out the fire!
Iʼll go and tell the fire brigade, you keep hosing it down!
4.14.4 Footnotes
HTML does not have a dedicated mechanism for marking up footnotes. Here
are the suggested alternatives.
__________________________________________________________________
For short inline annotations, the [31682]title attribute could be used.
In this example, two parts of a dialogue are annotated with
footnote-like content using the [31683]title attribute.
Customer: Hello! I wish to register a complaint. Hello. Miss?
Shopkeeper: Watcha mean, miss?
Customer: Uh, Iʼm sorry, I have a cold. I wish to make a complaint.
Shopkeeper: Sorry, weʼre
closing for lunch.
Unfortunately, relying on the [31684]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 [31685]title attribute is used, CSS can be 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 [31686]title attribute.
[title] { border-bottom: thin dashed; }
__________________________________________________________________
For longer annotations, the [31687]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.
Announcer: Number 16: The hand.
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 do you
contradict people?
For side notes, longer annotations that apply to entire sections of the
text rather than just specific words or sentences, the [31688]aside
element should be used.
In this example, a sidebar is given after a dialogue, giving it some
context.
Customer: I will not buy this record, it is scr
atched.
Shopkeeper: Iʼm sorry?
Customer: I will not buy this record, it is scr
atched.
Shopkeeper: No no no, thisʼsʼa tobacconistʼs.
__________________________________________________________________
For figures or tables, footnotes can be included in the relevant
[31689]figcaption or [31690]caption element, or in surrounding prose.
In this example, a table has cells with footnotes that are given in
prose. A [31691]figure element is used to give a single legend to the
combination of the table and its footnotes.
An element is said to be actually disabled if it is one of the
following:
* a [31692]button element that is [31693]disabled
* an [31694]input element that is [31695]disabled
* a [31696]select element that is [31697]disabled
* a [31698]textarea element that is [31699]disabled
* an [31700]optgroup element that has a [31701]disabled attribute
* an [31702]option element that is [31703]disabled
* a [31704]fieldset element that is a [31705]disabled fieldset
* a [31706]form-associated custom element that is [31707]disabled
This definition is used to determine what elements are [31708]focusable
and which elements match the [31709]:enabled and [31710]:disabled
[31711]pseudo classes.
4.16 Matching HTML elements using selectors and CSS
4.16.1 Case-sensitivity of the CSS [31712]'attr()' function
CSS Values and Units leaves the case-sensitivity of attribute names for
the purpose of the [31713]'attr()' function to be defined by the host
language. [31714][CSSVALUES]
When comparing the attribute name part of a CSS [31715]'attr()'
function to the names of namespace-less attributes on [31716]HTML
elements in [31717]HTML documents, the name part of the CSS
[31718]'attr()' function must first be [31719]converted to ASCII
lowercase. The same function when compared to other attributes must be
compared according to its original case. In both cases, to match the
values must be [31720]identical to each other (and therefore the
comparison is case sensitive).
This is the same as comparing the name part of a CSS [31721]attribute
selector, specified in the next section.
4.16.2 Case-sensitivity of selectors
Selectors leaves the case-sensitivity of element names, attribute
names, and attribute values to be defined by the host language.
[31722][SELECTORS]
When comparing a CSS element [31723]type selector to the names of
[31724]HTML elements in [31725]HTML documents, the CSS element
[31726]type selector must first be [31727]converted to ASCII lowercase.
The same selector when compared to other elements must be compared
according to its original case. In both cases, to match the values must
be [31728]identical to each other (and therefore the comparison is case
sensitive).
When comparing the name part of a CSS [31729]attribute selector to the
names of attributes on [31730]HTML elements in [31731]HTML documents,
the name part of the CSS [31732]attribute selector must first be
[31733]converted to ASCII lowercase. The same selector when compared to
other attributes must be compared according to its original case. In
both cases, the comparison is case-sensitive.
[31734]Attribute selectors on an [31735]HTML element in an [31736]HTML
document must treat the values of attributes with the following names
as [31737]ASCII case-insensitive:
* accept
* accept-charset
* align
* alink
* axis
* bgcolor
* charset
* checked
* clear
* codetype
* color
* compact
* declare
* defer
* dir
* direction
* disabled
* enctype
* face
* frame
* hreflang
* http-equiv
* lang
* language
* link
* media
* method
* multiple
* nohref
* noresize
* noshade
* nowrap
* readonly
* rel
* rev
* rules
* scope
* scrolling
* selected
* shape
* target
* text
* type
* valign
* valuetype
* vlink
For example, the selector [bgcolor="#ffffff"] will match any HTML
element with a bgcolor attribute with values including #ffffff, #FFFFFF
and #fffFFF. This happens even if bgcolor has no effect for a given
element (e.g., [31738]div).
The selector [type=a s] will match any HTML element with a type
attribute whose value is a, but not whose value is A, due to the s
flag.
All other attribute values and everything else must be treated as
entirely [31739]identical to each other for the purposes of selector
matching. This includes:
* [31740]IDs and [31741]classes in [31742]no-quirks mode and
[31743]limited-quirks mode
* the names of elements not in the [31744]HTML namespace
* the names of [31745]HTML elements in [31746]XML documents
* the names of attributes of elements not in the [31747]HTML
namespace
* the names of attributes of [31748]HTML elements in [31749]XML
documents
* the names of attributes that themselves have namespaces
Selectors defines that ID and class selectors (such as #foo and .bar),
when matched against elements in documents that are in [31750]quirks
mode, will be matched in an [31751]ASCII case-insensitive manner.
However, this does not apply for attribute selectors with "id" or
"class" as the name part. The selector [class="foobar"] will treat its
value as case-sensitive even in [31752]quirks mode.
4.16.3 Pseudo-classes
(BUTTON) MDN
[31753]Pseudo-classes
There are a number of dynamic selectors that can be used with HTML.
This section defines when these selectors match HTML elements.
[31754][SELECTORS] [31755][CSSUI]
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
The [31757]:defined [31758]pseudo-class must match any element
that is [31759]defined.
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android10.1+
All [31762]a elements that have an [31763]href attribute, and
all [31764]area elements that have an [31765]href attribute,
must match one of [31766]:link and [31767]:visited.
Other specifications might apply more specific rules regarding
how these elements are to match these [31768]pseudo-classes, to
mitigate some privacy concerns that apply with straightforward
implementations of this requirement.
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android10.1+
The [31770]:active [31771]pseudo-class is defined to match an
element "while an element is being activated by the user".
To determine whether a particular element is [31772]being
activated for the purposes of defining the [31773]:active
[31774]pseudo-class only, an HTML user agent must use the first
relevant entry in the following list.
If the element is a [31775]button element
If the element is an [31776]input element whose [31777]type
attribute is in the [31778]Submit Button, [31779]Image
Button, [31780]Reset Button, or [31781]Button state
If the element is an [31782]a element that has an [31783]href
attribute
If the element is an [31784]area element that has an [31785]href
attribute
If the element is [31786]focusable
The element is [31787]being activated if it is [31788]in a
formal activation state.
For example, if the user is using a keyboard to push a
[31789]button element by pressing the space bar, the
element would match this [31790]pseudo-class in between
the time that the element received the [31791]keydown
event and the time the element received the [31792]keyup
event.
If the element is [31793]being actively pointed at
The element is [31794]being activated.
An element is said to be in a formal activation state between
the time the user begins to indicate an intent to trigger the
element's [31795]activation behavior and either the time the
user stops indicating an intent to trigger the element's
[31796]activation behavior, or the time the element's
[31797]activation behavior has finished running, which ever
comes first.
An element is said to be being actively pointed at while the
user indicates the element using a pointing device while that
pointing device is in the "down" state (e.g. for a mouse,
between the time the mouse button is pressed and the time it is
depressed; for a finger in a multitouch environment, while the
finger is touching the display surface).
Per the definition in Selectors, [31798]:active also matches
[31799]flat tree ancestors of elements that are [31800]being
activated. [31801][SELECTORS]
Additionally, any element that is the [31802]labeled control of
a [31803]label element that is currently matching
[31804]:active, also matches [31805]:active. (But, it does not
count as being [31806]being activated.)
Firefox Android?Safari iOS1+Chrome Android?WebView
Android?Samsung Internet?Opera Android10.1+
The [31808]:hover [31809]pseudo-class is defined to match an
element "while the user designates an element with a pointing
device". For the purposes of defining the [31810]:hover
[31811]pseudo-class only, an HTML user agent must consider an
element as being one that the user [31812]designates if it is an
element that the user indicates using a pointing device.
Per the definition in Selectors, [31813]:hover also matches
[31814]flat tree ancestors of elements that are
[31815]designated. [31816][SELECTORS]
Additionally, any element that is the [31817]labeled control of
a [31818]label element that is currently matching [31819]:hover,
also matches [31820]:hover. (But, it does not count as being
[31821]designated.)
Consider in particular a fragment such as:
If the user designates the element with ID "a" with their
pointing device, then the [31822]p element (and all its
ancestors not shown in the snippet above), the [31823]label
element, the element with ID "a", and the element with ID "c"
will match the [31824]:hover [31825]pseudo-class. The element
with ID "a" matches it by being [31826]designated; the
[31827]label and [31828]p elements match it because of the
condition in Selectors about flat tree ancestors; and the
element with ID "c" matches it through the additional condition
above on [31829]labeled controls (i.e., its [31830]label element
matches [31831]:hover). However, the element with ID "b" does
not match [31832]:hover: its flat tree descendant is not
designated, even though that flat tree descendant matches
[31833]:hover.
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android10.1+
For the purposes of the CSS [31835]:focus [31836]pseudo-class,
an element has the focus when:
+ it is not itself a [31837]navigable container; and
+ any of the following are true:
o it is one of the elements listed in the [31838]current
focus chain of the top-level traversable; or
o its [31839]shadow root shadowRoot is not null and
shadowRoot is the [31840]root of at least one element
that [31841]has the focus.
Firefox Android?Safari iOS2+Chrome Android?WebView
Android2+Samsung Internet?Opera Android10.1+
For the purposes of the CSS [31843]:target [31844]pseudo-class,
the [31845]Document's target elements are a list containing the
[31846]Document's [31847]target element, if it is not null, or
containing no elements, if it is. [31848][SELECTORS]
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
The [31850]:popover-open [31851]pseudo-class is defined to match
any [31852]HTML element whose [31853]popover attribute is not in
the [31854]no popover state and whose [31855]popover visibility
state is [31856]showing.
Firefox Android?Safari iOS?Chrome Android?WebView
Android2+Samsung Internet?Opera Android10.1+
The [31858]:enabled [31859]pseudo-class must match any
[31860]button, [31861]input, [31862]select, [31863]textarea,
[31864]optgroup, [31865]option, [31866]fieldset element, or
[31867]form-associated custom element that is not
[31868]actually disabled.
Firefox Android?Safari iOS?Chrome Android?WebView
Android2+Samsung Internet?Opera Android10.1+
The [31870]:disabled [31871]pseudo-class must match any element
that is [31872]actually disabled.
Firefox Android4+Safari iOS?Chrome Android18+WebView
Android2+Samsung Internet?Opera Android10.1+
The [31874]:checked [31875]pseudo-class must match any element
falling into one of the following categories:
+ [31876]input elements whose [31877]type attribute is in the
[31878]Checkbox state and whose [31879]checkedness state is
true
+ [31880]input elements whose [31881]type attribute is in the
[31882]Radio Button state and whose [31883]checkedness state
is true
+ [31884]option elements whose [31885]selectedness is true
Firefox Android?Safari iOS1+Chrome Android?WebView
Android37+Samsung Internet?Opera Android10.1+
The [31887]:indeterminate [31888]pseudo-class must match any
element falling into one of the following categories:
+ [31889]input elements whose [31890]type attribute is in the
[31891]Checkbox state and whose [31892]indeterminate IDL
attribute is set to true
+ [31893]input elements whose [31894]type attribute is in the
[31895]Radio Button state and whose [31896]radio button group
contains no [31897]input elements whose [31898]checkedness
state is true.
+ [31899]progress elements with no [31900]value content
attribute
Firefox Android?Safari iOS5+Chrome Android?WebView
Android37+Samsung Internet?Opera Android10.1+
The [31902]:default [31903]pseudo-class must match any element
falling into one of the following categories:
+ [31904]Submit buttons that are [31905]default buttons of their
[31906]form owner.
+ [31907]input elements to which the [31908]checked attribute
applies and that have a [31909]checked attribute
+ [31910]option elements that have a [31911]selected attribute
:placeholder-shown
The [31912]:placeholder-shown [31913]pseudo-class must match any
element falling into one of the following categories:
+ [31914]input elements that have a [31915]placeholder attribute
whose value is currently being presented to the user
+ [31916]textarea elements that have a [31917]placeholder
attribute whose value is currently being presented to the user
Firefox Android?Safari iOS5+Chrome Android?WebView
Android37+Samsung Internet?Opera Android10.1+
The [31919]:valid [31920]pseudo-class must match any element
falling into one of the following categories:
+ elements that are [31921]candidates for constraint validation
and that [31922]satisfy their constraints
+ [31923]form elements that are not the [31924]form owner of any
elements that themselves are [31925]candidates for constraint
validation but do not [31926]satisfy their constraints
+ [31927]fieldset elements that have no descendant elements that
themselves are [31928]candidates for constraint validation but
do not [31929]satisfy their constraints
Firefox Android?Safari iOS5+Chrome Android?WebView
Android37+Samsung Internet?Opera Android10.1+
The [31931]:invalid [31932]pseudo-class must match any element
falling into one of the following categories:
+ elements that are [31933]candidates for constraint validation
but that do not [31934]satisfy their constraints
+ [31935]form elements that are the [31936]form owner of one or
more elements that themselves are [31937]candidates for
constraint validation but do not [31938]satisfy their
constraints
+ [31939]fieldset elements that have of one or more descendant
elements that themselves are [31940]candidates for constraint
validation but do not [31941]satisfy their constraints
:user-valid
The [31942]:user-valid [31943]pseudo-class must match
[31944]input, [31945]textarea, and [31946]select elements whose
[31947]user validity is true, are [31948]candidates for
constraint validation, and that [31949]satisfy their
constraints.
:user-invalid
The [31950]:user-invalid [31951]pseudo-class must match
[31952]input, [31953]textarea, and [31954]select elements whose
[31955]user validity is true, are [31956]candidates for
constraint validation but do not [31957]satisfy their
constraints.
Firefox Android16+Safari iOS?Chrome Android?WebView
Android2.2+Samsung Internet1.0+Opera Android11+
The [31959]:in-range [31960]pseudo-class must match all elements
that are [31961]candidates for constraint validation,
[31962]have range limitations, and that are neither
[31963]suffering from an underflow nor [31964]suffering from an
overflow.
Firefox Android16+Safari iOS?Chrome Android?WebView
Android2.2+Samsung Internet?Opera Android11+
The [31966]:out-of-range [31967]pseudo-class must match all
elements that are [31968]candidates for constraint validation,
[31969]have range limitations, and that are either
[31970]suffering from an underflow or [31971]suffering from an
overflow.
Firefox Android?Safari iOS5+Chrome Android?WebView
Android4.4.3+Samsung Internet?Opera Android10.1+
The [31973]:required [31974]pseudo-class must match any element
falling into one of the following categories:
+ [31975]input elements that are [31976]required
+ [31977]select elements that have a [31978]required attribute
+ [31979]textarea elements that have a [31980]required attribute
Firefox Android?Safari iOS5+Chrome Android?WebView
Android37+Samsung Internet?Opera Android10.1+
The [31982]:optional [31983]pseudo-class must match any element
falling into one of the following categories:
+ [31984]input elements to which the [31985]required attribute
applies that are not [31986]required
+ [31987]select elements that do not have a [31988]required
attribute
+ [31989]textarea elements that do not have a [31990]required
attribute
:-webkit-autofill
The [31992]:autofill and [31993]:-webkit-autofill
[31994]pseudo-classes must match [31995]input elements which
have been autofilled by user agent. These pseudo-classes must
stop matching if the user edits the autofilled field.
One way such autofilling might happen is via the
[31996]autocomplete attribute, but user agents could autofill
even without that attribute being involved.
Firefox Android🔰 4+Safari iOS?Chrome Android?WebView
Android37+Samsung Internet?Opera Android10.1+
The [31999]:read-write [32000]pseudo-class must match any
element falling into one of the following categories, which for
the purposes of Selectors are thus considered user-alterable:
[32001][SELECTORS]
+ [32002]input elements to which the [32003]readonly attribute
applies, and that are [32004]mutable (i.e. that do not have
the [32005]readonly attribute specified and that are not
[32006]disabled)
+ [32007]textarea elements that do not have a [32008]readonly
attribute, and that are not [32009]disabled
+ elements that are [32010]editing hosts or [32011]editable and
are neither [32012]input elements nor [32013]textarea elements
The [32014]:read-only [32015]pseudo-class must match all other
[32016]HTML elements.
:modal
The [32017]:modal [32018]pseudo-class must match any element
falling into one of the following categories:
+ [32019]dialog elements whose [32020]is modal is true
+ elements whose [32021]fullscreen flag is true
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
The [32023]:dir(ltr) [32024]pseudo-class must match all elements
whose [32025]directionality is '[32026]ltr'.
:dir(rtl)
The [32027]:dir(rtl) [32028]pseudo-class must match all elements
whose [32029]directionality is '[32030]rtl'.
Custom state pseudo-class
The [32031]:state(identifier) pseudo-class must match all
[32032]custom elements whose [32033]states set's [32034]set
entries contains identifier.
:playing
The [32035]:playing [32036]pseudo-class must match all
[32037]media elements whose [32038]paused attribute is false.
:paused
The [32039]:paused [32040]pseudo-class must match all
[32041]media elements whose [32042]paused attribute is true.
:seeking
The [32043]:seeking [32044]pseudo-class must match all
[32045]media elements whose [32046]seeking attribute is true.
:buffering
The [32047]:buffering [32048]pseudo-class must match all
[32049]media elements whose [32050]paused attribute is false,
[32051]networkState attribute is [32052]NETWORK_LOADING, and
ready state is [32053]HAVE_CURRENT_DATA or less.
:stalled
The [32054]:stalled [32055]pseudo-class must match all
[32056]media elements that match the [32057]:buffering
[32058]pseudo-class and whose [32059]is currently stalled is
true.
:muted
The [32060]:muted [32061]pseudo-class must match all
[32062]media elements that are [32063]muted.
:volume-locked
The [32064]:volume-locked [32065]pseudo-class must match all
[32066]media elements when the user agent's [32067]volume locked
is true.
:open
The [32068]:open [32069]pseudo-class must match any element
falling into one of the following categories:
+ [32070]details elements that have an [32071]open attribute
+ [32072]dialog elements that have an [32073]open attribute
+ [32074]select elements that are a [32075]drop-down box and
whose drop-down boxes are open
+ [32076]input elements that [32077]support a picker and whose
pickers are open
This specification does not define when an element matches the :lang()
dynamic [32078]pseudo-class, as it is defined in sufficient detail in a
language-agnostic fashion in Selectors. [32079][SELECTORS]
5 Microdata
5.1 Introduction
5.1.1 Overview
This section is non-normative.
Sometimes, it is desirable to annotate content with specific
machine-readable labels, e.g. to allow generic scripts to provide
services that are customized 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.
5.1.2 The basic syntax
This section is non-normative.
At a high level, microdata consists of a group of name-value pairs. The
groups are called [32080]items, and each name-value pair is a property.
Items and properties are represented by regular elements.
To create an item, the [32081]itemscope attribute is used.
To add a property to an item, the [32082]itemprop attribute is used on
one of the [32083]item's descendants.
Here there are two items, each of which has the property "name":
My name is Elizabeth.
My name is Daniel.
Markup without the microdata-related attributes does not have any
effect on the microdata model.
These two examples are exactly equivalent, at a microdata level, as the
previous two examples respectively:
My name is Elizabeth.
Properties generally have values that are strings.
Here the item has three properties:
My name is Neil.
My band is called Four Parts Water.
I am British.
When a string value is a [32084]URL, it is expressed using the [32085]a
element and its [32086]href attribute, the [32087]img element and its
[32088]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:
When a string value is in some machine-readable format unsuitable for
human consumption, it is expressed using the [32089]value attribute of
the [32090]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.
The Instigator 2000
For numeric data, the [32091]meter element and its [32092]value
attribute can be used instead.
Here a rating is given using a [32093]meter element.
Panasonic White 60L Refrigerator
Rated 3.5/5
(based on 11 customer reviews)
Similarly, for date- and time-related data, the [32094]time element and
its [32095]datetime attribute can be used instead.
In this example, the item has one property, "birthday", whose value is
a date:
I was born on
Properties can also themselves be groups of name-value pairs, by
putting the [32096]itemscope attribute on the element that declares the
property.
Items that are not part of others are called [32097]top-level microdata
items.
In this example, the outer item represents a person, and the inner one
represents a band:
Name: Amanda
Band: Jazz Band (12 players)
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
[32098]itemscope attribute can be associated with the [32099]item using
the [32100]itemref attribute. This attribute takes a list of IDs of
elements to crawl in addition to crawling the children of the element
with the [32101]itemscope attribute.
This example is the same as the previous one, but all the properties
are separated from their [32102]items:
Name: Amanda
Band: Jazz Band
Size: 12 players
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 [32103]item can have multiple properties with the same name and
different values.
This example describes an ice cream, with two flavors:
Flavors in my favorite ice cream:
Lemon sorbet
Apricot sorbet
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
"favorite-fruit", both set to the value "orange":
orange
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:
The Castle (198
6)The Castle (1986)
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 drag-and-drop data. In neither case is the
image in any way associated with the item.
5.1.3 Typed items
This section is non-normative.
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 [32104]item a type, such
as "https://example.com/person", or "https://example.org/cat", or
"https://band.example.net/". Types are identified as [32105]URLs.
The type for an [32106]item is given as the value of an [32107]itemtype
attribute on the same element as the [32108]itemscope attribute.
Here, the item's type is "https://example.org/animals#cat":
Hedral
Hedral is a male american domestic
shorthair, with a fluffy black fur with white paws and belly.
In this example the "https://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
"https://census.example/person" might refer to the economic class of an
individual, while a property named "class" given for an item with the
type "https://example.com/school/teacher" might refer to the classroom
a teacher has been assigned. Several types can share a vocabulary. For
example, the types "https://example.org/people/teacher" and
"https://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 "https://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 two types if they do not use
the same vocabulary, however.
5.1.4 Global identifiers for items
This section is non-normative.
Sometimes, an [32109]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 [32110]itemtype attribute) can be
designed such that [32111]items get associated with their global
identifier in an unambiguous way by expressing the global identifiers
as [32112]URLs given in an [32113]itemid attribute.
The exact meaning of the [32114]URLs given in [32115]itemid attributes
depends on the vocabulary used.
Here, an item is talking about a particular book:
Title
The Reality Dysfunction
Author
Peter F. Hamilton
Publication date
The "https://vocab.example.net/book" vocabulary in this example would
define that the [32116]itemid attribute takes a [32117]urn: [32118]URL
pointing to the ISBN of the book.
5.1.5 Selecting names when defining vocabularies
This section is non-normative.
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 [32119]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
https://example.com/~jon/... and https://example.com/~adam/...
respectively, then they could select identifiers of the form
"https://example.com/~jon/name" and "https://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 "https://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.
Hedral
Hedral is a male American domestic
shorthair, with a fluffy black fur with white paws and belly.
This example has one item with the type
"https://example.org/animals#cat" and the following properties:
Property Value
name Hedral
https://example.com/fn Hedral
desc Hedral is a male American domestic shorthair, with a fluffy black
fur with white paws and belly.
https://example.com/color black
https://example.com/color white
img .../hedral.jpeg
5.2 Encoding microdata
5.2.1 The microdata model
The microdata model consists of groups of name-value pairs known as
[32120]items.
Each group is known as an [32121]item. Each [32122]item can have
[32123]item types, a [32124]global identifier (if the vocabulary
specified by the [32125]item types [32126]support global identifiers
for items), and a list of name-value pairs. Each name in the name-value
pair is known as a [32127]property, and each [32128]property has one or
more [32129]values. Each [32130]value is either a string or itself a
group of name-value pairs (an [32131]item). The names are unordered
relative to each other, but if a particular name has multiple values,
they do have a relative order.
5.2.2 Items
(BUTTON) ✔MDN
[32132]Global_attributes/itemscope
Support in all current engines.
FirefoxYesSafariYesChromeYes
__________________________________________________________________
Every [32133]HTML element may have an itemscope attribute specified.
The [32134]itemscope attribute is a [32135]boolean attribute.
An element with the [32136]itemscope attribute specified creates a new
item, a group of name-value pairs.
__________________________________________________________________
(BUTTON) ✔MDN
[32137]Global_attributes/itemtype
Support in all current engines.
FirefoxYesSafariYesChromeYes
__________________________________________________________________
Elements with an [32138]itemscope attribute may have an itemtype
attribute specified, to give the [32139]item types of the [32140]item.
The [32141]itemtype attribute, if specified, must have a value that is
an [32142]unordered set of unique space-separated tokens, none of which
are [32143]identical to another token and each of which is a
[32144]valid URL string that is an [32145]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 [32146]item are the tokens obtained by
[32147]splitting the element's itemtype attribute's value on ASCII
whitespace. If the [32148]itemtype attribute is missing or parsing it
in this way finds no tokens, the [32149]item is said to have no
[32150]item types.
The [32151]item types must all be types defined in [32152]applicable
specifications and must all be defined to use the same vocabulary.
Except if otherwise specified by that specification, the [32153]URLs
given as the [32154]item types should not be automatically
dereferenced.
A specification could define that its [32155]item type can be
dereferenced to provide the user with help information, for example. In
fact, vocabulary authors are encouraged to provide useful information
at the given [32156]URL.
[32157]Item types are opaque identifiers, and user agents must not
dereference unknown [32158]item types, or otherwise deconstruct them,
in order to determine how to process [32159]items that use them.
The [32160]itemtype attribute must not be specified on elements that do
not have an [32161]itemscope attribute specified.
__________________________________________________________________
An [32162]item is said to be a typed item when either it has an
[32163]item type, or it is the [32164]value of a [32165]property of a
[32166]typed item. The relevant types for a [32167]typed item is the
[32168]item's [32169]item types, if it has any, or else is the
[32170]relevant types of the [32171]item for which it is a
[32172]property's [32173]value.
__________________________________________________________________
(BUTTON) ✔MDN
[32174]Global_attributes/itemid
Support in all current engines.
FirefoxYesSafariYesChromeYes
__________________________________________________________________
Elements with an [32175]itemscope attribute and an [32176]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 [32177]item, so that it
can be related to other [32178]items on pages elsewhere on the web.
The [32179]itemid attribute, if specified, must have a value that is a
[32180]valid URL potentially surrounded by spaces.
The global identifier of an [32181]item is the value of its element's
[32182]itemid attribute, if it has one, [32183]parsed relative to the
[32184]node document of the element on which the attribute is
specified. If the [32185]itemid attribute is missing or if parsing it
returns failure, it is said to have no [32186]global identifier.
The [32187]itemid attribute must not be specified on elements that do
not have both an [32188]itemscope attribute and an [32189]itemtype
attribute specified, and must not be specified on elements with an
[32190]itemscope attribute whose [32191]itemtype attribute specifies a
vocabulary that does not [32192]support global identifiers for items,
as defined by that vocabulary's specification.
The exact meaning of a [32193]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.
__________________________________________________________________
(BUTTON) ✔MDN
[32194]Global_attributes/itemref
Support in all current engines.
FirefoxYesSafariYesChromeYes
__________________________________________________________________
Elements with an [32195]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 [32196]item.
The [32197]itemref attribute, if specified, must have a value that is
an [32198]unordered set of unique space-separated tokens none of which
are [32199]identical to another token and consisting of [32200]IDs of
elements in the same [32201]tree.
The [32202]itemref attribute must not be specified on elements that do
not have an [32203]itemscope attribute specified.
The [32204]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 defines a separate [32205]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 [32206]item types:
https://md.example.com/loco
Rolling stock with an engine
https://md.example.com/passengers
Passenger rolling stock
https://md.example.com/track
Track pieces
https://md.example.com/lighting
Equipment with lighting
Each [32207]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:
Name:
Tank Locomotive (DB 80)
Product code:
33041
Scale:
HO
Digital:
Delta
A turnout lantern retrofit kit might be marked up as:
Name:
Turnout Lantern Kit
Product code:
74470
Purpose:
For retrofitting 2 C Track
turnouts.
A passenger car with no lighting might be marked up as:
Name:
Express Train Passenger Car (DB Am 203)
Product code:
8710
Scale:
Z
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.
5.2.3 Names: the itemprop attribute
(BUTTON) ✔MDN
[32208]Global_attributes/itemprop
Support in all current engines.
FirefoxYesSafariYesChromeYes
__________________________________________________________________
Every [32209]HTML element may have an [32210]itemprop attribute
specified, if doing so [32211]adds one or more properties to one or
more [32212]items (as defined below).
The [32213]itemprop attribute, if specified, must have a value that is
an [32214]unordered set of unique space-separated tokens none of which
are [32215]identical to another token, 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 [32216]typed item: a defined property name allowed
in this situation according to the specification that defines the
[32217]relevant types for the item, or
* A [32218]valid URL string that is an [32219]absolute URL defined as
an item property name allowed in this situation by a vocabulary
specification, or
* A [32220]valid URL string that is an [32221]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 [32222]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 [32223]defined property names must ensure
all such property names contain no U+002E FULL STOP characters (.), no
U+003A COLON characters (:), and no [32224]ASCII whitespace.
The rules above disallow U+003A COLON characters (:) in non-URL values
because otherwise they could not be distinguished from URLs. Values
with U+002E FULL STOP characters (.) are reserved for future
extensions. [32225]ASCII whitespace are disallowed because otherwise
the values would be parsed as multiple tokens.
When an element with an [32226]itemprop attribute [32227]adds a
property to multiple [32228]items, the requirement above regarding the
tokens applies for each [32229]item individually.
The property names of an element are the tokens that the element's
[32230]itemprop attribute is found to contain when its value is
[32231]split on ASCII whitespace, with the order preserved but with
duplicates removed (leaving only the first occurrence of each name).
Within an [32232]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 [32233]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:
1
2
test
Thus, the following is equivalent:
test
1
2
As is the following:
1
test
2
And the following:
1
test
2
5.2.4 Values
The property value of a name-value pair added by an element with an
[32234]itemprop attribute is as given for the first matching case in
the following list:
If the element also has an [32235]itemscope attribute
The value is the [32236]item created by the element.
If the element is a [32237]meta element
The value is the value of the element's [32238]content
attribute, if any, or the empty string if there is no such
attribute.
If the element is an [32239]audio, [32240]embed, [32241]iframe,
[32242]img, [32243]source, [32244]track, or [32245]video element
The value is the result of
[32246]encoding-parsing-and-serializing a URL given the
element's src attribute's value, relative to the element's
[32247]node document, at the time the attribute is set, or the
empty string if there is no such attribute or the result is
failure.
If the element is an [32248]a, [32249]area, or [32250]link element
The value is the result of
[32251]encoding-parsing-and-serializing a URL given the
element's href attribute's value, relative to the element's
[32252]node document, at the time the attribute is set, or the
empty string if there is no such attribute or the result is
failure.
If the element is an [32253]object element
The value is the result of
[32254]encoding-parsing-and-serializing a URL given the
element's data attribute's value, relative to the element's
[32255]node document, at the time the attribute is set, or the
empty string if there is no such attribute or the result is
failure.
If the element is a [32256]data element
The value is the value of the element's [32257]value attribute,
if it has one, or the empty string otherwise.
If the element is a [32258]meter element
The value is the value of the element's [32259]value attribute,
if it has one, or the empty string otherwise.
If the element is a [32260]time element
The value is the element's [32261]datetime value.
Otherwise
The value is the element's [32262]descendant text content.
The URL property elements are the [32263]a, [32264]area, [32265]audio,
[32266]embed, [32267]iframe, [32268]img, [32269]link, [32270]object,
[32271]source, [32272]track, and [32273]video elements.
If a property's [32274]value, as defined by the property's definition,
is an [32275]absolute URL, the property must be specified using a
[32276]URL property element.
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
[32277]a element, even though it looks like a [32278]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
[32279]a element (or one of the other [32280]URL property elements),
because of the requirement above.
5.2.5 Associating names with items
To find the properties of an item defined by the element root, the user
agent must run the following steps. These steps are also used to flag
[32281]microdata errors.
1. Let results, memory, and pending be empty lists of elements.
2. Add the element root to memory.
3. Add the child elements of root, if any, to pending.
4. If root has an [32282]itemref attribute, [32283]split the value of
that itemref attribute on ASCII whitespace. For each resulting
token ID, if there is an element in the [32284]tree of root with
the [32285]ID ID, then add the first such element to pending.
5. While pending is not empty:
1. Remove an element from pending and let current be that
element.
2. If current is already in memory, there is a [32286]microdata
error; [32287]continue.
3. Add current to memory.
4. If current does not have an [32288]itemscope attribute, then:
add all the child elements of current to pending.
5. If current has an [32289]itemprop attribute specified and has
one or more [32290]property names, then add current to
results.
6. Sort results in [32291]tree order.
7. Return results.
A document must not contain any [32292]items for which the algorithm to
find [32293]the properties of an item finds any microdata errors.
An [32294]item is a top-level microdata item if its element does not
have an [32295]itemprop attribute.
All [32296]itemref attributes in a [32297]Document must be such that
there are no cycles in the graph formed from representing each
[32298]item in the [32299]Document as a node in the graph and each
[32300]property of an item whose [32301]value is another item as an
edge in the graph connecting those two items.
A document must not contain any elements that have an [32302]itemprop
attribute that would not be found to be a property of any of the
[32303]items in that document were their [32304]properties all to be
determined.
In this example, a single license statement is applied to two works,
using [32305]itemref from the items representing the works:
Photo gallery
My photos
The house I found.The mailbox.
The above results in two items with the type
"http://n.whatwg.org/work", one with:
Currently, the [32306]itemscope, [32307]itemprop, and other microdata
attributes are only defined for [32308]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.
5.3 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.
5.3.1 vCard
An item with the [32310]item type http://microformats.org/profile/hcard
represents a person's or organization's contact information.
This vocabulary does not [32311]support global identifiers for items.
The following are the type's [32312]defined property names. They are
based on the vocabulary defined in vCard Format Specification (vCard)
and its extensions, where more information on how to interpret the
values can be found. [32313][RFC6350]
kind
Describes what kind of contact the item represents.
The [32314]value must be text that is [32315]identical to one of
the [32316]kind strings.
A single property with the name [32317]kind may be present
within each [32318]item with the type
[32319]http://microformats.org/profile/hcard.
fn
Gives the formatted text corresponding to the name of the person
or organization.
The [32320]value must be text.
Exactly one property with the name [32321]fn must be present
within each [32322]item with the type
[32323]http://microformats.org/profile/hcard.
n
Gives the structured name of the person or organization.
The [32324]value must be an [32325]item with zero or more of
each of the [32326]family-name, [32327]given-name,
[32328]additional-name, [32329]honorific-prefix, and
[32330]honorific-suffix properties.
Exactly one property with the name [32331]n must be present
within each [32332]item with the type
[32333]http://microformats.org/profile/hcard.
family-name (inside [32334]n)
Gives the family name of the person, or the full name of the
organization.
The [32335]value must be text.
Any number of properties with the name [32336]family-name may be
present within the [32337]item that forms the [32338]value of
the [32339]n property of an [32340]item with the type
[32341]http://microformats.org/profile/hcard.
given-name (inside [32342]n)
Gives the given-name of the person.
The [32343]value must be text.
Any number of properties with the name [32344]given-name may be
present within the [32345]item that forms the [32346]value of
the [32347]n property of an [32348]item with the type
[32349]http://microformats.org/profile/hcard.
additional-name (inside [32350]n)
Gives the any additional names of the person.
The [32351]value must be text.
Any number of properties with the name [32352]additional-name
may be present within the [32353]item that forms the
[32354]value of the [32355]n property of an [32356]item with the
type [32357]http://microformats.org/profile/hcard.
honorific-prefix (inside [32358]n)
Gives the honorific prefix of the person.
The [32359]value must be text.
Any number of properties with the name [32360]honorific-prefix
may be present within the [32361]item that forms the
[32362]value of the [32363]n property of an [32364]item with the
type [32365]http://microformats.org/profile/hcard.
honorific-suffix (inside [32366]n)
Gives the honorific suffix of the person.
The [32367]value must be text.
Any number of properties with the name [32368]honorific-suffix
may be present within the [32369]item that forms the
[32370]value of the [32371]n property of an [32372]item with the
type [32373]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 [32374]fn or [32375]n properties.
The [32376]value must be text.
Any number of properties with the name [32377]nickname may be
present within each [32378]item with the type
[32379]http://microformats.org/profile/hcard.
photo
Gives a photograph of the person or organization.
The [32380]value must be an [32381]absolute URL.
Any number of properties with the name [32382]photo may be
present within each [32383]item with the type
[32384]http://microformats.org/profile/hcard.
bday
Gives the birth date of the person or organization.
The [32385]value must be a [32386]valid date string.
A single property with the name [32387]bday may be present
within each [32388]item with the type
[32389]http://microformats.org/profile/hcard.
anniversary
Gives the birth date of the person or organization.
The [32390]value must be a [32391]valid date string.
A single property with the name [32392]anniversary may be
present within each [32393]item with the type
[32394]http://microformats.org/profile/hcard.
sex
Gives the biological sex of the person.
The [32395]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 [32396]sex may be present within
each [32397]item with the type
[32398]http://microformats.org/profile/hcard.
gender-identity
Gives the gender identity of the person.
The [32399]value must be text.
A single property with the name [32400]gender-identity may be
present within each [32401]item with the type
[32402]http://microformats.org/profile/hcard.
adr
Gives the delivery address of the person or organization.
The [32403]value must be an [32404]item with zero or more
[32405]type, [32406]post-office-box, [32407]extended-address,
and [32408]street-address properties, and optionally a
[32409]locality property, optionally a [32410]region property,
optionally a [32411]postal-code property, and optionally a
[32412]country-name property.
If no [32413]type properties are present within an [32414]item
that forms the [32415]value of an [32416]adr property of an
[32417]item with the type
[32418]http://microformats.org/profile/hcard, then the
[32419]address type string [32420]work is implied.
Any number of properties with the name [32421]adr may be present
within each [32422]item with the type
[32423]http://microformats.org/profile/hcard.
type (inside [32424]adr)
Gives the type of delivery address.
The [32425]value must be text that is [32426]identical to one of
the [32427]address type strings.
Any number of properties with the name [32428]type may be
present within the [32429]item that forms the [32430]value of an
[32431]adr property of an [32432]item with the type
[32433]http://microformats.org/profile/hcard, but within each
such [32434]adr property [32435]item there must only be one
[32436]type property per distinct value.
post-office-box (inside [32437]adr)
Gives the post office box component of the delivery address of
the person or organization.
The [32438]value must be text.
Any number of properties with the name [32439]post-office-box
may be present within the [32440]item that forms the
[32441]value of an [32442]adr property of an [32443]item with
the type [32444]http://microformats.org/profile/hcard.
vCard urges authors not to use this field.
extended-address (inside [32445]adr)
Gives an additional component of the delivery address of the
person or organization.
The [32446]value must be text.
Any number of properties with the name [32447]extended-address
may be present within the [32448]item that forms the
[32449]value of an [32450]adr property of an [32451]item with
the type [32452]http://microformats.org/profile/hcard.
vCard urges authors not to use this field.
street-address (inside [32453]adr)
Gives the street address component of the delivery address of
the person or organization.
The [32454]value must be text.
Any number of properties with the name [32455]street-address may
be present within the [32456]item that forms the [32457]value of
an [32458]adr property of an [32459]item with the type
[32460]http://microformats.org/profile/hcard.
locality (inside [32461]adr)
Gives the locality component (e.g. city) of the delivery address
of the person or organization.
The [32462]value must be text.
A single property with the name [32463]locality may be present
within the [32464]item that forms the [32465]value of an
[32466]adr property of an [32467]item with the type
[32468]http://microformats.org/profile/hcard.
region (inside [32469]adr)
Gives the region component (e.g. state or province) of the
delivery address of the person or organization.
The [32470]value must be text.
A single property with the name [32471]region may be present
within the [32472]item that forms the [32473]value of an
[32474]adr property of an [32475]item with the type
[32476]http://microformats.org/profile/hcard.
postal-code (inside [32477]adr)
Gives the postal code component of the delivery address of the
person or organization.
The [32478]value must be text.
A single property with the name [32479]postal-code may be
present within the [32480]item that forms the [32481]value of an
[32482]adr property of an [32483]item with the type
[32484]http://microformats.org/profile/hcard.
country-name (inside [32485]adr)
Gives the country name component of the delivery address of the
person or organization.
The [32486]value must be text.
A single property with the name [32487]country-name may be
present within the [32488]item that forms the [32489]value of an
[32490]adr property of an [32491]item with the type
[32492]http://microformats.org/profile/hcard.
tel
Gives the telephone number of the person or organization.
The [32493]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 [32494]item with zero or more [32495]type
properties and exactly one [32496]value property. [32497][E163]
[32498][X121]
If no [32499]type properties are present within an [32500]item
that forms the [32501]value of a [32502]tel property of an
[32503]item with the type
[32504]http://microformats.org/profile/hcard, or if the
[32505]value of such a [32506]tel property is text, then the
[32507]telephone type string [32508]voice is implied.
Any number of properties with the name [32509]tel may be present
within each [32510]item with the type
[32511]http://microformats.org/profile/hcard.
type (inside [32512]tel)
Gives the type of telephone number.
The [32513]value must be text that is [32514]identical to one of
the [32515]telephone type strings.
Any number of properties with the name [32516]type may be
present within the [32517]item that forms the [32518]value of a
[32519]tel property of an [32520]item with the type
[32521]http://microformats.org/profile/hcard, but within each
such [32522]tel property [32523]item there must only be one
[32524]type property per distinct value.
value (inside [32525]tel)
Gives the actual telephone number of the person or organization.
The [32526]value must be text that can be interpreted as a
telephone number as defined in the CCITT specifications E.163
and X.121. [32527][E163] [32528][X121]
Exactly one property with the name [32529]value must be present
within the [32530]item that forms the [32531]value of a
[32532]tel property of an [32533]item with the type
[32534]http://microformats.org/profile/hcard.
email
Gives the email address of the person or organization.
The [32535]value must be text.
Any number of properties with the name [32536]email may be
present within each [32537]item with the type
[32538]http://microformats.org/profile/hcard.
impp
Gives a [32539]URL for instant messaging and presence protocol
communications with the person or organization.
The [32540]value must be an [32541]absolute URL.
Any number of properties with the name [32542]impp may be
present within each [32543]item with the type
[32544]http://microformats.org/profile/hcard.
lang
Gives a language understood by the person or organization.
The [32545]value must be a valid BCP 47 language tag.
[32546][BCP47]
Any number of properties with the name [32547]lang may be
present within each [32548]item with the type
[32549]http://microformats.org/profile/hcard.
tz
Gives the time zone of the person or organization.
The [32550]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 [32551]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 [32552]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 [32553]tz may be present
within each [32554]item with the type
[32555]http://microformats.org/profile/hcard.
geo
Gives the geographical position of the person or organization.
The [32556]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 [32557]ASCII digits.
3. Optionally*, a U+002E FULL STOP character (.) followed by one
or more [32558]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 [32559]ASCII digits.
7. Optionally*, a U+002E FULL STOP character (.) followed by one
or more [32560]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 [32561]geo may be present
within each [32562]item with the type
[32563]http://microformats.org/profile/hcard.
title
Gives the job title, functional position or function of the
person or organization.
The [32564]value must be text.
Any number of properties with the name [32565]title may be
present within each [32566]item with the type
[32567]http://microformats.org/profile/hcard.
role
Gives the role, occupation, or business category of the person
or organization.
The [32568]value must be text.
Any number of properties with the name [32569]role may be
present within each [32570]item with the type
[32571]http://microformats.org/profile/hcard.
logo
Gives the logo of the person or organization.
The [32572]value must be an [32573]absolute URL.
Any number of properties with the name [32574]logo may be
present within each [32575]item with the type
[32576]http://microformats.org/profile/hcard.
agent
Gives the contact information of another person who will act on
behalf of the person or organization.
The [32577]value must be either an [32578]item with the type
[32579]http://microformats.org/profile/hcard, or an
[32580]absolute URL, or text.
Any number of properties with the name [32581]agent may be
present within each [32582]item with the type
[32583]http://microformats.org/profile/hcard.
org
Gives the name and units of the organization.
The [32584]value must be either text or an [32585]item with one
[32586]organization-name property and zero or more
[32587]organization-unit properties.
Any number of properties with the name [32588]org may be present
within each [32589]item with the type
[32590]http://microformats.org/profile/hcard.
organization-name (inside [32591]org)
Gives the name of the organization.
The [32592]value must be text.
Exactly one property with the name [32593]organization-name must
be present within the [32594]item that forms the [32595]value of
an [32596]org property of an [32597]item with the type
[32598]http://microformats.org/profile/hcard.
organization-unit (inside [32599]org)
Gives the name of the organization unit.
The [32600]value must be text.
Any number of properties with the name [32601]organization-unit
may be present within the [32602]item that forms the
[32603]value of the [32604]org property of an [32605]item with
the type [32606]http://microformats.org/profile/hcard.
member
Gives a [32607]URL that represents a member of the group.
The [32608]value must be an [32609]absolute URL.
Any number of properties with the name [32610]member may be
present within each [32611]item with the type
[32612]http://microformats.org/profile/hcard if the [32613]item
also has a property with the name [32614]kind whose value is
"[32615]group".
related
Gives a relationship to another entity.
The [32616]value must be an [32617]item with one [32618]url
property and one [32619]rel properties.
Any number of properties with the name [32620]related may be
present within each [32621]item with the type
[32622]http://microformats.org/profile/hcard.
url (inside [32623]related)
Gives the [32624]URL for the related entity.
The [32625]value must be an [32626]absolute URL.
Exactly one property with the name [32627]url must be present
within the [32628]item that forms the [32629]value of a
[32630]related property of an [32631]item with the type
[32632]http://microformats.org/profile/hcard.
rel (inside [32633]related)
Gives the relationship between the entity and the related
entity.
The [32634]value must be text that is [32635]identical to one of
the [32636]relationship strings.
Exactly one property with the name [32637]rel must be present
within the [32638]item that forms the [32639]value of a
[32640]related property of an [32641]item with the type
[32642]http://microformats.org/profile/hcard.
categories
Gives the name of a category or tag that the person or
organization could be classified as.
The [32643]value must be text.
Any number of properties with the name [32644]categories may be
present within each [32645]item with the type
[32646]http://microformats.org/profile/hcard.
note
Gives supplemental information or a comment about the person or
organization.
The [32647]value must be text.
Any number of properties with the name [32648]note may be
present within each [32649]item with the type
[32650]http://microformats.org/profile/hcard.
rev
Gives the revision date and time of the contact information.
The [32651]value must be text that is a [32652]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 [32653]rev may be present
within each [32654]item with the type
[32655]http://microformats.org/profile/hcard.
sound
Gives a sound file relating to the person or organization.
The [32656]value must be an [32657]absolute URL.
Any number of properties with the name [32658]sound may be
present within each [32659]item with the type
[32660]http://microformats.org/profile/hcard.
uid
Gives a globally unique identifier corresponding to the person
or organization.
The [32661]value must be text.
A single property with the name [32662]uid may be present within
each [32663]item with the type
[32664]http://microformats.org/profile/hcard.
url
Gives a [32665]URL relating to the person or organization.
The [32666]value must be an [32667]absolute URL.
Any number of properties with the name [32668]url may be present
within each [32669]item with the type
[32670]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).
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 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. [32671][XFN]
5.3.1.1 Conversion to vCard
Given a list of nodes nodes in a [32672]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 [32673]items with the [32674]item
type [32675]http://microformats.org/profile/hcard, then there is no
vCard. Abort the algorithm, returning nothing.
2. Let node be the first node in nodes that is an [32676]item with the
[32677]item type [32678]http://microformats.org/profile/hcard.
3. Let output be an empty string.
4. [32679]Add a vCard line with the type "BEGIN" and the value "VCARD"
to output.
5. [32680]Add a vCard line with the type "PROFILE" and the value
"VCARD" to output.
6. [32681]Add a vCard line with the type "VERSION" and the value "4.0"
to output.
7. [32682]Add a vCard line with the type "SOURCE" and the result of
[32683]escaping the vCard text string that is the document's
[32684]URL as the value to output.
8. If [32685]the title element is not null, [32686]add a vCard line
with the type "NAME" and with the result of [32687]escaping the
vCard text string obtained from [32688]the title element's
[32689]descendant text content 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 [32690]a property of the item
node: for each name name in element's [32691]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 [32692]value is an [32693]item subitem and
name is [32694]n
1. Let value be the empty string.
2. Append to value the result of [32695]collecting the
first vCard subproperty named [32696]family-name in
subitem.
3. Append a U+003B SEMICOLON character (;) to value.
4. Append to value the result of [32697]collecting the
first vCard subproperty named [32698]given-name in
subitem.
5. Append a U+003B SEMICOLON character (;) to value.
6. Append to value the result of [32699]collecting the
first vCard subproperty named [32700]additional-name
in subitem.
7. Append a U+003B SEMICOLON character (;) to value.
8. Append to value the result of [32701]collecting the
first vCard subproperty named
[32702]honorific-prefix in subitem.
9. Append a U+003B SEMICOLON character (;) to value.
10. Append to value the result of [32703]collecting the
first vCard subproperty named
[32704]honorific-suffix in subitem.
If the property's [32705]value is an [32706]item subitem and
name is [32707]adr
1. Let value be the empty string.
2. Append to value the result of [32708]collecting
vCard subproperties named [32709]post-office-box in
subitem.
3. Append a U+003B SEMICOLON character (;) to value.
4. Append to value the result of [32710]collecting
vCard subproperties named [32711]extended-address in
subitem.
5. Append a U+003B SEMICOLON character (;) to value.
6. Append to value the result of [32712]collecting
vCard subproperties named [32713]street-address in
subitem.
7. Append a U+003B SEMICOLON character (;) to value.
8. Append to value the result of [32714]collecting the
first vCard subproperty named [32715]locality in
subitem.
9. Append a U+003B SEMICOLON character (;) to value.
10. Append to value the result of [32716]collecting the
first vCard subproperty named [32717]region in
subitem.
11. Append a U+003B SEMICOLON character (;) to value.
12. Append to value the result of [32718]collecting the
first vCard subproperty named [32719]postal-code in
subitem.
13. Append a U+003B SEMICOLON character (;) to value.
14. Append to value the result of [32720]collecting the
first vCard subproperty named [32721]country-name in
subitem.
15. If there is a property named [32722]type in subitem,
and the first such property has a [32723]value that
is not an [32724]item and whose value consists only
of [32725]ASCII alphanumerics, then add a parameter
named "TYPE" whose value is the [32726]value of that
property to parameters.
If the property's [32727]value is an [32728]item subitem and
name is [32729]org
1. Let value be the empty string.
2. Append to value the result of [32730]collecting the
first vCard subproperty named
[32731]organization-name in subitem.
3. For each property named [32732]organization-unit in
subitem, run the following steps:
1. If the [32733]value of the property is an
[32734]item, then skip this property.
2. Append a U+003B SEMICOLON character (;) to
value.
3. Append the result of [32735]escaping the vCard
text string given by the [32736]value of the
property to value.
If the property's [32737]value is an [32738]item subitem
with the [32739]item type
[32740]http://microformats.org/profile/hcard and
name is [32741]related
1. Let value be the empty string.
2. If there is a property named [32742]url in subitem,
and its element is a [32743]URL property element,
then append the result of [32744]escaping the vCard
text string given by the [32745]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 [32746]rel in subitem,
and the first such property has a [32747]value that
is not an [32748]item and whose value consists only
of [32749]ASCII alphanumerics, then add a parameter
named "RELATION" whose value is the [32750]value of
that property to parameters.
If the property's [32751]value is an [32752]item and name is
none of the above
1. Let value be the result of [32753]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 [32754]value that is
not an [32755]item and whose value consists only of
[32756]ASCII alphanumerics, then add a parameter
named "TYPE" whose value is the [32757]value of that
property to parameters.
If the property's [32758]value is not an [32759]item and its
name is [32760]sex
If this is the first such property to be found, set
sex to the property's [32761]value.
If the property's [32762]value is not an [32763]item and its
name is [32764]gender-identity
If this is the first such property to be found, set
gender-identity to the property's [32765]value.
Otherwise (the property's [32766]value is not an
[32767]item)
1. Let value be the property's [32768]value.
2. If element is one of the [32769]URL property
elements, add a parameter with the name "VALUE" and
the value "URI" to parameters.
3. Otherwise, if name is [32770]bday or
[32771]anniversary and the value is a [32772]valid
date string, add a parameter with the name "VALUE"
and the value "DATE" to parameters.
4. Otherwise, if name is [32773]rev and the value is a
[32774]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 [32775]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. [32776]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, [32777]add a vCard line with the type "GENDER" and the
value consisting of the concatenation of sex, a U+003B SEMICOLON
character (;), and gender-identity to output.
13. [32778]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 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, [32779]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. While line's [32780]code point length is greater than maximum
length:
1. Append the first maximum length code points of line to output.
2. Remove the first maximum length 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:
1. Let value be the empty string.
2. For each property named subname in the item subitem, run the
following substeps:
1. If the [32781]value of the property is itself an [32782]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 [32783]escaping the vCard text string
given by the [32784]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 return
the empty string.
2. If the [32785]value of the first property named subname in subitem
is an [32786]item, then return the empty string.
3. Return the result of [32787]escaping the vCard text string given by
the [32788]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 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
[32789]http://microformats.org/profile/hcard [32790]item type and
[32791]defined property names.
5.3.1.2 Examples
This section is non-normative.
Here is a long example vCard for a fictional character called "Jack
Bauer":
JackBauer
Counter-Terrorist Unit
(Los Angeles Division)
10201 W. Pico Blvd. Los Angeles,
CA90064 United States 34.052339;-118.410623
Update!
My new home phone number is
01632 960 123.
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 [32792]address
element) containing an address with two street components:
AlfredPerson 1600 Amphitheatre Parkway Building 43, Second Floor Mountain View,
CA94043
The vCard vocabulary can be used to just mark up people's names:
GeorgeWashington
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
5.3.2 vEvent
An item with the [32793]item type
http://microformats.org/profile/hcalendar#vevent represents an event.
This vocabulary does not [32794]support global identifiers for items.
The following are the type's [32795]defined property names. They are
based on the vocabulary defined in Internet Calendaring and Scheduling
Core Object Specification (iCalendar), where more information on how to
interpret the values can be found. [32796][RFC5545]
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 [32797]value must be an [32798]absolute URL.
Any number of properties with the name [32799]attach may be
present within each [32800]item with the type
[32801]http://microformats.org/profile/hcalendar#vevent.
categories
Gives the name of a category or tag that the event could be
classified as.
The [32802]value must be text.
Any number of properties with the name [32803]categories may be
present within each [32804]item with the type
[32805]http://microformats.org/profile/hcalendar#vevent.
class
Gives the access classification of the information regarding the
event.
The [32806]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 [32807]class may be present
within each [32808]item with the type
[32809]http://microformats.org/profile/hcalendar#vevent.
comment
Gives a comment regarding the event.
The [32810]value must be text.
Any number of properties with the name [32811]comment may be
present within each [32812]item with the type
[32813]http://microformats.org/profile/hcalendar#vevent.
description
Gives a detailed description of the event.
The [32814]value must be text.
A single property with the name [32815]description may be
present within each [32816]item with the type
[32817]http://microformats.org/profile/hcalendar#vevent.
geo
Gives the geographical position of the event.
The [32818]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 [32819]ASCII digits.
3. Optionally*, a U+002E FULL STOP character (.) followed by one
or more [32820]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 [32821]ASCII digits.
7. Optionally*, a U+002E FULL STOP character (.) followed by one
or more [32822]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.
A single property with the name [32823]geo may be present within
each [32824]item with the type
[32825]http://microformats.org/profile/hcalendar#vevent.
location
Gives the location of the event.
The [32826]value must be text.
A single property with the name [32827]location may be present
within each [32828]item with the type
[32829]http://microformats.org/profile/hcalendar#vevent.
resources
Gives a resource that will be needed for the event.
The [32830]value must be text.
Any number of properties with the name [32831]resources may be
present within each [32832]item with the type
[32833]http://microformats.org/profile/hcalendar#vevent.
status
Gives the confirmation status of the event.
The [32834]value must be text with one of the following values:
+ tentative
+ confirmed
+ canceled
A single property with the name [32835]status may be present
within each [32836]item with the type
[32837]http://microformats.org/profile/hcalendar#vevent.
summary
Gives a short summary of the event.
The [32838]value must be text.
User agents should replace U+000A LINE FEED (LF) characters in
the [32839]value by U+0020 SPACE characters when using the
value.
A single property with the name [32840]summary may be present
within each [32841]item with the type
[32842]http://microformats.org/profile/hcalendar#vevent.
dtend
Gives the date and time by which the event ends.
If the property with the name [32843]dtend is present within an
[32844]item with the type
[32845]http://microformats.org/profile/hcalendar#vevent that has
a property with the name [32846]dtstart whose value is a
[32847]valid date string, then the [32848]value of the property
with the name [32849]dtend must be text that is a [32850]valid
date string also. Otherwise, the [32851]value of the property
must be text that is a [32852]valid global date and time string.
In either case, the [32853]value be later in time than the value
of the [32854]dtstart property of the same [32855]item.
The time given by the [32856]dtend property is not inclusive.
For day-long events, therefore, the [32857]dtend property's
[32858]value will be the day after the end of the event.
A single property with the name [32859]dtend may be present
within each [32860]item with the type
[32861]http://microformats.org/profile/hcalendar#vevent, so long
as that [32862]http://microformats.org/profile/hcalendar#vevent
does not have a property with the name [32863]duration.
dtstart
Gives the date and time at which the event starts.
The [32864]value must be text that is either a [32865]valid date
string or a [32866]valid global date and time string.
Exactly one property with the name [32867]dtstart must be
present within each [32868]item with the type
[32869]http://microformats.org/profile/hcalendar#vevent.
duration
Gives the duration of the event.
The [32870]value must be text that is a [32871]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 [32872]duration may be present
within each [32873]item with the type
[32874]http://microformats.org/profile/hcalendar#vevent, so long
as that [32875]http://microformats.org/profile/hcalendar#vevent
does not have a property with the name [32876]dtend.
transp
Gives whether the event is to be considered as consuming time on
a calendar, for the purpose of free-busy time searches.
The [32877]value must be text with one of the following values:
+ opaque
+ transparent
A single property with the name [32878]transp may be present
within each [32879]item with the type
[32880]http://microformats.org/profile/hcalendar#vevent.
contact
Gives the contact information for the event.
The [32881]value must be text.
Any number of properties with the name [32882]contact may be
present within each [32883]item with the type
[32884]http://microformats.org/profile/hcalendar#vevent.
url
Gives a [32885]URL for the event.
The [32886]value must be an [32887]absolute URL.
A single property with the name [32888]url may be present within
each [32889]item with the type
[32890]http://microformats.org/profile/hcalendar#vevent.
uid
Gives a globally unique identifier corresponding to the event.
The [32891]value must be text.
A single property with the name [32892]uid may be present within
each [32893]item with the type
[32894]http://microformats.org/profile/hcalendar#vevent.
exdate
Gives a date and time at which the event does not occur despite
the recurrence rules.
The [32895]value must be text that is either a [32896]valid date
string or a [32897]valid global date and time string.
Any number of properties with the name [32898]exdate may be
present within each [32899]item with the type
[32900]http://microformats.org/profile/hcalendar#vevent.
rdate
Gives a date and time at which the event recurs.
The [32901]value must be text that is one of the following:
+ A [32902]valid date string.
+ A [32903]valid global date and time string.
+ A [32904]valid global date and time string followed by a
U+002F SOLIDUS character (/) followed by a second [32905]valid
global date and time string representing a later time.
+ A [32906]valid global date and time string followed by a
U+002F SOLIDUS character (/) followed by a [32907]valid vevent
duration string.
Any number of properties with the name [32908]rdate may be
present within each [32909]item with the type
[32910]http://microformats.org/profile/hcalendar#vevent.
rrule
Gives a rule for finding dates and times at which the event
occurs.
The [32911]value must be text that matches the RECUR value type
defined in iCalendar. [32912][RFC5545]
A single property with the name [32913]rrule may be present
within each [32914]item with the type
[32915]http://microformats.org/profile/hcalendar#vevent.
created
Gives the date and time at which the event information was first
created in a calendaring system.
The [32916]value must be text that is a [32917]valid global date
and time string.
A single property with the name [32918]created may be present
within each [32919]item with the type
[32920]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 [32921]value must be text that is a [32922]valid global date
and time string.
A single property with the name [32923]last-modified may be
present within each [32924]item with the type
[32925]http://microformats.org/profile/hcalendar#vevent.
sequence
Gives a revision number for the event information.
The [32926]value must be text that is a [32927]valid
non-negative integer.
A single property with the name [32928]sequence may be present
within each [32929]item with the type
[32930]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 [32931]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:
1. A [32932]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.
2. 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:
1. A [32933]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.
2. A [32934]valid non-negative integer followed by a
U+004D LATIN CAPITAL LETTER M character (M). The
integer represents a duration of that number of
minutes.
3. A [32935]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.
5.3.2.1 Conversion to iCalendar
Given a list of nodes nodes in a [32936]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 [32937]items with the type
[32938]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. [32939]Add an iCalendar line with the type "BEGIN" and the value
"VCALENDAR" to output.
4. [32940]Add an iCalendar line with the type "PRODID" and the value
equal to a user-agent-specific string representing the user agent
to output.
5. [32941]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 [32942]item with the type
[32943]http://microformats.org/profile/hcalendar#vevent, run the
following steps:
1. [32944]Add an iCalendar line with the type "BEGIN" and the
value "VEVENT" to output.
2. [32945]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. [32946][RFC5545]
3. For each element element that is [32947]a property of the item
node: for each name name in element's [32948]property names,
run the appropriate set of substeps from the following list:
If the property's [32949]value is an [32950]item
Skip the property.
If the property is [32951]dtend
If the property is [32952]dtstart
If the property is [32953]exdate
If the property is [32954]rdate
If the property is [32955]created
If the property is [32956]last-modified
Let value be the result of stripping all U+002D
HYPHEN-MINUS (-) and U+003A COLON (:) characters
from the property's [32957]value.
If the property's [32958]value is a [32959]valid
date string then [32960]add an iCalendar line with
the type name and the value value to output, with
the annotation "VALUE=DATE".
Otherwise, if the property's [32961]value is a
[32962]valid global date and time string then
[32963]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
[32964]Add an iCalendar line with the type name and
the property's [32965]value to output.
4. [32966]Add an iCalendar line with the type "END" and the value
"VEVENT" to output.
7. [32967]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, [32968]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 (\).
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. While line's [32969]code point length is greater than maximum
length:
1. Append the first maximum length code points of line to output.
2. Remove the first maximum length 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
[32970]http://microformats.org/profile/hcalendar#vevent [32971]item
type and [32972]defined property names.
5.3.2.2 Examples
This section is non-normative.
Here is an example of a page that uses the vEvent vocabulary to mark up
an event:
An item with the [32973]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 [32974]defined property names.
work
Identifies the work being described.
The [32975]value must be an [32976]absolute URL.
Exactly one property with the name [32977]work must be present
within each [32978]item with the type
[32979]http://n.whatwg.org/work.
title
Gives the name of the work.
A single property with the name [32980]title may be present
within each [32981]item with the type
[32982]http://n.whatwg.org/work.
author
Gives the name or contact information of one of the authors or
creators of the work.
The [32983]value must be either an [32984]item with the type
[32985]http://microformats.org/profile/hcard, or text.
Any number of properties with the name [32986]author may be
present within each [32987]item with the type
[32988]http://n.whatwg.org/work.
license
Identifies one of the licenses under which the work is
available.
The [32989]value must be an [32990]absolute URL.
Any number of properties with the name [32991]license may be
present within each [32992]item with the type
[32993]http://n.whatwg.org/work.
5.3.3.1 Examples
This section is non-normative.
This example shows an embedded image entitled My Pond, licensed under
the Creative Commons Attribution-Share Alike 4.0 International License
and the MIT license simultaneously.
Given a list of nodes nodes in a [32994]Document, a user agent must run
the following algorithm to extract the microdata from those nodes into
a JSON form:
1. Let result be an empty object.
2. Let items be an empty array.
3. For each node in nodes, check if the element is a [32995]top-level
microdata item, and if it is then [32996]get the object for that
element and add it to items.
4. Add an entry to result called "items" whose value is the array
items.
5. Return the result of serializing result to JSON in the shortest
possible way (meaning no whitespace between tokens, no unnecessary
zero digits in numbers, and only using Unicode escapes in strings
for characters that do not have a dedicated escape sequence), and
with a lowercase "e" used, when appropriate, in the representation
of any numbers. [32997][JSON]
This algorithm returns an object with a single property that is an
array, instead of just returning an array, so that it is possible to
extend the algorithm in the future if necessary.
When the user agent is to get the object for an item item, optionally
with a list of elements memory, it must run the following substeps:
1. Let result be an empty object.
2. If no memory was passed to the algorithm, let memory be an empty
list.
3. Add item to memory.
4. If the item has any [32998]item types, add an entry to result
called "type" whose value is an array listing the [32999]item types
of item, in the order they were specified on the [33000]itemtype
attribute.
5. If the item has a [33001]global identifier, add an entry to result
called "id" whose value is the [33002]global identifier of item.
6. Let properties be an empty object.
7. For each element element that has one or more [33003]property names
and is one of [33004]the properties of the item item, in the order
those elements are given by the algorithm that returns [33005]the
properties of an item, run the following substeps:
1. Let value be the [33006]property value of element.
2. If value is an [33007]item, then: If value is in memory, then
let value be the string "ERROR". Otherwise, [33008]get the
object for value, passing a copy of memory, and then replace
value with the object returned from those steps.
3. For each name name in element's [33009]property names, run the
following substeps:
1. If there is no entry named name in properties, then add
an entry named name to properties whose value is an empty
array.
2. Append value to the entry named name in properties.
8. Add an entry to result called "properties" whose value is the
object properties.
9. Return result.
For example, take this markup:
My Blog
Progress report
All in all, heʼs doing well with his swim lessons. The biggest thing was he
had trouble
putting his head in, but we got it down.
All [33013]HTML elements may have the hidden content attribute set. The
[33014]hidden attribute is an [33015]enumerated attribute with the
following keywords and states:
Keyword State Brief description
hidden hidden Will not be rendered.
(the empty string)
until-found hidden until found Will not be rendered, but content inside
will be accessible to [33016]find-in-page and [33017]fragment
navigation.
The attribute's [33018]missing value default is the not hidden state,
and its [33019]invalid value default is the [33020]hidden state.
When an element has the [33021]hidden attribute in the [33022]hidden
state, 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 parts of the page as opposed
to being directly accessed by the user. User agents should not render
elements that are in the [33023]hidden state.
The requirement for user agents not to render elements that are in the
[33024]hidden state can be implemented indirectly through the style
layer. For example, a web browser could implement these requirements
[33025]using the rules suggested in the Rendering section.
When an element has the [33026]hidden attribute in the [33027]hidden
until found state, it indicates that the element is hidden like the
[33028]hidden state but the content inside the element will be
accessible to [33029]find-in-page and [33030]fragment navigation. When
these features attempt to scroll to a target which is in the element's
subtree, the user agent will remove the [33031]hidden attribute in
order to reveal the content before scrolling to it by running the
[33032]ancestor hidden-until-found revealing algorithm on the target
node.
Web browsers will use 'content-visibility: hidden' instead of 'display:
none' when the [33033]hidden attribute is in the [33034]hidden until
found state, as specified in the [33035]Rendering section.
Because this attribute is typically implemented using CSS, it's also
possible to override it using CSS. For instance, a rule that applies
'display: block' to all elements will cancel the effects of the
[33036]hidden state. Authors therefore have to take care when writing
their style sheets to make sure that the attribute is still styled as
expected. In addition, legacy user agents which don't support the
[33037]hidden until found state will have 'display: none' instead of
'content-visibility: hidden', so authors are encouraged to make sure
that their style sheets don't change the 'display' or
'content-visibility' properties of [33038]hidden until found elements.
Since elements with the [33039]hidden attribute in the [33040]hidden
until found state use 'content-visibility: hidden' instead of 'display:
none', there are two caveats of the [33041]hidden until found state
that make it different from the [33042]hidden state:
1. The element needs to be affected by [33043]layout containment in
order to be revealed by find-in-page. This means that if the
element in the [33044]hidden until found state has a 'display'
value of 'none', 'contents', or 'inline', then the element will not
be revealed by find-in-page.
2. The element will still have a [33045]generated box when in the
[33046]hidden until found state, which means that borders, margin,
and padding will still be rendered around the element.
In the following skeletal example, the attribute is used to hide the
web game's main screen until the user logs in:
The Example Game
Login
...
The [33047]hidden attribute must not be used to hide content that could
legitimately be shown in another presentation. For example, it is
incorrect to use [33048]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
[33049]hidden, it is hidden from all presentations, including, for
instance, screen readers.
Elements that are not themselves [33050]hidden must not
[33051]hyperlink to elements that are [33052]hidden. The for attributes
of [33053]label and [33054]output elements that are not themselves
[33055]hidden must similarly not refer to elements that are
[33056]hidden. In both cases, such references would cause user
confusion.
Elements and scripts may, however, refer to elements that are
[33057]hidden in other contexts.
For example, it would be incorrect to use the [33058]href attribute to
link to a section marked with the [33059]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 [33060]aria-describedby
attribute to refer to descriptions that are themselves [33061]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 elements that they
describe.
Similarly, a [33062]canvas element with the [33063]hidden attribute
could be used by a scripted graphics engine as an off-screen buffer,
and a form control could refer to a hidden [33064]form element using
its [33065]form attribute.
Elements in a section hidden by the [33066]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.
(BUTTON) ✔MDN
[33067]HTMLElement/hidden
Support in all current engines.
Firefox4+Safari5.1+Chrome6+
__________________________________________________________________
The hidden getter steps are:
1. If the [33068]hidden attribute is in the [33069]hidden until found
state, then return "[33070]until-found".
2. If the [33071]hidden attribute is set, then return true.
3. Return false.
The [33072]hidden setter steps are:
1. If the given value is a string that is an [33073]ASCII
case-insensitive match for "[33074]until-found", then set the
[33075]hidden attribute to "[33076]until-found".
2. Otherwise, if the given value is false, then remove the
[33077]hidden attribute.
3. Otherwise, if the given value is the empty string, then remove the
[33078]hidden attribute.
4. Otherwise, if the given value is null, then remove the
[33079]hidden attribute.
5. Otherwise, if the given value is 0, then remove the [33080]hidden
attribute.
6. Otherwise, if the given value is NaN, then remove the [33081]hidden
attribute.
7. Otherwise, set the [33082]hidden attribute to the empty string.
The ancestor hidden-until-found revealing algorithm is to run the
following steps on currentNode:
1. While currentNode has a parent node within the [33083]flat tree:
1. If currentNode has the [33084]hidden attribute in the
[33085]hidden until found state, then:
1. [33086]Fire an event named [33087]beforematch at
currentNode with the [33088]bubbles attribute initialized
to true.
2. Remove the [33089]hidden attribute from currentNode.
2. Set currentNode to the parent node of currentNode within the
[33090]flat tree.
6.2 Page visibility
A [33091]traversable navigable's [33092]system visibility state,
including its initial value upon creation, is determined by the user
agent. It represents, for example, whether the browser window is
minimized, a browser tab is currently in the background, or a system
element such as a task switcher obscures the page.
When a user-agent determines that the [33093]system visibility state
for [33094]traversable navigable traversable has changed to newState,
it must run the following steps:
1. Let navigables be the [33095]inclusive descendant navigables of
traversable's [33096]active document.
2. [33097]For each navigable of navigables in what order?:
1. Let document be navigable's [33098]active document.
2. [33099]Queue a global task on the [33100]user interaction task
source given document's [33101]relevant global object to
[33102]update the visibility state of document with newState.
A [33103]Document has a visibility state, which is either "hidden" or
"visible", initially set to "hidden".
(BUTTON) ✔MDN
[33104]Document/visibilityState
Support in all current engines.
Firefox18+Safari7+Chrome33+
__________________________________________________________________
The hidden getter steps are to return true if [33108]this's
[33109]visibility state is "hidden", otherwise false.
To update the visibility state of [33110]Document document to
visibilityState:
1. If document's [33111]visibility state equals visibilityState, then
return.
2. Set document's [33112]visibility state to visibilityState.
3. [33113]Queue a new [33114]VisibilityStateEntry whose
[33115]visibility state is visibilityState and whose
[33116]timestamp is the [33117]current high resolution time given
document's [33118]relevant global object.
4. Run the [33119]screen orientation change steps with document.
[33120][SCREENORIENTATION]
5. Run the [33121]view transition page visibility change steps with
document.
6. Run any page visibility change steps which may be defined in other
specifications, with [33122]visibility state and document.
It would be better if specification authors sent a pull request to
add calls from here into their specifications directly, instead of
using the [33123]page visibility change steps hook, to ensure
well-defined cross-specification call order. As of the time of this
writing the following specifications are known to have [33124]page
visibility change steps, which will be run in an unspecified order:
Device Posture API and Web NFC. [33125][DEVICEPOSTURE]
[33126][WEBNFC]
7. [33127]Fire an event named [33128]visibilitychange at document,
with its [33129]bubbles attribute initialized to true.
6.2.1 The [33130]VisibilityStateEntry interface
(BUTTON) ⚠MDN
[33131]VisibilityStateEntry
Support in one engine only.
FirefoxNoSafariNoChrome115+
__________________________________________________________________
The [33132]VisibilityStateEntry interface exposes visibility changes to
the document, from the moment the document becomes active.
For example, this allows JavaScript code in the page to examine
correlation between visibility changes and paint timing:
function wasHiddenBeforeFirstContentfulPaint() {
const fcpEntry = performance.getEntriesByName("first-contentful-paint")[0];
const visibilityStateEntries = performance.getEntriesByType("visibility-stat
e");
return visibilityStateEntries.some(e =>
e.startTime < fcpEntry.startTime &&
e.name === "hidden");
}
Since hiding a page can cause throttling of rendering and other
user-agent operations, it is common to use visibility changes as an
indication that such throttling has occurred. However, other things
could also cause throttling in different browsers, such as long periods
of inactivity.
[Exposed=(Window)]
interface VisibilityStateEntry : [33133]PerformanceEntry {
readonly attribute DOMString [33134]name; // shadows inherited
[33135]name
readonly attribute DOMString [33136]entryType; // shadows inherited
[33137]entryType
readonly attribute DOMHighResTimeStamp [33138]startTime; // shadows inherited
[33139]startTime
readonly attribute unsigned long [33140]duration; // shadows inherited
[33141]duration
};
The [33142]VisibilityStateEntry has an associated
[33143]DOMHighResTimeStamp timestamp.
The [33144]VisibilityStateEntry has an associated "visible" or "hidden"
visibility state.
The name getter steps are to return [33145]this's [33146]visibility
state.
The entryType getter steps are to return "visibility-state".
The startTime getter steps are to return [33147]this's
[33148]timestamp.
The duration getter steps are to return zero.
6.3 Inert subtrees
See also [33149]inert for an explanation of the attribute of the same
name.
A node (in particular elements and text nodes) can be inert. When a
node is [33150]inert:
* Hit-testing must act as if the [33151]'pointer-events' CSS property
were set to 'none'.
* Text selection functionality must act as if the
[33152]'user-select' CSS property were set to 'none'.
* If it is [33153]editable, the node behaves as if it were
non-editable.
* The user agent should ignore the node for the purposes of
[33154]find-in-page.
Inert nodes generally cannot be focused, and user agents do not expose
the inert nodes to accessibility APIs or assistive technologies. Inert
nodes that are [33155]commands will become inoperable to users, in the
manner described above.
User agents may allow the user to override the restrictions on
[33156]find-in-page and text selection, however.
By default, a node is not [33157]inert.
6.3.1 Modal dialogs and inert subtrees
A [33158]Document document is blocked by a modal dialog subject if
subject is the topmost [33159]dialog element in document's [33160]top
layer. While document is so blocked, every node that is
[33161]connected to document, with the exception of the subject element
and its [33162]flat tree descendants, must become [33163]inert.
subject can additionally become [33164]inert via the [33165]inert
attribute, but only if specified on subject itself (i.e., subject
escapes inertness of ancestors); subject's [33166]flat tree descendants
can become [33167]inert in a similar fashion.
The [33168]dialog element's [33169]showModal() method causes this
mechanism to trigger, by [33170]adding the [33171]dialog element to its
[33172]node document's [33173]top layer.
6.3.2 The inert attribute
(BUTTON) ✔MDN
[33174]Global_attributes/inert
Support in all current engines.
Firefox112+Safari15.5+Chrome102+
__________________________________________________________________
The [33175]inert attribute is a [33176]boolean attribute that
indicates, by its presence, that the element and all its [33177]flat
tree descendants which don't otherwise escape inertness (such as modal
dialogs) are to be made [33178]inert by the user agent.
An inert subtree should not contain any content or controls which are
critical to understanding or using aspects of the page which are not in
the inert state. Content in an inert subtree will not be perceivable by
all users, or interactive. Authors should not specify elements as inert
unless the content they represent are also visually obscured in some
way. In most cases, authors should not specify the [33179]inert
attribute on individual form controls. In these instances, the
[33180]disabled attribute is probably more appropriate.
The following example shows how to mark partially loaded content,
visually obscured by a "loading" message, as inert.
Population by City
Loading...
From 20-- to 20--
City
State
20-- Population
20-- Population
Percentage change
Screenshot of Population by City content with an overlaid loading
message which visually obscures the form controls and data table which
have not fully rendered, and thus are in the inert state.
The "loading" overlay obscures the inert content, making it visually
apparent that the inert content is not presently accessible. Notice
that the heading and "loading" text are not descendants of the element
with the [33181]inert attribute. This will ensure this text is
accessible to all users, while the inert content cannot be interacted
with by anyone.
By default, there is no persistent visual indication of an element or
its subtree being inert. Appropriate visual styles for such content is
often context-dependent. For instance, an inert off-screen navigation
panel would not require a default style, as its off-screen position
visually obscures the content. Similarly, a modal [33182]dialog
element's backdrop will serve as the means to visually obscure the
inert content of the web page, rather than styling the inert content
specifically.
However, for many other situations authors are strongly 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 using particularly small windows might not be able to see
the active part of a page and might get frustrated if inert sections
are not obviously inert.
(BUTTON) ✔MDN
[33183]HTMLElement/inert
Support in all current engines.
Firefox112+Safari15.5+Chrome102+
__________________________________________________________________
The inert IDL attribute must [33184]reflect the content attribute of
the same name.
6.4 Tracking user activation
To prevent abuse of certain APIs that could be annoying to users (e.g.,
opening popups or vibrating phones), user agents allow these APIs only
when the user is actively interacting with the web page or has
interacted with the page at least once. This "active interaction" state
is maintained through the mechanisms defined in this section.
6.4.1 Data model
For the purpose of tracking user activation, each [33185]Window W has
two relevant values:
* A last activation timestamp, which is either a
[33186]DOMHighResTimeStamp, positive infinity (indicating that W
has never been activated), or negative infinity (indicating that
the activation has been [33187]consumed). Initially positive
infinity.
* A last history-action activation timestamp, which is either a
[33188]DOMHighResTimeStamp or positive infinity, initially positive
infinity.
A user agent also defines a transient activation duration, which is a
constant number indicating how long a user activation is available for
certain [33189]user activation-gated APIs (e.g., for opening popups).
The [33190]transient activation duration is expected be at most a few
seconds, so that the user can possibly perceive the link between an
interaction with the page and the page calling the activation-gated
API.
We then have the following boolean user activation states for W:
Sticky activation
When the [33191]current high resolution time given W is greater
than or equal to the [33192]last activation timestamp in W, W is
said to have [33193]sticky activation.
This is W's historical activation state, indicating whether the
user has ever interacted in W. It starts false, then changes to
true (and never changes back to false) when W gets the very
first [33194]activation notification.
Transient activation
When the [33195]current high resolution time given W is greater
than or equal to the [33196]last activation timestamp in W, and
less than the [33197]last activation timestamp in W plus the
[33198]transient activation duration, then W is said to have
[33199]transient activation.
This is W's current activation state, indicating whether the
user has interacted in W recently. This starts with a false
value, and remains true for a limited time after every
[33200]activation notification W gets.
The [33201]transient activation state is considered expired if
it becomes false because the [33202]transient activation
duration time has elapsed since the last user activation. Note
that it can become false even before the expiry time through an
[33203]activation consumption.
History-action activation
When the [33204]last history-action activation timestamp of W is
not equal to the [33205]last activation timestamp of W, then W
is said to have [33206]history-action activation.
This is a special variant of user activation, used to allow
access to certain session history APIs which, if used too
frequently, would make it harder for the user to traverse back
using [33207]browser UI. It starts with a false value, and
becomes true whenever the user interacts with W, but is reset to
false through [33208]history-action activation consumption. This
ensures such APIs cannot be used multiple times in a row without
an intervening user activation. But unlike [33209]transient
activation, there is no time limit within which such APIs must
be used.
The [33210]last activation timestamp and [33211]last history-action
activation timestamp are retained even after the [33212]Document
changes its [33213]fully active status (e.g., after navigating away
from a [33214]Document, or navigating to a cached [33215]Document).
This means [33216]sticky activation state spans multiple navigations as
long as the same [33217]Document gets reused. For the transient
activation state, the original [33218]expiry time remains unchanged
(i.e., the state still expires within the [33219]transient activation
duration limit from the original [33220]activation triggering input
event). It is important to consider this when deciding whether to base
certain things off [33221]sticky activation or [33222]transient
activation.
6.4.2 Processing model
When a user interaction causes firing of an [33223]activation
triggering input event in a [33224]Document document, the user agent
must perform the following activation notification steps before
[33225]dispatching the event:
1. [33226]Assert: document is [33227]fully active.
2. Let windows be « document's [33228]relevant global object ».
3. [33229]Extend windows with the [33230]active window of each of
document's [33231]ancestor navigables.
4. [33232]Extend windows with the [33233]active window of each of
document's [33234]descendant navigables, filtered to include only
those [33235]navigables whose [33236]active document's
[33237]origin is [33238]same origin with document's [33239]origin.
5. [33240]For each window in windows:
1. Set window's [33241]last activation timestamp to the
[33242]current high resolution time.
2. [33243]Notify the close watcher manager about user activation
given window.
An activation triggering input event is any event whose
[33244]isTrusted attribute is true and whose [33245]type is one of:
* "[33246]keydown", provided the key is neither the Esc key nor a
shortcut key reserved by the user agent;
* "[33247]mousedown";
* "[33248]pointerdown", provided the event's [33249]pointerType is
"mouse";
* "[33250]pointerup", provided the event's [33251]pointerType is not
"mouse"; or
* "[33252]touchend".
[33253]Activation consuming APIs defined in this and other
specifications can consume user activation by performing the following
steps, given a [33254]Window W:
1. If W's [33255]navigable is null, then return.
2. Let top be W's [33256]navigable's [33257]top-level traversable.
3. Let navigables be the [33258]inclusive descendant navigables of
top's [33259]active document.
4. Let windows be the list of [33260]Window objects constructed by
taking the [33261]active window of each item in navigables.
5. [33262]For each window in windows, if window's [33263]last
activation timestamp is not positive infinity, then set window's
[33264]last activation timestamp to negative infinity.
[33265]History-action activation-consuming APIs can consume
history-action user activation by performing the following steps, given
a [33266]Window W:
1. If W's [33267]navigable is null, then return.
2. Let top be W's [33268]navigable's [33269]top-level traversable.
3. Let navigables be the [33270]inclusive descendant navigables of
top's [33271]active document.
4. Let windows be the list of [33272]Window objects constructed by
taking the [33273]active window of each item in navigables.
5. [33274]For each window in windows, set window's [33275]last
history-action activation timestamp to window's [33276]last
activation timestamp.
Note the asymmetry in the sets of [33277]browsing contexts in the page
that are affected by an [33278]activation notification vs an
[33279]activation consumption: an activation consumption changes (to
false) the [33280]transient activation states for all browsing contexts
in the page, but an activation notification changes (to true) the
states for a subset of those browsing contexts. The exhaustive nature
of consumption here is deliberate: it prevents malicious sites from
making multiple calls to an [33281]activation consuming API from a
single user activation (possibly by exploiting a deep hierarchy of
[33282]iframes).
6.4.3 APIs gated by user activation
APIs that are dependent on user activation are classified into
different levels:
Sticky activation-gated APIs
These APIs require the [33283]sticky activation state to be
true, so they are blocked until the very first user activation.
Transient activation-gated APIs
These APIs require the [33284]transient activation state to be
true, but they don't [33285]consume it, so multiple calls are
allowed per user activation until the transient state
[33286]expires.
Transient activation-consuming APIs
These APIs require the [33287]transient activation state to be
true, and they [33288]consume user activation in each call to
prevent multiple calls per user activation.
History-action activation-consuming APIs
These APIs require the [33289]history-action activation state to
be true, and they [33290]consume history-action user activation
in each call to prevent multiple calls per user activation.
Each [33293]Window has an associated UserActivation, which is a
[33294]UserActivation object. Upon creation of the [33295]Window
object, its [33296]associated UserActivation must be set to a
[33297]new [33298]UserActivation object created in the [33299]Window
object's [33300]relevant realm.
[Exposed=Window]
interface UserActivation {
readonly attribute boolean [33301]hasBeenActive;
readonly attribute boolean [33302]isActive;
};
The isActive getter steps are to return true if [33323]this's
[33324]relevant global object has [33325]transient activation, and
false otherwise.
6.4.5 User agent automation
For the purposes of user-agent automation and application testing, this
specification defines the following [33326]extension command for the
Web Driver specification. It is optional for a user agent to support
the following [33327]extension command. [33328][WEBDRIVER]
HTTP Method URI Template
`POST` /session/{session id}/window/consume-user-activation
The [33329]remote end steps are:
1. Let window be [33330]current browsing context's [33331]active
window.
2. Let consume be true if window has [33332]transient activation;
otherwise false.
3. If consume is true, then [33333]consume user activation of window.
4. Return [33334]success with data consume.
6.5 Activation behavior of elements
Certain elements in HTML have an [33335]activation behavior, which
means that the user can activate them. This is always caused by a
[33336]click event.
The user agent should allow the user to manually trigger elements that
have an [33337]activation behavior, for instance using keyboard or
voice input, or through mouse clicks. When the user triggers an element
with a defined [33338]activation behavior in a manner other than
clicking it, the default action of the interaction event must be to
[33339]fire a click event at the element.
Firefox Android4+Safari iOS?Chrome Android?WebView
Android4.4+Samsung Internet1.0+Opera Android11+
Acts as if the element was clicked.
Each element has an associated click in progress flag, which is
initially unset.
The click() method must run the following steps:
1. If this element is a form control that is [33342]disabled, then
return.
2. If this element's [33343]click in progress flag is set, then
return.
3. Set this element's [33344]click in progress flag.
4. [33345]Fire a synthetic pointer event named [33346]click at this
element, with the not trusted flag set.
5. Unset this element's [33347]click in progress flag.
6.5.1 The [33348]ToggleEvent interface
(BUTTON) ✔MDN
[33349]ToggleEvent/ToggleEvent
Support in all current engines.
Firefox🔰 114+Safari17+Chrome114+
__________________________________________________________________
event.[33371]command
Returns what action the element can take.
event.[33372]source
Returns the [33373]Element that was interacted with in order to
cause this event.
The command attribute must return the value it was initialized to.
The source getter steps are to return the result of [33374]retargeting
[33375]source against [33376]this's [33377]currentTarget.
[33378]DOM standard issue #1328 tracks how to better standardize
associated event data in a way which makes sense on Events. Currently
an event attribute initialized to a value cannot also have a getter,
and so an internal slot (or map of additional fields) is required to
properly specify this.
6.6 Focus
6.6.1 Introduction
This section is non-normative.
An HTML user interface typically consists of multiple interactive
widgets, such as form controls, scrollable regions, links, dialog
boxes, browser tabs, and so forth. These widgets form a hierarchy, with
some (e.g. browser tabs, dialog boxes) containing others (e.g. links,
form controls).
When interacting with an interface using a keyboard, key input is
channeled from the system, through the hierarchy of interactive
widgets, to an active widget, which is said to be [33379]focused.
Consider an HTML application running in a browser tab running in a
graphical environment. Suppose this application had a page with some
text controls and links, and was currently showing a modal dialog,
which itself had a text control and a button.
The hierarchy of focusable widgets, in this scenario, would include the
browser window, which would have, amongst its children, the browser tab
containing the HTML application. The tab itself would have as its
children the various links and text controls, as well as the dialog.
The dialog itself would have as its children the text control and the
button.
If the widget with [33380]focus in this example was the text control in
the dialog box, then key input would be channeled from the graphical
system to ① the web browser, then to ② the tab, then to ③ the dialog,
and finally to ④ the text control.
Keyboard events are always targeted at this [33381]focused element.
6.6.2 Data model
A [33382]top-level traversable has system focus when it can receive
keyboard input channeled from the operating system, possibly targeted
at one of its [33383]active document's [33384]descendant navigables.
A [33385]top-level traversable has user attention when its
[33386]system visibility state is "visible", and it either has
[33387]system focus or user agent widgets directly related to it can
receive keyboard input channeled from the operating system.
User attention is lost when a browser window loses focus, whereas
system focus might also be lost to other system widgets in the browser
window such as a location bar.
A [33388]Document d is a fully active descendant of a top-level
traversable with user attention when d is [33389]fully active and d's
[33390]node navigable's [33391]top-level traversable has [33392]user
attention.
The term focusable area is used to refer to regions of the interface
that can further become the target of such keyboard input. Focusable
areas can be elements, parts of elements, or other regions managed by
the user agent.
Each [33393]focusable area has a DOM anchor, which is a [33394]Node
object that represents the position of the [33395]focusable area in the
DOM. (When the [33396]focusable area is itself a [33397]Node, it is its
own [33398]DOM anchor.) The [33399]DOM anchor is used in some APIs as a
substitute for the [33400]focusable area when there is no other DOM
object to represent the [33401]focusable area.
The following table describes what objects can be [33402]focusable
areas. The cells in the left column describe objects that can be
[33403]focusable areas; the cells in the right column describe the
[33404]DOM anchors for those elements. (The cells that span both
columns are non-normative examples.)
[33405]Focusable area [33406]DOM anchor
Examples
Elements that meet all the following criteria:
* the element's [33407]tabindex value is non-null, or the element is
determined by the user agent to be focusable;
* the element is either not a [33408]shadow host, or has a
[33409]shadow root whose [33410]delegates focus is false;
* the element is not [33411]actually disabled;
* the element is not [33412]inert;
* the element is either [33413]being rendered, [33414]delegating its
rendering to its children, or [33415]being used as relevant canvas
fallback content.
In the following example, the [33426]area element creates two shapes,
one on each image. The [33427]DOM anchor of the first shape is the
first [33428]img element, and the [33429]DOM anchor of the second shape
is the second [33430]img element.
The user-agent provided subwidgets of elements that are [33431]being
rendered and are not [33432]actually disabled or [33433]inert. The
element for which the [33434]focusable area is a subwidget.
The [33435]controls in the user interface for a [33436]video element,
the up and down buttons in a spin-control version of [33437], the part of a [33438]details element's rendering that
enables the element to be opened or closed using keyboard input.
The scrollable regions of elements that are [33439]being rendered and
are not [33440]inert. The element for which the box that the scrollable
region scrolls was created.
The CSS [33441]'overflow' property's 'scroll' value typically creates a
scrollable region.
The [33442]viewport of a [33443]Document that has a non-null
[33444]browsing context and is not [33445]inert. The [33446]Document
for which the [33447]viewport was created.
The contents of an [33448]iframe.
Any other element or part of an element determined by the user agent to
be a focusable area, especially to aid with accessibility or to better
match platform conventions. The element.
A user agent could make all list item bullets [33449]sequentially
focusable, so that a user can more easily navigate lists.
Similarly, a user agent could make all elements with [33450]title
attributes [33451]sequentially focusable, so that their advisory
information can be accessed.
A [33452]navigable container (e.g. an [33453]iframe) is a
[33454]focusable area, but key events routed to a [33455]navigable
container get immediately routed to its [33456]content navigable's
[33457]active document. Similarly, in sequential focus navigation a
[33458]navigable container essentially acts merely as a placeholder for
its [33459]content navigable's [33460]active document.
__________________________________________________________________
One [33461]focusable area in each [33462]Document is designated the
focused area of the document. Which control is so designated changes
over time, based on algorithms in this specification.
Even if a document is not [33463]fully active and not shown to the
user, it can still have a [33464]focused area of the document. If a
document's [33465]fully active state changes, its [33466]focused area
of the document will stay the same.
The currently focused area of a top-level traversable traversable is
the [33467]focusable area-or-null returned by this algorithm:
1. If traversable does not have [33468]system focus, then return null.
2. Let candidate be traversable's [33469]active document.
3. While candidate's [33470]focused area is a [33471]navigable
container with a non-null [33472]content navigable: set candidate
to the [33473]active document of that [33474]navigable container's
[33475]content navigable.
4. If candidate's [33476]focused area is non-null, set candidate to
candidate's [33477]focused area.
5. Return candidate.
The current focus chain of a top-level traversable traversable is the
[33478]focus chain of the [33479]currently focused area of traversable,
if traversable is non-null, or an empty list otherwise.
An element that is the [33480]DOM anchor of a [33481]focusable area is
said to gain focus when that [33482]focusable area becomes the
[33483]currently focused area of a top-level traversable. When an
element is the [33484]DOM anchor of a [33485]focusable area of the
[33486]currently focused area of a top-level traversable, it is
focused.
The focus chain of a [33487]focusable area subject is the ordered list
constructed as follows:
1. Let output be an empty [33488]list.
2. Let currentObject be subject.
3. While true:
1. [33489]Append currentObject to output.
2. If currentObject is an [33490]area element's shape, then
[33491]append that [33492]area element to output.
Otherwise, if currentObject's [33493]DOM anchor is an element
that is not currentObject itself, then [33494]append
currentObject's [33495]DOM anchor to output.
3. If currentObject is a [33496]focusable area, then set
currentObject to currentObject's [33497]DOM anchor's
[33498]node document.
Otherwise, if currentObject is a [33499]Document whose
[33500]node navigable's [33501]parent is non-null, then set
currentObject to currentObject's [33502]node navigable's
[33503]parent.
Otherwise, [33504]break.
4. Return output.
The chain starts with subject and (if subject is or can be the
[33505]currently focused area of a top-level traversable) continues
up the focus hierarchy up to the [33506]Document of the
[33507]top-level traversable.
All elements that are [33508]focusable areas are said to be focusable.
There are two special types of focusability for [33509]focusable areas:
* A [33510]focusable area is said to be sequentially focusable if it
is included in its [33511]Document's [33512]sequential focus
navigation order and the user agent determines that it is
sequentially focusable.
* A [33513]focusable area is said to be click focusable if the user
agent determines that it is click focusable. User agents should
consider focusable areas with non-null [33514]tabindex values to be
click focusable.
Elements which are not [33515]focusable are not [33516]focusable areas,
and thus not [33517]sequentially focusable and not [33518]click
focusable.
Being [33519]focusable is a statement about whether an element can be
focused programmatically, e.g. via the [33520]focus() method or
[33521]autofocus attribute. In contrast, [33522]sequentially focusable
and [33523]click focusable govern how the user agent responds to user
interaction: respectively, to [33524]sequential focus navigation and as
[33525]activation behavior.
The user agent might determine that an element is not
[33526]sequentially focusable even if it is [33527]focusable and is
included in its [33528]Document's [33529]sequential focus navigation
order, according to user preferences. For example, macOS users can set
the user agent to skip non-form control elements, or can skip links
when doing [33530]sequential focus navigation with just the Tab key (as
opposed to using both the Option and Tab keys).
Similarly, the user agent might determine that an element is not
[33531]click focusable even if it is [33532]focusable. For example, in
some user agents, clicking on a non-editable form control does not
focus it, i.e. the user agent has determined that such controls are not
click focusable.
Thus, an element can be [33533]focusable, but neither
[33534]sequentially focusable nor [33535]click focusable. For example,
in some user agents, a non-editable form-control with a
negative-integer [33536]tabindex value would not be focusable via user
interaction, only via programmatic APIs.
When a user [33537]activates a [33538]click focusable [33539]focusable
area, the user agent must run the [33540]focusing steps on the
[33541]focusable area with focus trigger set to "click".
Note that focusing is not an [33542]activation behavior, i.e. calling
the [33543]click() method on an element or dispatching a synthetic
[33544]click event on it won't cause the element to get focused.
__________________________________________________________________
A node is a focus navigation scope owner if it is a [33545]Document, a
[33546]shadow host, a [33547]slot, or an element which is the
[33548]popover invoker of an element in the [33549]popover showing
state.
Each [33550]focus navigation scope owner has a focus navigation scope,
which is a list of elements. Its contents are determined as follows:
Every element element has an associated focus navigation owner, which
is either null or a [33551]focus navigation scope owner. It is
determined by the following algorithm:
1. If element's parent is null, then return null.
2. If element's parent is a [33552]shadow host, then return element's
[33553]assigned slot.
3. If element's parent is a [33554]shadow root, then return the
parent's [33555]host.
4. If element's parent is the [33556]document element, then return the
parent's [33557]node document.
5. If element is in the [33558]popover showing state and has a
[33559]popover invoker set, then return element's [33560]popover
invoker.
6. Return element's parent's [33561]associated focus navigation owner.
Then, the contents of a given [33562]focus navigation scope owner
owner's [33563]focus navigation scope are all elements whose
[33564]associated focus navigation owner is owner.
The order of elements within a [33565]focus navigation scope does not
impact any of the algorithms in this specification. Ordering only
becomes important for the [33566]tabindex-ordered focus navigation
scope and [33567]flattened tabindex-ordered focus navigation scope
concepts defined below.
A tabindex-ordered focus navigation scope is a list of [33568]focusable
areas and [33569]focus navigation scope owners. Every [33570]focus
navigation scope owner owner has [33571]tabindex-ordered focus
navigation scope, whose contents are determined as follows:
* It contains all elements in owner's [33572]focus navigation scope
that are themselves [33573]focus navigation scope owners, except
the elements whose [33574]tabindex value is a negative integer.
* It contains all of the [33575]focusable areas whose [33576]DOM
anchor is an element in owner's [33577]focus navigation scope,
except the [33578]focusable areas whose [33579]tabindex value is a
negative integer.
The order within a [33580]tabindex-ordered focus navigation scope is
determined by each element's [33581]tabindex value, as described in the
section below.
The rules there do not give a precise ordering, as they are composed
mostly of "should" statements and relative orderings.
A flattened tabindex-ordered focus navigation scope is a list of
[33582]focusable areas. Every [33583]focus navigation scope owner owner
owns a distinct [33584]flattened tabindex-ordered focus navigation
scope, whose contents are determined by the following algorithm:
1. Let result be a [33585]clone of owner's [33586]tabindex-ordered
focus navigation scope.
2. For each item of result:
1. If item is not a [33587]focus navigation scope owner, then
[33588]continue.
2. If item is not a [33589]focusable area, then replace item with
all of the items in item's [33590]flattened tabindex-ordered
focus navigation scope.
3. Otherwise, insert the contents of item's [33591]flattened
tabindex-ordered focus navigation scope after item.
6.6.3 The [33592]tabindex attribute
(BUTTON) ✔MDN
[33593]Global_attributes/tabindex
Support in all current engines.
Firefox1.5+Safari4+Chrome1+
__________________________________________________________________
The tabindex content attribute allows authors to make an element and
regions that have the element as its [33594]DOM anchor be
[33595]focusable areas, allow or prevent them from being
[33596]sequentially focusable, and determine their relative ordering
for [33597]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 [33598]sequentially focusable [33599]focusable
areas.
The [33600]tabindex attribute, if specified, must have a value that is
a [33601]valid integer. Positive numbers specify the relative position
of the element's [33602]focusable areas in the [33603]sequential focus
navigation order, and negative numbers indicate that the control is not
[33604]sequentially focusable.
Developers should use caution when using values other than 0 or −1 for
their [33605]tabindex attributes as this is complicated to do
correctly.
The following provides a non-normative summary of the behaviors of the
possible [33606]tabindex attribute values. The below processing model
gives the more precise rules.
omitted (or non-integer values)
The user agent will decide whether the element is
[33607]focusable, and if it is, whether it is
[33608]sequentially focusable or [33609]click focusable (or
both).
−1 (or other negative integer values)
Causes the element to be [33610]focusable, and indicates that
the author would prefer the element to be [33611]click focusable
but not [33612]sequentially focusable. The user agent might
ignore this preference for click and sequential focusability,
e.g., for specific element types according to platform
conventions, or for keyboard-only users.
0
Causes the element to be [33613]focusable, and indicates that
the author would prefer the element to be both [33614]click
focusable and [33615]sequentially focusable. The user agent
might ignore this preference for click and sequential
focusability.
positive integer values
Behaves the same as 0, but in addition creates a relative
ordering within a [33616]tabindex-ordered focus navigation
scope, so that elements with higher [33617]tabindex attribute
value come later.
Note that the [33618]tabindex attribute cannot be used to make an
element non-focusable. The only way a page author can do that is by
[33619]disabling the element, or making it [33620]inert.
__________________________________________________________________
The tabindex value of an element is the value of its [33621]tabindex
attribute, parsed using the [33622]rules for parsing integers. If
parsing fails or the attribute is not specified, then the
[33623]tabindex value is null.
The [33624]tabindex value of a [33625]focusable area is the
[33626]tabindex value of its [33627]DOM anchor.
The [33628]tabindex value of an element must be interpreted as follows:
If the value is null
The user agent should follow platform conventions to determine
if the element should be considered as a [33629]focusable area
and if so, whether the element and any [33630]focusable areas
that have the element as their [33631]DOM anchor are
[33632]sequentially focusable, and if so, what their relative
position in their [33633]tabindex-ordered focus navigation scope
is to be. If the element is a [33634]focus navigation scope
owner, it must be included in its [33635]tabindex-ordered focus
navigation scope even if it is not a [33636]focusable area.
The relative ordering within a [33637]tabindex-ordered focus
navigation scope for elements and [33638]focusable areas that
belong to the same [33639]focus navigation scope and whose
[33640]tabindex value is null should be in
[33641]shadow-including tree order.
Modulo platform conventions, it is suggested that the following
elements should be considered as [33642]focusable areas and be
[33643]sequentially focusable:
+ [33644]a elements that have an [33645]href attribute
+ [33646]button elements
+ [33647]input elements whose [33648]type attribute are not in
the [33649]Hidden state
+ [33650]select elements
+ [33651]textarea elements
+ [33652]summary elements that are the first [33653]summary
element child of a [33654]details element
+ Elements with a [33655]draggable attribute set, if that would
enable the user agent to allow the user to begin drag
operations for those elements without the use of a pointing
device
+ [33656]Editing hosts
+ [33657]Navigable containers
If the value is a negative integer
The user agent must consider the element as a [33658]focusable
area, but should omit the element from any
[33659]tabindex-ordered focus navigation scope.
One valid reason to ignore the requirement that sequential focus
navigation not allow the author to lead to the element would be
if the user's only mechanism for moving the focus is sequential
focus navigation. For instance, a keyboard-only user would be
unable to click on a text control with a negative
[33660]tabindex, so that user's user agent would be well
justified in allowing the user to tab to the control regardless.
If the value is a zero
The user agent must allow the element to be considered as a
[33661]focusable area and should allow the element and any
[33662]focusable areas that have the element as their [33663]DOM
anchor to be [33664]sequentially focusable.
The relative ordering within a [33665]tabindex-ordered focus
navigation scope for elements and [33666]focusable areas that
belong to the same [33667]focus navigation scope and whose
[33668]tabindex value is zero should be in
[33669]shadow-including tree order.
If the value is greater than zero
The user agent must allow the element to be considered as a
[33670]focusable area and should allow the element and any
[33671]focusable areas that have the element as their [33672]DOM
anchor to be [33673]sequentially focusable, and should place the
element — referenced as candidate below — and the aforementioned
[33674]focusable areas in the [33675]tabindex-ordered focus
navigation scope where the element is a part of so that,
relative to other elements and [33676]focusable areas that
belong to the same [33677]focus navigation scope, they are:
+ before any [33678]focusable area whose [33679]DOM anchor is an
element whose [33680]tabindex attribute has been omitted or
whose value, when parsed, returns an error,
+ before any [33681]focusable area whose [33682]DOM anchor is an
element whose [33683]tabindex attribute has a value less than
or equal to zero,
+ after any [33684]focusable area whose [33685]DOM anchor is an
element whose [33686]tabindex attribute has a value greater
than zero but less than the value of the [33687]tabindex
attribute on candidate,
+ after any [33688]focusable area whose [33689]DOM anchor is an
element whose [33690]tabindex attribute has a value equal to
the value of the [33691]tabindex attribute on candidate but
that is located earlier than candidate in
[33692]shadow-including tree order,
+ before any [33693]focusable area whose [33694]DOM anchor is an
element whose [33695]tabindex attribute has a value equal to
the value of the [33696]tabindex attribute on candidate but
that is located later than candidate in
[33697]shadow-including tree order, and
+ before any [33698]focusable area whose [33699]DOM anchor is an
element whose [33700]tabindex attribute has a value greater
than the value of the [33701]tabindex attribute on candidate.
(BUTTON) ✔MDN
[33702]HTMLElement/tabIndex
Support in all current engines.
Firefox1+Safari3.1+Chrome1+
__________________________________________________________________
The tabIndex IDL attribute must [33703]reflect the value of the
[33704]tabindex content attribute. The [33705]default value is 0 if the
element is an [33706]a, [33707]area, [33708]button, [33709]frame,
[33710]iframe, [33711]input, [33712]object, [33713]select,
[33714]textarea, or [33715]SVG a element, or is a [33716]summary
element that is a [33717]summary for its parent details. The
[33718]default value is −1 otherwise.
The varying default value based on element type is a historical
artifact.
6.6.4 Processing model
To get the focusable area for a focus target that is either an element
that is not a [33719]focusable area, or is a [33720]navigable, given an
optional string focus trigger (default "other"), run the first matching
set of steps from the following list:
If focus target is an [33721]area element with one or more shapes that
are [33722]focusable areas
Return the shape corresponding to the first [33723]img element
in [33724]tree order that uses the image map to which the
[33725]area element belongs.
If focus target is an element with one or more scrollable regions that
are [33726]focusable areas
Return the element's first scrollable region, according to a
pre-order, depth-first traversal of the [33727]flat tree.
[33728][CSSSCOPING]
If focus target is the [33729]document element of its [33730]Document
Return the [33731]Document's [33732]viewport.
If focus target is a [33733]navigable
Return the [33734]navigable's [33735]active document.
If focus target is a [33736]navigable container with a non-null
[33737]content navigable
Return the [33738]navigable container's [33739]content
navigable's [33740]active document.
If focus target is a [33741]shadow host whose [33742]shadow root's
[33743]delegates focus is true
1. Let focusedElement be the [33744]currently focused area of a
top-level traversable's [33745]DOM anchor.
2. If focus target is a [33746]shadow-including inclusive
ancestor of focusedElement, then return focusedElement.
3. Return the [33747]focus delegate for focus target given focus
trigger.
For [33748]sequential focusability, the handling of
[33749]shadow hosts and [33750]delegates focus is done when
constructing the [33751]sequential focus navigation order. That
is, the [33752]focusing steps will never be called on such
[33753]shadow hosts as part of sequential focus navigation.
Otherwise
Return null.
The focus delegate for a focusTarget, given an optional string
focusTrigger (default "other"), is given by the following steps:
1. If focusTarget is a [33754]shadow host and its [33755]shadow root's
[33756]delegates focus is false, then return null.
2. Let whereToLook be focusTarget.
3. If whereToLook is a [33757]shadow host, then set whereToLook to
whereToLook's [33758]shadow root.
4. Let autofocusDelegate be the [33759]autofocus delegate for
whereToLook given focusTrigger.
5. If autofocusDelegate is not null, then return autofocusDelegate.
6. [33760]For each descendant of whereToLook's [33761]descendants, in
[33762]tree order:
1. Let focusableArea be null.
2. If focusTarget is a [33763]dialog element and descendant is
[33764]sequentially focusable, then set focusableArea to
descendant.
3. Otherwise, if focusTarget is not a [33765]dialog and
descendant is a [33766]focusable area, set focusableArea to
descendant.
4. Otherwise, set focusableArea to the result of [33767]getting
the focusable area for descendant given focusTrigger.
This step can end up recursing, i.e., the [33768]get the
focusable area steps might return the [33769]focus delegate of
descendant.
5. If focusableArea is not null, then return focusableArea.
It's important that we are not looking at the
[33770]shadow-including descendants here, but instead only at the
[33771]descendants. [33772]Shadow hosts are instead handled by the
recursive case mentioned above.
7. Return null.
The above algorithm essentially returns the first suitable
[33773]focusable area where the path between its [33774]DOM anchor and
focusTarget delegates focus at any shadow tree boundaries.
The autofocus delegate for a focus target given a focus trigger is
given by the following steps:
1. For each [33775]descendant descendant of focus target, in
[33776]tree order:
1. If descendant does not have an [33777]autofocus content
attribute, then [33778]continue.
2. Let focusable area be descendant, if descendant is a
[33779]focusable area; otherwise let focusable area be the
result of [33780]getting the focusable area for descendant
given focus trigger.
3. If focusable area is null, then [33781]continue.
4. If focusable area is not [33782]click focusable and focus
trigger is "click", then [33783]continue.
5. Return focusable area.
2. Return null.
The focusing steps for an object new focus target that is either a
[33784]focusable area, or an element that is not a [33785]focusable
area, or a [33786]navigable, are as follows. They can optionally be run
with a fallback target and a string focus trigger.
1. If new focus target is not a [33787]focusable area, then set new
focus target to the result of [33788]getting the focusable area for
new focus target, given focus trigger if it was passed.
2. If new focus target is null, then:
1. If no fallback target was specified, then return.
2. Otherwise, set new focus target to the fallback target.
3. If new focus target is a [33789]navigable container with non-null
[33790]content navigable, then set new focus target to the
[33791]content navigable's [33792]active document.
4. If new focus target is a [33793]focusable area and its [33794]DOM
anchor is [33795]inert, then return.
5. If new focus target is the [33796]currently focused area of a
top-level traversable, then return.
6. Let old chain be the [33797]current focus chain of the top-level
traversable in which new focus target finds itself.
7. Let new chain be the [33798]focus chain of new focus target.
8. Run the [33799]focus update steps with old chain, new chain, and
new focus target respectively.
User agents must [33800]immediately run the [33801]focusing steps for a
[33802]focusable area or [33803]navigable candidate whenever the user
attempts to move the focus to candidate.
The unfocusing steps for an object old focus target that is either a
[33804]focusable area or an element that is not a [33805]focusable area
are as follows:
1. If old focus target is a [33806]shadow host whose [33807]shadow
root's [33808]delegates focus is true, and old focus target's
[33809]shadow root is a [33810]shadow-including inclusive ancestor
of the [33811]currently focused area of a top-level traversable's
[33812]DOM anchor, then set old focus target to that
[33813]currently focused area of a top-level traversable.
2. If old focus target is [33814]inert, then return.
3. If old focus target is an [33815]area element and one of its shapes
is the [33816]currently focused area of a top-level traversable,
or, if old focus target is an element with one or more scrollable
regions, and one of them is the [33817]currently focused area of a
top-level traversable, then let old focus target be that
[33818]currently focused area of a top-level traversable.
4. Let old chain be the [33819]current focus chain of the top-level
traversable in which old focus target finds itself.
5. If old focus target is not one of the entries in old chain, then
return.
6. If old focus target is not a [33820]focusable area, then return.
7. Let topDocument be old chain's last entry.
8. If topDocument's [33821]node navigable has [33822]system focus,
then run the [33823]focusing steps for topDocument's
[33824]viewport.
Otherwise, apply any relevant platform-specific conventions for
removing [33825]system focus from topDocument's [33826]node
navigable, and run the [33827]focus update steps given old chain,
an empty list, and null.
The [33828]unfocusing steps do not always result in the focus changing,
even when applied to the [33829]currently focused area of a top-level
traversable. For example, if the [33830]currently focused area of a
top-level traversable is a [33831]viewport, then it will usually keep
its focus regardless until another [33832]focusable area is explicitly
focused with the [33833]focusing steps.
__________________________________________________________________
The focus update steps, given an old chain, a new chain, and a new
focus target respectively, are as follows:
1. If the last entry in old chain and the last entry in new chain are
the same, pop the last entry from old chain and the last entry from
new chain and redo this step.
2. For each entry entry in old chain, in order, run these substeps:
1. If entry is an [33834]input element, and the [33835]change
event [33836]applies to the element, and the element does not
have a defined [33837]activation behavior, and the user has
changed the element's [33838]value or its list of
[33839]selected files while the control was focused without
committing that change (such that it is different to what it
was when the control was first focused), then:
1. Set entry's [33840]user validity to true.
2. [33841]Fire an event named [33842]change at the element,
with the [33843]bubbles attribute initialized to true.
2. If entry is an element, let blur event target be entry.
If entry is a [33844]Document object, let blur event target be
that [33845]Document object's [33846]relevant global object.
Otherwise, let blur event target be null.
3. If entry is the last entry in old chain, and entry is an
[33847]Element, and the last entry in new chain is also an
[33848]Element, then let related blur target be the last entry
in new chain. Otherwise, let related blur target be null.
4. If blur event target is not null, [33849]fire a focus event
named [33850]blur at blur event target, with related blur
target as the related target.
In some cases, e.g., if entry is an [33851]area element's
shape, a scrollable region, or a [33852]viewport, no event is
fired.
3. Apply any relevant platform-specific conventions for focusing new
focus target. (For example, some platforms select the contents of a
text control when that control is focused.)
4. For each entry entry in new chain, in reverse order, run these
substeps:
1. If entry is a [33853]focusable area, and the [33854]focused
area of the document is not entry:
1. Set document's [33855]relevant global object's
[33856]navigation API's [33857]focus changed during
ongoing navigation to true.
2. Designate entry as the [33858]focused area of the
document.
2. If entry is an element, let focus event target be entry.
If entry is a [33859]Document object, let focus event target
be that [33860]Document object's [33861]relevant global
object.
Otherwise, let focus event target be null.
3. If entry is the last entry in new chain, and entry is an
[33862]Element, and the last entry in old chain is also an
[33863]Element, then let related focus target be the last
entry in old chain. Otherwise, let related focus target be
null.
4. If focus event target is not null, [33864]fire a focus event
named [33865]focus at focus event target, with related focus
target as the related target.
In some cases, e.g. if entry is an [33866]area element's
shape, a scrollable region, or a [33867]viewport, no event is
fired.
To fire a focus event named e at an element t with a given related
target r, [33868]fire an event named e at t, using [33869]FocusEvent,
with the [33870]relatedTarget attribute initialized to r, the
[33871]view attribute initialized to t's [33872]node document's
[33873]relevant global object, and the [33874]composed flag set.
__________________________________________________________________
When a key event is to be routed in a [33875]top-level traversable, the
user agent must run the following steps:
1. Let target area be the [33876]currently focused area of the
top-level traversable.
2. [33877]Assert: target area is not null, since key events are only
routed to [33878]top-level traversables that have [33879]system
focus. Therefore, target area is a [33880]focusable area.
3. Let target node be target area's [33881]DOM anchor.
4. If target node is a [33882]Document that has a [33883]body element,
then let target node be [33884]the body element of that
[33885]Document.
Otherwise, if target node is a [33886]Document object that has a
non-null [33887]document element, then let target node be that
[33888]document element.
5. If target node is not [33889]inert, then:
1. Let canHandle be the result of [33890]dispatching the key
event at target node.
2. If canHandle is true, then let target area handle the key
event. This might include [33891]firing a click event at
target node.
__________________________________________________________________
The has focus steps, given a [33892]Document object target, are as
follows:
1. If target's [33893]node navigable's [33894]top-level traversable
does not have [33895]system focus, then return false.
2. Let candidate be target's [33896]node navigable's [33897]top-level
traversable's [33898]active document.
3. While true:
1. If candidate is target, then return true.
2. If the [33899]focused area of candidate is a [33900]navigable
container with a non-null [33901]content navigable, then set
candidate to the [33902]active document of that
[33903]navigable container's [33904]content navigable.
3. Otherwise, return false.
6.6.5 Sequential focus navigation
Each [33905]Document has a sequential focus navigation order, which
orders some or all of the [33906]focusable areas in the [33907]Document
relative to each other. Its contents and ordering are given by the
[33908]flattened tabindex-ordered focus navigation scope of the
[33909]Document.
Per the rules defining the [33910]flattened tabindex-ordered focus
navigation scope, the ordering is not necessarily related to the
[33911]tree order of the [33912]Document.
If a [33913]focusable area is omitted from the [33914]sequential focus
navigation order of its [33915]Document, then it is unreachable via
[33916]sequential focus navigation.
There can also be a sequential focus navigation starting point. It is
initially unset. The user agent may set it when the user indicates that
it should be moved.
For example, the user agent could set it to the position of the user's
click if the user clicks on the document contents.
User agents are required to set the [33917]sequential focus navigation
starting point to the [33918]target element when [33919]navigating to a
fragment.
A sequential focus direction is one of two possible values: "forward",
or "backward". They are used in the below algorithms to describe the
direction in which sequential focus travels at the user's request.
A selection mechanism is one of two possible values: "DOM", or
"sequential". They are used to describe how the [33920]sequential
navigation search algorithm finds the [33921]focusable area it returns.
When the user requests that focus move from the [33922]currently
focused area of a top-level traversable to the next or previous
[33923]focusable area (e.g., as the default action of pressing the tab
key), or when the user requests that focus sequentially move to a
[33924]top-level traversable in the first place (e.g., from the
browser's location bar), the user agent must use the following
algorithm:
1. Let starting point be the [33925]currently focused area of a
top-level traversable, if the user requested to move focus
sequentially from there, or else the [33926]top-level traversable
itself, if the user instead requested to move focus from outside
the [33927]top-level traversable.
2. If there is a [33928]sequential focus navigation starting point
defined and it is inside starting point, then let starting point be
the [33929]sequential focus navigation starting point instead.
3. Let direction be "[33930]forward" if the user requested the next
control, and "[33931]backward" if the user requested the previous
control.
Typically, pressing tab requests the next control, and pressing
shift + tab requests the previous control.
4. Loop: Let selection mechanism be "[33932]sequential" if starting
point is a [33933]navigable or if starting point is in its
[33934]Document's [33935]sequential focus navigation order.
Otherwise, starting point is not in its [33936]Document's
[33937]sequential focus navigation order; let selection mechanism
be "[33938]DOM".
5. Let candidate be the result of running the [33939]sequential
navigation search algorithm with starting point, direction, and
selection mechanism.
6. If candidate is not null, then run the [33940]focusing steps for
candidate and return.
7. Otherwise, unset the [33941]sequential focus navigation starting
point.
8. If starting point is a [33942]top-level traversable, or a
[33943]focusable area in the [33944]top-level traversable, the user
agent should transfer focus to its own controls appropriately (if
any), honouring direction, and then return.
For example, if direction is backward, then the last
[33945]sequentially focusable control before the browser's
rendering area would be the control to focus.
If the user agent has no [33946]sequentially focusable controls — a
kiosk-mode browser, for instance — then the user agent may instead
restart these steps with the starting point being the
[33947]top-level traversable itself.
9. Otherwise, starting point is a [33948]focusable area in a
[33949]child navigable. Set starting point to that [33950]child
navigable's [33951]parent and return to the step labeled loop.
The sequential navigation search algorithm, given a [33952]focusable
area starting point, [33953]sequential focus direction direction, and
[33954]selection mechanism selection mechanism, consists of the
following steps. They return a [33955]focusable area-or-null.
1. Pick the appropriate cell from the following table, and follow the
instructions in that cell.
The appropriate cell is the one that is from the column whose
header describes direction and from the first row whose header
describes starting point and selection mechanism.
direction is "[33956]forward" direction is "[33957]backward"
starting point is a [33958]navigable Let candidate be the first
[33959]suitable sequentially focusable area in starting point's
[33960]active document, if any; or else null Let candidate be the last
[33961]suitable sequentially focusable area in starting point's
[33962]active document, if any; or else null
selection mechanism is "[33963]DOM"
Let candidate be the [33964]suitable sequentially focusable area, that
appears nearest after starting point in starting point's
[33965]Document, in [33966]shadow-including tree order, if any; or else
null
In this case, starting point does not necessarily belong to its
[33967]Document's [33968]sequential focus navigation order, so we'll
select the [33969]suitable [33970]item from that list that comes after
starting point in [33971]shadow-including tree order.
Let candidate be the [33972]suitable sequentially focusable area, that
appears nearest before starting point in starting point's
[33973]Document, in [33974]shadow-including tree order, if any; or else
null
selection mechanism is "[33975]sequential" Let candidate be the first
[33976]suitable sequentially focusable area after starting point, in
starting point's [33977]Document's [33978]sequential focus navigation
order, if any; or else null Let candidate be the last [33979]suitable
sequentially focusable area before starting point, in starting point's
[33980]Document's [33981]sequential focus navigation order, if any; or
else null
A suitable sequentially focusable area is a [33982]focusable area
whose [33983]DOM anchor is not [33984]inert and is
[33985]sequentially focusable.
2. If candidate is a [33986]navigable container with a non-null
[33987]content navigable, then:
1. Let recursive candidate be the result of running the
[33988]sequential navigation search algorithm with candidate's
[33989]content navigable, direction, and "[33990]sequential".
2. If recursive candidate is null, then return the result of
running the [33991]sequential navigation search algorithm with
candidate, direction, and selection mechanism.
3. Otherwise, set candidate to recursive candidate.
3. Return candidate.
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android?
Returns the deepest element in documentOrShadowRoot through
which or to which key events are being routed. This is, roughly
speaking, the focused element in the document.
For the purposes of this API, when a [33997]child navigable is
focused, its [33998]container is [33999]focused within its
[34000]parent's [34001]active document. For example, if the user
moves the focus to a text control in an [34002]iframe, the
[34003]iframe is the element returned by the
[34004]activeElement API in the [34005]iframe's [34006]node
document.
Similarly, when the focused element is in a different
[34007]node tree than documentOrShadowRoot, the element returned
will be the [34008]host that's located in the same [34009]node
tree as documentOrShadowRoot if documentOrShadowRoot is a
[34010]shadow-including inclusive ancestor of the focused
element, and null if not.
Firefox Android?Safari iOS?Chrome Android?WebView
Android37+Samsung Internet?Opera Android?
Returns true if key events are being routed through or to
document; otherwise, returns false. Roughly speaking, this
corresponds to document, or a document nested inside document,
being focused.
element.[34018]focus({ [34019]preventScroll, [34020]focusVisible })
Moves the focus to element.
If element is a [34021]navigable container, moves the focus to
its [34022]content navigable instead.
By default, this method also scrolls element into view.
Providing the [34023]preventScroll option and setting it to true
prevents this behavior.
By default, user agents use [34024]implementation-defined
heuristics to determine whether to [34025]indicate focus via a
focus ring. Providing the [34026]focusVisible option and setting
it to true will ensure the focus ring is always visible.
Firefox Android?Safari iOS1+Chrome Android?WebView
Android?Samsung Internet?Opera Android10.1+
Moves the focus to the [34029]viewport. Use of this method is
discouraged; if you want to focus the [34030]viewport, call the
[34031]focus() method on the [34032]Document's [34033]document
element.
Do not use this method to hide the focus ring if you find the
focus ring unsightly. Instead, use the [34034]:focus-visible
pseudo-class to override the [34035]'outline' property, and
provide a different way to show what element is focused. Be
aware that if an alternative focusing style isn't made
available, the page will be significantly less usable for people
who primarily navigate pages 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 [34036]textarea elements
and instead use a yellow background to indicate focus, you could
use:
The [34037]DocumentOrShadowRoot activeElement getter steps are:
1. Let candidate be [34038]this's [34039]node document's
[34040]focused area's [34041]DOM anchor.
2. Set candidate to the result of [34042]retargeting candidate against
[34043]this.
3. If candidate's [34044]root is not [34045]this, then return null.
4. If candidate is not a [34046]Document object, then return
candidate.
5. If candidate has a [34047]body element, then return that
[34048]body element.
6. If candidate's [34049]document element is non-null, then return
that [34050]document element.
7. Return null.
The [34051]Document hasFocus() method steps are to return the result of
running the [34052]has focus steps given [34053]this.
__________________________________________________________________
The [34054]Window focus() method steps are:
1. Let current be [34055]this's [34056]navigable.
2. If current is null, then return.
3. If the [34057]allow focus steps given current's [34058]active
document return false, then return.
4. Run the [34059]focusing steps with current.
5. If current is a [34060]top-level traversable, user agents are
encouraged to trigger some sort of notification to indicate to the
user that the page is attempting to gain focus.
(BUTTON) ✔MDN
[34061]Window/blur
Support in all current engines.
Firefox1+Safari1+Chrome1+
__________________________________________________________________
The [34062]Window blur() method steps are to do nothing.
Historically, the [34063]focus() and [34064]blur() methods actually
affected the system-level focus of the system widget (e.g., tab or
window) that contained the [34065]navigable, but hostile sites widely
abuse this behavior to the user's detriment.
__________________________________________________________________
The [34066]HTMLOrSVGElement focus(options) method steps are:
1. If the [34067]allow focus steps given [34068]this's [34069]node
document return false, then return.
2. Run the [34070]focusing steps for [34071]this.
3. If options["focusVisible"] is true, or does not [34072]exist but in
an [34073]implementation-defined way the user agent determines it
would be best to do so, then [34074]indicate focus.
4. If options["preventScroll"] is false, then [34075]scroll a target
into view given [34076]this, "auto", "center", and "center".
The [34077]HTMLOrSVGElement blur() method steps are:
1. The user agent should run the [34078]unfocusing steps given
[34079]this.
User agents may instead selectively or uniformly do nothing, for
usability reasons.
For example, if the [34080]blur() method is unwisely being used to
remove the focus ring for aesthetics reasons, the page would become
unusable by keyboard users. Ignoring calls to this method would thus
allow keyboard users to interact with the page.
__________________________________________________________________
The allow focus steps, given a [34081]Document object target, are:
1. If target is [34082]allowed to use the
"[34083]focus-without-user-activation" feature, then return true.
2. If target's [34084]relevant global object has [34085]transient
activation, then return true.
3. Return false.
6.6.7 The [34086]autofocus attribute
The autofocus content attribute allows the author to indicate that an
element is to be focused as soon as the page is loaded, allowing the
user to just start typing without having to manually focus the main
element.
When the [34087]autofocus attribute is specified on an element inside
[34088]dialog elements or [34089]HTML elements whose [34090]popover
attribute is set, then it will be focused when the dialog or popover
becomes shown.
The [34091]autofocus attribute is a [34092]boolean attribute.
To find the nearest ancestor autofocus scoping root element given an
[34093]Element element:
1. If element is a [34094]dialog element, then return element.
2. If element's [34095]popover attribute is not in the [34096]no
popover state, then return element.
3. Let ancestor be element.
4. While ancestor has a [34097]parent element:
1. Set ancestor to ancestor's [34098]parent element.
2. If ancestor is a [34099]dialog element, then return ancestor.
3. If ancestor's [34100]popover attribute is not in the [34101]no
popover state, then return ancestor.
5. Return ancestor.
There must not be two elements with the same [34102]nearest ancestor
autofocus scoping root element that both have the [34103]autofocus
attribute specified.
Each [34104]Document has an autofocus candidates [34105]list, initially
empty.
Each [34106]Document has an autofocus processed flag boolean, initially
false.
When an element with the [34107]autofocus attribute specified is
[34108]inserted into a document, run the following steps:
1. If the user has indicated (for example, by starting to type in a
form control) that they do not wish focus to be changed, then
optionally return.
2. Let target be the element's [34109]node document.
3. If target is not [34110]fully active, then return.
4. If target's [34111]active sandboxing flag set has the
[34112]sandboxed automatic features browsing context flag, then
return.
5. If the [34113]allow focus steps given target return false, then
return.
6. [34114]For each ancestorNavigable of target's [34115]ancestor
navigables: if ancestorNavigable's [34116]active document's
[34117]origin is not [34118]same origin with target's
[34119]origin, then return.
7. Let topDocument be target's [34120]node navigable's
[34121]top-level traversable's [34122]active document.
8. If topDocument's [34123]autofocus processed flag is false, then
[34124]remove the element from topDocument's [34125]autofocus
candidates, and [34126]append the element to topDocument's
[34127]autofocus candidates.
We do not check if an element is a [34128]focusable area before storing
it in the [34129]autofocus candidates list, because even if it is not a
focusable area when it is inserted, it could become one by the time
[34130]flush autofocus candidates sees it.
To flush autofocus candidates for a document topDocument, run these
steps:
1. If topDocument's [34131]autofocus processed flag is true, then
return.
2. Let candidates be topDocument's [34132]autofocus candidates.
3. If candidates [34133]is empty, then return.
4. If topDocument's [34134]focused area is not topDocument itself, or
topDocument has non-null [34135]target element, then:
1. [34136]Empty candidates.
2. Set topDocument's [34137]autofocus processed flag to true.
3. Return.
5. While candidates is not [34138]empty:
1. Let element be candidates[0].
2. Let doc be element's [34139]node document.
3. If doc is not [34140]fully active, then [34141]remove element
from candidates, and [34142]continue.
4. If doc's [34143]node navigable's [34144]top-level traversable
is not the same as topDocument's [34145]node navigable, then
[34146]remove element from candidates, and [34147]continue.
5. If doc's [34148]script-blocking style sheet set is not
[34149]empty, then return.
In this case, element is the currently-best candidate, but doc
is not ready for autofocusing. We'll try again next time
[34150]flush autofocus candidates is called.
6. [34151]Remove element from candidates.
7. Let inclusiveAncestorDocuments be a [34152]list consisting of
the [34153]active document of doc's [34154]inclusive ancestor
navigables.
8. If any [34155]Document in inclusiveAncestorDocuments has
non-null [34156]target element, then [34157]continue.
9. Let target be element.
10. If target is not a [34158]focusable area, then set target to
the result of [34159]getting the focusable area for target.
[34160]Autofocus candidates can [34161]contain elements which
are not [34162]focusable areas. In addition to the special
cases handled in the [34163]get the focusable area algorithm,
this can happen because a non-[34164]focusable area element
with an [34165]autofocus attribute was [34166]inserted into a
document and it never became focusable, or because the element
was focusable but its status changed while it was stored in
[34167]autofocus candidates.
11. If target is not null, then:
1. [34168]Empty candidates.
2. Set topDocument's [34169]autofocus processed flag to
true.
3. Run the [34170]focusing steps for target.
This handles the automatic focusing during document load. The
[34171]show() and [34172]showModal() methods of [34173]dialog elements
also processes the [34174]autofocus attribute.
Focusing the element does not imply that the user agent has to focus
the browser window if it has lost focus.
(BUTTON) ⚠MDN
[34175]Global_attributes/autofocus
Support in one engine only.
Firefox🔰 1+Safari🔰 4+Chrome79+
__________________________________________________________________
The autofocus IDL attribute must [34176]reflect the content attribute
of the same name.
In the following snippet, the text control would be focused when the
document was loaded.
The [34177]autofocus attribute applies to all elements, not just to
form controls. This allows examples such as the following:
Edit me!
6.7 Assigning keyboard shortcuts
6.7.1 Introduction
This section is non-normative.
Each element that can be activated or focused can be assigned a single
key combination to activate it, using the [34178]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 [34179]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 [34180]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 [34181]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 possible key.
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 "⌥⎋", and an Emacs browser might use "M-ESC"
or "ESC ESC".
In general, therefore, it is unwise to attempt to parse the value
returned from the [34182]accessKeyLabel IDL attribute.
6.7.2 The accesskey attribute
(BUTTON) ✔MDN
[34183]Global_attributes/accesskey
Support in all current engines.
Firefox1+Safari4+Chrome1+
__________________________________________________________________
All [34184]HTML elements may have the [34185]accesskey content
attribute set. The [34186]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 [34187]ordered set of unique
space-separated tokens none of which are [34188]identical to another
token and each of which must be exactly one 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:
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:
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.
...
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
assign a key, it will be just "Compose". The exact string depends on
what the [34189]assigned access key is, and on how the user agent
represents that key combination.
6.7.3 Processing model
An element's assigned access key is a key combination derived from the
element's [34190]accesskey content attribute. Initially, an element
must not have an [34191]assigned access key.
Whenever an element's [34192]accesskey attribute is set, changed, or
removed, the user agent must update the element's [34193]assigned
access key by running the following steps:
1. If the element has no [34194]accesskey attribute, then skip to the
fallback step below.
2. Otherwise, [34195]split the attribute's value on ASCII whitespace,
and let keys be the resulting tokens.
3. For each value in keys in turn, in the order the tokens appeared in
the attribute's value, run the following substeps:
1. If the value is not a string exactly one code point in length,
then skip the remainder of these steps for this value.
2. If the value does not correspond to a key on the system's
keyboard, then skip the remainder of these steps for this
value.
3. [34196](This is a tracking vector.) If the user agent can find
a mix of zero or more modifier keys that, combined with the
key that corresponds to the value given in the attribute, can
be used as the access key, then the user agent may assign that
combination of keys as the element's [34197]assigned access
key and return.
4. Fallback: Optionally, the user agent may assign a key combination
of its choosing as the element's [34198]assigned access key and
then return.
5. If this step is reached, the element has no [34199]assigned access
key.
Once a user agent has selected and assigned an access key for an
element, the user agent should not change the element's [34200]assigned
access key unless the [34201]accesskey content attribute is changed or
the element is moved to another [34202]Document.
When the user presses the key combination corresponding to the
[34203]assigned access key for an element, if the element
[34204]defines a command, the command's [34205]Hidden State facet is
false (visible), the command's [34206]Disabled State facet is also
false (enabled), the element is [34207]in a document that has a
non-null [34208]browsing context, and neither the element nor any of
its ancestors has a [34209]hidden attribute specified, then the user
agent must trigger the [34210]Action of the command.
User agents [34211]might expose elements that have an [34212]accesskey
attribute in other ways as well, e.g. in a menu displayed in response
to a specific key combination.
__________________________________________________________________
(BUTTON) ✔MDN
[34213]HTMLElement/accessKey
Support in all current engines.
Firefox5+Safari6+Chrome17+
__________________________________________________________________
The accessKeyLabel IDL attribute must return a string that represents
the element's [34217]assigned access key, if any. If the element does
not have one, then the IDL attribute must return the empty string.
6.8 Editing
6.8.1 Making document regions editable: The [34218]contenteditable content
attribute
(BUTTON) ✔MDN
[34219]HTMLElement/contentEditable
Support in all current engines.
Firefox3+Safari3+Chrome1+
__________________________________________________________________
The contenteditable content attribute is an [34228]enumerated attribute
with the following keywords and states:
Keyword State Brief description
true true The element is editable.
(the empty string)
false false The element is not editable.
plaintext-only plaintext-only Only the element's raw text content is
editable; rich formatting is disabled.
The attribute's [34229]missing value default and [34230]invalid value
default are both the inherit state. The inherit state indicates that
the element is editable (or not) based on the parent element's state.
For example, consider a page that has a [34231]form and a
[34232]textarea to publish a new article, where the user is expected to
write the article using HTML:
When scripting is enabled, the [34233]textarea element could be
replaced with a rich text control instead, using the
[34234]contenteditable attribute:
Features to enable, e.g., inserting links, can be implemented using the
[34235]document.execCommand() API, or using [34236]Selection APIs and
other DOM APIs. [34237][EXECCOMMAND] [34238][SELECTION] [34239][DOM]
The [34240]contenteditable attribute can also be used to great effect:
Live CSS editing!
element.[34241]contentEditable [ = value ]
Returns "true", "plaintext-only", "false", or "[34242]inherit",
based on the state of the [34243]contenteditable attribute.
Can be set, to change that state.
Throws a [34244]"SyntaxError" [34245]DOMException if the new
value isn't one of those strings.
Firefox Android?Safari iOS1+Chrome Android?WebView
Android?Samsung Internet?Opera Android12.1+
Returns true if the element is editable; otherwise, returns
false.
The contentEditable IDL attribute, on getting, must return the string
"true" if the content attribute is set to the [34248]true state,
"plaintext-only" if the content attribute is set to the
[34249]plaintext-only state, "false" if the content attribute is set to
the [34250]false state, and "[34251]inherit" otherwise. On setting, if
the new value is an [34252]ASCII case-insensitive match for the string
"inherit" then the content attribute must be removed, if the new value
is an [34253]ASCII case-insensitive match for the string "true" then
the content attribute must be set to the string "true", if the new
value is an [34254]ASCII case-insensitive match for the string
"plaintext-only" then the content attribute must be set to the string
"plaintext-only", if the new value is an [34255]ASCII case-insensitive
match for the string "false" then the content attribute must be set to
the string "false", and otherwise the attribute setter must throw a
[34256]"SyntaxError" [34257]DOMException.
The isContentEditable IDL attribute, on getting, must return true if
the element is either an [34258]editing host or [34259]editable, and
false otherwise.
6.8.2 Making entire documents editable: the [34260]designMode getter and
setter
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet?Opera Android10.1+
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 and resets the selection in that document.
[34263]Document objects have an associated design mode enabled, which
is a boolean. It is initially false.
The designMode getter steps are to return "on" if [34264]this's
[34265]design mode enabled is true; otherwise "off".
The [34266]designMode setter steps are:
1. Let value be the given value, [34267]converted to ASCII lowercase.
2. If value is "on" and [34268]this's [34269]design mode enabled is
false, then:
1. Set [34270]this's [34271]design mode enabled to true.
2. Reset [34272]this's [34273]active range's start and end
boundary points to be at the start of [34274]this.
3. Run the [34275]focusing steps for [34276]this's
[34277]document element, if non-null.
3. If value is "off", then set [34278]this's [34279]design mode
enabled to false.
6.8.3 Best practices for in-page editors
Authors are encouraged to set the [34280]'white-space' property on
[34281]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
[34282]'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␣␣ball", with
two spaces (here represented by "␣") between the words. With the
editing rules in place for the default value of [34283]'white-space'
('normal'), the resulting markup will either consist of
"yellow ball" or "yellow 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
[34284]'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 [34285]'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.
6.8.4 Editing APIs
An editing host is either an [34286]HTML element with its
[34287]contenteditable attribute in the true state or plaintext-only
state, or a [34288]child [34289]HTML element of a [34290]Document whose
[34291]design mode enabled is true.
The definition of the terms [34292]active range, [34293]editing host
of, and [34294]editable, the user interface requirements of elements
that are [34295]editing hosts or [34296]editable, the
[34297]execCommand(), [34298]queryCommandEnabled(),
[34299]queryCommandIndeterm(), [34300]queryCommandState(),
[34301]queryCommandSupported(), and [34302]queryCommandValue() methods,
text selections, and the [34303]delete the selection algorithm are
defined in execCommand. [34304][EXECCOMMAND]
6.8.5 Spelling and grammar checking
User agents can support the checking of spelling and grammar of
editable text, either in form controls (such as the value of
[34305]textarea elements), or in elements in an [34306]editing host
(e.g. using [34307]contenteditable).
For each element, user agents must establish a default behavior, either
through defaults or through preferences expressed by the user. There
are three possible default behaviors for each element:
true-by-default
The element will be checked for spelling and grammar if its
contents are editable and spellchecking is not explicitly
disabled through the [34308]spellcheck attribute.
false-by-default
The element will never be checked for spelling and grammar
unless spellchecking is explicitly enabled through the
[34309]spellcheck attribute.
inherit-by-default
The element's default behavior is the same as its parent
element's. Elements that have no parent element cannot have this
as their default behavior.
__________________________________________________________________
(BUTTON) ✔MDN
[34310]Global_attributes/spellcheck
Support in all current engines.
FirefoxYesSafariYesChrome9+
__________________________________________________________________
The spellcheck attribute is an [34311]enumerated attribute with the
following keywords and states:
Keyword State Brief description
true true Spelling and grammar will be checked.
(the empty string)
false false Spelling and grammar will not be checked.
The attribute's [34312]missing value default and [34313]invalid value
default are both the default state. The default state indicates that
the element is to act according to a default behavior, possibly based
on the parent element's own [34314]spellcheck state, as defined below.
__________________________________________________________________
element.[34315]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
[34316]spellcheck content attribute.
The spellcheck IDL attribute, on getting, must return true if the
element's [34317]spellcheck content attribute is in the [34318]true
state, or if the element's [34319]spellcheck content attribute is in
the [34320]default state and the element's [34321]default behavior is
[34322]true-by-default, or if the element's [34323]spellcheck content
attribute is in the [34324]default state and the element's
[34325]default behavior is [34326]inherit-by-default and the element's
parent element's [34327]spellcheck IDL attribute would return true;
otherwise, if none of those conditions applies, then the attribute must
instead return false.
The [34328]spellcheck IDL attribute is not affected by user preferences
that override the [34329]spellcheck content attribute, and therefore
might not reflect the actual spellchecking state.
On setting, if the new value is true, then the element's
[34330]spellcheck content attribute must be set to "true", otherwise it
must be set to "false".
__________________________________________________________________
User agents should only consider the following pieces of text as
checkable for the purposes of this feature:
* The [34331]value of [34332]input elements whose [34333]type
attributes are in the [34334]Text, [34335]Search, [34336]URL, or
[34337]Email states and that are [34338]mutable (i.e. that do not
have the [34339]readonly attribute specified and that are not
[34340]disabled).
* The [34341]value of [34342]textarea elements that do not have a
[34343]readonly attribute and that are not [34344]disabled.
* Text in [34345]Text nodes that are children of [34346]editing hosts
or [34347]editable elements.
* Text in attributes of [34348]editable elements.
For text that is part of a [34349]Text node, the element with which the
text is associated is the element that is the immediate parent of the
first character of the word, sentence, or other piece of text. For text
in attributes, it is the attribute's element. For the values of
[34350]input and [34351]textarea elements, it is the element itself.
To determine if a word, sentence, or other piece of text in an
applicable element (as defined above) is to have spelling- and
grammar-checking enabled, the UA must use the following algorithm:
1. If the user has disabled the checking for this text, then the
checking is disabled.
2. Otherwise, if the user has forced the checking for this text to
always be enabled, then the checking is enabled.
3. Otherwise, if the element with which the text is associated has a
[34352]spellcheck content attribute, then: if that attribute is in
the [34353]true state, then checking is enabled; otherwise, if that
attribute is in the [34354]false state, then checking is disabled.
4. Otherwise, if there is an ancestor element with a [34355]spellcheck
content attribute that is not in the [34356]default state, then: if
the nearest such ancestor's [34357]spellcheck content attribute is
in the [34358]true state, then checking is enabled; otherwise,
checking is disabled.
5. Otherwise, if the element's [34359]default behavior is
[34360]true-by-default, then checking is enabled.
6. Otherwise, if the element's [34361]default behavior is
[34362]false-by-default, then checking is disabled.
7. Otherwise, if the element's parent element has its checking
enabled, then checking is enabled.
8. Otherwise, checking is disabled.
If the checking is enabled for a word/sentence/text, the user agent
should indicate spelling and grammar errors in that text. User agents
should take into account the other semantics given in the document when
suggesting spelling and grammar corrections. User agents may use the
language of the element to determine what spelling and grammar rules to
use, or may use the user's preferred language settings. UAs should use
[34363]input element attributes such as [34364]pattern to ensure that
the resulting value is valid, where possible.
If checking is disabled, the user agent should not indicate spelling or
grammar errors for that text.
The element with ID "a" in the following example would be the one used
to determine if the word "Hello" is checked for spelling errors. In
this example, it would not be.
Hello!
The element with ID "b" in the following example would have checking
enabled (the leading space character in the attribute's value on the
[34365]input element causes the attribute to be ignored, so the
ancestor's value is used instead, regardless of the default).
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.
6.8.6 Writing suggestions
User agents offer writing suggestions as users type into editable
regions, either in form controls (e.g., the [34366]textarea element) or
in elements in an [34367]editing host.
The writingsuggestions content attribute is an [34368]enumerated
attribute with the following keywords and states:
Keyword State Brief description
true true Writing suggestions should be offered on this element.
(the empty string)
false false Writing suggestions should not be offered on this element.
The attribute's [34369]missing value default is the default state. The
default state indicates that the element is to act according to a
default behavior, possibly based on the parent element's own
[34370]writingsuggestions state, as defined below.
The attribute's [34371]invalid value default is the [34372]true state.
element.[34373]writingSuggestions [ = value ]
Returns "true" if the user agent is to offer writing suggestions
under the scope of the element; otherwise, returns "false".
Can be set, to override the default and set the
[34374]writingsuggestions content attribute.
The computed writing suggestions value of a given element is determined
by running the following steps:
1. If element's [34375]writingsuggestions content attribute is in the
[34376]false state, return "false".
2. If element's [34377]writingsuggestions content attribute is in the
[34378]default state, element has a parent element, and the
[34379]computed writing suggestions value of element's parent
element is "false", then return "false".
3. Return "true".
The [34382]writingSuggestions IDL attribute is not affected by user
preferences that override the [34383]writingsuggestions content
attribute, and therefore might not reflect the actual writing
suggestions state.
The [34384]writingSuggestions setter steps are:
1. Set [34385]this's [34386]writingsuggestions content attribute to
the given value.
__________________________________________________________________
User agents should only offer suggestions within an element's scope if
the result of running the following algorithm given element returns
true:
1. If the user has disabled writing suggestions, then return false.
2. If none of the following conditions are true:
+ element is an [34387]input element whose [34388]type attribute
is in either the [34389]Text, [34390]Search, [34391]Telephone,
[34392]URL, or [34393]Email state and is [34394]mutable;
+ element is a [34395]textarea element that is [34396]mutable;
or
+ element is an [34397]editing host or is [34398]editable,
then return false.
3. If element has an [34399]inclusive ancestor with a
[34400]writingsuggestions content attribute that's not in the
[34401]default and the nearest such ancestor's
[34402]writingsuggestions content attribute is in the [34403]false
state, then return false.
4. Otherwise, return true.
This specification does not define the user interface for writing
suggestions. A user agent could offer on-demand suggestions, continuous
suggestions as the user types, inline suggestions, autofill-like
suggestions in a popup, or could use other interfaces.
6.8.7 Autocapitalization
Some methods of entering text, for example virtual keyboards on mobile
devices, and also voice input, often assist users by automatically
capitalizing the first letter of sentences (when composing text in a
language with this convention). A virtual keyboard that implements
autocapitalization might automatically switch to showing uppercase
letters (but allow the user to toggle it back to lowercase) when a
letter that should be autocapitalized is about to be typed. Other types
of input, for example voice input, may perform autocapitalization in a
way that does not give users an option to intervene first. The
[34404]autocapitalize attribute allows authors to control such
behavior.
The [34405]autocapitalize attribute, as typically implemented, does not
affect behavior when typing on a physical keyboard. (For this reason,
as well as the ability for users to override the autocapitalization
behavior in some cases or edit the text after initial input, the
attribute must not be relied on for any sort of input validation.)
The [34406]autocapitalize attribute can be used on an [34407]editing
host to control autocapitalization behavior for the hosted editable
region, on an [34408]input or [34409]textarea element to control the
behavior for inputting text into that element, or on a [34410]form
element to control the default behavior for all
[34411]autocapitalize-and-autocorrect inheriting elements associated
with the [34412]form element.
The [34413]autocapitalize attribute never causes autocapitalization to
be enabled for [34414]input elements whose [34415]type attribute is in
one of the [34416]URL, [34417]Email, or [34418]Password states. (This
behavior is included in the [34419]used autocapitalization hint
algorithm below.)
The autocapitalization processing model is based on selecting among
five autocapitalization hints, defined as follows:
default
The user agent and input method should make their own
determination of whether or not to enable autocapitalization.
none
No autocapitalization should be applied (all letters should
default to lowercase).
sentences
The first letter of each sentence should default to a capital
letter; all other letters should default to lowercase.
words
The first letter of each word should default to a capital
letter; all other letters should default to lowercase.
characters
All letters should default to uppercase.
(BUTTON) ✔MDN
[34420]Global_attributes/autocapitalize
Support in all current engines.
Firefox111+SafariNoChrome43+
__________________________________________________________________
The autocapitalize attribute is an [34421]enumerated attribute whose
states are the possible [34422]autocapitalization hints. The
[34423]autocapitalization hint specified by the attribute's state
combines with other considerations to form the [34424]used
autocapitalization hint, which informs the behavior of the user agent.
The keywords for this attribute and their state mappings are as
follows:
Keyword State
off [34425]none
none
on [34426]sentences
sentences
words [34427]words
characters [34428]characters
The attribute's [34429]missing value default is the [34430]default
state, and its [34431]invalid value default is the [34432]sentences
state.
element.[34433]autocapitalize [ = value ]
Returns the current autocapitalization state for the element, or
an empty string if it hasn't been set. Note that for
[34434]input and [34435]textarea elements that inherit their
state from a [34436]form element, this will return the
autocapitalization state of the [34437]form element, but for an
element in an editable region, this will not return the
autocapitalization state of the editing host (unless this
element is, in fact, the [34438]editing host).
Can be set, to set the [34439]autocapitalize content attribute
(and thereby change the autocapitalization behavior for the
element).
To compute the own autocapitalization hint of an element element, run
the following steps:
1. If the [34440]autocapitalize content attribute is present on
element, and its value is not the empty string, return the state of
the attribute.
2. If element is an [34441]autocapitalize-and-autocorrect inheriting
element and has a non-null [34442]form owner, return the [34443]own
autocapitalization hint of element's [34444]form owner.
3. Return [34445]default.
The autocapitalize getter steps are to:
1. Let state be the [34446]own autocapitalization hint of [34447]this.
2. If state is [34448]default, then return the empty string.
3. If state is [34449]none, then return "[34450]none".
4. If state is [34451]sentences, then return "[34452]sentences".
5. Return the keyword value corresponding to state.
The [34453]autocapitalize setter steps are to set the
[34454]autocapitalize content attribute to the given value.
__________________________________________________________________
User agents that support customizable autocapitalization behavior for a
text input method and wish to allow web developers to control this
functionality should, during text input into an element, compute the
used autocapitalization hint for the element. This will be an
[34455]autocapitalization hint that describes the recommended
autocapitalization behavior for text input into the element.
User agents or input methods may choose to ignore or override the
[34456]used autocapitalization hint in certain circumstances.
The [34457]used autocapitalization hint for an element element is
computed using the following algorithm:
1. If element is an [34458]input element whose [34459]type attribute
is in one of the [34460]URL, [34461]Email, or [34462]Password
states, then return [34463]default.
2. If element is an [34464]input element or a [34465]textarea element,
then return element's [34466]own autocapitalization hint.
3. If element is an [34467]editing host or an [34468]editable element,
then return the [34469]own autocapitalization hint of the
[34470]editing host of element.
4. [34471]Assert: this step is never reached, since text input only
occurs in elements that meet one of the above criteria.
6.8.8 Autocorrection
Some methods of entering text assist users by automatically correcting
misspelled words while typing, a process also known as autocorrection.
User agents can support autocorrection of editable text, either in form
controls (such as the value of [34472]textarea elements), or in
elements in an [34473]editing host (e.g., using
[34474]contenteditable). Autocorrection may be accompanied by user
interfaces indicating that text is about to be autocorrected or has
been autocorrected, and is commonly performed when inserting
punctuation characters, spaces, or new paragraphs after misspelled
words. The [34475]autocorrect attribute allows authors to control such
behavior.
The [34476]autocorrect attribute can be used on an editing host to
control autocorrection behavior for the hosted editable region, on an
[34477]input or [34478]textarea element to control the behavior when
inserting text into that element, or on a [34479]form element to
control the default behavior for all
[34480]autocapitalize-and-autocorrect inheriting elements associated
with the [34481]form element.
The [34482]autocorrect attribute never causes autocorrection to be
enabled for [34483]input elements whose [34484]type attribute is in one
of the [34485]URL, [34486]E-mail, or [34487]Password states. (This
behavior is included in the [34488]used autocorrection state algorithm
below.)
The autocorrect attribute is an enumerated attribute with the following
keywords and states:
Keyword State Brief description
on on The user agent is permitted to automatically correct spelling
errors while the user types. Whether spelling is automatically
corrected while typing left is for the user agent to decide, and may
depend on the element as well as the user's preferences.
(the empty string)
off off The user agent is not allowed to automatically correct spelling
while the user types.
The attribute's [34489]invalid value default and [34490]missing value
default are both the [34491]on state.
The autocorrect getter steps are: return true if the element's
[34492]used autocorrection state is [34493]on and false if the
element's [34494]used autocorrection state is [34495]off. The setter
steps are: if the given value is true, then the element's
[34496]autocorrect attribute must be set to "on"; otherwise it must be
set to "off".
To compute the used autocorrection state of an element element, run
these steps:
1. If element is an [34497]input element whose [34498]type attribute
is in one of the [34499]URL, [34500]E-mail, or [34501]Password
states, then return [34502]off.
2. If the [34503]autocorrect content attribute is present on element,
then return the state of the attribute.
3. If element is an [34504]autocapitalize-and-autocorrect inheriting
element and has a non-null [34505]form owner, then return the state
of element's [34506]form owner's [34507]autocorrect attribute.
4. Return [34508]on.
element . [34509]autocorrect
Returns the autocorrection behavior of the element. Note that
for [34510]autocapitalize-and-autocorrect inheriting elements
that inherit their state from a [34511]form element, this will
return the autocorrection behavior of the [34512]form element,
but for an element in an editable region, this will not return
the autocorrection behavior of the [34513]editing host (unless
this element is, in fact, the [34514]editing host).
element . [34515]autocorrect = value
Updates the [34516]autocorrect content attribute (and thereby
changes the autocorrection behavior of the element).
The [34517]input element in the following example would not allow
autocorrection, since it does not have an [34518]autocorrect content
attribute and therefore inherits from the [34519]form element, which
has an attribute of "[34520]off". However, the [34521]textarea element
would allow autocorrection, since it has an [34522]autocorrect content
attribute with a value of "[34523]on".
6.8.9 Input modalities: the [34524]inputmode attribute
User agents can support the [34525]inputmode attribute on form controls
(such as the value of [34526]textarea elements), or in elements in an
[34527]editing host (e.g., using [34528]contenteditable).
(BUTTON) ✔MDN
[34529]Global_attributes/inputmode
Support in all current engines.
Firefox95+SafariNoChrome66+
__________________________________________________________________
The inputmode content attribute is an [34530]enumerated attribute that
specifies what kind of input mechanism would be most helpful for users
entering content.
Keyword Description
none The user agent should not display a virtual keyboard. This keyword
is useful for content that renders its own keyboard control.
text The user agent should display a virtual keyboard capable of text
input in the user's locale.
tel The user agent should display a virtual keyboard capable of
telephone number input. This should 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).
url The user agent should display a virtual keyboard capable of text
input in the user's locale, with keys for aiding in the input of
[34531]URLs, such as that for the "/" and "." characters and for quick
input of strings commonly found in domain names such as "www." or
".com".
email The user agent should display a virtual keyboard capable of 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.
numeric The user agent should display a virtual keyboard capable of
numeric input. This keyword is useful for PIN entry.
decimal The user agent should display a virtual keyboard capable of
fractional numeric input. Numeric keys and the format separator for the
locale should be shown.
search The user agent should display a virtual keyboard optimized for
search.
(BUTTON) ✔MDN
[34532]HTMLElement/inputMode
Support in all current engines.
Firefox95+Safari12.1+Chrome66+
__________________________________________________________________
The inputMode IDL attribute must [34533]reflect the [34534]inputmode
content attribute, [34535]limited to only known values.
When [34536]inputmode is unspecified (or is in a state not supported by
the user agent), the user agent should determine the default virtual
keyboard to be shown. Contextual information such as the input
[34537]type or [34538]pattern attributes should be used to determine
which type of virtual keyboard should be presented to the user.
6.8.10 Input modalities: the [34539]enterkeyhint attribute
User agents can support the [34540]enterkeyhint attribute on form
controls (such as the value of [34541]textarea elements), or in
elements in an [34542]editing host (e.g., using
[34543]contenteditable).
(BUTTON) ✔MDN
[34544]Global_attributes/enterkeyhint
Support in all current engines.
Firefox94+Safari13.1+Chrome77+
__________________________________________________________________
The enterkeyhint content attribute is an [34545]enumerated attribute
that specifies what action label (or icon) to present for the enter key
on virtual keyboards. This allows authors to customize the presentation
of the enter key in order to make it more helpful for users.
Keyword Description
enter The user agent should present a cue for the operation 'enter',
typically inserting a new line.
done The user agent should present a cue for the operation 'done',
typically meaning there is nothing more to input and the input method
editor (IME) will be closed.
go The user agent should present a cue for the operation 'go',
typically meaning to take the user to the target of the text they
typed.
next The user agent should present a cue for the operation 'next',
typically taking the user to the next field that will accept text.
previous The user agent should present a cue for the operation
'previous', typically taking the user to the previous field that will
accept text.
search The user agent should present a cue for the operation 'search',
typically taking the user to the results of searching for the text they
have typed.
send The user agent should present a cue for the operation 'send',
typically delivering the text to its target.
(BUTTON) ✔MDN
[34546]HTMLElement/enterKeyHint
Support in all current engines.
Firefox94+Safari13.1+Chrome77+
__________________________________________________________________
The enterKeyHint IDL attribute must [34547]reflect the
[34548]enterkeyhint content attribute, [34549]limited to only known
values.
When [34550]enterkeyhint is unspecified (or is in a state not supported
by the user agent), the user agent should determine the default action
label (or icon) to present. Contextual information such as the
[34551]inputmode, [34552]type, or [34553]pattern attributes should be
used to determine which action label (or icon) to present on the
virtual keyboard.
6.9 Find-in-page
6.9.1 Introduction
This section defines find-in-page — a common user-agent mechanism which
allows users to search through the contents of the page for particular
information.
Access to the [34554]find-in-page feature is provided via a
find-in-page interface. This is a user-agent provided user interface,
which allows the user to specify input and the parameters of the
search. This interface can appear as a result of a shortcut or a menu
selection.
A combination of text input and settings in the [34555]find-in-page
interface represents the user query. This typically includes the text
that the user wants to search for, as well as optional settings (e.g.,
the ability to restrict the search to whole words only).
The user-agent processes page contents for a given [34556]query, and
identifies zero or more matches, which are content ranges that satisfy
the user [34557]query.
One of the [34558]matches is identified to the user as the active
match. It is highlighted and scrolled into view. The user can navigate
through the [34559]matches by advancing the [34560]active match using
the [34561]find-in-page interface.
[34562]Issue #3539 tracks standardizing how [34563]find-in-page
underlies the currently-unspecified window.find() API.
6.9.2 Interaction with [34564]details and [34565]hidden=until-found
When find-in-page begins searching for matches, all [34566]details
elements in the page which do not have their [34567]open attribute set
should have the [34568]skipped contents of their second slot become
accessible, without modifying the [34569]open attribute, in order to
make find-in-page able to search through it. Similarly, all HTML
elements with the [34570]hidden attribute in the [34571]hidden until
found state should have their [34572]skipped contents become accessible
without modifying the [34573]hidden attribute in order to make
find-in-page able to search through them. After find-in-page finishes
searching for matches, the [34574]details elements and the elements
with the [34575]hidden attribute in the [34576]hidden until found state
should have their contents become skipped again. This entire process
must happen synchronously (and so is not observable to users or to
author code). [34577][CSSCONTAIN]
When find-in-page chooses a new [34578]active match, perform the
following steps:
1. Let node be the first node in the [34579]active match.
2. [34580]Queue a global task on the [34581]user interaction task
source given node's [34582]relevant global object to run the
following steps:
1. Run the [34583]ancestor details revealing algorithm on node.
2. Run the [34584]ancestor hidden-until-found revealing algorithm
on node.
[34585](This is a tracking vector.) When find-in-page auto-expands a
[34586]details element like this, it will fire a [34587]toggle event.
As with the separate [34588]scroll event that find-in-page fires, this
event could be used by the page to discover what the user is typing
into the find-in-page dialog. If the page creates a tiny scrollable
area with the current search term and every possible next character the
user could type separated by a gap, and observes which one the browser
scrolls to, it can add that character to the search term and update the
scrollable area to incrementally build the search term. By wrapping
each possible next match in a closed [34589]details element, the page
could listen to [34590]toggle events instead of [34591]scroll events.
This attack could be addressed for both events by not acting on every
character the user types into the find-in-page dialog.
6.9.3 Interaction with selection
The find-in-page process is invoked in the context of a document, and
may have an effect on the [34592]selection of that document.
Specifically, the range that defines the [34593]active match can
dictate the current selection. These selection updates, however, can
happen at different times during the find-in-page process (e.g. upon
the [34594]find-in-page interface dismissal or upon a change in the
[34595]active match range).
6.10 Close requests and close watchers
6.10.1 Close requests
In an [34596]implementation-defined (and likely device-specific)
manner, a user can send a close request to the user agent. This
indicates that the user wishes to close something that is currently
being shown on the screen, such as a popover, menu, dialog, picker, or
display mode.
Some example close requests are:
* The Esc key on desktop platforms.
* The back button or gesture on certain mobile platforms such as
Android.
* Any assistive technology's dismiss gesture, such as iOS VoiceOver's
two-finger scrub "z" gesture.
* A game controller's canonical "back" button, such as the circle
button on a DualShock gamepad.
Whenever the user agent receives a potential close request targeted at
a [34597]Document document, it must [34598]queue a global task on the
[34599]user interaction task source given document's [34600]relevant
global object to perform the following close request steps:
1. If document's [34601]fullscreen element is not null, then:
1. [34602]Fully exit fullscreen given document's [34603]node
navigable's [34604]top-level traversable's [34605]active
document.
2. Return.
This does not fire any relevant event, such as [34606]keydown; it
only causes [34607]fullscreenchange to be eventually fired.
2. Optionally, skip to the step labeled [34608]alternative processing.
For example, if the user agent detects user frustration at repeated
close request interception by the current web page, it might take
this path.
3. Fire any relevant events, per UI Events or other relevant
specifications. [34609][UIEVENTS]
An example of a relevant event in the UI Events model would be the
[34610]keydown event that UI Events [34611]suggests firing when the
user presses the Esc key on their keyboard. On most platforms with
keyboards, this is treated as a [34612]close request, and so would
trigger these [34613]close request steps.
An example of relevant events that are outside of the model given
in UI Events would be assistive technology synthesizing an Esc
[34614]keydown event when the user sends a [34615]close request by
using a dismiss gesture.
4. Let event be null if no such events are fired, or the [34616]Event
object representing one of the fired events otherwise. If multiple
events are fired, which one is chosen is
[34617]implementation-defined.
5. If event is not null, and its [34618]canceled flag is set, then
return.
6. If document is not [34619]fully active, then return.
This step is necessary because, if event is not null, then an event
listener might have caused document to no longer be [34620]fully
active.
7. Let closedSomething be the result of [34621]processing close
watchers on document's [34622]relevant global object.
8. If closedSomething is true, then return.
9. Alternative processing: Otherwise, there was nothing watching for a
[34623]close request. The user agent may instead interpret this
interaction as some other action, instead of interpreting it as a
close request.
On platforms where pressing the Esc key is interpreted as a
[34624]close request, the user agent must interpret the key being
pressed down as the close request, instead of the key being released.
Thus, in the above algorithm, the "relevant events" that are fired must
be the single [34625]keydown event.
On platforms where Esc is the [34626]close request, the user agent will
first fire an appropriately-initialized [34627]keydown event. If the
web developer cancels the event by calling [34628]preventDefault(),
then nothing further happens. But if the event fires without being
canceled, then the user agent proceeds to [34629]process close
watchers.
On platforms where a back button is a potential [34630]close request,
no event is involved, so when the back button is pressed, the user
agent proceeds directly to [34631]process close watchers. If there is
an [34632]active [34633]close watcher, then that will get triggered. If
there is not, then the user agent can interpret the back button press
in another way, for example as a request to [34634]traverse the history
by a delta of −1.
6.10.2 Close watcher infrastructure
Each [34635]Window has a close watcher manager, which is a
[34636]struct with the following [34637]items:
* Groups, a [34638]list of [34639]lists of [34640]close watchers,
initially empty.
* Allowed number of groups, a number, initially 1.
* Next user interaction allows a new group, a boolean, initially
true.
Most of the complexity of the [34641]close watcher manager comes from
anti-abuse protections designed to prevent developers from disabling
users' history traversal abilities, for platforms where a [34642]close
request's [34643]fallback action is the main mechanism of history
traversal. In particular:
The grouping of [34644]close watchers is designed so that if multiple
close watchers are created without [34645]history-action activation,
they are grouped together, so that a user-triggered [34646]close
request will close all of the close watchers in a group. This ensures
that web developers can't intercept an unlimited number of close
requests by creating close watchers; instead they can create a number
equal to at most 1 + the number of times the [34647]user activates the
page.
The [34648]next user interaction allows a new group boolean encourages
web developers to create [34649]close watchers in a way that is tied to
individual [34650]user activations. Without it, each user activation
would increase the [34651]allowed number of groups, even if the web
developer isn't "using" those user activations to create close
watchers. In short:
* Allowed: user interaction; create a close watcher in its own group;
user interaction; create a close watcher in a second independent
group.
* Disallowed: user interaction; user interaction; create a close
watcher in its own group; create a close watcher in a second
independent group.
* Allowed: user interaction; user interaction; create a close watcher
in its own group; create a close watcher grouped with the previous
one.
This protection is not important for upholding our desired invariant of
creating at most (1 + the number of times the [34652]user activates the
page) groups. A determined abuser will just create one close watcher
per user interaction, "banking" them for future abuse. But this system
causes more predictable behavior for the normal case, and encourages
non-abusive developers to create close watchers directly in response to
user interactions.
To notify the close watcher manager about user activation given a
[34653]Window window:
1. Let manager be window's [34654]close watcher manager.
2. If manager's [34655]next user interaction allows a new group is
true, then increment manager's [34656]allowed number of groups.
3. Set manager's [34657]next user interaction allows a new group to
false.
__________________________________________________________________
A close watcher is a [34658]struct with the following [34659]items:
* A window, a [34660]Window.
* A cancel action, an algorithm accepting a boolean argument and
returning a boolean. The argument indicates whether or not the
cancel action algorithm can prevent the close request from
proceeding via the algorithm's return value. If the boolean
argument is true, then the algorithm can return either true to
indicate that the caller will proceed to the [34661]close action,
or false to indicate that the caller will bail out. If the argument
is false, then the return value is always false. This algorithm can
never throw an exception.
* A close action, an algorithm accepting no arguments and returning
nothing. This algorithm can never throw an exception.
* An is running cancel action boolean.
* A get enabled state, an algorithm accepting no arguments and
returning a boolean. This algorithm can never throw an exception.
A [34662]close watcher closeWatcher is active if closeWatcher's
[34663]window's [34664]close watcher manager [34665]contains any list
which [34666]contains closeWatcher.
__________________________________________________________________
To establish a close watcher given a [34667]Window window, a list of
steps cancelAction, a list of steps closeAction, and an algorithm that
returns a boolean getEnabledState:
1. [34668]Assert: window's [34669]associated Document is [34670]fully
active.
2. Let closeWatcher be a new [34671]close watcher, with
[34672]window
window
[34673]cancel action
cancelAction
[34674]close action
closeAction
[34675]is running cancel action
false
[34676]get enabled state
getEnabledState
3. Let manager be window's [34677]close watcher manager.
4. If manager's [34678]groups's [34679]size is less than manager's
[34680]allowed number of groups, then [34681]append « closeWatcher
» to manager's [34682]groups.
5. Otherwise:
1. [34683]Assert: manager's [34684]groups's [34685]size is at
least 1 in this branch, since manager's [34686]allowed number
of groups is always at least 1.
2. [34687]Append closeWatcher to manager's [34688]groups's last
[34689]item.
6. Set manager's [34690]next user interaction allows a new group to
true.
7. Return closeWatcher.
To request to close a [34691]close watcher closeWatcher with boolean
requireHistoryActionActivation:
1. If closeWatcher [34692]is not active, then return true.
2. If the result of running closeWatcher's [34693]get enabled state is
false, then return true.
3. If closeWatcher's [34694]is running cancel action is true, then
return true.
4. Let window be closeWatcher's [34695]window.
5. If window's [34696]associated Document is not [34697]fully active,
then return true.
6. Let canPreventClose be true if requireHistoryActionActivation is
false, or if window's [34698]close watcher manager's
[34699]groups's [34700]size is less than window's [34701]close
watcher manager's [34702]allowed number of groups, and window has
[34703]history-action activation; otherwise false.
7. Set closeWatcher's [34704]is running cancel action to true.
8. Let shouldContinue be the result of running closeWatcher's
[34705]cancel action given canPreventClose.
9. Set closeWatcher's [34706]is running cancel action to false.
10. If shouldContinue is false, then:
1. [34707]Assert: canPreventClose is true.
2. [34708]Consume history-action user activation given window.
3. Return false.
Note that since these substeps [34709]consume history-action user
activation, [34710]requesting to close a [34711]close watcher twice
without any intervening [34712]user activation will result in
canPreventClose being false the second time.
11. [34713]Close closeWatcher.
12. Return true.
To close a [34714]close watcher closeWatcher:
1. If closeWatcher [34715]is not active, then return.
2. If the result of running closeWatcher's [34716]get enabled state is
false, then return.
3. If closeWatcher's [34717]window's [34718]associated Document is not
[34719]fully active, then return.
4. [34720]Destroy closeWatcher.
5. Run closeWatcher's [34721]close action.
To destroy a [34722]close watcher closeWatcher:
1. Let manager be closeWatcher's [34723]window's [34724]close watcher
manager.
2. [34725]For each group of manager's [34726]groups: [34727]remove
closeWatcher from group.
3. [34728]Remove any item from manager's [34729]groups that [34730]is
empty.
__________________________________________________________________
To process close watchers given a [34731]Window window:
1. Let processedACloseWatcher be false.
2. If window's [34732]close watcher manager's [34733]groups is not
empty:
1. Let group be the last [34734]item in window's [34735]close
watcher manager's [34736]groups.
2. [34737]For each closeWatcher of group, in reverse order:
1. If the result of running closeWatcher's [34738]get
enabled state is true, set processedACloseWatcher to
true.
2. Let shouldProceed be the result of [34739]requesting to
close closeWatcher with true.
3. If shouldProceed is false, then [34740]break.
3. If window's [34741]close watcher manager's [34742]allowed number of
groups is greater than 1, decrement it by 1.
4. Return processedACloseWatcher.
watcher = new [34755]CloseWatcher()
watcher = new [34756]CloseWatcher({ [34757]signal })
Creates a new [34758]CloseWatcher instance.
If the [34759]signal option is provided, then watcher can be
destroyed (as if by [34760]watcher.destroy()) by aborting the
given [34761]AbortSignal.
If any [34762]close watcher is already active, and the
[34763]Window does not have [34764]history-action activation,
then the resulting [34765]CloseWatcher will be closed together
with that already-active [34766]close watcher in response to any
[34767]close request. (This already-active [34768]close watcher
does not necessarily have to be a [34769]CloseWatcher object; it
could be a modal [34770]dialog element, or a popover generated
by an element with the [34771]popover attribute.)
watcher.[34772]requestClose()
Acts as if a [34773]close request was sent targeting watcher, by
first firing a [34774]cancel event, and if that event is not
canceled with [34775]preventDefault(), proceeding to fire a
[34776]close event before deactivating the close watcher as if
[34777]watcher.destroy() was called.
This is a helper utility that can be used to consolidate
cancelation and closing logic into the [34778]cancel and
[34779]close event handlers, by having all non-[34780]close
request closing affordances call this method.
watcher.[34781]close()
Immediately fires the [34782]close event, and then deactivates
the close watcher as if [34783]watcher.destroy() was called.
This is a helper utility that can be used trigger the closing
logic into the [34784]close event handler, skipping any logic in
the [34785]cancel event handler.
watcher.[34786]destroy()
Deactivates watcher, so that it will no longer receive
[34787]close events and so that new independent
[34788]CloseWatcher instances can be constructed.
This is intended to be called if the relevant UI element is torn
down in some other way than being closed.
Each [34789]CloseWatcher instance has an internal close watcher, which
is a [34790]close watcher.
The new CloseWatcher(options) constructor steps are:
1. If [34791]this's [34792]relevant global object's [34793]associated
Document is not [34794]fully active, then throw an
[34795]"InvalidStateError" [34796]DOMException.
2. Let closeWatcher be the result of [34797]establishing a close
watcher given [34798]this's [34799]relevant global object, with:
+ [34800]cancelAction given canPreventClose being to return the
result of [34801]firing an event named [34802]cancel at
[34803]this, with the [34804]cancelable attribute initialized
to canPreventClose.
+ [34805]closeAction being to [34806]fire an event named
[34807]close at [34808]this.
+ [34809]getEnabledState being to return true.
3. If options["[34810]signal"] [34811]exists, then:
1. If options["[34812]signal"] is [34813]aborted, then
[34814]destroy closeWatcher.
2. [34815]Add the following steps to options["[34816]signal"]:
1. [34817]Destroy closeWatcher.
4. Set [34818]this's [34819]internal close watcher to closeWatcher.
The requestClose() method steps are to [34820]request to close
[34821]this's [34822]internal close watcher with false.
The close() method steps are to [34823]close [34824]this's
[34825]internal close watcher.
The destroy() method steps are to [34826]destroy [34827]this's
[34828]internal close watcher.
The following are the [34829]event handlers (and their corresponding
[34830]event handler event types) that must be supported, as
[34831]event handler IDL attributes, by all objects implementing the
[34832]CloseWatcher interface:
[34833]Event handler [34834]Event handler event type
oncancel [34835]cancel
onclose [34836]close
If one wanted to implement a custom picker control, which closed itself
on a user-provided [34837]close request as well as when a close button
is pressed, the following code shows how one would use the
[34838]CloseWatcher API to process close requests:
const watcher = new CloseWatcher();
const picker = setUpAndShowPickerDOMElement();
Note how the logic to gather the chosen value is centralized in the
[34839]CloseWatcher object's [34840]close event handler, with the
[34841]click event handler for the close button delegating to that
logic by calling [34842]requestClose().
The [34843]cancel event on [34844]CloseWatcher objects can be used to
prevent the [34845]close event from firing, and the [34846]CloseWatcher
from being destroying. A typical use case is as follows:
watcher.oncancel = async (e) => {
if (hasUnsavedData && e.cancelable) {
e.preventDefault();
const userReallyWantsToClose = await askForConfirmation("Are you sure you wa
nt to close?");
if (userReallyWantsToClose) {
hasUnsavedData = false;
watcher.close();
}
}
};
For abuse prevention purposes, this event is only [34847]cancelable if
the page has [34848]history-action activation, which will be lost after
any given [34849]close request. This ensures that if the user sends a
close request twice in a row without any intervening user activation,
the request definitely succeeds; the second request ignores any
[34850]cancel event handler's attempt to call [34851]preventDefault()
and proceeds to close the [34852]CloseWatcher.
Combined, the above two examples show how [34853]requestClose() and
[34854]close() differ. Because we used [34855]requestClose() in the
[34856]click event handler for the close button, clicking that button
will trigger the [34857]CloseWatcher's [34858]cancel event, and thus
potentially ask the user for confirmation if there is unsaved data. If
we had used [34859]close(), then this check would be skipped. Sometimes
that is appropriate, but usually [34860]requestClose() is the better
option for user-triggered close requests.
In addition to the [34861]user activation restrictions for
[34862]cancel events, there is a more subtle form of user activation
gating for [34863]CloseWatcher construction. If one creates more than
one [34864]CloseWatcher without user activation, then the newly-created
one will get grouped together with the most-recently-created
[34865]close watcher, so that a single [34866]close request will close
them both:
window.onload = () => {
// This will work as normal: it is the first close watcher created without use
r activation.
(new CloseWatcher()).onclose = () => { /* ... */ };
};
button1.onclick = () => {
// This will work as normal: the button click counts as user activation.
(new CloseWatcher()).onclose = () => { /* ... */ };
};
button2.onclick = () => {
// These will be grouped together, and both will close in response to a single
close request.
(new CloseWatcher()).onclose = () => { /* ... */ };
(new CloseWatcher()).onclose = () => { /* ... */ };
};
This means that calling [34867]destroy(), [34868]close(), or
[34869]requestClose() properly is important. Doing so is the only way
to get back the "free" ungrouped close watcher slot. Such close
watchers created without user activation are useful for cases like
session inactivity timeout dialogs or urgent notifications of
server-triggered events, which are not generated in response to user
activation.
6.11 Drag and drop
(BUTTON) ✔MDN
[34870]HTML_Drag_and_Drop_API
Support in all current engines.
Firefox3.5+Safari3.1+Chrome4+
__________________________________________________________________
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 [34871]mousedown event that is followed by a
series of [34872]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-and-drop operation, stating what they wish to drag and where they
wish to drop it, respectively.
However it is implemented, drag-and-drop operations must have a
starting point (e.g. where the mouse was clicked, or the start of the
selection or element that was selected for the drag), may have any
number of intermediate steps (elements that the mouse moves over during
a drag, or elements that the user picks as possible drop points as they
cycle through possibilities), and must either have an end point (the
element above which the mouse button was released, or the element that
was finally selected), or be canceled. The end point must be the last
element selected as a possible drop point before the drop occurs (so if
the operation is not canceled, there must be at least one element in
the middle step).
6.11.1 Introduction
This section is non-normative.
To make an element draggable, give the element a [34873]draggable
attribute, and set an event listener for [34874]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
[34875]DataTransfer object and set the allowed effects (copy, move,
link, or some combination).
To accept a drop, the drop target has to listen to the following
events:
1. The [34876]dragenter event handler reports whether or not the drop
target is potentially willing to accept the drop, by canceling the
event.
2. The [34877]dragover event handler specifies what feedback will be
shown to the user, by setting the [34878]dropEffect attribute of
the [34879]DataTransfer associated with the event. This event also
needs to be canceled.
3. The [34880]drop event handler has a final chance to accept or
reject the drop. If the drop is accepted, the event handler must
perform the drop operation on the target. This event needs to be
canceled, so that the [34881]dropEffect attribute's value can be
used by the source. Otherwise, the drop operation is rejected.
To remove the original element (the one that was dragged) from the
display, the [34882]dragend event can be used.
For our example here, that means updating the original markup to handle
that event:
What fruits do you like?
...as before...
6.11.2 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:
Text
Text.
File
Binary data with a filename.
The drag data item type string
A Unicode string giving the type or format of the data,
generally given by a [34883]MIME type. Some values that
are not [34884]MIME types are special-cased for legacy
reasons. The API does not enforce the use of [34885]MIME
types; other values can be used as well. In all cases,
however, the values are all [34886]converted to ASCII
lowercase by the API.
There is a limit of one text item per [34887]item type
string.
The actual data
A Unicode or binary string, in some cases with a filename
(itself a Unicode string), as per [34888]the drag data
item kind.
The [34889]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 [34890]dragstart event. New data can be added to
the [34891]drag data store.
Read-only mode
For the [34892]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
[34893]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 [34894]drag data store is created, it must be initialized such
that its [34895]drag data store item list is empty, it has no
[34896]drag data store default feedback, it has no [34897]drag data
store bitmap and [34898]drag data store hot spot coordinate, its
[34899]drag data store mode is [34900]protected mode, and its
[34901]drag data store allowed effects state is the string
"[34902]uninitialized".
6.11.3 The [34903]DataTransfer interface
(BUTTON) ✔MDN
[34904]DataTransfer
Support in all current engines.
Firefox3.5+Safari4+Chrome3+
__________________________________________________________________
[34905]DataTransfer objects are used to expose the [34906]drag data
store that underlies a drag-and-drop operation.
[Exposed=Window]
interface DataTransfer {
[34907]constructor();
Firefox Android?Safari iOS?Chrome Android?WebView
Android?Samsung Internet8.0+Opera Android44+
Creates a new [34921]DataTransfer object with an empty
[34922]drag data store.
Firefox Android?Safari iOS?Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
Returns the kind of operation that is currently selected. If the
kind of operation isn't one of those that is allowed by the
[34925]effectAllowed attribute, then the operation will fail.
Can be set, to change the selected operation.
The possible values are "[34926]none", "[34927]copy",
"[34928]link", and "[34929]move".
Firefox Android?Safari iOS?Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
Returns the kinds of operations that are to be allowed.
Can be set (during the [34932]dragstart event), to change the
allowed operations.
The possible values are "[34933]none", "[34934]copy",
"[34935]copyLink", "[34936]copyMove", "[34937]link",
"[34938]linkMove", "[34939]move", "[34940]all", and
"[34941]uninitialized",
Firefox Android52+Safari iOS?Chrome Android?WebView
Android37+Samsung Internet?Opera Android12+
Returns a [34944]DataTransferItemList object, with the drag
data.
Firefox Android?Safari iOS?Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
Uses the given element to update the drag feedback, replacing
any previously specified feedback.
Firefox Android?Safari iOS?Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
Returns a [34949]frozen array listing the formats that were set
in the [34950]dragstart event. In addition, if any files are
being dragged, then one of the types will be the string "Files".
Firefox Android?Safari iOS?Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
Returns the specified data. If there is no such data, returns
the empty string.
Firefox Android?Safari iOS?Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
Removes the data of the specified formats. Removes all data if
the argument is omitted.
Firefox Android?Safari iOS?Chrome Android?WebView
Android37+Samsung Internet?Opera Android12.1+
Returns a [34959]FileList of the files being dragged, if any.
[34960]DataTransfer objects that are created as part of
[34961]drag-and-drop events are only valid while those events are being
fired.
A [34962]DataTransfer object is associated with a [34963]drag data
store while it is valid.
A [34964]DataTransfer object has an associated types array, which is a
[34965]FrozenArray, initially empty. When the contents of
the [34966]DataTransfer object's [34967]drag data store item list
change, or when the [34968]DataTransfer object becomes no longer
associated with a [34969]drag data store, run the following steps:
1. Let L be an empty sequence.
2. If the [34970]DataTransfer object is still associated with a
[34971]drag data store, then:
1. For each item in the [34972]DataTransfer object's [34973]drag
data store item list whose [34974]kind is text, add an entry
to L consisting of the item's [34975]type string.
2. If there are any items in the [34976]DataTransfer object's
[34977]drag data store item list whose [34978]kind is File,
then add an entry to L consisting of the string "Files". (This
value can be distinguished from the other values because it is
not lowercase.)
3. Set the [34979]DataTransfer object's [34980]types array to the
result of [34981]creating a frozen array from L.
The DataTransfer() constructor, when invoked, must return a newly
created [34982]DataTransfer object initialized as follows:
1. Set the [34983]drag data store's [34984]item list to be an empty
list.
2. Set the [34985]drag data store's [34986]mode to [34987]read/write
mode.
3. Set the [34988]dropEffect and [34989]effectAllowed to "none".
The dropEffect attribute controls the drag-and-drop feedback that the
user is given during a drag-and-drop operation. When the
[34990]DataTransfer object is created, the [34991]dropEffect attribute
is set to a string value. On getting, it must return its current value.
On setting, if the new value is one of "none", "copy", "link", or
"move", then the attribute's current value must be set to the new
value. Other values must be ignored.
The effectAllowed attribute is used in the drag-and-drop processing
model to initialize the [34992]dropEffect attribute during the
[34993]dragenter and [34994]dragover events. When the
[34995]DataTransfer object is created, the [34996]effectAllowed
attribute is set to a string value. On getting, it must return its
current value. On setting, if [34997]drag data store's [34998]mode is
the [34999]read/write mode and the new value is one of "none", "copy",
"copyLink", "copyMove", "link", "linkMove", "move", "all", or
"uninitialized", then the attribute's current value must be set to the
new value. Otherwise, it must be left unchanged.
The items attribute must return a [35000]DataTransferItemList object
associated with the [35001]DataTransfer object.
The setDragImage(image, x, y) method must run the following steps:
1. If the [35002]DataTransfer object is no longer associated with a
[35003]drag data store, return. Nothing happens.
2. If the [35004]drag data store's [35005]mode is not the
[35006]read/write mode, return. Nothing happens.
3. If image is an [35007]img element, then set the [35008]drag data
store bitmap to the element's image (at its [35009]natural size);
otherwise, set the [35010]drag data store bitmap to an image
generated from the given element (the exact mechanism for doing so
is not currently specified).
4. Set the [35011]drag data store hot spot coordinate to the given x,
y coordinate.
The types attribute must return this [35012]DataTransfer object's
[35013]types array.
The getData(format) method must run the following steps:
1. If the [35014]DataTransfer object is no longer associated with a
[35015]drag data store, then return the empty string.
2. If the [35016]drag data store's [35017]mode is the [35018]protected
mode, then return the empty string.
3. Let format be the first argument, [35019]converted to ASCII
lowercase.
4. Let convert-to-URL be false.
5. If format equals "text", change it to "text/plain".
6. If format equals "url", change it to "text/uri-list" and set
convert-to-URL to true.
7. If there is no item in the [35020]drag data store item list whose
[35021]kind is text and whose [35022]type string is equal to
format, return the empty string.
8. Let result be the data of the item in the [35023]drag data store
item list whose [35024]kind is Plain Unicode string and whose
[35025]type string is equal to format.
9. If convert-to-URL is true, then parse result as appropriate for
text/uri-list data, and then set result to the first URL from the
list, if any, or the empty string otherwise. [35026][RFC2483]
10. Return result.
The setData(format, data) method must run the following steps:
1. If the [35027]DataTransfer object is no longer associated with a
[35028]drag data store, return. Nothing happens.
2. If the [35029]drag data store's [35030]mode is not the
[35031]read/write mode, return. Nothing happens.
3. Let format be the first argument, [35032]converted to ASCII
lowercase.
4. If format equals "text", change it to "text/plain".
If format equals "url", change it to "text/uri-list".
5. Remove the item in the [35033]drag data store item list whose
[35034]kind is text and whose [35035]type string is equal to
format, if there is one.
6. Add an item to the [35036]drag data store item list whose
[35037]kind is text, whose [35038]type string is equal to format,
and whose data is the string given by the method's second argument.
The clearData(format) method must run the following steps:
1. If the [35039]DataTransfer object is no longer associated with a
[35040]drag data store, return. Nothing happens.
2. If the [35041]drag data store's [35042]mode is not the
[35043]read/write mode, return. Nothing happens.
3. If the method was called with no arguments, remove each item in the
[35044]drag data store item list whose [35045]kind is Plain Unicode
string, and return.
4. Set format to format, [35046]converted to ASCII lowercase.
5. If format equals "text", change it to "text/plain".
If format equals "url", change it to "text/uri-list".
6. Remove the item in the [35047]drag data store item list whose
[35048]kind is text and whose [35049]type string is equal to
format, if there is one.
The [35050]clearData() method does not affect whether any files were
included in the drag, so the [35051]types attribute's list might still
not be empty after calling [35052]clearData() (it would still contain
the "Files" string if any files were included in the drag).
The files attribute must return a [35053]live [35054]FileList sequence
consisting of [35055]File objects representing the files found by the
following steps. Furthermore, for a given [35056]FileList object and a
given underlying file, the same [35057]File object must be used each
time.
1. Start with an empty list L.
2. If the [35058]DataTransfer object is no longer associated with a
[35059]drag data store, the [35060]FileList is empty. Return the
empty list L.
3. If the [35061]drag data store's [35062]mode is the [35063]protected
mode, return the empty list L.
4. For each item in the [35064]drag data store item list whose
[35065]kind is File, add the item's data (the file, in particular
its name and contents, as well as its [35066]type) to the list L.
5. The files found by these steps are those in the list L.
This version of the API does not expose the types of the files during
the drag.
6.11.3.1 The [35067]DataTransferItemList interface
(BUTTON) ✔MDN
[35068]DataTransferItemList
Support in all current engines.
Firefox50+Safari6+Chrome13+
__________________________________________________________________
items.[35094]add(data, type)
Adds a new entry for the given data to the [35095]drag data
store. If the data is plain text then a type string has to be
provided also.
While the [35096]DataTransferItemList object's [35097]DataTransfer
object is associated with a [35098]drag data store, the
[35099]DataTransferItemList object's mode is the same as the
[35100]drag data store mode. When the [35101]DataTransferItemList
object's [35102]DataTransfer object is not associated with a
[35103]drag data store, the [35104]DataTransferItemList object's mode
is the disabled mode. The [35105]drag data store referenced in this
section (which is used only when the [35106]DataTransferItemList object
is not in the disabled mode) is the [35107]drag data store with which
the [35108]DataTransferItemList object's [35109]DataTransfer object is
associated.
The length attribute must return zero if the object is in the disabled
mode; otherwise it must return the number of items in the [35110]drag
data store item list.
When a [35111]DataTransferItemList object is not in the disabled mode,
its [35112]supported property indices are the [35113]indices of the
[35114]drag data store item list.
To [35115]determine the value of an indexed property i of a
[35116]DataTransferItemList object, the user agent must return a
[35117]DataTransferItem object representing the ith item in the
[35118]drag data store. The same object must be returned each time a
particular item is obtained from this [35119]DataTransferItemList
object. The [35120]DataTransferItem object must be associated with the
same [35121]DataTransfer object as the [35122]DataTransferItemList
object when it is first created.
The add() method must run the following steps:
1. If the [35123]DataTransferItemList object is not in the
[35124]read/write mode, return null.
2. Jump to the appropriate set of steps from the following list:
If the first argument to the method is a string
If there is already an item in the [35125]drag data store
item list whose [35126]kind is text and whose [35127]type
string is equal to the value of the method's second
argument, [35128]converted to ASCII lowercase, then throw
a [35129]"NotSupportedError" [35130]DOMException.
Otherwise, add an item to the [35131]drag data store item
list whose [35132]kind is text, whose [35133]type string
is equal to the value of the method's second argument,
[35134]converted to ASCII lowercase, and whose data is the
string given by the method's first argument.
If the first argument to the method is a [35135]File
Add an item to the [35136]drag data store item list whose
[35137]kind is File, whose [35138]type string is the
[35139]type of the [35140]File, [35141]converted to ASCII
lowercase, and whose data is the same as the [35142]File's
data.
3. [35143]Determine the value of the indexed property corresponding to
the newly added item, and return that value (a newly created
[35144]DataTransferItem object).
The remove(index) method must run these steps:
1. If the [35145]DataTransferItemList object is not in the
[35146]read/write mode, throw an [35147]"InvalidStateError"
[35148]DOMException.
2. If the [35149]drag data store does not contain an indexth item,
then return.
3. Remove the indexth item from the [35150]drag data store.
The clear() method, if the [35151]DataTransferItemList object is in the
[35152]read/write mode, must remove all the items from the [35153]drag
data store. Otherwise, it must do nothing.
6.11.3.2 The [35154]DataTransferItem interface
(BUTTON) ✔MDN
[35155]DataTransferItem
Support in all current engines.
Firefox50+Safari5.1+Chrome11+
__________________________________________________________________
Firefox Android?Safari iOS?Chrome Android?WebView
Android4+Samsung Internet?Opera Android14+
Invokes the callback with the string data as the argument, if
[35172]the drag data item kind is text.
Firefox Android?Safari iOS?Chrome Android?WebView
Android4+Samsung Internet?Opera Android14+
Returns a [35175]File object, if [35176]the drag data item kind
is File.
While the [35177]DataTransferItem object's [35178]DataTransfer object
is associated with a [35179]drag data store and that [35180]drag data
store's [35181]drag data store item list still contains the item that
the [35182]DataTransferItem object represents, the
[35183]DataTransferItem object's mode is the same as the [35184]drag
data store mode. When the [35185]DataTransferItem object's
[35186]DataTransfer object is not associated with a [35187]drag data
store, or if the item that the [35188]DataTransferItem object
represents has been removed from the relevant [35189]drag data store
item list, the [35190]DataTransferItem object's mode is the disabled
mode. The [35191]drag data store referenced in this section (which is
used only when the [35192]DataTransferItem object is not in the
disabled mode) is the [35193]drag data store with which the
[35194]DataTransferItem object's [35195]DataTransfer object is
associated.
The kind attribute must return the empty string if the
[35196]DataTransferItem object is in the disabled mode; otherwise it
must return the string given in the cell from the second column of the
following table from the row whose cell in the first column contains
[35197]the drag data item kind of the item represented by the
[35198]DataTransferItem object:
Kind String
Text "string"
File "file"
The type attribute must return the empty string if the
[35199]DataTransferItem object is in the disabled mode; otherwise it
must return [35200]the drag data item type string of the item
represented by the [35201]DataTransferItem object.
The getAsString(callback) method must run the following steps:
1. If the callback is null, return.
2. If the [35202]DataTransferItem object is not in the
[35203]read/write mode or the [35204]read-only mode, return. The
callback is never invoked.
3. If [35205]the drag data item kind is not text, then return. The
callback is never invoked.
4. Otherwise, [35206]queue a task to invoke callback, passing the
actual data of the item represented by the [35207]DataTransferItem
object as the argument.
The getAsFile() method must run the following steps:
1. If the [35208]DataTransferItem object is not in the
[35209]read/write mode or the [35210]read-only mode, then return
null.
2. If [35211]the drag data item kind is not File, then return null.
3. Return a new [35212]File object representing the actual data of the
item represented by the [35213]DataTransferItem object.
6.11.4 The [35214]DragEvent interface
(BUTTON) ✔MDN
[35215]DragEvent/DragEvent
Support in all current engines.
Firefox3.5+Safari14+Chrome46+
__________________________________________________________________
The drag-and-drop processing model involves several events. They all
use the [35217]DragEvent interface.
[Exposed=Window]
interface DragEvent : [35218]MouseEvent {
constructor(DOMString type, optional [35219]DragEventInit eventInitDict = {});
Firefox Android?Safari iOSNoChrome AndroidNoWebView
Android?Samsung Internet?Opera Android?
Returns the [35226]DataTransfer object for the event.
Although, for consistency with other event interfaces, the
[35227]DragEvent interface has a constructor, it is not particularly
useful. In particular, there's no way to create a useful
[35228]DataTransfer object from script, as [35229]DataTransfer objects
have a processing and security model that is coordinated by the browser
during drag-and-drops.
The dataTransfer attribute of the [35230]DragEvent interface must
return the value it was initialized to. It represents the context
information for the event.
When a user agent is required to fire a DND event named e at an
element, using a particular [35231]drag data store, and optionally with
a specific related target, the user agent must run the following steps:
1. Let dataDragStoreWasChanged be false.
2. If no specific related target was provided, set related target to
null.
3. Let window be the [35232]relevant global object of the
[35233]Document object of the specified target element.
4. If e is [35234]dragstart, then set the [35235]drag data store mode
to the [35236]read/write mode and set dataDragStoreWasChanged to
true.
If e is [35237]drop, set the [35238]drag data store mode to the
[35239]read-only mode.
5. Let dataTransfer be a newly created [35240]DataTransfer object
associated with the given [35241]drag data store.
6. Set the [35242]effectAllowed attribute to the [35243]drag data
store's [35244]drag data store allowed effects state.
7. Set the [35245]dropEffect attribute to "[35246]none" if e is
[35247]dragstart, [35248]drag, or [35249]dragleave; to the value
corresponding to the [35250]current drag operation if e is
[35251]drop or [35252]dragend; and to a value based on the
[35253]effectAllowed attribute's value and the drag-and-drop
source, as given by the following table, otherwise (i.e. if e is
[35254]dragenter or [35255]dragover):
[35256]effectAllowed [35257]dropEffect
"[35258]none" "[35259]none"
"[35260]copy" "[35261]copy"
"[35262]copyLink" "[35263]copy", or, [35264]if appropriate,
"[35265]link"
"[35266]copyMove" "[35267]copy", or, [35268]if appropriate,
"[35269]move"
"[35270]all" "[35271]copy", or, [35272]if appropriate, either
"[35273]link" or "[35274]move"
"[35275]link" "[35276]link"
"[35277]linkMove" "[35278]link", or, [35279]if appropriate,
"[35280]move"
"[35281]move" "[35282]move"
"[35283]uninitialized" when what is being dragged is a selection from a
text control "[35284]move", or, [35285]if appropriate, either
"[35286]copy" or "[35287]link"
"[35288]uninitialized" when what is being dragged is a selection
"[35289]copy", or, [35290]if appropriate, either "[35291]link" or
"[35292]move"
"[35293]uninitialized" when what is being dragged is an [35294]a
element with an [35295]href attribute "[35296]link", or, [35297]if
appropriate, either "[35298]copy" or "[35299]move"
Any other case "[35300]copy", or, [35301]if appropriate, either
"[35302]link" or "[35303]move"
Where the table above provides possibly appropriate alternatives,
user agents may instead use the listed alternative values if
platform conventions dictate that the user has requested those
alternate effects.
For example, Windows platform conventions are such that dragging
while holding the "alt" key indicates a preference for linking the
data, rather than moving or copying it. Therefore, on a Windows
system, if "[35304]link" is an option according to the table above
while the "alt" key is depressed, the user agent could select that
instead of "[35305]copy" or "[35306]move".
8. Let event be the result of [35307]creating an event using
[35308]DragEvent.
9. Initialize event's [35309]type attribute to e, its [35310]bubbles
attribute to true, its [35311]view attribute to window, its
[35312]relatedTarget attribute to related target, and its
[35313]dataTransfer attribute to dataTransfer.
10. If e is not [35314]dragleave or [35315]dragend, then initialize
event's [35316]cancelable attribute to true.
11. Initialize event's mouse and key attributes according to the state
of the input devices as they would be for user interaction events.
If there is no relevant pointing device, then initialize event's
screenX, screenY, [35317]clientX, [35318]clientY, and button
attributes to 0.
12. [35319]Dispatch event at the specified target element.
13. Set the [35320]drag data store allowed effects state to the current
value of dataTransfer's [35321]effectAllowed attribute. (It can
only have changed value if e is [35322]dragstart.)
14. If dataDragStoreWasChanged is true, then set the [35323]drag data
store mode back to the [35324]protected mode.
15. Break the association between dataTransfer and the [35325]drag data
store.
6.11.5 Processing model
When the user attempts to begin a drag operation, the user agent must
run the following steps. User agents must act as if these steps were
run even if the drag actually started in another document or
application and the user agent was not aware that the drag was
occurring until it intersected with a document under the user agent's
purview.
1. Determine what is being dragged, as follows:
If the drag operation was invoked on a selection, then it is the
selection that is being dragged.
Otherwise, if the drag operation was invoked on a [35326]Document,
it is the first element, going up the ancestor chain, starting at
the node that the user tried to drag, that has the IDL attribute
[35327]draggable set to true. If there is no such element, then
nothing is being dragged; return, the drag-and-drop operation is
never started.
Otherwise, the drag operation was invoked outside the user agent's
purview. What is being dragged is defined by the document or
application where the drag was started.
[35328]img elements and [35329]a elements with an [35330]href
attribute have their [35331]draggable attribute set to true by
default.
2. [35332]Create a drag data store. All the DND events fired
subsequently by the steps in this section must use this [35333]drag
data store.
3. Establish which DOM node is the source node, as follows:
If it is a selection that is being dragged, then the [35334]source
node is the [35335]Text node that the user started the drag on
(typically the [35336]Text node that the user originally clicked).
If the user did not specify a particular node, for example if the
user just told the user agent to begin a drag of "the selection",
then the [35337]source node is the first [35338]Text node
containing a part of the selection.
Otherwise, if it is an element that is being dragged, then the
[35339]source node is the element that is being dragged.
Otherwise, the [35340]source node is part of another document or
application. When this specification requires that an event be
dispatched at the [35341]source node in this case, the user agent
must instead follow the platform-specific conventions relevant to
that situation.
Multiple events are fired on the [35342]source node during the
course of the drag-and-drop operation.
4. Determine the list of dragged nodes, as follows:
If it is a selection that is being dragged, then the [35343]list of
dragged nodes contains, in [35344]tree order, every node that is
partially or completely included in the selection (including all
their ancestors).
Otherwise, the [35345]list of dragged nodes contains only the
[35346]source node, if any.
5. If it is a selection that is being dragged, then add an item to the
[35347]drag data store item list, with its properties set as
follows:
[35348]The drag data item type string
"[35349]text/plain"
[35350]The drag data item kind
Text
The actual data
The text of the selection
Otherwise, if any files are being dragged, then add one item per
file to the [35351]drag data store item list, with their properties
set as follows:
[35352]The drag data item type string
The MIME type of the file, if known, or
"[35353]application/octet-stream" otherwise.
[35354]The drag data item kind
File
The actual data
The file's contents and name.
Dragging files can currently only happen from outside a
[35355]navigable, for example from a file system manager
application.
If the drag initiated outside of the application, the user agent
must add items to the [35356]drag data store item list as
appropriate for the data being dragged, honoring platform
conventions where appropriate; however, if the platform conventions
do not use [35357]MIME types to label dragged data, the user agent
must make a best-effort attempt to map the types to MIME types,
and, in any case, all the [35358]drag data item type strings must
be [35359]converted to ASCII lowercase.
User agents may also add one or more items representing the
selection or dragged element(s) in other forms, e.g. as HTML.
6. If the [35360]list of dragged nodes is not empty, then
[35361]extract the microdata from those nodes into a JSON form, and
add one item to the [35362]drag data store item list, with its
properties set as follows:
[35363]The drag data item type string
[35364]application/microdata+json
[35365]The drag data item kind
Text
The actual data
The resulting JSON string.
7. Run the following substeps:
1. Let urls be « ».
2. For each node in the [35366]list of dragged nodes:
If the node is an [35367]a element with an [35368]href
attribute
Add to urls the result of
[35369]encoding-parsing-and-serializing a URL given
the element's [35370]href content attribute's value,
relative to the element's [35371]node document.
If the node is an [35372]img element with a [35373]src
attribute
Add to urls the result of
[35374]encoding-parsing-and-serializing a URL given
the element's [35375]src content attribute's value,
relative to the element's [35376]node document.
3. If urls is still empty, then return.
4. Let url string be the result of concatenating the strings in
urls, in the order they were added, separated by a U+000D
CARRIAGE RETURN U+000A LINE FEED character pair (CRLF).
5. Add one item to the [35377]drag data store item list, with its
properties set as follows:
[35378]The drag data item type string
[35379]text/uri-list
[35380]The drag data item kind
Text
The actual data
url string
8. Update the [35381]drag data store default feedback as appropriate
for the user agent (if the user is dragging the selection, then the
selection would likely be the basis for this feedback; if the user
is dragging an element, then that element's rendering would be
used; if the drag began outside the user agent, then the platform
conventions for determining the drag feedback should be used).
9. [35382]Fire a DND event named [35383]dragstart at the [35384]source
node.
If the event is canceled, then the drag-and-drop operation should
not occur; return.
Since events with no event listeners registered are, almost by
definition, never canceled, drag-and-drop is always available to
the user if the author does not specifically prevent it.
10. [35385]Fire a pointer event at the [35386]source node named
[35387]pointercancel, and fire any other follow-up events as
required by Pointer Events. [35388][POINTEREVENTS]
11. [35389]Initiate the drag-and-drop operation in a manner consistent
with platform conventions, and as described below.
The drag-and-drop feedback must be generated from the first of the
following sources that is available:
1. The [35390]drag data store bitmap, if any. In this case, the
[35391]drag data store hot spot coordinate should be used as
hints for where to put the cursor relative to the resulting
image. The values are expressed as distances in [35392]CSS
pixels from the left side and from the top side of the image
respectively. [35393][CSS]
2. The [35394]drag data store default feedback.
From the moment that the user agent is to initiate the drag-and-drop
operation, until the end of the drag-and-drop operation, device input
events (e.g. mouse and keyboard events) must be suppressed.
During the drag operation, the element directly indicated by the user
as the drop target is called the immediate user selection. (Only
elements can be selected by the user; other nodes must not be made
available as drop targets.) However, the [35395]immediate user
selection is not necessarily the current target element, which is the
element currently selected for the drop part of the drag-and-drop
operation.
The [35396]immediate user selection changes as the user selects
different elements (either by pointing at them with a pointing device,
or by selecting them in some other way). The [35397]current target
element changes when the [35398]immediate user selection changes, based
on the results of event listeners in the document, as described below.
Both the [35399]current target element and the [35400]immediate user
selection can be null, which means no target element is selected. They
can also both be elements in other (DOM-based) documents, or other
(non-web) programs altogether. (For example, a user could drag text to
a word-processor.) The [35401]current target element is initially null.
In addition, there is also a current drag operation, which can take on
the values "none", "copy", "link", and "move". Initially, it has the
value "[35402]none". It is updated by the user agent as described in
the steps below.
User agents must, as soon as the drag operation is [35403]initiated and
every 350ms (±200ms) thereafter for as long as the drag operation is
ongoing, [35404]queue a task to perform the following steps in
sequence:
1. If the user agent is still performing the previous iteration of the
sequence (if any) when the next iteration becomes due, return for
this iteration (effectively "skipping missed frames" of the
drag-and-drop operation).
2. [35405]Fire a DND event named [35406]drag at the [35407]source
node. If this event is canceled, the user agent must set the
[35408]current drag operation to "[35409]none" (no drag operation).
3. If the [35410]drag event was not canceled and the user has not
ended the drag-and-drop operation, check the state of the
drag-and-drop operation, as follows:
1. If the user is indicating a different [35411]immediate user
selection than during the last iteration (or if this is the
first iteration), and if this [35412]immediate user selection
is not the same as the [35413]current target element, then
update the [35414]current target element as follows:
If the new [35415]immediate user selection is null
Set the [35416]current target element to null also.
If the new [35417]immediate user selection is in a non-DOM
document or application
Set the [35418]current target element to the
[35419]immediate user selection.
Otherwise
[35420]Fire a DND event named [35421]dragenter at
the [35422]immediate user selection.
If the event is canceled, then set the
[35423]current target element to the
[35424]immediate user selection.
Otherwise, run the appropriate step from the
following list:
If the [35425]immediate user selection is a text
control (e.g., [35426]textarea, or an
[35427]input element whose [35428]type
attribute is in the [35429]Text state) or an
[35430]editing host or [35431]editable
element, and the [35432]drag data store item
list has an item with [35433]the drag data
item type string "[35434]text/plain" and
[35435]the drag data item kind text
Set the [35436]current target element to the
[35437]immediate user selection anyway.
If the [35438]immediate user selection is [35439]the
body element
Leave the [35440]current target element
unchanged.
Otherwise
[35441]Fire a DND event named [35442]dragenter
at [35443]the body element, if there is one,
or at the [35444]Document object, if not.
Then, set the [35445]current target element to
[35446]the body element, regardless of whether
that event was canceled or not.
2. If the previous step caused the [35447]current target element
to change, and if the previous target element was not null or
a part of a non-DOM document, then [35448]fire a DND event
named [35449]dragleave at the previous target element, with
the new [35450]current target element as the specific related
target.
3. If the [35451]current target element is a DOM element, then
[35452]fire a DND event named [35453]dragover at this
[35454]current target element.
If the [35455]dragover event is not canceled, run the
appropriate step from the following list:
If the [35456]current target element is a text control
(e.g., [35457]textarea, or an [35458]input element
whose [35459]type attribute is in the [35460]Text
state) or an [35461]editing host or [35462]editable
element, and the [35463]drag data store item list
has an item with [35464]the drag data item type
string "[35465]text/plain" and [35466]the drag data
item kind text
Set the [35467]current drag operation to either
"[35468]copy" or "[35469]move", as appropriate given
the platform conventions.
Otherwise
Reset the [35470]current drag operation to
"[35471]none".
Otherwise (if the [35472]dragover event is canceled), set the
[35473]current drag operation based on the values of the
[35474]effectAllowed and [35475]dropEffect attributes of the
[35476]DragEvent object's [35477]dataTransfer object as they
stood after the event [35478]dispatch finished, as per the
following table:
[35479]effectAllowed [35480]dropEffect Drag operation
"[35481]uninitialized", "[35482]copy", "[35483]copyLink",
"[35484]copyMove", or "[35485]all" "[35486]copy" "[35487]copy"
"[35488]uninitialized", "[35489]link", "[35490]copyLink",
"[35491]linkMove", or "[35492]all" "[35493]link" "[35494]link"
"[35495]uninitialized", "[35496]move", "[35497]copyMove",
"[35498]linkMove", or "[35499]all" "[35500]move" "[35501]move"
Any other case "[35502]none"
4. Otherwise, if the [35503]current target element is not a DOM
element, use platform-specific mechanisms to determine what
drag operation is being performed (none, copy, link, or move),
and set the [35504]current drag operation accordingly.
5. Update the drag feedback (e.g. the mouse cursor) to match the
[35505]current drag operation, as follows:
Drag operation Feedback
"[35506]copy" Data will be copied if dropped here.
"[35507]link" Data will be linked if dropped here.
"[35508]move" Data will be moved if dropped here.
"[35509]none" No operation allowed, dropping here will cancel the
drag-and-drop operation.
4. Otherwise, if the user ended the drag-and-drop operation (e.g. by
releasing the mouse button in a mouse-driven drag-and-drop
interface), or if the [35510]drag event was canceled, then this
will be the last iteration. Run the following steps, then stop the
drag-and-drop operation:
1. If the [35511]current drag operation is "[35512]none" (no drag
operation), or, if the user ended the drag-and-drop operation
by canceling it (e.g. by hitting the Escape key), or if the
[35513]current target element is null, then the drag operation
failed. Run these substeps:
1. Let dropped be false.
2. If the [35514]current target element is a DOM element,
[35515]fire a DND event named [35516]dragleave at it;
otherwise, if it is not null, use platform-specific
conventions for drag cancelation.
3. Set the [35517]current drag operation to "[35518]none".
Otherwise, the drag operation might be a success; run these
substeps:
1. Let dropped be true.
2. If the [35519]current target element is a DOM element,
[35520]fire a DND event named [35521]drop at it;
otherwise, use platform-specific conventions for
indicating a drop.
3. If the event is canceled, set the [35522]current drag
operation to the value of the [35523]dropEffect attribute
of the [35524]DragEvent object's [35525]dataTransfer
object as it stood after the event [35526]dispatch
finished.
Otherwise, the event is not canceled; perform the event's
default action, which depends on the exact target as
follows:
If the [35527]current target element is a text control
(e.g., [35528]textarea, or an [35529]input
element whose [35530]type attribute is in the
[35531]Text state) or an [35532]editing host
or [35533]editable element, and the
[35534]drag data store item list has an item
with [35535]the drag data item type string
"[35536]text/plain" and [35537]the drag data
item kind text
Insert the actual data of the first item in
the [35538]drag data store item list to have
[35539]a drag data item type string of
"[35540]text/plain" and [35541]a drag data
item kind that is text into the text control
or [35542]editing host or [35543]editable
element in a manner consistent with
platform-specific conventions (e.g. inserting
it at the current mouse cursor position, or
inserting it at the end of the field).
Otherwise
Reset the [35544]current drag operation to
"[35545]none".
2. [35546]Fire a DND event named [35547]dragend at the
[35548]source node.
3. Run the appropriate steps from the following list as the
default action of the [35549]dragend event:
If dropped is true, the [35550]current target element is a
text control (see below), the [35551]current drag
operation is "[35552]move", and the source of the
drag-and-drop operation is a selection in the DOM
that is entirely contained within an [35553]editing
host
[35554]Delete the selection.
If dropped is true, the [35555]current target element is a
text control (see below), the [35556]current drag
operation is "[35557]move", and the source of the
drag-and-drop operation is a selection in a text
control
The user agent should delete the dragged selection
from the relevant text control.
If dropped is false or if the [35558]current drag operation
is "[35559]none"
The drag was canceled. If the platform conventions
dictate that this be represented to the user (e.g.
by animating the dragged selection going back to the
source of the drag-and-drop operation), then do so.
Otherwise
The event has no default action.
For the purposes of this step, a text control is a
[35560]textarea element or an [35561]input element whose
[35562]type attribute is in one of the [35563]Text,
[35564]Search, [35565]Tel, [35566]URL, [35567]Email,
[35568]Password, or [35569]Number states.
User agents are encouraged to consider how to react to drags near the
edge of scrollable regions. For example, if a user drags a link to the
bottom of the [35570]viewport on a long page, it might make sense to
scroll the page so that the user can drop the link lower on the page.
This model is independent of which [35571]Document object the nodes
involved are from; the events are fired as described above and the rest
of the processing model runs as described above, irrespective of how
many documents are involved in the operation.
6.11.6 Events summary
This section is non-normative.
The following events are involved in the drag-and-drop model.
Event name Target Cancelable? [35572]Drag data store mode
[35573]dropEffect Default Action
dragstart
(BUTTON) ✔MDN
[35574]HTMLElement/dragstart_event
Support in all current engines.
Firefox9+Safari3.1+Chrome1+
__________________________________________________________________
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung
Internet?Opera Android12+
[35583]Immediate user selection or [35584]the body element ✓ Cancelable
[35585]Protected mode [35586]Based on effectAllowed value Reject
[35587]immediate user selection as potential [35588]target element
dragleave
(BUTTON) ✔MDN
[35589]HTMLElement/dragleave_event
Support in all current engines.
Firefox9+Safari3.1+Chrome1+
__________________________________________________________________
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung
Internet?Opera Android12+
[35594]Current target element ✓ Cancelable [35595]Protected mode
[35596]Based on effectAllowed value Reset the [35597]current drag
operation to "none"
drop
(BUTTON) ✔MDN
[35598]HTMLElement/drop_event
Support in all current engines.
Firefox9+Safari3.1+Chrome1+
__________________________________________________________________
All of these events bubble, are composed, and the [35606]effectAllowed
attribute always has the value it had after the [35607]dragstart event,
defaulting to "[35608]uninitialized" in the [35609]dragstart event.
6.11.7 The [35610]draggable attribute
(BUTTON) ✔MDN
[35611]Global_attributes/draggable
Support in all current engines.
Firefox2+Safari5+Chrome4+
__________________________________________________________________
All [35612]HTML elements may have the draggable content attribute set.
The [35613]draggable attribute is an [35614]enumerated attribute with
the following keywords and states:
Keyword State Brief description
true true The element will be draggable.
false false The element will not be draggable.
The attribute's [35615]missing value default and [35616]invalid value
default are both the auto state. The auto state uses the default
behavior of the user agent.
An element with a [35617]draggable attribute should also have a
[35618]title attribute that names the element for the purpose of
non-visual interactions.
element.[35619]draggable [ = value ]
Returns true if the element is draggable; otherwise, returns
false.
Can be set, to override the default and set the [35620]draggable
content attribute.
The draggable IDL attribute, whose value depends on the content
attribute's in the way described below, controls whether or not the
element is draggable. Generally, only text selections are draggable,
but elements whose [35621]draggable IDL attribute is true become
draggable as well.
If an element's [35622]draggable content attribute has the state
[35623]true, the [35624]draggable IDL attribute must return true.
Otherwise, if the element's [35625]draggable content attribute has the
state [35626]false, the [35627]draggable IDL attribute must return
false.
Otherwise, the element's [35628]draggable content attribute has the
state [35629]auto. If the element is an [35630]img element, an
[35631]object element that [35632]represents an image, or an [35633]a
element with an [35634]href content attribute, the [35635]draggable IDL
attribute must return true; otherwise, the [35636]draggable IDL
attribute must return false.
If the [35637]draggable IDL attribute is set to the value false, the
[35638]draggable content attribute must be set to the literal value
"false". If the [35639]draggable IDL attribute is set to the value
true, the [35640]draggable content attribute must be set to the literal
value "true".
6.11.8 Security risks in the drag-and-drop model
User agents must not make the data added to the [35641]DataTransfer
object during the [35642]dragstart event available to scripts until the
[35643]drop event, because otherwise, if a user were to drag sensitive
information from one document to a second document, crossing a hostile
third document in the process, the hostile document could intercept the
data.
For the same reason, user agents must consider a drop to be successful
only if the user specifically ended the drag operation — if any scripts
end the drag operation, it must be considered unsuccessful (canceled)
and the [35644]drop event must not be fired.
User agents should take care to not start drag-and-drop operations in
response to script actions. For example, in a mouse-and-window
environment, if a script moves a window while the user has their mouse
button depressed, the UA would not consider that to start a drag. This
is important because otherwise UAs could cause data to be dragged from
sensitive sources and dropped into hostile documents without the user's
consent.
User agents should filter potentially active (scripted) content (e.g.
HTML) when it is dragged and when it is dropped, using a safelist of
known-safe features. Similarly, [35645]relative URLs should be turned
into absolute URLs to avoid references changing in unexpected ways.
This specification does not specify how this is performed.
Consider a hostile page providing some content and getting the user to
select and drag and drop (or indeed, copy and paste) that content to a
victim page's [35646]contenteditable region. If the browser does not
ensure that only safe content is dragged, potentially unsafe content
such as scripts and event handlers in the selection, once dropped (or
pasted) into the victim site, get the privileges of the victim site.
This would thus enable a cross-site scripting attack.
6.12 The [35647]popover attribute
(BUTTON) ✔MDN
[35648]Global_attributes/popover
Support in all current engines.
Firefox🔰 114+Safaripreview+Chrome114+
__________________________________________________________________
All [35649]HTML elements may have the popover content attribute set.
When specified, the element won't be rendered until it becomes shown,
at which point it will be rendered on top of other page content.
The [35650]popover attribute is a global attribute that allows authors
flexibility to ensure popover functionality can be applied to elements
with the most relevant semantics.
The following demonstrates how one might create a popover
sub-navigation list of links, within the global navigation for a
website.
When using [35651]popover on elements without accessibility semantics,
for instance the [35652]div element, authors should use the appropriate
ARIA attributes to ensure the popover is accessible.
The following shows the baseline markup to create a custom menu
popover, where the first menuitem will receive keyboard focus when the
popover is invoked due to the use of the autofocus attribute.
Navigating the menuitems with arrow keys and activation behaviors would
still need author scripting. Additional requirements for building
custom menus widgets are defined in the [35653]WAI-ARIA specification.
A popover can be useful for rendering a status message, confirming the
action performed by the user. The following demonstrates how one could
reveal a popover in an [35654]output element.
Inserting a popover element into an [35655]output element will
generally cause screen readers to announce the content when it becomes
visible. Depending on the complexity or frequency of the content, this
could be either useful or annoying to users of these assistive
technologies. Keep this in mind when using the [35656]output element or
other ARIA live regions to ensure the best user experience.
The [35657]popover attribute is an [35658]enumerated attribute with the
following keywords and states:
Keyword State Brief description
auto auto Closes other popovers when opened; has [35659]light dismiss
and responds to [35660]close requests.
(the empty string)
manual manual Does not close other popovers; does not [35661]light
dismiss or respond to [35662]close requests.
hint hint Closes other hint popovers when opened, but not other auto
popovers; has [35663]light dismiss and responds to [35664]close
requests.
The attribute's [35665]missing value default is the no popover state,
and its [35666]invalid value default is the [35667]manual state.
(BUTTON) ✔MDN
[35668]HTMLElement/popover
Support in all current engines.
Firefox🔰 114+Safari17+Chrome114+
__________________________________________________________________
The popover IDL attribute must [35669]reflect the [35670]popover
attribute, [35671]limited to only known values.
Every [35672]HTML element has a popover visibility state, initially
[35673]hidden, with these potential values:
* hidden
* showing
Every [35674]Document has a popover pointerdown target, which is an
[35675]HTML element or null, initially null.
Every [35676]HTML element has a popover invoker, which is an
[35677]HTML element or null, initially set to null.
Every [35678]HTML element has a popover showing or hiding, which is a
boolean, initially set to false.
Every [35679]HTML element popover toggle task tracker, which is a
[35680]toggle task tracker or null, initially null.
Every [35681]HTML element has a popover close watcher, which is a
[35682]close watcher or null, initially null.
Every [35683]HTML element has an opened in popover mode, which is a
string or null, initially null.
The following [35684]attribute change steps, given element, localName,
oldValue, value, and namespace, are used for all [35685]HTML elements:
1. If namespace is not null, then return.
2. If localName is not [35686]popover, then return.
3. If element's [35687]popover visibility state is in the
[35688]showing state and oldValue and value are in different
[35689]states, then run the [35690]hide popover algorithm given
element, true, true, and false.
element.[35691]showPopover()
Shows the popover element by adding it to the top layer. If
element's [35692]popover attribute is in the [35693]auto state,
then this will also close all other [35694]auto popovers unless
they are an ancestor of element according to the [35695]topmost
popover ancestor algorithm.
element.[35696]hidePopover()
Hides the popover element by removing it from the top layer and
applying display: none to it.
element.[35697]togglePopover()
If the popover element is not showing, then this method shows
it. Otherwise, this method hides it. This method returns true if
the popover is open after calling it, otherwise false.
(BUTTON) ✔MDN
[35698]HTMLElement/showPopover
Support in all current engines.
Firefox🔰 114+Safari17+Chrome114+
__________________________________________________________________
The showPopover(options) method steps are:
1. Let invoker be options["[35699]source"] if it [35700]exists;
otherwise, null.
2. Run [35701]show popover given [35702]this, true, and invoker.
To show popover, given an [35703]HTML element element, a boolean
throwExceptions, and an [35704]HTML element or null invoker:
1. If the result of running [35705]check popover validity given
element, false, throwExceptions, and null is false, then return.
2. Let document be element's [35706]node document.
3. [35707]Assert: element's [35708]popover invoker is null.
4. [35709]Assert: element is not in document's [35710]top layer.
5. Let nestedShow be element's [35711]popover showing or hiding.
6. Let fireEvents be the boolean negation of nestedShow.
7. Set element's [35712]popover showing or hiding to true.
8. Let cleanupShowingFlag be the following steps:
1. If nestedShow is false, then set element's [35713]popover
showing or hiding to false.
9. If the result of [35714]firing an event named [35715]beforetoggle,
using [35716]ToggleEvent, with the [35717]cancelable attribute
initialized to true, the [35718]oldState attribute initialized to
"closed", and the [35719]newState attribute initialized to "open"
at element is false, then run cleanupShowingFlag and return.
10. If the result of running [35720]check popover validity given
element, false, throwExceptions, and document is false, then run
cleanupShowingFlag and return.
[35721]Check popover validity is called again because firing the
[35722]beforetoggle event could have disconnected this element or
changed its [35723]popover attribute.
11. Let shouldRestoreFocus be false.
12. Let originalType be the current state of element's [35724]popover
attribute.
13. Let stackToAppendTo be null.
14. Let autoAncestor be the result of running the [35725]topmost
popover ancestor algorithm given element, document's [35726]showing
auto popover list, invoker, and true.
15. Let hintAncestor be the result of running the [35727]topmost
popover ancestor algorithm given element, document's [35728]showing
hint popover list, invoker, and true.
16. If originalType is the [35729]auto state, then:
1. Run [35730]close entire popover list given document's
[35731]showing hint popover list, shouldRestoreFocus, and
fireEvents.
2. Let ancestor be the result of running the [35732]topmost
popover ancestor algorithm given element, document's
[35733]showing auto popover list, invoker, and true.
3. If ancestor is null, then set ancestor to document.
4. Run [35734]hide all popovers until given ancestor,
shouldRestoreFocus, and fireEvents.
5. Set stackToAppendTo to "auto".
17. If originalType is the [35735]hint state, then:
1. If hintAncestor is not null, then:
1. Run [35736]hide all popovers until given hintAncestor,
shouldRestoreFocus, and fireEvents.
2. Set stackToAppendTo to "hint".
2. Otherwise:
1. Run [35737]close entire popover list given document's
[35738]showing hint popover list, shouldRestoreFocus, and
fireEvents.
2. If autoAncestor is not null, then:
1. Run [35739]hide all popovers until given
autoAncestor, shouldRestoreFocus, and fireEvents.
2. Set stackToAppendTo to "auto".
3. Otherwise, set stackToAppendTo to "hint".
18. If originalType is [35740]auto or [35741]hint, then:
1. [35742]Assert: stackToAppendTo is not null.
2. If originalType is not equal to the value of element's
[35743]popover attribute, then:
1. If throwExceptions is true, then throw a
[35744]"InvalidStateError" [35745]DOMException.
2. Return.
3. If the result of running [35746]check popover validity given
element, false, throwExceptions, and document is false, then
run cleanupShowingFlag and return.
[35747]Check popover validity is called again because running
[35748]hide all popovers until above could have fired the
[35749]beforetoggle event, and an event handler could have
disconnected this element or changed its [35750]popover
attribute.
4. If the result of running [35751]topmost auto or hint popover
on document is null, then set shouldRestoreFocus to true.
This ensures that focus is returned to the previously-focused
element only for the first popover in a stack.
5. If stackToAppendTo is "auto":
1. [35752]Assert: document's [35753]showing auto popover
list does not contain element.
2. Set element's [35754]opened in popover mode to "auto".
Otherwise:
1. [35755]Assert: stackToAppendTo is "hint".
2. [35756]Assert: document's [35757]showing hint popover
list does not contain element.
3. Set element's [35758]opened in popover mode to "hint".
6. Set element's [35759]popover close watcher to the result of
[35760]establishing a close watcher given element's
[35761]relevant global object, with:
o [35762]cancelAction being to return true.
o [35763]closeAction being to [35764]hide a popover given
element, true, true, and false.
o [35765]getEnabledState being to return true.
19. Set element's [35766]previously focused element to null.
20. Let originallyFocusedElement be document's [35767]focused area of
the document's [35768]DOM anchor.
21. [35769]Add an element to the top layer given element.
22. Set element's [35770]popover visibility state to [35771]showing.
23. Set element's [35772]popover invoker to invoker.
24. Set element's [35773]implicit anchor element to invoker.
25. Run the [35774]popover focusing steps given element.
26. If shouldRestoreFocus is true and element's [35775]popover
attribute is not in the [35776]no popover state, then set element's
[35777]previously focused element to originallyFocusedElement.
27. [35778]Queue a popover toggle event task given element, "closed",
and "open".
28. Run cleanupShowingFlag.
To queue a popover toggle event task given an element element, a string
oldState, and a string newState:
1. If element's [35779]popover toggle task tracker is not null, then:
1. Set oldState to element's [35780]popover toggle task tracker's
[35781]old state.
2. Remove element's [35782]popover toggle task tracker's
[35783]task from its [35784]task queue.
3. Set element's [35785]popover toggle task tracker to null.
2. [35786]Queue an element task given the [35787]DOM manipulation task
source and element to run the following steps:
1. [35788]Fire an event named [35789]toggle at element, using
[35790]ToggleEvent, with the [35791]oldState attribute
initialized to oldState and the [35792]newState attribute
initialized to newState.
2. Set element's [35793]popover toggle task tracker to null.
3. Set element's [35794]popover toggle task tracker to a struct with
[35795]task set to the just-queued [35796]task and [35797]old state
set to oldState.
(BUTTON) ✔MDN
[35798]HTMLElement/hidePopover
Support in all current engines.
Firefox🔰 114+Safari17+Chrome114+
__________________________________________________________________
The hidePopover() method steps are:
1. Run the [35799]hide popover algorithm given [35800]this, true,
true, and true.
To hide a popover given an [35801]HTML element element, a boolean
focusPreviousElement, a boolean fireEvents, and a boolean
throwExceptions:
1. If the result of running [35802]check popover validity given
element, true, throwExceptions, and null is false, then return.
2. Let document be element's [35803]node document.
3. Let nestedHide be element's [35804]popover showing or hiding.
4. Set element's [35805]popover showing or hiding to true.
5. If nestedHide is true, then set fireEvents to false.
6. Let cleanupSteps be the following steps:
1. If nestedHide is false, then set element's [35806]popover
showing or hiding to false.
2. If element's [35807]popover close watcher is not null, then:
1. [35808]Destroy element's [35809]popover close watcher.
2. Set element's [35810]popover close watcher to null.
7. If element's [35811]opened in popover mode is "auto" or "hint",
then:
1. Run [35812]hide all popovers until given element,
focusPreviousElement, and fireEvents.
2. If the result of running [35813]check popover validity given
element, true, and throwExceptions is false, then run
cleanupSteps and return.
[35814]Check popover validity is called again because running
[35815]hide all popovers until could have disconnected element
or changed its [35816]popover attribute.
8. Let autoPopoverListContainsElement be true if document's
[35817]showing auto popover list's last item is element, otherwise
false.
9. Set element's [35818]popover invoker to null.
10. If fireEvents is true:
1. [35819]Fire an event named [35820]beforetoggle, using
[35821]ToggleEvent, with the [35822]oldState attribute
initialized to "open" and the [35823]newState attribute
initialized to "closed" at element.
2. If autoPopoverListContainsElement is true and document's
[35824]showing auto popover list's last item is not element,
then run [35825]hide all popovers until given element,
focusPreviousElement, and false.
3. If the result of running [35826]check popover validity given
element, true, throwExceptions, and null is false, then run
cleanupSteps and return.
[35827]Check popover validity is called again because firing
the [35828]beforetoggle event could have disconnected element
or changed its [35829]popover attribute.
4. [35830]Request an element to be removed from the top layer
given element.
5. Set element's [35831]implicit anchor element to null.
11. Otherwise, [35832]remove an element from the top layer immediately
given element.
12. Set element's [35833]opened in popover mode to null.
13. Set element's [35834]popover visibility state to [35835]hidden.
14. If fireEvents is true, then [35836]queue a popover toggle event
task given element, "open", and "closed".
15. Let previouslyFocusedElement be element's [35837]previously focused
element.
16. If previouslyFocusedElement is not null, then:
1. Set element's [35838]previously focused element to null.
2. If focusPreviousElement is true and document's [35839]focused
area of the document's [35840]DOM anchor is a
[35841]shadow-including inclusive descendant of element, then
run the [35842]focusing steps for previouslyFocusedElement;
the viewport should not be scrolled by doing this step.
17. Run cleanupSteps.
(BUTTON) ✔MDN
[35843]HTMLElement/togglePopover
Support in all current engines.
Firefox🔰 114+Safari17+Chrome114+
__________________________________________________________________
The togglePopover(options) method steps are:
1. Let force be null.
2. If options is a boolean, set force to options.
3. Otherwise, if options["[35844]force"] [35845]exists, set force to
options["[35846]force"].
4. Let invoker be options["[35847]source"] if it [35848]exists;
otherwise, null.
5. If [35849]this's [35850]popover visibility state is [35851]showing,
and force is null or false, then run the [35852]hide popover
algorithm given [35853]this, true, true, and true.
6. Otherwise, if force is null or true, then run [35854]show popover
given [35855]this, true, and invoker.
7. Otherwise:
1. Let expectedToBeShowing be true if [35856]this's
[35857]popover visibility state is [35858]showing; otherwise
false.
2. Run [35859]check popover validity given expectedToBeShowing,
true, and null.
8. Return true if [35860]this's [35861]popover visibility state is
[35862]showing; otherwise false.
To hide all popovers until, given an [35863]HTML element or
[35864]Document endpoint, a boolean focusPreviousElement, and a boolean
fireEvents:
1. If endpoint is an [35865]HTML element and endpoint is not in the
[35866]popover showing state, then return.
2. Let document be endpoint's [35867]node document.
3. [35868]Assert: endpoint is a [35869]Document or endpoint's
[35870]popover visibility state is [35871]showing.
4. [35872]Assert: endpoint is a [35873]Document or endpoint's
[35874]popover attribute is in the [35875]auto state or endpoint's
[35876]popover attribute is in the [35877]hint state.
5. If endpoint is a [35878]Document:
1. Run [35879]close entire popover list given document's
[35880]showing hint popover list, focusPreviousElement, and
fireEvents.
2. Run [35881]close entire popover list given document's
[35882]showing auto popover list, focusPreviousElement, and
fireEvents.
3. Return.
6. If document's [35883]showing hint popover list contains endpoint:
1. [35884]Assert: endpoint's [35885]popover attribute is in the
[35886]hint state.
2. Run [35887]hide popover stack until given endpoint, document's
[35888]showing hint popover list, focusPreviousElement, and
fireEvents.
3. Return.
7. Run [35889]close entire popover list given document's
[35890]showing hint popover list, focusPreviousElement, and
fireEvents.
8. If document's [35891]showing auto popover list does not contain
endpoint, then return.
9. Run [35892]hide popover stack until given endpoint, document's
[35893]showing auto popover list, focusPreviousElement, and
fireEvents.
To hide popover stack until, given an [35894]HTML element endpoint, a
[35895]list popoverList, a boolean focusPreviousElement, and a boolean
fireEvents:
1. Let repeatingHide be false.
2. Perform the following steps at least once:
1. Let lastToHide be null.
2. For each popover in popoverList:
1. If popover is endpoint, then [35896]break.
2. Set lastToHide to popover.
3. If lastToHide is null, then return.
4. [35897]While lastToHide's [35898]popover visibility state is
[35899]showing:
1. [35900]Assert: popoverList is not empty.
2. Run the [35901]hide popover algorithm given the last item
in popoverList, focusPreviousElement, fireEvents, and
false.
5. [35902]Assert: repeatingHide is false or popoverList's last
item is endpoint.
6. Set repeatingHide to true if popoverList contains endpoint and
popoverList's last item is not endpoint, otherwise false.
7. If repeatingHide is true, then set fireEvents to false.
and keep performing them [35903]while repeatingHide is true.
The [35904]hide all popovers until algorithm is used in several cases
to hide all popovers that don't stay open when something happens. For
example, during light-dismiss of a popover, this algorithm ensures that
we close only the popovers that aren't related to the node clicked by
the user.
To find the topmost popover ancestor, given a [35905]Node
newPopoverOrTopLayerElement, a [35906]list popoverList, an [35907]HTML
element or null invoker, and a boolean isPopover, perform the following
steps. They return an [35908]HTML element or null.
The [35909]topmost popover ancestor algorithm will return the topmost
(latest in the [35910]showing auto popover list) ancestor popover for
the provided popover or top layer element. Popovers can be related to
each other in several ways, creating a tree of popovers. There are two
paths through which one popover (call it the "child" popover) can have
a topmost ancestor popover (call it the "parent" popover):
1. The popovers are nested within each other in the node tree. In this
case, the descendant popover is the "child" and its topmost
ancestor popover is the "parent".
2. An invoking element (e.g., a [35911]button) has a
[35912]popovertarget attribute pointing to a popover. In this case,
the popover is the "child", and the popover subtree the invoking
element is in is the "parent". The invoker has to be in a popover
and reference an open popover.
In each of the relationships formed above, the parent popover has to be
strictly earlier in the [35913]showing auto popover list than the child
popover, or it does not form a valid ancestral relationship. This
eliminates non-showing popovers and self-pointers (e.g., a popover
containing an invoking element that points back to the containing
popover), and it allows for the construction of a well-formed tree from
the (possibly cyclic) graph of connections. Only [35914]auto popovers
are considered.
If the provided element is a top layer element such as a [35915]dialog
which is not showing as a popover, then [35916]topmost popover ancestor
will only look in the node tree to find the first popover.
1. If isPopover is true:
1. [35917]Assert: newPopoverOrTopLayerElement is an [35918]HTML
element.
2. [35919]Assert: newPopoverOrTopLayerElement's [35920]popover
attribute is not in the [35921]no popover state or the
[35922]manual state.
3. [35923]Assert: newPopoverOrTopLayerElement's [35924]popover
visibility state is not in the [35925]popover showing state.
2. Otherwise:
1. [35926]Assert: invoker is null.
3. Let popoverPositions be an empty [35927]ordered map.
4. Let index be 0.
5. For each popover of popoverList:
1. [35928]Set popoverPositions[popover] to index.
2. Increment index by 1.
6. If isPopover is true, then [35929]set
popoverPositions[newPopoverOrTopLayerElement] to index.
7. Increment index by 1.
8. Let topmostPopoverAncestor be null.
9. Let checkAncestor be an algorithm which performs the following
steps given candidate:
1. If candidate is null, then return.
2. Let okNesting be false.
3. Let candidateAncestor be null.
4. [35930]While okNesting is false:
1. Set candidateAncestor to the result of running
[35931]nearest inclusive open popover given candidate.
2. If candidateAncestor is null or popoverPositions does not
contain candidateAncestor, then return.
3. [35932]Assert: candidateAncestor's [35933]popover
attribute is not in the [35934]manual or [35935]none
state.
4. Set okNesting to true if newPopoverOrTopLayerElement's
[35936]popover attribute is in the [35937]hint state or
candidateAncestor's [35938]popover attribute is in the
[35939]auto state.
5. If okNesting is false, then set candidate to
candidateAncestor's parent in the [35940]flat tree.
5. Let candidatePosition be popoverPositions[candidateAncestor].
6. If topmostPopoverAncestor is null or
popoverPositions[topmostPopoverAncestor] is less than
candidatePosition, then set topmostPopoverAncestor to
candidateAncestor.
10. Run checkAncestor given newPopoverOrTopLayerElement's parent node
within the [35941]flat tree.
11. Run checkAncestor given invoker.
12. Return topmostPopoverAncestor.
To find the nearest inclusive open popover given a [35942]Node node,
perform the following steps. They return an [35943]HTML element or
null.
1. Let currentNode be node.
2. While currentNode is not null:
1. If currentNode's [35944]popover attribute is in the
[35945]auto state and currentNode's [35946]popover visibility
state is [35947]showing, then return currentNode.
2. Set currentNode to currentNode's parent in the [35948]flat
tree.
3. Return null.
To find the topmost auto or hint popover given a [35949]Document
document, perform the following steps. They return an [35950]HTML
element or null.
1. If document's [35951]showing hint popover list is not empty, then
return document's [35952]showing hint popover list's last element.
2. If document's [35953]showing auto popover list is not empty, then
return document's [35954]showing auto popover list's last element.
3. Return null.
To perform the popover focusing steps for an [35955]HTML element
subject:
1. If the [35956]allow focus steps given subject's [35957]node
document return false, then return.
2. If subject is a [35958]dialog element, then run the [35959]dialog
focusing steps given subject and return.
3. If subject has the [35960]autofocus attribute, then let control be
subject.
4. Otherwise, let control be the [35961]autofocus delegate for subject
given "other".
5. If control is null, then return.
6. Run the [35962]focusing steps given control.
7. Let topDocument be control's [35963]node navigable's
[35964]top-level traversable's [35965]active document.
8. If control's [35966]node document's [35967]origin is not the
[35968]same as the [35969]origin of topDocument, then return.
9. [35970]Empty topDocument's [35971]autofocus candidates.
10. Set topDocument's [35972]autofocus processed flag to true.
To check popover validity for an [35973]HTML element element given a
boolean expectedToBeShowing, a boolean throwExceptions, and a
[35974]Document or null expectedDocument, perform the following steps.
They throw an exception or return a boolean.
1. If element's [35975]popover attribute is in the [35976]no popover
state, then:
1. If throwExceptions is true, then throw a
[35977]"NotSupportedError" [35978]DOMException.
2. Return false.
2. If any of the following are true:
+ expectedToBeShowing is true and element's [35979]popover
visibility state is not [35980]showing; or
+ expectedToBeShowing is false and element's [35981]popover
visibility state is not [35982]hidden,
then return false.
3. If any of the following are true:
+ element is not [35983]connected;
+ element's [35984]node document is not [35985]fully active;
+ expectedDocument is not null and element's [35986]node
document is not expectedDocument;
+ element is a [35987]dialog element and its [35988]is modal is
set to true; or
+ element's [35989]fullscreen flag is set,
then:
1. If throwExceptions is true, then throw a
[35990]"InvalidStateError" [35991]DOMException.
2. Return false.
4. Return true.
To get the showing auto popover list for a [35992]Document document:
1. Let popovers be « ».
2. [35993]For each [35994]Element element in document's [35995]top
layer:
1. If all of the following are true:
o element is an [35996]HTML element;
o element's [35997]opened in popover mode is "auto"; and
o element's [35998]popover visibility state is
[35999]showing,
then [36000]append element to popovers.
3. Return popovers.
To get the showing hint popover list for a [36001]Document document:
1. Let popovers be « ».
2. [36002]For each [36003]Element element in document's [36004]top
layer:
1. If all of the following are true:
o element is an [36005]HTML element;
o element's [36006]opened in popover mode is "hint"; and
o element's [36007]popover visibility state is
[36008]showing,
then [36009]append element to popovers.
3. Return popovers.
To close entire popover list given a [36010]list popoverList, a boolean
focusPreviousElement, and a boolean fireEvents:
1. While popoverList is not empty:
1. Run the [36011]hide popover algorithm given popoverList's last
item, focusPreviousElement, fireEvents, and false.
6.12.1 The popover target attributes
[36012]Buttons may have the following content attributes:
* popovertarget
* popovertargetaction
If specified, the [36013]popovertarget attribute value must be the
[36014]ID of an element with a [36015]popover attribute in the same
[36016]tree as the [36017]button with the [36018]popovertarget
attribute.
The [36019]popovertargetaction attribute is an [36020]enumerated
attribute with the following keywords and states:
Keyword State Brief description
toggle toggle Shows or hides the targeted popover element.
show show Shows the targeted popover element.
hide hide Hides the targeted popover element.
The attribute's [36021]missing value default and [36022]invalid value
default are both the [36023]toggle state.
Whenever possible ensure the popover element is placed immediately
after its triggering element in the DOM. Doing so will help ensure that
the popover is exposed in a logical programmatic reading order for
users of assistive technology, such as screen readers.
The following shows how the [36024]popovertarget attribute in
combination with the [36025]popovertargetaction attribute can be used
to show and close a popover:
This is a popover article!
If a [36026]popovertargetaction attribute is not specified, the default
action will be to toggle the associated popover. The following shows
how only specifying the [36027]popovertarget attribute on its invoking
button can toggle a manual popover between its opened and closed
states. A manual popover will not respond to [36028]light dismiss or
[36029]close requests:
The popoverTargetAction IDL attribute must [36041]reflect the
[36042]popovertargetaction attribute, [36043]limited to only known
values.
To run the popover target attribute activation behavior given a
[36044]Node node and a [36045]Node eventTarget:
1. Let popover be node's [36046]popover target element.
2. If popover is null, then return.
3. If eventTarget is a [36047]shadow-including inclusive descendant of
popover and popover is a [36048]shadow-including descendant of
node, then return.
4. If node's [36049]popovertargetaction attribute is in the
[36050]show state and popover's [36051]popover visibility state is
[36052]showing, then return.
5. If node's [36053]popovertargetaction attribute is in the
[36054]hide state and popover's [36055]popover visibility state is
[36056]hidden, then return.
6. If popover's [36057]popover visibility state is [36058]showing,
then run the [36059]hide popover algorithm given popover, true,
true, and false.
7. Otherwise, if popover's [36060]popover visibility state is
[36061]hidden and the result of running [36062]check popover
validity given popover, false, false, and null is true, then run
[36063]show popover given popover, false, and node.
To get the popover target element given a [36064]Node node, perform the
following steps. They return an [36065]HTML element or null.
1. If node is not a [36066]button, then return null.
2. If node is [36067]disabled, then return null.
3. If node has a [36068]form owner and node is a [36069]submit button,
then return null.
4. Let popoverElement be the result of running node's [36070]get the
popovertarget-associated element.
5. If popoverElement is null, then return null.
6. If popoverElement's [36071]popover attribute is in the [36072]no
popover state, then return null.
7. Return popoverElement.
6.12.2 Popover light dismiss
"Light dismiss" means that clicking outside of a popover whose
[36073]popover attribute is in the [36074]auto state will close the
popover. This is in addition to how such popovers respond to
[36075]close requests.
To light dismiss open popovers, given a [36076]PointerEvent event:
1. [36077]Assert: event's [36078]isTrusted attribute is true.
2. Let target be event's [36079]target.
3. Let document be target's [36080]node document.
4. Let topmostPopover be the result of running [36081]topmost auto
popover given document.
5. If topmostPopover is null, then return.
6. If event's [36082]type is "[36083]pointerdown", then: set
document's [36084]popover pointerdown target to the result of
running [36085]topmost clicked popover given target.
7. If event's [36086]type is "[36087]pointerup", then:
1. Let ancestor be the result of running [36088]topmost clicked
popover given target.
2. Let sameTarget be true if ancestor is document's
[36089]popover pointerdown target.
3. Set document's [36090]popover pointerdown target to null.
4. If ancestor is null, then set ancestor to document.
5. If sameTarget is true, then run [36091]hide all popovers until
given ancestor, false, and true.
To find the topmost clicked popover, given a [36092]Node node:
1. Let clickedPopover be the result of running [36093]nearest
inclusive open popover given node.
2. Let invokerPopover be the result of running [36094]nearest
inclusive target popover for invoker given node.
3. If the result of [36095]getting the popover stack position given
clickedPopover is greater than the result of [36096]getting the
popover stack position given invokerPopover, then return
clickedPopover.
4. Return invokerPopover.
To get the popover stack position, given an [36097]HTML element
popover:
1. Let hintList be popover's [36098]node document's [36099]showing
hint popover list.
2. Let autoList be popover's [36100]node document's [36101]showing
auto popover list.
3. If popover is in hintList, then return the index of popover in
hintList + the size of autoList + 1.
4. If popover is in autoList, then return the index of popover in
autoList + 1.
5. Return 0.
To find the nearest inclusive target popover for invoker given a
[36102]Node node:
1. Let currentNode be node.
2. While currentNode is not null:
1. Let targetPopover be currentNode's [36103]popover target
element.
2. If targetPopover is not null and targetPopover's
[36104]popover attribute is in the [36105]auto state and
targetPopover's [36106]popover visibility state is
[36107]showing, then return targetPopover.
3. Set currentNode to currentNode's ancestor in the [36108]flat
tree.
7 Loading web pages
This section describes features that apply most directly to web
browsers. Having said that, except where specified otherwise, the
requirements defined in this section do apply to all user agents,
whether they are web browsers or not.
7.1 Supporting concepts
7.1.1 Origins
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 [36109]"SecurityError" [36110]DOMException will
be raised.
__________________________________________________________________
An origin is one of the following:
An opaque origin
An internal value, with no serialization it can be recreated
from (it is serialized as "null" per [36111]serialization of an
origin), for which the only meaningful operation is testing for
equality.
A tuple origin
A [36112]tuple consisting of:
+ A scheme (an [36113]ASCII string).
+ A host (a [36114]host).
+ A port (null or a 16-bit unsigned integer).
+ A domain (null or a [36115]domain). Null unless stated
otherwise.
[36116]Origins can be shared, e.g., among multiple [36117]Document
objects. Furthermore, [36118]origins are generally immutable. Only the
[36119]domain of a [36120]tuple origin can be changed, and only through
the [36121]document.domain API.
The effective domain of an [36122]origin origin is computed as follows:
1. If origin is an [36123]opaque origin, then return null.
2. If origin's [36124]domain is non-null, then return origin's
[36125]domain.
3. Return origin's [36126]host.
The serialization of an origin is the string obtained by applying the
following algorithm to the given [36127]origin origin:
1. If origin is an [36128]opaque origin, then return "null".
2. Otherwise, let result be origin's [36129]scheme.
3. Append "://" to result.
4. Append origin's [36130]host, [36131]serialized, to result.
5. If origin's [36132]port is non-null, append a U+003A COLON
character (:), and origin's [36133]port, [36134]serialized, to
result.
6. Return result.
The [36135]serialization of ("https", "xn--maraa-rta.example", null,
null) is "https://xn--maraa-rta.example".
There used to also be a Unicode serialization of an origin. However, it
was never widely adopted.
__________________________________________________________________
Two [36136]origins, A and B, are said to be same origin if the
following algorithm returns true:
1. If A and B are the same [36137]opaque origin, then return true.
2. If A and B are both [36138]tuple origins and their [36139]schemes,
[36140]hosts, and [36141]port are identical, then return true.
3. Return false.
Two [36142]origins, A and B, are said to be same origin-domain if the
following algorithm returns true:
1. If A and B are the same [36143]opaque origin, then return true.
2. If A and B are both [36144]tuple origins:
1. If A and B's [36145]schemes are identical, and their
[36146]domains are identical and non-null, then return true.
2. Otherwise, if A and B are [36147]same origin and their
[36148]domains are both null, return true.
3. Return false.
A B [36149]same origin [36150]same origin-domain
("https", "example.org", null, null) ("https", "example.org", null,