W3C

HTML 5.1

W3C Recommendation,

This version:
https://www.w3.org/TR/2016/REC-html-5.1-20161101/
Latest published version:
http://www.w3.org/TR/html51/
Editor's Draft:
https://w3c.github.io/html/
Previous Versions:
http://www.w3.org/TR/2016/WD-html51-20160503/
Editors:
(The Paciello Group)
(Microsoft)
(Microsoft)
(Google)
Former Editors:
(Microsoft)
(Apple Inc.)
Robin Berjon (W3C)
Participate:
File an issue (open issues)
Others:
Single page version

Abstract

This specification defines the 5th major version, first minor revision of the core language of the World Wide Web: the Hypertext Markup Language (HTML). In this version, new features continue to be introduced to help Web application authors, new elements continue to be introduced based on research into prevailing authoring practices, and special attention continues to be given to defining clear conformance criteria for user agents in an effort to improve interoperability.

Status of this document

The following features are at-risk, and may be dropped during the CR period:

“At-risk” is a W3C Process term-of-art, and does not necessarily imply that the feature is in danger of being dropped or delayed. It means that the WG believes the feature may have difficulty being interoperably implemented in a timely manner, and marking it as such allows the WG to drop the feature if necessary when transitioning to the Proposed Rec stage, without having to publish a new Candidate Rec without the feature first.

1. 소개

1.1. 배경

이 섹션은 비규범적입니다.

HTML은 월드 와이드 웹의 핵심 마크업 언어입니다. 본래, HTML은 주로 의미론적으로 체계적인 문서를 기술하기 위한 언어로서 설계되었습니다. 그러나, 그것의 일반적인 설계는 이후 몇 년간 다수의 문서와 심지어 어플리케이션을 기술하기 위해 응용될 수 있도록 되었습니다.

1.2. 독자

이 섹션은 비규범적입니다.

이 명세는 이 명세에 정의된 특징을 사용하는 문서와 스크립트의 작성자들과, 이 명세에 정의된 특징을 사용하는 페이지에서 동작하는 도구의 구현자들과, 문서의 정확성이나 이 명세의 요구의 필요성에 대한 구현을 확인하기 원하는 개개인을 위해 의도된 것입니다.

이 문서는 정확성을 위해 명료성을, 그리고 완정성을 위해 간결성을 희생시키기 때문에 적어도 웹 기술 들에 익숙하지 않은 독자들에게는 적합하지 않을 것입니다. 좀 더 이해하기 쉬운 튜토리얼과 작성 가이드들이 그 주제에 적당한 소개를 제공할 수 있습니다.

특히, 이 명세의 약간의 좀 더 기술적인 부분의 완전한 이해를 위해 DOM의 기초에 익숙함이 필요합니다. 웹 IDL, HTTP, XML, 유니코드, 문자 인코딩, 자바스크립트, CSS의 이해 역시 곳곳에서 도움이 되겠지만 필수는 아닙니다.

1.3. 범위

이 섹션은 비규범적입니다.

이 명세는 범위가 정적 문서로부터 동적 어플리케이션까지에 이르는 웹 상의 접근 가능한 페이지를 작성하기 위한 시맨틱 레벨 마크업 언어와 연관된 시맨틱 레벨 스크립팅 API들을 제공하는데 제한됩니다.

이 명세의 범위는 표현의 매체 별 사용자정의에 대한 메커니즘을 제공하는 것을 포함하지 않습니다. (웹 브라우저에 대한 기본 렌더링 규칙이 이 명세의 마지막에 포함되어 있고, CSS로 후킹을 위한 몇 몇 메커니즘이 언어의 일부로서 제공되어 있기는 하지만.)

이 명세의 범위는 전체 운영 체제를 설명하는 것이 아닙니다. 특히, 하드웨어 구성 소프트웨어, 이미지 편집 툴, 날마다 하이엔드 워크스테이션을 가지고 사용할 것으로 예상되는 응용프로그램들은 범위 밖입니다. 응용프로그램의 관점에서, 이 명세는 특히 비정기적으로 사용자들에 의해 사용될 것으로 예상되거나, 정기적이나 다른 위치에서 사용될 것으로 예상되는, 낮은 CPU가 필요한 응용프로그램을 대상으로 합니다. 그러한 응용 프로그램들의 예로는, 온라인 구매 시스템, 검색 시스템, 게임(특히 멀티플레이어 온라인 게임), 전화번호부나 주소책, 통신용 소프트웨어 (이메일 클라이언트, 인스턴트 메세지 클라이언트, 디스커션 소프트웨어), 문서 편집 소프트웨어, 기타 등등 입니다.

1.4. 연혁

이 섹션은 비규범적입니다.

첫 5년 동안(1990-1995), HTML은 처음 CERN에서, 그리고 이후 IETF에서 주로 주최되어 다수의 개정이 이루어졌고 다수의 확장을 겪었습니다.

W3C의 창설과 함께, HTML의 개발은 다시 위치가 변경되었습니다. HTML 3.0으로 알려진 1995년의 HTML 확장에 첫 번째 실패 이후 HTML3.2로 알려진 좀 더 실용적인 접근 방법을 만들었고, 그것이 1997년에 완성되었습니다. HTML 4.01이 빠르게 같은 해에 뒤따랐습니다.

그 다음 해, W3C 회원들은 HTML을 발전시키는 것을 중단하고 대신 XHTML이라 불리는 XML 기반의 동등한 것에 착수하기로 결정했습니다. 이러한 노력은 XHTML 1.0 으로 알려진, XML에서 HTML 4.01의 재구성을 시작하였고, 새로운 직렬화를 제외하고 새로운 기능을 추가하지 않고, 2000년에 완료되었습니다. XHTML 1.0 이후, W3C의 관심은 XHTML 모듈화의 기치 아래, XHTML을 확장하기 위한 다른 작업 그룹을 쉽게 하는 것으로 바뀌었습니다. 이와 병행하여, W3C는 또한 XHTML 2.0이라 불리는 이전의 HTML과 XHTML언어와 호환이 되지 않는 새로운 언어에 착수했습니다.

1998년 HTML의 발전이 종료된 당시에, 브라우저 벤더들에 의해 개발된 HTML에 대한 API의 일부가 DOM Level 1 (1998년), DOM Level 2 Core와 DOM Level HTML (2000년에 시작하여 2003년에 절정에 달하는)라는 이름으로 명세화되고 발행되었습니다. 이러한 노력은 이후 2004년에 몇몇의 DOM Level 3 명세가 발행되었지만 모든 Level 3 초안이 완성되기 전에 작업 그룹이 종료 됨과 함께 점차 작아졌습니다.

2003년, 웹 양식의 다음 세대로 자리잡은 기술인 XForms의 발표는 HTML에 대한 대체품을 찾는 것보다 HTML 자체를 발전시키는 것에 새로워진 관심을 촉발시켰습니다. 이 관심은 웹 기술로서 XML의 발전이 기존의 배포된 기술(HTML 같은)에 대한 대체품으로서 보다, 완전히 새로운 기술(RSS와 이후 Atom 같은)로 제한되는 것에서부터 나타났습니다.

Xforms 1.0이 도입한 많은 기능들을 제공하기 위해 HTML4.01의 양식들을 확장하는 것이 기존의 HTML 웹 페이지와 맞지 않는 렌더링 엔진을 구현하기 위해 브라우저 없이도 가능하다는 것을 보여주는 개념의 증명은 이 새로운 관심사의 첫 결과물이었습니다. 초기 단계에, 초안이 이미 공개적으로 사용 가능했고 정보가 이미 모든 자료들로부터 얻어지고 있었던 반면, 명세는 오직 오페라 소프트웨어의 저작권 아래에 있었습니다.

HTML의 발전이 재개되어야 한다는 아이디어가 2004년 W3C 워크샵에서 검토되었고, 여기서 양식 관련 기능을 대신하는 앞서 언급된 기존의 초안 제안 뿐 아니라, HTML 작업의 기저(아래 설명 된)를 이루는 몇 몇 원칙들이 모질라와 오페라에 의해 공동으로 W3C에 소개되었습니다. 이 제안은 착수되지 않았습니다; 반대자들은 이전에 선택된 웹의 발전에 대한 방향과 충돌된다고 주장했습니다; 대신 W3C는 XML 기반의 대체품 개발을 지속했습니다.

이후 얼마 되지 않아, 애플, 모질라, 오페라가 공동으로 WHATWG라고 불리는 새로운 무대에서 계속하여 노력을 기울일 것을 발표했습니다. 공동 메일링 리스트가 생성되었고, 초안이 WHATWG 사이트로 이관되었습니다. 이후 저작권이 세 벤더들에 의해 공동으로 소유되고 명세의 재사용이 허용되도록 개정되었습니다.

WAHTWG는 몇 가지 핵심 원칙, 특히 기술은 이전과 호환 되어야할 필요가 있고, 명세들과 구현은 구현보다 명세 변경을 의도한다하더라도 일치해야 할 필요가 있으며, 그 명세는 각각의 리버스 엔지니어링 없이 완벽히 상호 운용성을 달성할 수 있도록 충분히 자세해야 할 필요가 있음 등에 근거합니다.

특히 후자의 요구 사항은 HTML 명세의 범위가 세 가지 분리 된 문서: HTML 4.01, XHTML 1.1, DOM Level 2 HTML에 이전에 명시된 것들을 포함할 것을 요구 되었습니다. 이는 또한 이전에 고려된 규범들보다 좀 더 상당히 상세한 것을 포함할 것을 의미합니다.

2006년에, 마침내 W3C는 HTML 5.0의 개발에 참여하는 것에 관심을 나타냈고, 2007년에 HTML 명세의 개발에 WHATWG와 함께 작업하기 위해 인가된 워킹 그룹이 형성되었습니다. 애플, 모질라, 오페라는 WAHTWG 사이트에 제한이 적은 라이센스를 가진 버전을 유지하는 동시에, W3C가 W3C 저작권 하에 명세를 발행하는 것을 허용했습니다.

수 년간, 이후 두 그룹은 동일한 편집자 하에 함께 작업하였습니다: Ian Hickson. 2011년에, 그룹들은 서로 다른 목표를 가지고 있다는 결론에 도달했습니다: W3C는 HTML 5.0 권고안에 대한 기능을 분명히 선을 긋기를 원한 반면, WHATWG는 계속적으로 명세를 유지하고 새로운 기능을 추가하여 HTML에 대해 라이브 표준에 작업이 계속되기를 원했습니다. 2012년 중반에, HTML 5.0 권고안 생성을 책임지고 다음 HTML 버전에 대한 규격 초안을 준비하기 위한 새로운 편집 팀이 W3C에 도입되었습니다.

그때부터, W3C HTML WG는 W3C HTML 명세에 등록되거나 유저 에이전트들에 실제 구현되어 좀 더 정밀하게 나타난 버그들이 해결된 것을 WHATWG로부터 패치를 체리 피킹하고 있습니다.이 문서의 발행 시점에, WHATWG HTML 명세로부터 패치들은 2016년 1월 12일까지 병합되었습니다. W3C HTML 편집자들은 또한 WHATWG에 의해 공유되지 않은 버그들로부터 버그 수정한 것 뿐 아니라 W3C HTML WG에 의해 만들어진 논의와 결정으로 나온 패치들을 추가하였습니다.

별도의 문서에 이 문서에 명시된 HTML과 HTML 4.01 명세 내 설명된 언어 사이의 다른점이 발행되었습니다. [HTML5-DIFF]

1.5. 설계 노트

이 섹션은 비규범적입니다.

HTML의 많은 측면들이 첫 눈에 무의미하고 규범에 맞지 않게 보일 수 있음을 인정해야 합니다.

HTML, HTML의 지원 DOM API들 뿐 아니라 많은 HTML의 지원 기술들은 서로 다른 우선권들을 가진, 많은 경우 서로의 존재를 모르는 다수의 사람들에 의해 몇 십년 동안 개발되어 왔습니다.

이 기능들은 이와 같이 많은 자료들로부터 생겨났고, 특히 일관된 방법으로 항상 설계되지 않았습니다. 뿐만 아니라, 웹의 고유한 특징들 때문에 구현 버그는 콘텐트가 종종 그 버그들이 해결될 수 있기 전에 그것들에 의존하여 그 방법으로 무심결에 작성되기 때문에 종종 사실 상의 그리고 정식 표준이 되었습니다.

그럼에도 불구하고, 노력은 명확한 설계 목적을 충실히 지켜져 왔습니다. 이것들은 다음 몇 세부항목에 기술됩니다.

1.5.1. 스크립트 실행의 직렬화

이 섹션은 비규범적입니다.

웹 작성자를 멀티스레딩의 복잡도에 노출되지 않도록 하기 위해, HTML과 DOM API들은 다른 스크립트들의 동시 실행을 감지하는 스크립트가 없도록 설계됩니다. 심지어 workers에도, 의도는 모든 브라우징 컨텍스트의 모든 스크립트의 실행이 완전히 직렬화 하는 것으로 고려될 수 있는 구현의 반응입니다.

1.5.2. 다른 명세 준수

이 섹션은 비규범적입니다.

이 명세는 매우 다양한 다른 명세들과 상호 작용하며 이들을 필요로 합니다. 불행하게도, 특정 상황에서 상반되는 요구들은 이 명세가 이러한 다른 명세들의 요구 사항들을 위반하는 것으로 이어집니다. 이것이 발생될 때마다, 위반은 "고의적인 위반"으로 언급되고, 위반에 대한 이유가 언급됩니다.

1.5.3. 확장성

이 섹션은 비규범적입니다.

HTML은 안전한 방법으로 의미(semantics)를 추가하기 위해 사용될 수 있는 다수의 확장성 메커니즘을 가집니다:

1.6. HTML vs XHTML

이 섹션은 비규범적입니다.

이 명세는 문서와 어플리케이션을 기술하기 위해 추상적인 언어와 이 언어에서 사용하는 리소스의 메모리 내부 표현과 상호작용을 위한 몇 API들을 정의합니다.

메모리 내부 표현은 "DOM HTML", 혹은 요약하여 "DOM"으로 알려져 있습니다.

이 추상적인 언어를 사용하는 리소스를 전송하는데 사용될 수 있는 여러 구체적인 구문이 있는데, 이 명세에서 정의되는 것이 두 가지입니다.

그 첫 번째 구문은 HTML 구문입니다. 이것은 대다수 작성자에게 권장되는 형식입니다. 대다수 레거시 웹 브라우저들과 호환됩니다. 브라우저가 text/html MIME 타입으로 전송된다면, 웹 브라우저들에 의해 HTML 문서로 처리 될 것입니다. 이 명세는 "HTML 5.1"로 알려진 HTML 문법의 가장 최근 버전을 정의합니다.

두 번째 구문은 XHTML 구문이고, 이것은 XML의 적용입니다. 문서가 application/xhtml+xml와 같은, XML MIME 타입으로 전송된다면, XML 처리기에 의해 해석되기 위해, 웹 브라우저들에 의해 XML 문서로 취급됩니다. 작성자는 XML과 HTML에 대한 처리가 다름을 상기해야 합니다; 특히, HTML 구문에서는 무시될 사소한 구문 오류 조차 XML로 분류된 문서가 완전히 렌더링 되는 것을 방해할 것입니다. 이 명세는 "XHTML 5.1"로 알려진, XHTML 구문의 최신 버전을 정의합니다.

DOM, HTML 구문, XHTML 구문은 모두 동일한 콘텐트를 나타낼 수 없습니다. 예를 들어, 네임스페이스는 HTML 구문을 사용하여 표현될 수 없지만, DOM과 XHTML 구문에서는 지원됩니다. 비슷하게, noscript 기능을 사용하는 문서는 HTML 구문을 사용하여 표현될 수 있지만, DOM과 XHTML 구문에서는 표현될 수 없습니다. 문자열 "-->"를 포함한 주석은 HTML, XHTML 구문에서는 사용할 수 없고 오직 DOM에서만 표현될 수 있습니다.

1.7. 이 명세의 구조

이 섹션은 비규범적입니다.

이 명세는 다음 주요 섹션들로 나뉘어 있습니다:

§1 소개

HTML 표준에 대한 컨텍스트를 제공하는 비규범적 자료.

§2 공통 인프라

적합한 클래스, 알고리즘, 정의, 명세 나머지 부분의 공통적인 기초 보강

§3 HTML 문서의 의미론, 구조, API

문서는 요소들로 이루어져있습니다. 이 요소들은 DOM을 사용하는 트리로 구성됩니다. 이 섹션은 이 DOM의 기능뿐 아니라, 모든 요소에 대한 공통 기능과, 정의하는 요소들에 사용되는 개념을 정의합니다.

§4 HTML의 요소(element)들

각 요소들은 사전에 정의된 의미(meaning)를 가지고, 이것이 이 섹션에서 설명됩니다. 작성자가 요소를 사용하는 방법에 대한 규칙이, 유저 에이전트가 각 요소를 처리하는 방법에 대한 요구사항들과 함께 제공됩니다. 이것은 비디오 재생과 자막, 양식 제어와 양식 전송, HTML 캔버스로 알려진 2D 그래픽 API 같은 HTML의 큰 특징들을 포함합니다.

§5 User interaction

HTML 문서는 사용자가 콘텐트와 상호작용하고 수정하도록 다수의 메커니즘을 제공할 수 있고, 이는 포커스가 동작하는 방식, 드래그 앤 드롭 같은 것이 이 섹션에 기술됩니다.

§6 Loading Web pages

HTML 문서는 의미 없이 존재하지 않습니다 — 이 섹션은 웹 브라우저들과 웹 어플리케이션의 오프라인 캐싱 같은, 여러 페이지를 처리하는 환경에 영향을 미치는 많은 기능들을 정의합니다.

§7 Web application APIs

이 섹션은 HTML에서 어플리케이션의 스크립팅에 대한 기본 기능을 소개합니다.

§8 The HTML syntax

§9 The XHTML syntax

모든 이 기능들은 직렬화 된 양식으로 표현될 수 없고 다른 사람에게 보낼 수 없다면 쓸모 없게 될 것이고, 그래서 이 섹션들은 HTML과 XHTML의 구문과 함께, 그 구문들을 사용하여 콘텐트를 해석하는 방법에 대한 규칙을 정의합니다.

§10 Rendering

이 섹션은 웹 브라우저에 대한 기본 렌더링 규칙들을 정의합니다.

또한 §11 Obsolete features§12 IANA considerations을 나열하는 몇 가지 부록이 있고, 약간의 색인이 있습니다.

1.7.1. 이 명세를 읽는 방법

이 명세는 모든 다른 명세들처럼 읽어야(should) 합니다. 먼저, 처음부터 끝까지, 여러 번 읽어야(should) 합니다. 그 후, 적어도 한 번은 거꾸로 읽어야(should) 합니다. 그리고 나서 콘텐트 리스트에서 임의의 섹션을 고르고 모든 상호 참조를 따라서 읽어야(should) 합니다.

아래 적합성 요구 사항 섹션에서 설명된대로, 이 명세는 여러 적합성 클래스들에 대한 적합성 기준을 설명합니다. 특히, 제작자, 예를 들어 작성자와 그들이 만드는 문서에 적용되는 적합성 요구 사항이 있고, 소비자, 예를 들어 웹 브라우저들에 적용되는 적합성 요구 사항이 있습니다. 이것들은 요구하는 것에 의해 구별될 수 있습니다: 소비자 입장에서 요구 사항은 소프트웨어가 어떻게 동작해야 하는가인 반면, 제작자 입장에서 요구 사항은 무엇이 허용되는가 입니다.

예를 들어, "foo 속성(attribute)의 값은 유효한 정수이어야(must) 합니다."는 허용된 값을 제시하는 것으로서, 제작자에 대한 요구사항입니다; 그에 반해, "foo 속성(attribute)의 값은 정수를 해석하기 위한 규칙을 사용하여 해석되어야(must) 합니다."는 콘텐트를 어떻게 처리해야 하는지를 설명하는 것으로, 소비자에 대한 요구사항입니다.

생산자에 대한 요구 사항은 소비자에 아무런 관련이 없습니다.

위 예에 이어서, 특정한 속성(attribute)의 값이 유효한 정수로 강요된다고 서술된 요구 사항은 전혀 소비자에 대한 요구사항에 대하여 어떠한 것도 의미하지 않습니다. 소비자는 사실 불분명한 문자열로 속성을 취급하도록 요구될 수도 있으며, 값이 요구사항에 맞는지 맞지 않는지에 전혀 영향을 받지 않습니다. (이전 예제에서와 같이) 소비자는 값을 유효하지 않은 값(이 경우에는 숫자가 아닌)을 처리하는 방법을 정의하는 특정한 규칙을 사용하여 해석하도록 요구될 수도 있습니다.

1.7.2. 표기법

이것은 정의, 또는 요구사항, 또는 설명입니다.

이것은 주석(note)입니다.

이것은 예시입니다.

이것은 해결되지 않은 이슈입니다.

이것은 경고입니다.

interface Example {
    // 이것은 IDL 정의입니다.
};
variable = object . method( [ optionalArgument ] )
이것은 사용자에게 인터페이스 사용을 설명하는 주석입니다.
/*  CSS  . */

용어를 정의하는 것은 this와 같이 마크업 됩니다. 그 용어의 사용은 thisthis와 같이 마크업 됩니다.

요소(element), 속성(attribute), API를 정의하는 것은 this와 같이 마크업됩니다. 그 요소(element), 속성(attribute), API를 참조하는 것은 this와 같이 마크업 됩니다.

다른 코드 조각들은 이렇게 마크업 됩니다..

0x00 부터 0x7F까지 폭넓은 범위 내 바이트를 가진 바이트 시퀀스는 `this`와 같이 마크업 됩니다.

변수는 this와 같이 마크업 됩니다.

알고리즘에서, 동기 섹션 내 단계들은 ⌛과 함께 마크업 됩니다.

경우에 따라, 요구 사항들은 조건과 해당하는 요구 사항들을 가지고 리스트 형태로 주어집니다. 그러한 경우에, 조건에 적용되는 요구 사항들은, 그 요구 사항들에 대한 여러 세트의 조건이 존재하는 경우에도, 항상, 조건이 따르는 요구 사항의 첫 번째 세트입니다. 그러한 경우들이 다음과 같이 표현됩니다:

이것은 조건입니다.
이것은 다른 조건입니다.
이것은 위 조건에 적용되는 요구 사항입니다.
이것은 세 번째 조건입니다.
이것은 세 번째 조건에 적용되는 요구 사항 입니다.

1.8. 개인 정보 보호

이 섹션은 비규범적입니다.

HTML의 일부 기능은 사용자 개인 정보의 정책과 사용자 편의를 맞바꿉니다.

일반적으로, 인터넷의 아키텍쳐 때문에, 사용자는 사용자의 IP 주소에 따라 서로 구별 될 수 있습니다. IP 주소는 사용자와 전적으로 일치하지 않습니다; 사용자는 디바이스에서 디바이스로, 혹은 네트워크에서 네트워크로 이동하기 때문에, IP 주소는 변화합니다; 비슷하게, NAT 라우팅, 프록시 서버, 공유 컴퓨터는 단일 IP 주소로부터 오는 모든 것이 실제로는 여러 사용자에게 대응하는 것으로 나타나는 패킷이 가능하게 합니다. 어니언 라우팅 같은 기술은 인터넷의 한 노드에서 단일 사용자로부터의 요청이 네트워크의 많은 다른 부분으로부터 오는 것으로 나타내기 위해 요청을 더욱 익명으로 하는 데 사용될 수 있습니다.

그러나, 사용자의 요청에 사용되는 IP 주소는 사용자의 요청이 서로 연관 될 수 있는 유일한 메커니즘은 아닙니다.

예를 들어, 쿠키는 이것이 가능하도록 특별히 설계되었고, 이것은 계정을 가지고 있는 사이트에서 로그인 하는 것을 가능하게 하는 대다수 웹 세션 기능의 근간입니다.

응용프로그램 캐시는 개인정보에 대하여 비슷한 방향을 가집니다. 예를 들어 캐시를 제공할 때 사이트가 사용자를 식별할 수 있다면, 캐시에 쿠키 부활에 사용될 수 있는 데이터를 저장할 수 있습니다.

좀 더 영리한 다른 메커니즘이 있습니다. 사용자의 시스템의 어떤 특성은 각각으로부터 사용자 그룹을 구별하는데 사용될 수 있습니다; 그러한 정보를 충분히 수집함으로써, 개인 사용자의 브라우저의 "디지털 지문"은 계산될 수 있고, 이것은 동일한 사용자로부터 요청을 확인하는 방법으로 IP 주소로는 아니더라도 더 좋을 수 있습니다.

이 방법으로 요청을 그룹핑하는 것은, 특히 여러 사이트에 걸쳐, 악의적인 목적 뿐 아니라, 모두 유익한 (그리고 거의 틀림없이 긍정적인) 목적으로 사용될 수 있습니다. 상당히 유익한 목적의 예는 특정한 사람이 강아지 삽화가 있는 사이트를 선호하는 것 같이 보이는지 반대로 고양이 삽화가 있는 사이트를 선호하는 것 같이 보이는지 여부를 결정하고(그들이 해당 사이트를 방문하는 빈도에 기반하여) 그 후 연관된 사이트에 차후 방문 시 선호된 삽화를 자동으로 사용하도록 하는 것일 것입니다. 그러나, 악의적인 목적은 선거에서 어떤 이가 투표하는 것을 막을 것인지를 결정하기 위해 그 사람의 집 주소(사이트에서 운전 경로를 얻을 때 사용하는 주소로부터 알아낸)와 같은 정보와 그들의 분명한 정당 소속(그가 참여한 포럼 사이트를 조사하여 알아낸) 정보를 결합하는 조직을 포함할 수 있습니다.

악의적인 목적은 매우 악랄할 수 있기 때문에, 유저 에이전트 구현자들은 사용자의 지문을 채취하는데 사용될 수 있는 유출되는 정보를 최소화 하는 툴을 가지고 사용자에게 제공하는 방법을 고려하는 것이 권장됩니다.

아쉽게도, 이 섹션의 첫 문단이 의미하듯이, 때때로 지문을 채취하는 목적으로 사용될 수 있는 바로 그 정보를 노출하여 말미암는 대단한 이익들이 종종 있기 때문에, 모든 가능한 유출을 간단히 막는 것은 아주 손쉬운 것은 아닙니다. 예를 들어, 특정 ID로 게시하는 사이트에 로그인 할 수 있는 기능은 동일한 사용자로부터의 모든 사용자의 요청이 식별 가능하도록 요구 됩니다. 좀 더 미묘하긴 하지만, 캔버스에 텍스트를 그리는 것을 포함하는 많은 효과(예를 들어, 텍스트 주변에 테두리를 그리는 것을 포함하는 효과)가 필요한 큰 텍스트와 같은 정보 또한 사용자의 요청을 그룹핑 하는데 필요할 수 있는 정보(이 경우, 잠재적으로 노출함으로서 악랄한 수색을 통해, 사용자가 어떤 폰트를 설치했는지, 사용자마다 상당히 달라질 수 있는 정보)를 유출합니다.

이 명세에서 사용자의 지문 채취에 사용될 수 있는 기능들은 이 문단처럼 표시됩니다. (이것은 지문 그림입니다.)

플랫폼에서 다른 기능들은 아래 내용을 포함하더라도 제한되지 않고 같은 목적으로 사용될 수 있습니다:

1.9. HTML 간단한 소개

이 섹션은 비규범적입니다.

기본적인 HTML 문서는 다음과 같습니다:

<!DOCTYPE html>
<html>
  <head>
    <title>Sample page</title>
  </head>
  <body>
    <h1>Sample page</h1>
    <p>This is a <a href="demo.html">simple</a> sample.</p>
    <!-- this is a comment -->
  </body>
</html>

HTML 문서는 요소(element)와 텍스트의 트리로 구성됩니다. 각 요소(element)는 "body"와 같은 시작 태그와 "/body>"과 같은 종료 태그로 소스에 표시됩니다. (특정 시작 태그와 종료 태그는 어떤 경우에 생략될 수 있고 다른 태그들에 함축될 수 있습니다.)

태그는 서로 중복되는 일 없이, 요소들이 서로 안에 완전히 있도록 중첩되어야 합니다:

<p>This is <em>very <strong>wrong</em>!</strong></p>
<p>This <em>is <strong>correct</strong>.</em></p>

이 명세는 요소들이 중첩될 수 있는 방법에 대한 규칙과 함께, HTML에 사용될 수 있는 요소의 세트를 정의합니다.

요소는 속성(attribute)를 가질 수 있고, 이것은 요소들이 동작하는 방법을 제어합니다. 아래 예에서, a 요소와 href 속성(attirbute)을 사용하여 형성되는 하이퍼링크가 있습니다:

<a href="demo.html">simple</a>

속성은 시작 태그 내에 위치하고, "=" 문자로 구분되는 이름으로 구성됩니다. 속성 값은 공백 문자" ' ` = < >를 포함하지 않는 다면 따옴표 없이 남을 수 있습니다. 그렇지 않으면, 홑따옴표나 쌍따옴표를 사용하여야 합니다. 속성 값은 값이 빈 문자열이라면 "=" 문자와 함께 생략될 수 있습니다.

<!-- empty attributes -->
<input name=address disabled>
<input name=address disabled="">

<!-- attributes with a value -->
<input name=address maxlength=200>
<input name=address maxlength='200'>
<input name=address maxlength="200">

HTML 유저 에이전트들은 (예를 들어, 웹 브라우저) 이 마크업을 해석한 이후, DOM(Document Object Model) 트리로 바꿉니다. DOM 트리는 문서의 메모리 내 표현입니다.

DOM 트리는 여러 종류의 노드, 특히 DocumentType 노드, Element 노드, Text 노드, Comment 노드, 경우에 따라서는 ProcessingInstruction 노드를 포함합니다.

이 섹션의 가장 처음에 있는 마크업 조각은 다음 DOM 트리로 바뀔 것 입니다:

이 트리의 루트 요소(element)html 요소(element)이고, 이것은 항상 HTML 문서의 루트에서 발견됩니다. 이 요소는 두 요소(element), headbody 뿐 아니라 둘 사이에 Text 노드로 구성됩니다.

소스가 다수의 공백(여기에는 "␣"로 표기 된)과 DOM에서 Text 노드가 되는 모든 줄 바꿈("⏎")을 포함하기 때문에, 초기에 예상할 수 있는 것보다 DOM 트리에는 더욱 많은 Text 노드가 있습니다. 하지만, 역사적인 이유로 원본 마크업의 모든 공백과 줄바꿈은 DOM에 나타나지 않습니다. 특히, head 시작 태그 전의 모든 빈공간은 묵시적으로 생략되게 되고, body 종료 태그 후의 모든 빈공간은 body의 끝에 위치하게 됩니다.

head 요소(element)는 title 요소를 포함하고, title 요소는 문자열 "Sample page"를 가진 Text 노드를 포함합니다. 비슷하게 body 요소(element)는 h1 요소(element), p 요소(element), 주석을 포함합니다.


이 DOM 트리는 페이지의 스크립트에 의해 조작될 수 있습니다. 스크립트(일반적으로 자바스크립트)는 script 요소(element)를 사용하거나 이벤트 핸들러 콘텐트 속성(attribute)를 사용하여 삽입될 수 있는 작은 프로그램입니다. 예를 들어, "Hello World"를 출력하기 위해 양식의 output 요소(element)의 값을 설정하는 스크립트를 가진 양식이 있습니다.

<form name="main">
  Result: <output name="result"></output>
  <script>
    document.forms.main.elements.result.value = 'Hello World';
  </script>
</form>

DOM 트리 내 각 요소(element)는 객체로 나타나고, 이 객체들은 API들을 가지기 때문에 조작될 수 있습니다. 예를 들어, 링크(예를 들어 위 트리에서 a 요소(element))는 몇 가지 방법으로 변경된 "href" 속성(attribute)을 가질 수 있습니다:

var a = document.links[0]; // obtain the first link in the document
a.href = 'sample.html'; // change the destination URL of the link
a.protocol = 'https'; // change just the scheme part of the URL
a.setAttribute('href', 'https://example.com/'); // change the content attribute directly

DOM 트리는 HTML 문서가 처리되고 실행에 의해 표현될 때 (특히 웹 브라우저 같은 대화형 실행) HTML 문서를 나타내는 방식으로 사용되기 때문에, 이 명세는 위에 기술된 마크업 대신에, 일반적으로 DOM 트리의 관점으로 표현됩니다.


HTML 문서는 대화형 콘텐트의 매체 독립 설명을 나타냅니다. HTML 문서는 스크린이나 음성 합성 장치를 통해, 혹은 점자 디스플레이에 렌더링 될 수 있습니다. 그러한 렌더링이 일어나는 방법에 정확히 영향을 주기 위해, 작성자는 CSS 같은 스타일링 언어를 사용할 수 있습니다.

다음 예에서, 페이지는 CSS를 사용하여 파란색 위에 노랜색으로 만들어졌습니다.

<!DOCTYPE html>
<html>
  <head>
    <title>Sample styled page</title>
    <style>
      body { background: navy; color: yellow; }
    </style>
  </head>
  <body>
    <h1>Sample styled page</h1>
    <p>This page is just a demo.</p>
  </body>
</html>

HTML을 사용하는 방법에 더 자세한 내용에 대해, 작성자는 튜토리얼과 가이드를 찾아볼 것이 권장됩니다. 이 명세에 포함된 몇 몇 예제들은 사용 될 수도 있지만, 초급 작성자는 이 명세가 처음에 이해하기에 어려울 수 있는 자세한 수준으로 언어를 설명할 수 밖에 없기 때문에 주의가 주어집니다.

1.9.1. HTML로 안전한 어플리케이션 작성

이 섹션은 비규범적입니다.

HTML이 대화형 사이트를 생성하는데 사용될 경우, 사이트 자체나 사이트의 사용자의 무결성을 위태롭게 할 수 있는 공격자를 통해 취약성을 도입하지 않도록 주의할 필요가 있습니다.

이 문제의 포괄적인 연구는 이 문서의 범위 밖에 있고, 작성자 좀 더 자세하게 문제를 연구할 것을 강력히 권장됩니다. 다만, 이 섹션은 HTML 어플리케이션 개발에 일부 공통된 위험들에 대한 간단한 소개를 제공하려고 합니다.

웹의 보안 모델은 "origins" 개념에 기초하고, 많은 웹 상의 잠재적인 공격은 그에 대응하여 교차 출처(cross-origin) 행동을 수반합니다. [ORIGIN]

사용자 입력의 유효성을 검사하지 않음

교차 사이트 스크립팅 (XSS)

SQL 인젝션(injection)

신뢰할 수 없는 입력, 예를 들어, 텍스트 주석 같은 사용자 생성 콘텐트, URL 파라미터 안의 값, 서드 파티 사이트로부터의 메세지, 등을 받아들일 경우, 데이터는 사용하기 전에 반드시 검증되어야 하고, 표시 될 때 적절히 이스케이프(escape)되어야 합니다. 이를 수행하는 것이 실패하는 것은, 가짜 나이 같은 가짜 사용자 정보를 제공하는 것과 같은 잠재적으로 무해한 것에서부터 사용자가 정보를 포함하는 페이지를 보는 매 순간 스크립트를 실행하는 것 같은 심각한 것까지, 잠재적으로 처리 중 공격을 전파하여 서버 내 모든 데이터를 삭제하는 것 같은 최악까지, 적대적인 사용자의 다양한 공격 수행을 허용할 수 있습니다.

사용자 입력을 검증하기 위한 필터를 작성할 경우, 필터는 반드시, 알려진 안전한 구조를 허용하고 모든 다른 입력은 불허하여, 항상 안전한 목록 기반으로 되어야 합니다. 알려진 해로운 입력을 불허하고 나머지 모든 것을 허용하는 차단 목록 기반 필터는 해로운 모든 것이 아직 다 알려진 것이 아니기 때문에(예를 들어, 미래에 만들어 질 수도 있기 때문에) 안전하지 않습니다.

예를 들어, 다음 경우와 같이, 무엇을 표시할 것인지를 결정하기 위해 페이지가 URL의 쿼리 스트링을 보고, 그 후 메세지를 표시하기 위해 그 페이지로 사용자를 리다이렉트 시킨다고 가정해 봅시다:
<ul>
  <li><a href="message.cgi?say=Hello">Say Hello</a>
  <li><a href="message.cgi?say=Welcome">Say Welcome</a>
  <li><a href="message.cgi?say=Kittens">Say Kittens</a>
</ul>

메세지가 사용자에게 이스케이프 없이 바로 표시되었다면, 적대적인 공격자는 스크립트 요소(element)가 포함된 URL을 만들 수 있습니다:

https://example.com/message.cgi?say=%3Cscript%3Ealert%28%27Oh%20no%21%27%29%3C/script%3E

공격자가 이후 공격 대상자가 이 페이지를 방문할 것으로 확신했다면, 공격자가 선택한 스크립트는 페이지에서 실행될 것입니다. 그런 스크립트는 사이트가 제공하는 것에 의해서만 제한되고, 얼마든지 적대적인 행동을 할 수 있습니다: 예를 들어, 사이트가 e-커머스 상점이라면 그러한 스크립트는 사용자 모르게 마음대로 많은 원치않는 구매를 야기할 수 있습니다.

이것이 교차 사이트 스크립팅(cross-site scripting) 공격이라고 불립니다.

사이트를 속여서 코드를 실행하게 하는데 사용될 수 있는 많은 구성 요소들이 있습니다. 안전한 목록 필터들을 작성할 경우 작성자가 고려하도록 권장되는 몇 가지가 있습니다:

  • img 처럼 무해해 보이는 요소(element)를 허용할 경우, 최소 권한의 원리를 집행하고 요소의 속성(attribute)를 오직 요구되는 것(예를 들어, 안전 목록)으로만 제한시킵니다. 모든 속성(attribute)이 허용된다면 공격자는 예를 들어, 임의의 스크립트를 수행하기 위해 onload 속성(attribute)을 사용할 수 있습니다.

  • 제공된 URL(예를 들어 링크)이 허용되는 경우, 각 URL의 스키마는 악용 될 수 있는 많은 스키마들이 있기 때문에 명시적으로 안전목록에 있을 필요가 있습니다. 가장 유명한 예는 "javascript:"이지만, 유저 에이전트들은 다른 스크립트를 구현할 수 있습니다. (그리고 실제로 역사적으로 구현 되었습니다.)

  • base 요소(element)가 삽입되는 것을 허용하는 것은 페이지 내에 관련 링크를 가진 script 요소(element)들이 탈취될 수 있음을 의미하고, 유사하게 양식 전송이 적대적인 사이트로 리다이렉트 될 수 있습니다.

교차 사이트 요청 위조 (CSRF)

사이트가 사용자가 사용자 특정 사이드 이펙트를 가진 양식 전송, 예를 들어 사용자의 이름으로 포럼에 메세지를 게시하거나, 구매하거나, 여권을 신청하는 것이 이루어지는 것을 허용한다면, 요청이 사용자 모르게 요청을 만들도록 속이는 다른 사이트가 아니라,사용자에 의해 의도적으로 만들어진 것인지 검증하는 것이 중요합니다.

이 문제는 HTML 양식이 다른 origin으로 전송될 수 있기 때문에 존재합니다.

사이트들은 사용자 특정 숨김 토큰을 가진 양식을 채우거나, 모든 요청에 Origin 헤더를 검사하여 그런 공격을 막을 수 있습니다.

클릭잭킹

사용자가 수행되는 것을 원하지 않는 행동을 수행하는 인터페이스를 사용자에게 제공하는 페이지는 사용자가 속아서 인터페이스를 활성화 할 수 있는 가능성이 방지되도록 설계 될 필요가 있습니다.

사용자가 속을 수 있는 하나의 방법은 적대적인 사이트가 작은 iframe에 공격 대상 사이트를 위치시키고 사용자가 클릭하도록 믿게 하는 것 ,예를 들어 사용자가 반응 게임을 하도록 하는 것입니다. 일단 사용자가 게임을 하면, 적대적인 사이트는 사용자가 클릭 할 때 빠르게 마우스 커서 아래에 iframe을 위치 시키고, 따라서 사용자가 공격 대상 사이트의 인터페이스를 클릭하도록 속입니다.

이를 방지하기 위해, 프레임 사용이 예상되지 않는 사이트는 인터페이스가 프레임 내에 있지 않음이 감지되는 경우(예를 들어, Window 객체와 top 속성(attribute)의 값을 비교하여) 에만 활성화 되도록 권장됩니다.

1.9.2. API 스크립팅을 사용하는 경우를 막는 일반적인 위험

이 섹션은 비규범적입니다.

HTML 내 스크립트는 일반적으로 브라우저가 추가적인 이벤트를 발생시키거나, 문서 해석을 계속하는 것 같은 다른 것을 수행하기 전에 중단하지 않고 스크립트를 수행 함을 의미하는 "run-to-completion" 의미(semantics)를 가집니다.

다른 한편으로, HTML 파일의 해석은 병렬로 그리고 파서가 스크립트를 수행하는 지점에서 중단 됨을 의미하는, 점진적으로 발생합니다. 이것은 일반적으로 좋은 일이지만, 이는 작성자가 이벤트가 되도록 발생한 이후에 이벤트 핸들러를 후킹하는 것을 방지하도록 조심해야 할 필요가 있음을 의미합니다.

이것을 확실하게 수행하기 위한 두 가지 기술이 있습니다: 이벤트 핸들러 콘텐트 속성(attribute)을 사용하거나 동일한 스크립트에서 요소(element)를 생성하고 이벤트 핸들러를 추가하는 것입니다. 앞서 언급 되었듯이, 스크립트는 더 많은 이벤트들이 발생하기 전에 스크립트는 수행부터 완료되기 때문에 후자가 안전합니다.

한 가지 방법은 img 요소들과 load 이벤트로 명시할 수 있습니다. 이벤트는 요소(element)가 해석 되자마자, 특히 이미지가 이미 캐시되었다면(이것이 일반적입니다), 발생 될 수 있습니다.

여기서, 작성자는 load 이벤트를 발견하기 위해 img 요소(element)의 onload 핸들러를 사용합니다:

<img src="games.png" alt="Games" onload="gamesLogoHasLoaded(event)">

요소(element)가 스크립트에 의해 추가된 후 이벤트 핸들러가 동일한 스크립트에서 추가되는 한, 이벤트는 If the element is being added by script, then so long as the event handlers are added in the 여전히 놓치지 않습니다:

<script>
var img = new Image();
img.src = 'games.png';
img.alt = 'Games';
img.onload = gamesLogoHasLoaded;
// img.addEventListener('load', gamesLogoHasLoaded, false); // would work also
</script>

그러나, 작성자가 처음 img 요소(element)를 생성했고 분리된 스크립트에서 이벤트 리스너가 추가되었다면, 그것을 놓치게 유도하여 load 이벤트가 그 사이에 발생되는 기회가 생깁니다.

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

1.9.3. HTML을 작성할 때 실수를 찾는 방법: 유효성 검사기와 적합성 검사기

이 섹션은 비규범적입니다.

작성자는 적합성 검사기(유효성 검사기로 알려진)의 사용으로 일반적인 실수를 찾도록 권장됩니다. W3C는 Nu Markup Validation Service를 포함하여 다수의 온라인 유효성 서비스를 제공합니다.

1.10. 작성자를 위한 적합성 요구사항

이 섹션은 비규범적입니다.

HTML 명세의 이전 버전과는 달리, 이 명세는 유효한 문서 뿐 아니라 유효하지 않은 문서에 대한 처리에 요구되는 몇 가지 자세한 사항으로 정의합니다.

그러나, 비록 유효하지 않은 콘텐트의 처리가 대부분의 경우 명확하지만, 문서에 대한 적합성 요구사항은 여전히 중요합니다: 실제로는, 상호운용성은 (모든 구현이 믿을 만하고 똑같거나 동등한 수준의 방법으로 특정 콘텐츠를 처리하는 상황) 문서 적합성 요구 사항의 목적만은 아닙니다. 이 섹션은 적합한 문서와 오류가 있는 문서를 구별하기 위한 몇 가지 더 일반적인 이유들을 상술합니다.

1.10.1. 표현 마크업

이 섹션은 비규범적입니다.

HTML의 이전 버전에서의 대다수 표현 기능은 더 이상 허용되지 않습니다. 일반적으로 표현 마크업음 많은 문제를 가지고 있는 것이 발견되었습니다:

표현 요소(element)의 사용은 낮은 접근성으로 이어집니다.

보조 기술(AT) 사용자에게 적절한 경험을 제공하는 방법으로(예를 들어, ARIA를 사용하여) 표현 마크업을 사용하는 것이 가능한 반면, 그렇게 하는 것은 의미론적으로 적절한 마크업을 사용하여 그렇게 하는 경우보다 상당히 더 어렵습니다. 게다가, 표현 마크업은 비 AT 사용자, 비 그래픽 유저 에이전트(텍스트 모드 브라우저 같은)에 대한 접근성을 보장하지 않습니다.

반면, 매체 독립 마크업을 사용하는 것은 좀 더 많은 사용자(예를 들어 텍스트 브라우저 사용자들)에 대한 "접근 가능"한 방법으로 작성된 문서에 대한 쉬운 방법을 제공합니다.

유지보수의 높은 비용

마크업이 스타일 독립적인 방법으로 작성된 사이트를 유지보수하는 것은 상당히 쉽습니다. 예를 들어, <font color="">를 사용하는 사이트의 색상을 변경하는 것은 전체 사이트에 걸쳐 변경을 요구하는 반면, CSS 기반의 사이트를 비슷하게 변경하는 것은 단일 파일의 변경으로 가능합니다.

큰 문서 크기

표현 마크업은 더구나 불필요한 경향이 있고, 따라서 큰 문서 크기의 결과를 가져옵니다.

그러한 이유로, 이 버전에서는 HTML로부터 표현 마크업이 제거되었습니다. 이 변화는 놀라운 일이 아닙니다; HTML 4.0은 수 년전부터 표현 마크업을 반대했고, 사용자가 표현 마크업으로부터 떠나도록 돕는 모드(HTML Transitional)를 제공했습니다; 이후, XHTML 1.1은 더 나아가 그 기능들을 완전히 폐기했습니다.

HTML에 유일하게 남은 표현 마크업 기능은 style 속성(attribute)과 style 요소(element)입니다. style 속성(attribute)의 사용은 생산 환경에서 다소 지양되지만, 빠른 프로토타이핑(그것의 규칙이 나중에 별도의 스타일 시트로 직접 옮겨질 수 있는)과 별도의 스타일 시트가 충족시키지 못하는 일반적이지 않은 상황에서 특정 스타일을 제공에 유용할 수 있습니다. 비슷하게, style 요소(element)는 그룹핑이나 페이지 특정 스타일에 유용할 수 있지만, 일반적으로 외부 스타일 시트는 스타일이 여러 페이지에 적용되는 경우 더 많은 편리할 가능성이 있습니다.

몇 몇의 이전의 표현 요소(element)들이 이 명세에서 매체 독립적으로 재정의 되는 것에 주목할 가치가 있습니다: b, i, hr, s, small, u.

1.10.2. 구문 오류

이 섹션은 비규범적입니다.

HTML의 구문은 다양한 갖가지 문제들을 방지하게 만듭니다.

비직관적인 이벤트 핸들링 동작

특정한 유효하지 앟은 구문 구성은, 해석 될 때, 매우 비직관적인 DOM 트리를 야기합니다.

예를 들어, 다음 마크업 조각은 DOM에서 table 요소(element)와 상응하는 앞선 형제인 hr을 야기합니다:
<table><hr>...

선택적 오류 복구를 가진 오류

더 기이하고 난해한 오류 처리 규칙을 구현할 필요 없이 유저 에이전트들이 환경이 제어될 수 있도록 사용되는 것을 허용하기 위해, 유저 에이전트들은 해석 오류를 맞닥뜨릴 때 마다 실패하는 것을 허용합니다.

오류 처리 행동이 스트리밍 유저 에이전트들과 호환되지 않는 오류

위에 언급된 <table><hr>...예에 대한 행동 같은, 일부 오류 처리 행동은 스트리밍 유저 에이전트들과 (상태를 저장하지 않고 단일 패스(one-pass)로 HTML 파일을 처리하는 유저 에이전트들) 호환되지 않습니다. 그러한 유저 에이전트들로 상호운용성 문제를 방지하기 위한, 그러한 행동을 야기하는 어떠한 구문도 유효하지 않은 것으로 고려됩니다.

infoset 강제를 야기하는 오류

XML 기반의 유저 에이전트가 HTML 해석기에 연결되는 경우, 주석은 두 개의 연속된 하이픈을 포함해서는 안 된다는 것과 같은, XML이 강요하는 특정한 불변성은 HTML 파일에 의해 위반 될 것입니다. 이를 처리하는 것은 해석기가 HTML DOM을 XML 호환 infoset으로 강제하는 것을 요구할 수 있습니다. 그러한 처리를 요구하는 대부분의 구문은 유효하지 않은 것으로 고려됩니다. considered invalid.

균형이 맞지 않는 빈약한 성능을 초래하는 오류

특정 구문 구성은 균형이 맞지 않는 빈약한 성능을 초래할 수 있습니다. 그런 구성의 사용을 막기 위해 그것들은 일반적으로 부적합이 됩니다.

예를 들어, 다음 마크업은, 모든 닫히지 않은 i 요소(element)가 각 문단에서 재구성되어야 하기 때문에, 각 문단에서 계속해서 더 많은 요소(element)들을 야기하여 빈약한 퍼포먼스를 야기합니다:
<p><i>He dreamt.
<p><i>He dreamt that he ate breakfast.
<p><i>Then lunch.
<p><i>And finally dinner.

이 코드 조각에 대한 결과 DOM은 다음이 될 것입니다:

  • p
    • i
      • #text: He dreamt.
  • p
    • i
      • i
        • #text: He dreamt that he ate breakfast.
  • p
    • i
      • i
        • i
          • #text: Then lunch.
  • p
    • i
      • i
        • i
          • i
            • #text: And finally dinner.

취약한 구문 구조를 수반하는 오류

역사적인 이유로, 상대적으로 취약한 구문 구조가 있습니다. 뜻하지 않게 그러한 문제로 빠지는 다수의 사용자를 줄이기 위해, 그것들은 부적합이 됩니다.

예를 들어, 속성 내 특정한 명명된 문자 참조의 해석은, 닫는 세미콜론이 생략된 경우에도 발생됩니다. 명명된 문자 참조를 형성하지 않는 글자가 따르는 앰퍼샌드를 포함하는 것이 안전하지만, 글자가 명명된 문자 참조를 형성하는 문자열로 변경된다면, 그것들은 문자열 대신 그 문자로 해석 될 것입니다.

이 코드 조각에서, 속성의 값은 "?bill&ted"입니다:

<a href="?bill&ted">Bill and Ted</a>

하지만 다음 코드 조각에서 속성의 값은 심지어 마지막 세미콜론이 없기 때문에, "&copy"는 "&copy;"과 같은 것으로 처리되고 따라서 "©"로 해석되어, 의도된 "?art&copy"아니라 실제로 "?art©" 입니다:

<a href="?art&copy">Art and Copy</a>

이 문제를 방지하기 위해, 모든 명명된 문자 참조들은 세미콜론으로 종료되는 것이 요구되고, 세미콜론이 없이 명명된 문자 참조의 사용은 오류로 표시됩니다.

따라서, 위 경우를 나타내기 위한 올바른 방법은 다음과 같습니다:

<a href="?bill&ted">Bill and Ted</a> <!-- &ted 는 명명된 문자 참조가 아니기 때문에 ok -->
<a href="?art&amp;copy">Art and Copy</a> <!-- &copy 는 명명된 문자 참조 이기 때문에 &는 이스케이프 되어야 합니다. -->

레거시 유저 에이전트들에서 알려진 상호 운용성 문제를 수반하는 오류

특정 구문 구성은 레거시 유저 에이전트들에서 특히 미묘하거나 심각한 문제를 야기하는 것으로 알려져 있고, 그러므로 작성자가 그것들을 방지하는 것을 돕기 위해 부적합으로 표기됩니다.

예를 들어, 이것은 U+0060 억음 악센트 문자가 따옴표 없는 속성(attribute)에 허용되지 않는 이유입니다. 특정 레거시 유저 에이전트들에서, 그것은 종종 따옴표 문자로 취급됩니다.

이것의 또 다른 예는 DOCTYPE이고, 이것은 비쿼크 모드를 발생시키도록 요구되는데, 이는 쿼크 모드에서의 레거시 유저 에이전트들의 동작은 종종 주로 비문서화 되기 때문입니다.

작성자를 보안 공격에 노출시키는 리스크 오류

특정 제약사항은 순수하게 알려진 보안 문제들을 방지하기 위해 존재합니다.

예를 들어, UTF-7 사용의 제약사항은 순수하게 UTF-7를 사용하여 알려진 교차 사이트 스크립팅 공격의 희생양이 되는 것을 방지하기 위해 존재합니다. [RFC2152]

작성자의 의도가 분명하지 않은 경우

작성자의 의도가 매우 분명하지 않은 마크업은 종종 부적합이 됩니다. 이 오류들을 초기에 보완하는 것이 차후 유지보수를 쉽게 만듭니다.

예를 들어, 다음은 h1 헤딩이 되는지 h2 헤딩이 되는지 작성자가 의도한 것이 분명하지 않습니다:

<h2>Contact details</h1>

오타일 가능성이 있는 경우

사용자가 단순 오타를 만들 경우, 오류가 쉽게 잡힐 수 있다면 이는 작성자의 디버깅 시간을 단축시킬 수 있기 때문에 유용합니다. 그러므로 이 명세는 보통 이 명세에 정의 된 이름과 일치하지 않는 요소(element)명, 속성(element)명 등등을 사용하는 것을 오류로 간주합니다.

예를 들어, 작성자가 <caption> 대신에 <capton>라고 타이핑 했다면, 이 오류로 표기될 것이고 작성자는 즉시 오타를 수정할 수 있습니다.

미래에 새로운 구문과 충돌할 수 있는 오류

언어 구문이 미래에 확장 되는 것을 허용하기 위해, 특정한 다른 무해한 기능들이 허용되지 않습니다.

예를 들어, 종료 태그 안의 속성(attribute)들은 현재 유효하지 않고 무시됩니다. 언어에 대한 향후 변화는 이 구문 기능을 사용할 수 있고 이미 배포된(그리고 유효한!) 콘텐트와 충돌 없이 사용할 수 있습니다.

일부 작성자는, HTML 구문의 유연성을 이용하여 제공된 간결함의 작은 편의 넘어 그런 습관으로부터 얻어진 일관성을 택하여, 항상 모든 속성(attribute)들을 따옴표로 묶는 것과 모든 선택적 태그들을 포함하는 것에 노력을 기울이는 것이 유용하다는 것을 발견합니다. 그러한 작성자들을 지원하기 위해, 적합성 검사기는 그러한 규칙이 적용되는 운영 모드를 제공할 수 있습니다.

1.10.3. 콘텐트 모델과 속성(attribute) 값에 대한 제한 사항

이 섹션은 비규범적입니다.

언어의 구문을 넘어서, 이 명세는 또한 요소(element)와 속성(attribute)가 명시될 수 있는 방법에 대한 제한사항을 둡니다. 이 제한사항들은 비슷한 이유로 존재합니다:

모호한 의미(semantics)를 가진 콘텐트를 수반하는 오류

정의된 의미(meanings)를 가진 요소의 오용을 방지하기 위해, 콘텐트 모델들은 중첩이 모호한 값을 발생 시킬 수 있는 경우 요소들이 중첩될 수 있는 방법에 대한 제한이 정의됩니다.

예를 들어, 이 명세는, 작성자가 전체 섹션이 입력되어야 할 것이라고 나타낼 가능성이 아주 없기 때문에, kbd 요소(element) 안에 section 요소(element)가 중첩되는 것을 불허합니다.

전달된 의미(semantics)에 충돌을 수반하는 오류

비슷하게, 요소(elememt) 사용의 잘못에 작성자의 관심을 끌기 위해, 전달된 의미(semantics)의 분명한 모순 역시 접합성 오류로 간주됩니다.

예를 들어 아래 코드 조각에서, 의미(semantics)는 말도 안됩니다: 구분선은 동시에 셀이 될 수 없으며, 라디오 버튼 또한 진행 바(progress bar)가 될 수 없습니다.
<hr role="cell">
<input type=radio role=progressbar>

또 다른 예는 ul 요소(element)의 콘텐트 모델의 제약사항인데, li 자식 요소(element)만을 허용합니다. 정의에 따라 리스트는 0개 이상의 리스트 항목으로 구성되고, 따라서 ul 요소(element)가 li 요소(element)가 아닌 다른 어떤 것을 포함한다면, 의미하는 바가 불분명한 것입니다.

기본 스타일이 혼란을 이끌어 낼 가능성이 있는 경우

특정 요소(element)들은 특정 조합이 혼란을 이끌어 낼 가능성을 만들어내는 기본 스타일이나 동작을 가집니다. 이 요소(element)들이 이 문제 없는 동등한 수준의 대안을 가지는 경우, 혼란스러운 조합은 불허됩니다.

예를 들어, div 요소(element)는 블럭 박스로 렌더링 되고, span 요소(element)는 인라인 박스로 렌더링 됩니다. 인라인 박스 안에 블럭 박스를 두는 것은 불필요하게 혼란스럽습니다; div 요소(element)만을 중첩하거나, span 요소(element)만을 중첩하거나, div 요소(element) 안에 span 요소(element) 중첩하거나 모두 span 요소(element) 안에 div 요소(element)를 중첩하는 것과 동일한 목적을 제공하지만, 후자만이 인라인 박스 안에 블럭 박스를 수반하기 때문에 후자의 조합은 불허됩니다.

또 다른 예는 인터랙티브 콘텐트가 중첩될 수 있는 방법은 없다는 것 입니다. 예를 들어 button 요소(element)는 textarea 요소(element)를 포함할 수 없습니다. 이것은 그렇게 인터랙티브 요소(element)들을 중첩하는 것의 동작은 사용자를 매우 혼란스럽게 만들 것입니다. 이 요소(element)들을 중첩하는 대신 나란히 위치시킬 수 있습니다.

명세를 오해할 가능성을 나타내는 오류

때때로, 어떤 것들은 작성자를 혼란에 빠뜨릴 가능성을 허용하기 때문에 불허됩니다.

예를 들어, disabled 속성(attribute)를 "false" 값으로 설정하는 것은, 요소가 활성화 되었음을 의미하는 것의 표현임에도 불구하고 실은 요소가 비활성화 되었음을 의미하기 때문에 불허됩니다. (속성(attribute)의 존재가 구현의 문제이지 값의 문제는 아닙니다.)

단순히 언어를 간소화 하기 위해 도입된 제한을 수반하는 오류

어떤 적합성 오류는 작성자가 학습할 필요가 있는 언어를 간소화 합니다.

예를 들어, area 요소의 shape 속성(attribute)은, circcircle 값을 실제로 동의어로서 모두 허용함에도 불구하고, 튜토리얼과 다른 학습 지원을 간소화 하기 위해, circ 값의 사용을 불허합니다. 둘을 허용하는 것에 이득은 없는 반면, 언어를 가르칠 경우 추가적인 혼란을 야기할 수 있습니다.

해석기의 특이점을 수반하는 오류

특정 요소(element)들은 기이한 방법으로 해석되고(보통 역사적인 이유로), 그것들의 콘텐트 모델 제약사항들은 작성자가 이 이슈에 노출되는 것을 방지하기 위해 의도된 것입니다.

예를 들어, form 요소(element)는 HTML로 해석되는 경우 form 요소(element)의 시작 태그는 p 요소(element)의 종료 태그를 암시하기 때문에 프레이징 콘텐트 안에 허용되지 않습니다. 따라서 다음 마크업은 하나가 아닌 두 문단을 야기합니다:
<p>Welcome. <form><label>Name:</label> <input></form>

이것은 정확히 다음과 같이 해석됩니다:

<p>Welcome. </p><form><label>Name:</label> <input></form>

디버그 하기 어려운 방법으로 스크립트 실패를 야기할 가능성이 있는 오류

어떤 오류들은 디버그 하기 어려울 스크립트 문제들을 방지하는 것을 돕기 위해 의도되었습니다.

예를 들어, 동일한 값을 가진 두 id 속성(attribute)을 가지는 것은 부적합 사유입니다. 중복 ID는, 종종 원인을 규명하기 어려운 형편없는 효과와 함께, 선택되는 잘못된 요소를 이끌어 냅니다.

작성 시간을 낭비하는 오류

어떤 구조는 역사적으로 많은 낭비된 작성 시간의 원인이 되어왔기 때문에 비허용되고, 그것들을 만드는 것을 방지하기 위해 작성자에게 권장하여 작성자가 앞으로의 수고를 줄일 수 있습니다.

예를 들어, script 요소(element)의 src 속성(attribute)은 요소(element)의 콘텐츠가 무시되는 것을 야기합니다. 하지만 이것은, 특히 요소(element)의 콘텐츠가 실행 가능한 스크립트 — 작성자로 하여금 실행되고 있지 않음을 깨닫지 못하고 인라인 스크립트를 디버그하기 위한 노력에 많은 시간을 소모하게 만들 수 있는,를 나타낸다면, 명확하지 않습니다. 이 문제를 줄이기 위해 ,이 명세는 src 속성(attribute)이 존재할 경우, script 요소(element) 안에 실행 가능한 스크립트를 가지는 것을 부적합으로 만듭니다. 이것은 그들의 문서를 감사하는 작성자가 이러한 종류의 실수로 시간을 허비할 가능성이 적음을 의미합니다.

XHTML으로 그리고 XHTML로부터 마이그레이션 하는 작성자에게 영향을 주는 영역을 수반하는 오류

일부 작성자는 비슷한 결과를 가지는 XML과 HTML 양쪽 모두로 해석될 수 있는 파일을 작성하는 것을 좋아합니다. 이 습관이 무수히 많은 미묘한 복잡한 문제들이 수반되기 때문에(특히 스크립팅, 스타일링, 임의의 종류의 자동화 된 직렬화 등을 수반하는 경우) 일반적으로 권장되지 않기는 하지만, 이 명세는 최소한 어느 정도 어려움을 완화하기 위한 몇 가지 제약사항들을 가집니다. 이는 HTML과 XHTML 사이에서 마이그레이션 하는 경우 과도기적 단계로 작성자가 이것을 사용하는 것을 더 쉽게 합니다.

예를 들어, 동기화를 유지하도록 의도된 langxml:lang 속성(attribute) 주위의 다소 복잡한 규칙이 있습니다.

또 다른 예는 HTML 직렬화에서 xmlns 속성(attribute)의 값에 대한 제약사항들 일 것이고, 이는 적합한 문서에서 요소(element)들이 HTML로 처리되든 XML로 처리되든 동일한 네임스페이스에 있게 되는 것을 보장하도록 의도된 것입니다.

미래 확정을 위해 예약된 영역을 수반하는 오류

언어의 향후 개정에서 새로운 구문을 허용하도록 의도된 구문의 제약사항과 마찬가지로, 요소(element)의 콘텐트 모델과 속성(attribute)의 값의 일부 제약사항은 HTML 어휘의 미래 확장을 허용하도록 의도됩니다.

예를 들어, U+005F 밑줄 문자 (_)로 시작하는 target 속성(attribute)의 값을 오직 특정한 미리 정의된 값으로 제한하는 것은 새로운 미리 정의된 값이 미래에 작성자에 의해 정의된 값과 충돌 없이 도입되는 것을 허용합니다.

다른 명세의 오용을 나타내는 오류

특정 제약사항은 다른 명세에 의해 만들어진 제약사항을 지원하도록 의도됩니다.

예를 들어, 미디어 쿼리 목록을 취하는 속성(attribute)이 오직 유효한 미디어 쿼리 목록을 사용함을 요구하는 것은 그 명세의 적합성 규칙을 따르는 것의 중요성을 강화합니다.

1.11. 추천 읽을 거리

이 섹션은 비규범적입니다.

다음 문서들은 이 명세의 독자들이 관심을 가질 수 있습니다.

Character Model for the World Wide Web 1.0: Fundamentals [CHARMOD]

이 구성적인 명세는 명세의 작성자들, 소프트웨어 개발자들, 콘텐트 개발자에게, 유니코드 표준과 ISO/IEC 10646 공동으로 정의된 국제 부호화 문자 집합을 기반으로 하여, 월드 와이드 웹 상의 상호 운용적 텍스트 조작을 위한 일반적인 참조를 가지고 제공합니다. 제기된 주제는 "문자", "인코딩", "문자열", 참조 처리 모델, 문자 인코딩의 선택과 식별, 문자 이스케이핑, 문자열 인덱싱 이라는 용어의 사용을 포함합니다.

Unicode Security Considerations [UNICODE-SECURITY]

유니코드는 매우 많은 수의 문자들을 포함하고 세상의 다양한 작성 시스템을 포함하기 때문에, 잘못된 사용은 프로그램이나 시스템이 보안 공격이 가능하게 노출시킬 수 있습니다. 이것은 특히 더 많은 제품들이 국제화 되기 때문에 중요합니다. 이 문서는 프로그래머, 시스템 분석가, 표준 개발자, 사용자들이 고려해야하는 약간의 보안 고려사항을 설명하고, 문제의 리스크를 줄이기 위한 명세 권고안을 제공합니다.

Web Content Accessibility Guidelines (WCAG) 2.0 [WCAG20]

웹 콘텐트 접근성 지침 (WCAG) 2.0은 웹 콘텐트를 더 접근 가능하게 만들도록 권고안의 넓은 범위를 다룹니다. 이 지침들을 따르는 것은, 전맹과 저시력, 난청과 청력 손실, 학습 장애, 인지 장애, 상지 장애, 언어 장애, 광선과민증과 장애의 복합을 포함하여, 넓은 범위의 장애를 가진 사람들에게 범위 접근 가능한 콘텐트를 만들 것입니다. 이 지침을 따르는 것은 또한 일반적인 사용자에게도 종종 당신의 웹 콘텐트를 더 유용하게 만듭니다.

Authoring Tool Accessibility Guidelines (ATAG) 2.0 [ATAG20]

이 명세는 장애를 가진 사람들을 위한 더 접근 가능한 웹 콘텐트 저작 도구 설계에 대한 지침들을 제공합니다. 이 지침을 따르는 저작 도구는 접근 가능한 유저 인터페이스를 장애를 가진 저작자에게 제공하여, 게다가 모든 저작자에 의한 접근 가능한 웹 콘텐트 제품을 활성화하고 지원하고 촉진하여 접근성을 촉진할 것입니다.

User Agent Accessibility Guidelines (UAAG) 2.0 [UAAG20]

이 문서는 장애를 가진 사람들을 위한 웹 접근성에 대한 장벽을 낮추는 유저 에이전트 설계에 대한 지침을 제공합니다. 유저 에이전트들은 브라우저와 웹 콘텐트를 검색하고 렌더링 하는 다른 형태의 소프트웨어를 포함합니다. 이 지침을 따르는 유저 에이전트들은, 다른 기술과 통신하기 위한 능력(특히 보조 기술)을 포함하여, 그 자신의 유저 인터페이스를 통해 그리고 다른 내부 기능을 통해 접근성을 촉진할 것입니다. 뿐만 아니라, 장애를 가진 사용자 뿐 아닌, 모든 사용자들은 지침을 따르는 유저 에이전트들이 더 유용함을 찾을 수 있어야 합니다.

Polyglot Markup: HTML-Compatible XHTML Documents [HTML-POLYGLOT]

여러 언어를 사용하는 마크업(polyglot 마크업)을 사용하는 문서는 HTML로 해석할 때와 XML로 해석 할 때 동일한 문서 트리로(루트 요소(element)에 xmlns 속성(attribute)의 예외가 있는) 해석하는 일련의 바이트인 문서입니다. 잘 정의된 제약사항 세트를 만나는 polyglot 마크업은, 그것들이 HTML로 해석되든 XHTML로 해석되든 상관 없이, HTML 명세에 대하여 호환 가능한 것으로 해석됩니다. polyglot 마크업은 특정 DOCTYPE, 네임스페이스 선언, 요소(element)와 속성(attribute) 이름에 대해 특정 대소문자 — 일반적으로 소문자이지만 가끔 카멜 케이스 — 를 사용합니다. 더 나아가 제약사항은 빈 요소(element), 명명된 엔티티 참조, 스크립트와 스타일의 사용에 그것들을 포함합니다.

HTML Accessibility APIs Mappings 1.0 [HTML-AAM-1.0]

유저 에이전트가 HTML 5.1 요소(element)들과 속성(attibute)들을 플랫폼 접근성 API에 대응시키는 방법을 정의합니다. 이러한 매핑을 문서화 하는 것은 역할(role), 상태(state), 속성(property)과 접근성 API들에 의해 구현된 이벤트의 상호 운용 가능한 노출을 촉진하고 이 정보가 작성자 의도와 일관된 방식으로 나타남을 보장하는 것을 돕습니다.

2. 공통 인프라

2.1. 전문 용어

이 명세는 종종 동일한 상황에서 HTML과 XML 속성(attribute)와 IDL 속성(attribute) 양쪽 모두를 지칭합니다. 어떤 것을 지칭하고 있는지 분명하지 않을 경우, 그것들은 HTML과 XML 속성(attribute)에 대해서는 콘텐트 속성(attribute)으로, IDL 인터페이스에서 명시된 것에 대해서는 IDL 속성(attribute)으로 지칭합니다. 유사하게, "속성(property)"이라는 용어는 자바스크립트 객체 속성(property)와 CSS 속성(property) 모두에 대해 사용됩니다. 이것들이 모호한 경우 각각 객체 속성(property)CSS 속성(property)으로서 자격이 주어집니다 .

일반적으로, 명세가 기능이 HTML 구문 혹은 XHTML 구문에 적용된다고 서술하는 경우, 둘 다 포함하는 것입니다. 기능이 명확하게 두 언어 중 하나에만 적용하는 경우 "HTML에 대해, ... (이것은 XHTML에 적용하지 않습니다)" 처럼, 다른 형식에 적용하지 않는다고 명시적으로 서술하여 불립니다.

이 명세는 짧은 정적 문서로부터 긴 에세이나 리치 멀티미디어가 있는 리포트, 뿐만아니라 훌륭한 인터랙티브 어플리케이션에 이르기까지 모든 HTML의 사용에 지칭하는데 document이라는 용어를 사용합니다. 이 용어는 Document 객체와 그 객체의 후손 DOM 트리 둘 모두를 지칭하는데, 그리고 상황에 따라 HTML 구문이나 XHTML 구문을 사용하여 직렬화된 바이트 스트림을 지칭하는데 사용됩니다.

DOM 구조의 경우, HTML 문서XML 문서라는 용어는 DOM 명세에서 정의된 대로 사용되고, Document 객체가 찾아질 수 있는 두 다른 모드를 명확하게 지칭합니다. [DOM] (그런 사용법은 항상 그들의 정의에 하이퍼링크 되어 있습니다.)

바이트 스트림의 경우, HTML 문서라는 용어는 text/html로 라벨링 된 리소스를 지칭하고, XML 문서라는 용어는 XML MIME 타입으로 라벨링 된 리소스를 지칭합니다.

XHTML 문서라는 용어는 상황에 따라, HTML 네임스페이스 내 요소(element) 노드를 포함하는 XML 문서 모드인 문서HTML 네임스페이스의 요소를 포함하는 XML MIME 타입으로 라벨링 된 바이트 스트림을 지칭하는데 사용됩니다.


간결성을 위해, shown, displayed, visible와 같은 용어들은 (종종) 문서가 사용자에게 렌더링되는 방법을 지칭할 경우 사용됩니다. 이 용어들은 시각적 매체를 의미하는 것이 아닙니다; 동등한 방법으로 다른 매체에도 적용될 수 있도록 고려되어야 합니다.

알고리즘 B가 다른 알고리즘 A로 돌아간다 말하는 경우, A가 B를 호출했음을 의미합니다. A로 돌아가면, 구현은 B의 호출에서 멈춘 곳에서부터 계속 진행해야 합니다. 일부 알고리즘은 병렬로 수행합니다; 이것은 알고리즘의 다음 단계가 명세 내 다른 로직과 동시에 (예를 들어, 이벤트 반복이 동시에) 잇따라서 수행 됨을 의미합니다. 이 명세는 다른 하이퍼쓰레드, 코어, CPU, 기계 등을 사용하여 시분할 다중 작업, fibers, 프로세스가 달성되는 정밀한 메커니즘을 정의하지 않습니다. 그와 대조적으로, 즉시 수행하기 위한 작업은 현재 수행 중인 작업을 중단하고 수행해야 하며, 그후 이전에 수행 작업을 재개해야 합니다.

"투명한 검정"이라는 용어는 빨강, 초록, 파랑, 알파 채널이 모두 0으로 설정된 색상을 지칭합니다.

2.1.1. 리소스

유저 에이전트가 외부 리소스의 의미(semantics)를 디코딩할 수 있는 구현을 가지는지를 지칭하는 경우 명세는 지원된다라는 용어를 사용합니다. 형식(format)이나 유형(type)은 구현이 외부 리소스의 중요한 측면이 무시되지 않고 그 형식(foramt)이나 유형(type)의 리소스를 처리할 수 있다면 지원된다고 불립니다. 특정 리소스가 지원되는지 여부는 리소스의 형식이 사용되는 기능에 따라 달라질 수 있습니다.

예를 들어, PNG 이미지는 구현에 알려지지 않은 이미지가 애니메이션 데이터를 포함하고 있다 하더라도 픽셀 데이터가 디코드되고 렌더링 될 수 있다면 구현 지원되는 형식(format)으로 간주될 것입니다.

MPEG-4 비디오 파일은 사용된 압축 형식(format)이 지원되지 않았다면, 구현이 파일의 메타데이터로부터 영상의 크기를 결정할 수 있다하더라도 지원되는 형식(format)으로 간주되지 않을 것입니다.

일부 명세가, 특히 HTTP 명세에서, 표현(representation)으로 지칭된 것은 이 명세에서 리소스로 지칭됩니다. [HTTP]

MIME 타입 이라는 용어는 프로토콜 문서에서 종종 인터넷 미디어 타입으로 불리는 것을 지칭하는데 사용됩니다. 이 명세에서 media 타입 이라는 용어는 CSS 명세에 의해 사용된 것 처럼, 표현을 위해 의도된 미디어의 유형을 지칭하는데 사용됩니다. [RFC2046] [MEDIAQ]

문자열이 media-type 규칙과 일치한다면 유효한 MIME 타입입니다. 특히 유효한 MIME 타입은 MIME 타입 파라미터들을 포함할 수 있습니다. [HTTP]

문자열이 media-type 규칙과 일치하지만, 어떤 U+003B 세미콜론 문자 (;)도 포함하지 않는다면 파라미터를 가지지 않는 유효한 MIME 타입입니다. 다시 말해, 그것이 MIME 타입 파라미터 없이 오로지 타입과 서브 타입으로만 구성된다면. [HTTP]

HTML MIME 타입 이라는 용어는 MIME 타입 text/html를 지칭하는데 사용됩니다.

리소스의 중요한 하위 리소스들은 완전히 처리되기 위해 사용 가능(available)해야 하는 것이 필요한 리소스 입니다. 어떤 자원이 중요한 것으로 간주되거나 그렇지 않은 지는 리소스의 형식(format)을 정의하는 명세에 의해 정의되어 있습니다.

data: URL이라는 용어는 data: 스킴을 URLs 사용하는 URL들을 지칭합니다. [RFC2397]

2.1.2. XML

HTML에서 XHTML로 쉽게 마이그레이션 하기 위해, 이 명세를 따르는 유저 에이전트들은 적어도 DOM과 CSS의 용도를 위해 https://www.w3.org/1999/xhtml 네임스페이스의 HTML에 요소(element)들을 위치시킬 것입니다. "HTML 요소"라는 용어는 이 명세에서 사용될 경우, 그 네임스페이스의 요소를 지칭하고, 따라서 HTML과 XHTML 요소들 모두를 지칭합니다.

달리 명시된 것을 제외하고, 이 명세에 정의되거나 언급된 모든 요소(element)들은 HTML 네임스페이스 ("https://www.w3.org/1999/xhtml")에 있고, 이 명세에 정의되거나 언급된 모든 속성(attribute)들은 네임스페이스를 가지지 않습니다.

요소(element) 유형은 주어진 로컬 이름과 네임스페이스를 가진 요소들의 세트를 지칭하는데 사용됩니다. 예를 들어, button 요소(element)는 로컬 이름 "button"과 (위에 정의된 대로 암묵적으로) HTML 네임스페이스를 가지는 것을 의미하는, 요소 유형을 가진 요소(element)입니다.

속성(attirbute) 이름은 XML에 정의된 Name 생성과 일치하고 U+003A 콜론 문자(:)를 포함하지 않는다면 XML 호환 가능하다 불립니다. [XML]

XML MIME 타입이라는 용어는 MIME 타입 text/xml, application/xml, 서브 타입이 4개 문자 "+xml"로 끝나는 MIME 타입을 지칭하는데 사용됩니다. [RFC7303]

2.1.3. DOM 트리

Document 객체의 루트 요소(element)는 그 Document의 첫 번째 자식이 있다면 그것입니다. 첫 번째 자식이 없다면 Document는 루트 요소(element)가 없습니다.

루트 요소(element)라는 용어는, Document 객체의 루트 요소(element)를 지칭하지 않는 경우, 검토되는 노드의 가장 먼 조상 요소(element) 노드나 조상 노드가 없다면 자기 자신을 의미합니다.노드가 문서의 일부인 경우, 노드의 요소(element)는 확실히 문서의 루트 요소(element)입니다; 하지만, 노드가 현재 문서 트리의 일부가 아니라면, 루트 요소(element)는 부모가 없는 노드일 것입니다.

요소(element)의 루트 요소(element)Document 객체의 루트 요소(element)인 경우, 이 요소(element)는 Document 안에 있다고 불립니다. 요소(element)는 그것의 루트 요소(element)가 변경되고 그 요소(element)가 이제 문서의 루트 요소(element)인 경우, 문서에 삽입 되었다고 불립니다. 비슷하게, 요소(element)는 그것의 루트 요소(element)가 문서의 루트 요소(element)에서 다른 요소(element)로 변경되는 경우 문서에서 제거 되었다고 불립니다.

노드의 홈 서브트리가 그 노드의 루트 요소(element)에 루트를 둔 서브트리입니다. 노드가 Document안에 있는 경우, 그것의 홈 서브트리는 그 Document의 트리입니다.

Node(요소(element) 같은)의 DocumentNodeownerDocument IDL 속성(attribute)이 반환하는 Document 입니다. NodeDocument 안에 있는 경우 그 Document는 항상 NodeDocument이고, NodeownerDocument IDL 속성(attribute)은 따라서 항상 Document를 반환합니다.

콘텐트 속성(attribute)의 Document는 속성(attirbute)의 요소(element)의 Document입니다.

트리 순서라는 용어는 (parentNode/childNodes 관계를 통해) 수반된 DOM 노드의 전위 순회, 깊이 우선 탐색을 의미합니다.

어떤 요소(element)나 속성(attribute)이 무시되거나, 어떤 다른 값으로 취급되거나, 마치 또 다른 것처럼 처리되는 것으로 명시되는 경우, 이것은 노드가 DOM 안에 위치된 이후 처리되는 것을 지칭합니다.

콘텐트 속성(attribute)는 그것의 새로운 값이 이전 값과 다를 경우에 한해 값을 바꾼다라고 불립니다; 이미 가지고 있던 값으로 속성을 설정하는 것은 바꾸는 것이 아닙니다.

Text 노드, 문자열 속성 값이 비어있음으로 기술되는 경우, 그것은 텍스트의 길이가 0임을 의미합니다. (즉, 공백이나 제어 문자조차도 아닙니다).

요소(element)의 자식 텍스트 콘텐트트리 순서에서 요소(element)의 자식(주석이나 요소(element)같은 다른 노드는 제외하고)인 모든 Text 노드의 data의 연결입니다.

삽입 단계가 인자로 A를 가지고 작동되고 A의 새로운 부모가 B인 경우 노드 B노드 A가 삽입됩니다. 비슷하게, removedNode 인자로 AoldParent 인자로 B를 가지고 제거 단계가 작동되는 경우 노드 B로부터 노드 A가 제거 됩니다.

2.1.4. 스크립팅

Foo가 실제로 인터페이스인 경우, 구조 "Foo 객체"는 때때로 좀 더 정확한 "Foo 인터페이스를 구현하는 객체" 대신 사용됩니다.

IDL 속성(attribute)는 그것의 값이 검색 되는(예를 들어, 작성자 스크립트에 의해) 경우 가져온다라고 불리고 새로운 값이 할당되는 경우 설정한다라고 불립니다.

DOM 객체가 존속된다라고 불리는 경우, 그 객체의 속성(attribute)과 메서드(method)는 데이터의 스냅샷이 아닌, 실제 내부 데이터로 운용되어야 합니다.

이벤트의 측면에서, 발생발송이라는 용어는 DOM 명세에서 정의된 대로 사용됩니다: 이벤트가 발생한다는 것은 생성하고 발송 한다는 것을 의미하고, 이벤트를 발송한다는 것은 트리를 통해 이벤트를 전파하는 단계를 따른다는 것을 의미합니다. 신뢰할 수 있는 이벤트isTrusted 속성(attribute)이 true로 초기화 된 이벤트를 지칭하는데 사용됩니다. [DOM]

2.1.5. Plugin 콘텐트 처리기

plugin이라는 용어는 유저 에이전트에 의해 사용될 수 있는 콘텐츠 처리기의 유저 에이전트 정의 세트를 지칭합니다. 콘텐트 처리기는 유저 에이전트의 Document 객체의 렌더링에 참여할 수 있지만, Document자식 브라우징 컨텍스트로 행동하거나 Document의 DOM에 임의의 Node 객체를 도입하지 않습니다.

일반적으로 그러한 콘텐트 처리기들은 서드 파티로 제공되기는 하지만, 유저 에이전트는 내장 콘텐트 처리기도 플러그인으로 지정할 수 있습니다.

유저 에이전트는 text/plainapplication/octet-stream 유형을 등록된 플러그인을 가지는 것으로 간주해서는 안됩니다.

플러그인의 한 가지 예는 사용자가 PDF 파일을 탐색할 때 브라우징 컨텍스트에 인스턴스화 된 PDF 뷰어일 것입니다. 이것은 PDF 뷰어 컴포넌트를 구현한 단체가 유저 에이전트를 구현한 단체와 동일한지 여부와 상관 없이 플러그인으로 인정할 것입니다. 하지만, 유저 에이전트와 분리되어 시작하는 (동일한 인터페이스를 사용하는 것이 아닌) PDF뷰어 어플리케이션은 이 정의에 의해 플러그인이 아닙니다.

이 명세는 플러그인이 유저 에이전트와 플랫폼 종속인 것으로 예상되기 때문에 플러그인과 상호작용에 대한 메커니즘을 정의하지 않습니다. 일부 유저 에이전트들은 넷스케이프 플러그인 API와 같은 플러그인 메커니즘을 지원하는 것을 선택할 수 있습니다; 또 어떤 것들은 원격 콘텐트 변환기를 사용하거나 특정 유형에 대한 내장 지원을 가질 수도 있습니다. 실제로, 이 명세는 플러그인을 지원하는 유저 에이전트들이 전혀 필요하지 않습니다. [NPAPI]

플러그인은 sandbox 속성(attribute)의 의미(semantics)를 만족하면 보호 될 수 있습니다.

예를 들어, 보호된 플러그인은 플러그인이 샌드박스 된 iframe 안에서 인스턴스화 된 경우 콘텐트가 팝업 윈도우를 생성하는 것을 차단할 것입니다.

브라우저는 플러그인을 위해 의도된 외부 콘텐트와 상호작용을 할 경우 극도의 주의를 기울여야(should) 합니다. 서드 파티 소프트웨어가 유저 에이전트처럼 동일한 특권을 가지고 수행되는 경우, 서드 파티 소프트웨어의 취약성은 유저 에이전트의 취약성이 있는 것만큼 위험하게 됩니다.

다른 plugins 세트를 가지는 다른 사용자는 사용자를 유일하게 식별되게 하는 기회를 증가시키는 지문 그림을 제공하기 때문에, 유저 에이전트들은 각 사용자에 대해 정확히 동일한 플러그인 세트를 지원하도록 권장 됩니다. (이것은 지문 그림입니다.)

2.1.6. 문자 인코딩

문자 인코딩, 혹은 애매모호하지 않은 인코딩은 WHATWG 인코딩 표준에 정의된 대로, 바이트 스트림과 유니코드 문자열 사이를 전환하기 위한 정의된 방법입니다. 인코딩은, 인코딩 표준에 인코딩의 이름라벨로 지칭된, 인코딩 이름이나 하나 이상의 인코딩 라벨을 가집니다. [ENCODING]

UTF-16 인코딩UTF-16BEUTF-16LE입니다. [ENCODING]

ASCII 호환 인코딩UTF-16 인코딩이 아닌 모든 인코딩입니다. [ENCODING]

WHATWG 인코딩 표준에 정의되지 않은 인코딩에 대한 지원은 금지되어 있기 때문에, UTF-16 인코딩은 이 명세가 ASCII 호환 인코딩이 되지 않는 것으로 처리할 필요가 있는 유일한 인코딩입니다.

코드 단위이라는 용어는웹 IDL 명세에 정의된 대로 사용됩니다: DOMString의 가장 작은 최소 구성 요소인 16비트 무부호 정수입니다. (이것은 유니코드에 사용된 것 보다 좁은 정의이고 code point와 동일하지 않습니다.) [WEBIDL]

유니코드 코드 포인트라는 용어는 그것이 가능한 경우 유니코드 스칼라 값을 의미하고, 불가능한 경우 독자적인 대용 코드 포인트(isolated surrogate code point)를 의미합니다. 적합성 요구사항이 이 문자나 유니코드 코드 포인트 용어로 정의되는 경우, 낮은 대용 코드가 뒤따르는 높은 대용 코드로 구성되는 한 쌍의 코드 단위는 대용 코드쌍으로 나타나는 단일 코드 포인트로 취급되어야 하지만, 독자적인 대용 코드는 각각 대용 코드의 값을 가지고 단일 코드로 취급 되어야 합니다. [UNICODE]

이 명세에서, 문자라는 용어는, 유니코드 문자로서 자격이 없는 경우, 유니코드 코드 포인트 용어와 같은 것을 의미합니다.

유니코드 문자유니코드 스칼라 값을 의미하는데 사용됩니다.(즉, 독자적인 코드 포인트가 아닌 모든 유니코드 코드 포인트) [UNICODE]

문자열의 코드 단위 길이는 그 문자열의 코드 단위들의 갯수입니다.

이 복잡성은 유니코드 문자의 용어에서 보다 16비트(UTF-8) 코드 단위(UTF-16)의 용어에서 DOM API를 정의하기 위한 역사적인 결정이 원인입니다.

2.2. 적합성 요구사항

이 명세의 모든 다이어그램, 예제, 주석은 모든 섹션에 비범적이라고 명시적으로 표시된 것 처럼 비규범적입니다. 이 명세에서 다른 모든 것들은 규범적입니다.

이 문서의 규범적 부분에 있는 "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", "OPTIONAL" 키워드들은 RFC2119에 설명된 대로 해석되어야 합니다. 이 문서의 규범적인 부분에 있는 "OPTIONALLY" 키워드는 "MAY"와 "OPTIONAL"처럼 동일한 규범적 의미로 해석되어야 합니다. 가독성을 위해, 이 단어들은 이 명세에서 모두 대문자 글자로 나타내지는 않습니다. [RFC2119]

본 번역본에서는 가급적 위 표기들을 한글과 함께 영문을 괄호 안에 표기하려 하고 있으나, 깜박하고 놓치고 지나갈 수 있기 때문에 가급적 위 키워드와 관련된 한글 표현에 대해서는 영문으로 된 원문과 비교하여 보시기를 권합니다.

알고리즘의 일부분으로 명령조로 표현된 요구사항들은("선두의 모든 공백 문자를 제거"나 "false를 반환하고 이 단계들을 중단" 같은) 알고리즘 도입에 사용되는 키워드("must", "should", "may", 등등)의 의미(meaning)로 해석되어야 합니다.

예를 들어, 다음과 같은 명세가 있었다면:
To eat an orange, the user must:
1. Peel the orange.
2. Separate each slice of the orange.
3. Eat the orange slices.

...이것은 다음과 동등할 것입니다:

To eat an orange:
1. The user must peel the orange.
2. The user must separate each slice of the orange.
3. The user must eat the orange slices.

여기서 키워드는 "must"입니다.

전자의(명령조) 방식은 일반적으로 문제상의 이유로 이 명세에서 선호됩니다.

알고리즘이나 구체적인 단계들로 표현된 적합성 요구사항은 최종 결과가 동등한 것이기만 하면 임의의 방법으로 구현될 수 있습니다. (특히, 이 명세에 정의된 알고리즘은 쉽게 따라할 수 있도록 의도된 것이고, 고성능이 되도록 의도된 것이 아닙니다.)

2.2.1. 적합성 종류

이 명세는 유저 에이전트들과 (구현자에 관련된) 문서에 (작성자와 작성 도구 구현자에 관련된) 대한 적합성 기준을 설명합니다.

적합한 문서는 문서에 대한 모든 적합성 기준을 따르는 문서입니다. 가독성을 위해, 이 적합성 요구사항의 일부는 작성자에 대한 적합성 요구사항으로 표현됩니다; 그 요구사항들은 암묵적으로 문서에 대한 요구사항입니다: 정의에 의해, 모든 문서들은 작성자가 있었다고 가정됩니다. (어떤 경우, 그 작성자는 유저 에이전트 자체가 될 수 있습니다. — 그러한 유저 에이전트들은 아래 설명된 대로, 추가적인 규칙의 적용을 받습니다.)

예를 들어, 요구사항이 "작성자는 foobar 요소(element)를 사용하지 않아야(must not) 합니다" 라고 명시한다면, 이는 문서가 foobar라고 명명된 요소(element)를 포함하는 것을 허용하지 않는다는 것을 암시합니다.

문서 적합성 요구사항과 구현 적합성 요구사항 사이의 암묵적인 관계는 없습니다. 유저 에이전트는 원하는 대로 부적합한 문서를 처리하는데 자유롭지 않습니다; 이 명세에 설명된 처리 모델은 입력 문서의 적합성에 상관없이 구현에 적용됩니다.

유저 에이전트는 서로 다른 적합성 요구사항을 가진 몇 가지 범주에 (중복하여) 속합니다.

웹 브라우저와 다른 인터랙티브 유저 에이전트들

XHTML 구문을 지원하는 웹 브라우저는 이 명세에 설명된 대로 XML 문서에서 찾아지는 HTML 네임스페이스의 요소(element)와 속성(attribute)을 처리 해야(must)하기 때문에, 그 요소들의 의미(semantics)가 다른 명세에 의해 재정의되지 않는 한 사용자는 그것들을 가지고 상호작용 할 수 있습니다.

적합한 HTML 처리기는, XHTML 문서에서 XHTML script 요소(element)를 찾자마자, 그 요소에 포함된 스크립트를 실행합니다. 하지만, 요소가 XSLT에서 표현된 변형 내에서 찾아진다면 (유저 에이전트가 XSLT도 지원한다고 가정하여), 처리기는 대신 변형의 일부를 형성하는 불분명한 요소(element)로서 script 요소(element)를 대신 다룰 것입니다.

HTML 구문을 지원하는 웹 브라우저는 이 명세에 설명된 대로 HTML MIME 타입으로 라벨링 된 문서를 처리해야(must) 하기 때문에, 사용자는 그 문서와 상호작용 할 수 있습니다.

스크립팅을 지원하는 유저 에이전트들은 또한 웹 IDL 명세에 정의된 대로, 이 명세의 IDL 코드 조각의 구현이 준수되어야(must) 합니다. [WEBIDL]

명시적으로 명시되지 않은 한, HTML 요소(element)들의 의미(semantics)를 재정의 하는 명세는 그 요소(element)들을 나타내는 DOM 객체에서의 요구사항을 재정의 하지 않습니다. 예를 들어, 위 예제에서 script 요소(element)는 여전히 HTMLScriptElement 인터페이스를 구현합니다.

비상호작용 프리젠테이션 유저 에이전트들

순수하게 HTML과 XHTML 문서의 비상호작용 버전을 렌더링하기 위해 문서를 처리하는 유저 에이전트는, 사용자 인터랙션에 관하여 요구사항이 면제되는 것을 제외하고, 웹 브라우저 같이 동일한 적합성 기준을 따라야(must) 합니다.

비상호작용 유저 에이전트의 전형적인 예는 프린터(정적 유저 에이전트들)와 오버헤드 디스플레이(동적 유저 에이전트들)입니다. 대부분의 정적 비상호작용 프리젠테이션 유저 에이전트도 스크립팅 지원을 필요로 하기로 선택할 것이 예상됩니다.

비상호작용이지만 동적 프리젠테이션 유저 에이전트는, 동적으로 전송되는 양식을 허용 하는등으로, 여전히 스크립트를 실행합니다. 그러나, 사용자가 문서와 상호작용 할 수 없는 경우 "focus"의 개념이 상관없기 때문에, 유저 에이전트는 포커스 관련 DOM API를 지원할 필요가 없습니다.

제안된 기본 렌더링을 지원하는 시각적 유저 에이전트들

유저 에이전트는, 상호작용이든 아니든, 이 명세에 정의된 제안된 기본 렌더링을 지원하는 것으로 (아마도 사용자 옵션으로) 지정됩니다.

이것은 필요하지 않습니다. 특히, 제안된 기본 렌더링을 구현하는 유저 에이전트도 사용자에 대한 경험을 개선하기 위해, 예를 들어 색상 대비를 바꾸거나, 다른 포커스 스타일을 사용하거나, 그렇지 않으면 사용자에게 더 접근 가능하고 사용 가능한 경험을 만들기 위해, 이 기본 값을 재정의 하는 설정을 제공하도록 권장됩니다.

제안된 기본 렌더링을 지원하는 것으로 지정된 유저 에이전트는, 그렇게 지정된 동안, §10 Rendering 섹션 내 규칙을 구현해야(must) 합니다. 그 섹션은 유저에이전트가 구현할 것으로 기대되는 행동을 정의합니다.

스크립트를 지원하지 않는 유저 에이전트들

스크립팅을 지원하지 않는(혹은 스크립트 기능이 완전히 비활성화 된) 구현은 이벤트와 이 명세에서 언급된 DOM 인터페이스 지원이 면제됩니다. 이벤트 모델의 측면이나 DOM의 측면에서 정의된 이 명세의 일부에 대해, 그런 유저 에이전트는 여전히 이벤트와 DOM이 지원된 것처럼 수행해야 합니다.

스크립팅은 어플리케이션의 필수적인 부분을 형성할 수 있습니다. 스크립팅을 지원하지 않거나 스크립트가 비활성화 된 웹 브라우저는 작성작의 의도를 완전히 전달 할 수 없을 수도 있습니다.

적합성 검사기

적합성 검사기는 이 명세에 정의된 적절한 적합성 기준을 따르는 문서를 검증해야(must) 합니다. 자동화 된 적합성 검사기는 작성자 의도의 해석을 요구하는 오류를 발견하는 것은 적용되지 않습니다. (예를 들어, blockquote 요소(element)의 콘텐트가 따옴표로 묶여있지 않다면 문서는 비적합 함에도 불구하고, 사람의 판단의 입력 없이 수행하는 적합성 검사기는 blockquote 요소(element)가 인용된 문장만을 포함함을 검사할 필요가 없습니다.)

적합성 검사기는 입력 문서가 브라우징 컨텍스트 없이 해석되는 경우 (스크립가 수행되지 않고, 해석기의 스크립팅 플래그가 비활성화 된 것을 의미) 적합한지 검사해야(must) 하고, 또한 입력 문서가 스크립트를 수행하는 브라우징 컨텍스트를 가지고 해석되는 경우 적합한지, 그리고 스크립트는 스크립트가 자신을 수행하는 동안 비적합 상태가 다른 것을 발생시키는 것을 야기하지 않음을 검사해야(should) 합니다. (이것은 불가능한 것으로 증명되었기 때문에 "SHOULD"일 뿐 "MUST" 요구사항이 아닙니다. [COMPUTABLE])

"HTML 유효성 검사기"라는 용어는 이 명세의 적절한 요구사항을 준수하는 적합성 검사기를 지칭하는데 사용될 수 있습니다.

XML DTD는 이 명세의 모든 적합성 요구사항들을 나타낼 수 없습니다. 그러므로, 검증 XML 처리기와 DTD는 적합성 검사기가 될 수 없습니다. 또한, 이 명세에 정의된 두 가지 작성 형식(format) 어느 것도 SGML 어플리케이션이 아니기 때문에 검증 SGML 시스템 역시 적합성 검사기가 될 수 없습니다.

바꿔 말하면, 3가지 유형의 적합성 기준이 있습니다:

  1. DTD에 표현될 수 있는 기준.

  2. DTD에 표현될 수 없지만, 여전히 기계(machine)에 의해 검사 될 수 있는 기준.

  3. 사람에 의해서만 검사 될 수 있는 기준.

적합성 검사기는 처음 두 가지에 대해 검사해야(must) 합니다. 간단한 DTD 기반 유효성 검사기는 첫 번째 등급의 오류에 대해서만 검사하고 그렇기 때문에 이 명세를 따르는 적합한 적합성 검사기가 아닙니다.

데이터 마이닝 도구

문서를 렌더링 하거나 적합성에 대해 검사를 하는 것 외에 다른 이유로 HTML과 XHTML 문서를 처리하는 어플리케이션과 도구들은 그들이 처리하는 문서의 의미(semantics)에 부합하게 수행해야(should) 합니다.

문서 아웃라인을 생성하지만 각 문단에 대한 중첩 레벨을 증가시키고 각 섹션에 대한 중첩 레벨을 증가시키지 않는 도구는 부적합 할 것입니다.

작성 도구와 마크업 생성기

작성 도구와 마크업 생성기는 적합한 문서를 생성해야(must) 합니다. 작성자에게 적용되는 적합성 기준은 또한 작성 도구에 적용합니다.

작성 도구는 오직 작성 도구가 아직 작성자 의도를 결정할 수 없는 정도에만, 명시된 목적에 대한 요소(element) 사용의 요구사항이 적용되지 않습니다. 하지만, 저작 도구는 자동으로 요소(element)를 오용하거나 사용자가 그렇게 하는 것을 권장해서는(must) 안됩니다.

예를 들어, 임의의 연락 정보를 위해 address 요소(element)를 사용하는 것은 비적합합니다; 그 요소(element)는 문서나 섹션의 작성자에 대한 연락 정보를 마크업 하는 용도로만 사용 가능합니다. 하지만, 작성 도구는 차이를 결정하는 것이 불가능 할 것이기 때문에, 작성 도구는 그 요구사항이 적용 되지 않습니다. 그러나 이것은 작성 도구가 임의의 이탤릭체 본문(예를 들어)을 위해 address 요소(element)를 사용할 수 있다는 것을 의미하지 않습니다; 사용자가 섹션이나 다른 무언가에 대한 연락 정보를 삽입한다면, 그것은 단지 작성 도구가 검증할 필요가 없다는 것을 의미합니다.

적합성 검사의 측면에서, 편집기는 접근성 검사기가 검증하는 동일한 범위를 준수하는 문서를 출력해야 합니다.

작성 도구가 비적합한 문서를 편집하는데 사용되는 경우, 편집 세션 동안 편집되지 않은 문서의 섹션 내의 적합성 오류를 보존할 수 있습니다.(즉, 편집 도구는 잘못된 콘텐트 왕복을 허용합니다.) 그러나, 저작 도구는 오류가 그렇게 보존된다면 출력이 준수하다고 주장해서는(must) 안됩니다.

저작 도구는 두 개의 광범위한 종류로 제공 될 것으로 예상됩니다: 구조적 혹은 의미론적 데이터에서 동작하는 도구와, What-You-See-Is-What-You-Get 매체 특정 편집 기준에서 동작하는 도구(WYSIWYG) 입니다.

소스 정보의 구조는 어떤 HTML 요소(element)와 속성(attribute)이 가장 적절한지에 관하여 선택을 하는데 사용될 수 있기 때문에, 전자는 HTML을 작성하는 도구에 대한 선호된 메커니즘입니다.

하지만, WYSIWYG 도구는 타당합니다. WYSIWYG 도구는 그것이 적절하다고 알고 있는 요소(element)들을 사용해야(should) 하고, 그것이 적절하다고 알지 못하는 요소(element)들을 사용해서는(should) 안됩니다. 이것은 어떤 극단적인 경우에 플로우 요소(flow element)의 사용을 div, b, i, span과 같은 단지 몇 가지 요소(element)로 제한하는 것과 style를 자유롭게 사용하는 것을 의미할 수 있습니다.

WYSIWYG 이든 아니든 모든 작성 도구는 사용자들이 잘 구조화 되고, 의미론적으로 풍부하며, 미디어 독립적인 콘텐트를 만드는 것이 가능하도록 최선의 노력을 기울여야(should) 합니다.

유저 에이전트는 그 외 자유로운 입력에 구현 특정(implementation-specific) 제한, 예를 들어 서비스 거부 공격을 막기 위한 제한, 또는 메모리 부족이 생기지 않도록 하기 위한 제한, 또는 플랫폼 특정 한계를 피하기 위한 제한을 부과할 수 있습니다. (이것은 지문 그림입니다.)

기존 콘텐트와 이전 명세와의 호환성을 위해, 이 명세는 두 가지 작성 형식을 설명합니다: 하나는 XML(XHTML 구문으로 언급되는) 기반, 그리고 하나는 SGML (HTML 구문으로 언급되는)에 영감을 받은 사용자 정의 형식입니다. 구현은 이 두가지 형식 중 적어도 하나를 지원해야(must) 하지만, 둘 모두를 지원하는 것이 권장됩니다.

일부 적합성 요구사항은 요소(element), 속성(attribute), 메서드(method), 객체(object)의 요구사항으로 표현됩니다. 그러한 요구사항은 두 가지 범주로 나뉩니다: 콘텐츠 모델 제약사항을 기술하는 것과 구현 동작을 기술하는 것. 전자의 범주의 것은 문서와 작성 도구의 요구사항입니다. 두 번째 범주의 것은 유저 에이전트의 요구사항입니다. 비슷하게, 일부 적합성 요구사항은 저자에 대한 요구사항으로 표현됩니다; 그러한 요구사항은 작성자가 생산한 문서에 대한 적합성 요구사항으로 해석되어야 합니다. (다시 말해, 이 명세는 저자에 대한 적합성 기준과 문서에 대한 적합성 기준을 구분하지 않습니다.)

2.2.2. 의존성

이 명세는 몇 다른 기초적인 명세에 의존합니다.

유니코드와 인코딩

유니코드 문자 집합은 텍스트 데이터를 나타내는데 사용되고, 인코딩 표준은 문자 인코딩 요구사항을 정의합니다. [UNICODE]

이 명세는 앞서 설명된 대로, 그 명세에 정의된 용어에 기초하여 전문용어를 소개합니다.

다음 용어들은 인코딩 표준에 정의된 대로 사용됩니다: [ENCODING]

  • 인코딩 가져오기

  • 출력 인코딩 가져오기

  • 바이트 스트림과 인코딩을 가져오고 문자 스트림을 반환하는 일반 디코드 알고리즘

  • 선두의 UTF-8 바이트 순서 표식(BOM)이 있다면 제거하여, 바이트 스트림을 가져오고 문자 스트림을 반환하는 UTF-8 디코드 알고리즘

  • 선두의 UTF-8 바이트 순서 표식(BOM)을 제거하지 않는 것을 제외하고 UTF-8 디코드와 동일한 BOM 없는 UTF-8 디코드 알고리즘

  • 오류를 만날 때 실패가 반환되는 BOM 없는 UTF-8 디코드와 동일한 BOM 없는 UTF-8 디코드나 실패 알고리즘

  • 문자 스트림과 인코딩을 가져오고 바이트 스트림을 반환하는 인코드 알고리즘

  • 문자 스트림을 가져오고 바이트 스트림을 반환하는 UTF-8 인코드 알고리즘

XML 그리고 관련된 명세

XHTML 구문을 지원하는 구현은 XML의 여러 버전뿐 아니라, 그 구문이 네임스페이스를 가진 XML 직렬화를 사용하기 때문에, 해당하는 네임스페이스 명세를 지원해야(must) 합니다. [XML] [XML-NAMES]

XML 네임스페이스에서 xml:space 태그 이름을 가진 속성(attribute)은 XML 명세에 의해 정의되어 있습니다. [XML]

이 명세는 또한, 스타일 시트와 XML 문서를 연관짓기 명세에 정의된, <?xml-stylesheet?> 처리 명령을 참조합니다. [XML-STYLESHEET]

이 명세는 또한 비규범적으로 XSLTProcessor 인터페이스와 그것의 transformToFragment()transformToDocument() 메서드를 언급합니다.

URLs

다음 용어들은 WHATWG URL 표준에 정의되어 있습니다: [URL]

몇 가지 스키마와 프로토콜들은 또한 이 명세에 의해 참조됩니다:

HTTP 그리고 관련된 명세

다음 용어들은 HTTP 명세에 정의되어 있습니다: [HTTP]

다음 용어들은 쿠키(Cookie) 명세에 정의되어 있습니다: [COOKIES]

다음 용어들은 웹 링크하기(Web Linking) 명세에 정의되어 있습니다: [RFC5988]

가져오기(Fetch)

다음 용어들은 WHATWG Fetch 표준에 정의되어 있습니다: [FETCH]

웹 IDL

이 명세에서 IDL 코드 조각은 웹 IDL 명세에 정의된 대로, IDL 코드 조각에 적합하도록 요구된 대로 해석되어야(must) 합니다. [WEBIDL]

다음 용어들은 Web IDL 명세에 정의되어 있습니다:

웹 IDL 명세는 또한 이 명세의 웹 IDL 코드 조각에 사용된 다음 유형들을 정의합니다:

이 명세에서 던지다(throw)라는 용어는 WebIDL 명세에 정의된 대로 사용됩니다. 다음 예외 이름들은 WebIDL에서 정의되고 이 명세에서 사용됩니다:

이 명세가 유저 에이전트가 특정 시간(특별한 값 Not-a-Number이 될 수 있는)을 나타내는 Date 객체 생성을 요구하는 경우, 그 시간의 밀리초 요소가 있다면 이는 정수로 잘라내져야(must) 하고, 새롭게 생성된 Date 객체의 시간 값은 결과적으로 잘라낸 시간을 나타내야(must) 합니다.

예를 들어, 2000년 1월 1일 01:00 UTC 이후 100만분의 23045초, 즉 2000-01-01T00:00:00.023045Z가 주어진 경우, 100만분의 45초 빠른, 2000-01-01T00:00:00.023Z를 나타내도록 생성된 Date 객체와 동일한 시간을 나타내는 Date 객체가 생성됩니다. 주어진 시간이 NaN이라면, 결과는 시간 값 NaN을 나타내는 (객체가 특정 시간을 나타내지 않는 것을 보여주는) Date 객체입니다.

자바스크립트

이 명세에 의해 설명되는 언어의 일부분은 오직 기본 스크립팅 언어로 자바스크립트를 지원합니다. [ECMA-262]

"자바스크립트"라는 용어는 공식적인 ECMAScript라는 용어보다 자바스크립트라는 용어가 좀 더 널리 알려져있기 때문에 ECMA262를 지칭하는데 사용됩니다. 비슷하게, 이 명세에서 자바스크립트를 지칭하는데 사용된 MIME 타입text/javascript이 거의 보통 사용되는 유형이기 때문에, RFC 4329에 따라 공식적으로 폐기된 유형임에도 불구하고 text/javascript입니다. [RFC4329]

다음 용어들은 자바스크립트 명세에 정의 되고 이 명세에서 사용됩니다 [ECMA-262]:

DOM

문서 객체 모델(DOM)은 문서와 그것의 콘텐트의 표현 — 모델 —입니다. DOM은 단지 API가 아닙니다; HTML 구현의 적합성 기준은 DOM에서의 작업의 관점에서 이 명세에 정의되어 있습니다. [DOM]

구현은 이 명세가 DOM과 DOM 인터페이스로의 확장으로 정의되는 몇 가지 기능의 관점에서 정의되기 때문에 DOM과 UI 이벤트에 정의된 이벤트를 지원해야(must) 합니다. [DOM] [UIEVENTS]

특히, 다음 기능들은 DOM 명세에 정의되어 있습니다: [DOM]

이 명세에서 던지다라는 용어는 DOM 명세에 정의된 대로 사용됩니다. 다음 DOMException 유형들은 DOM 명세에 정의되어 있습니다: [DOM]

예를 들어, TimeoutError 예외를 던지기 위해, 유저 에이전트는 유형이 문자열 "TimeoutError"이고(그리고 레거시 이유로, 코드가 23번인) 실제로 예외로 그 객체를 던지는 DOMException 객체를 구성할 것입니다.

다음 기능들은 UI 이벤트 명세에 정의되어 있습니다: [UIEVENTS]

다음 기능들은 터치 이벤트 명세에 정의되어 있습니다: [TOUCH-EVENTS]

이 명세는 때때로 이벤트의 type을 지칭하기 위해, "click이라고 명명된 이벤트"나 "이벤트 이름이 keypress라면"의 경우와 같이, 이름이라는 용어를 사용합니다. 이벤트에 대한 "이름"과 "타입"이라는 용어는 동의어입니다.

다음 기능들은 DOM 해석과 직렬화 명세에 정의되어 있습니다: [DOM-Parsing]

Selection 인터페이스는 선택 API 명세에 정의되어 있습니다. [SELECTION-API]

유저 에이전트는 또한 HTML 편집 API들UndoManager와 DOM 처리 명세에 설명된 기능들을 구현하도록 권장됩니다. [EDITING] [UNDO]

풀스크린 명세의 다음 부분들은, 풀스크린 API가 HTML에서 샌드박싱 기능과 상호작용하는 방법을 정의하기 위한 부분에서, 이 명세에서 참조됩니다: [FULLSCREEN]

고분해능 시간 명세는 DOMHighResTimeStamp 형식 정의와 Performance 객체의 now() 메서드를 제공합니다. [HR-TIME-2]

파일 API

이 명세는 파일 API 명세에 정의된 다음 기능들을 사용합니다: [FILEAPI]

미디어 소스 확장

다음 용어들은 미디어 소스 확장 명세에 정의되어 있습니다: [MEDIA-SOURCE]

미디어 캡쳐와 스트림

다음 용어는 미디어 캡쳐와 스트림 명세에 정의되어 있습니다: [MEDIACAPTURE-STREAMS]

XMLHttpRequest

이 명세는 두 명세가 상호 작용하는 방법을 설명하기 위해 XMLHttpRequest 명세를 참조합니다. 다음 기능들과 용어들은 XMLHttpRequest 명세에 정의되어 있습니다: [XHR]

ProgressEvent

이 명세는 두 명세가 상호작용하는 방법과 그것의 ProgressEvent 기능을 사용하는 방법을 설명하기 위해 프로그레스 이벤트(Progress Events) 명세를 참조합니다. 다음 기능은 프로그레스 이벤트 명세에 정의되어 있습니다: [PROGRESS-EVENTS]

서버 발송 이벤트(Server-Sent Events)

이 명세는 서버 발송 이벤트 명세에 명시된 EventSource를 참조합니다. [EVENTSOURCE]

미디어 쿼리(Media Queries)

구현은 미디어 쿼리 언어를 지원해야(must) 합니다. [MEDIAQ]

CSS 모듈(modules)

CSS를 전체적으로 지원하는 것은 이 명세의 구현에 필요하지 않지만(권장되기는 하지만, 웹 브라우저에 대해 최소한), 일부 기능들은 CSS 특정 요구사항의 관점에서 정의되어 있습니다.

특히, 일부 기능은 문자열이 CSS <color> 값으로 해석 되는 것을 요구합니다. CSS 값을 해석하는 경우, 유저 에이전트는 CSS 명세에 의해 일부 오류 처리 규칙이 적용되도록 요구됩니다. 이것들은 이 명세에도 적용됩니다. [CSS3COLOR] [CSS-2015]

예를 들어, 유저 에이전트는 스타일 시트의 끝을 찾자마자 모든 열려진 구성을 닫도록 요구됩니다. 따라서, 색상 값에 대한 문자열 "rgb(0,0,0" (닫는 괄호가 누락된)을 해석하는 경우, 이 오류 처리 규칙에 의해 닫는 괄호가 암묵적이 되고, 값이 얻어집니다 (색상 검정). 하지만, 비슷한 구성 "rgb(0,0,"는 (괄호와 "blue" 값이 모두 누락된) 열려진 구성을 닫는 것이 실행 가능한 값이 되지 않기 때문에 해석될 수 없습니다.

다음 용어들과 기능들은 CSS 명세에 정의되어 있습니다: [CSS-2015]

  • 뷰포트(viewport)

  • 대체 요소(element)

  • 고유 치수

명명된 색상이라는 용어는 CSS 색상 명세에 정의되어 있습니다. [CSS3COLOR]

고유 너비고유 높이라는 용어는 각각 고유 치수의 너비 치수와 높이 치수를 지칭합니다.

페인트 소스를 제공한다는 용어는 CSS 'element()' 함수와 특정 HTML 요소(element)의 상호작용을 정의하기 위해 CSS 이미지 값과 대체 콘텐트 명세에 정의된 대로 사용됩니다. [CSS3-IMAGES]

기본 객체 사이즈라는 용어 역시 CSS 이미지 값과 대체 콘텐트 명세에 정의되어 있습니다. [CSS3-IMAGES]

스크립팅을 지원하는 구현은 CSS 객체 모델을 지원해야 합니다. 다음 기능들과 용어들은 CSSOM 명세에 정의되어 있습니다: [CSSOM] [CSSOM-VIEW]

다음 기능들과 용어들은 CSS 구문 명세에 정의되어 있습니다: [CSS-SYNTAX-3]

<length> 특성은 CSS 값과 단위 명세에 정의되어 있습니다. [CSS-VALUES]

CSS 스타일링 속성(attribute)라는 용어는 CSS Style 속성(attribute) 명세에 정의되어 있습니다. [CSS-STYLE-ATTR]

CanvasRenderingContext2D 객체의 폰트 사용은 CSS 폰트폰트 로딩 명세에 설명된 기능에 따라, 특히 FontFace 객체와 폰트 소스 개념을 포함하여, 달라집니다. [CSS-FONTS-3] [CSS-FONT-LOADING-3]

다음 인터페이스는 외형 인터페이스 모듈(Geometry Interfaces Module) 명세에 정의되어 있습니다: [GEOMETRY-1]

SVG

CanvasRenderingContext2D 객체의 폰트 사용은 CSS 폰트폰트 로딩 명세에 설명된 기능에 따라, 특히 FontFace 객체와 폰트 소스 개념을 포함하여, 달라집니다. [CSS-FONTS-3] [CSS-FONT-LOADING-3]

다음 인터페이스는 SVG 명세에 정의되어 있습니다: [SVG11]

WebGL

다음 인터페이스는 WebGL 명세에 정의되어 있습니다: [WEBGL]

WebVTT

구현은 미디어 리소스에 대한 자막(subtitle), 캡션(caption), 챕터 제목, 메타데이터 등으로서 WebVTT를 지원할 수 있습니다. [WEBVTT]

이 명세에 사용된 다음 용어들은 WebVTT 명세에 정의되어 있습니다:

  • WebVTT 파일

  • 큐 텍스트를 사용하는 WebVTT 파일

  • 챕터 제목 텍스트를 사용하는 WebVTT 파일

  • 중첩된 큐만을 사용하는 WebVTT 파일

  • WebVTT 해석기

  • WebVTT 텍스트 트랙의 표시 갱신을 위한 규칙

  • WebVTT 큐 텍스트 해석을 위한 규칙

  • WebVTT 텍스트 트랙 큐 쓰기 방향

웹소켓 프로토콜

다음 용어들은 웹소켓 프로토콜 명세에 정의되어 있습니다: [RFC6455]

  • 웹 소켓 연결 수립

  • 웹 소켓 연결 수립됨

  • 서버 응답 검증

  • 쓰이고 있는 확장

  • 쓰이고 있는 서브프로토콜

  • 적절한 쿠키를 보내기 위한 헤더

  • 서버의 여는 핸드쉐이크(opening handshake) 동안 쿠키 설정

  • 웹소켓 메세지가 수신되었습니다

  • 웹소켓 메시지 전송

  • 웹소켓 연결 실패

  • 웹소켓 연결 종료

  • 웹소켓 닫는 핸드쉐이크(closing handshake) 시작

  • 웹소켓 닫는 핸드쉐이크(closing handshake)가 시작되었습니다

  • 웹소켓 연결이 종료되었습니다 (아마도 완전히)

  • 웹소켓 연결 종료 코드

  • 웹소켓 연결 종료 사유

  • Sec-WebSocket-Protocol 필드

ARIA

role 속성(attirbute)는 다음 역할(role)들과 같이 ARIA 명세에 정의되어 있습니다: [WAI-ARIA]

게다가, 다음 aria-* 콘텐트 속성(attribute)는 ARIA 명세에 정의되어 있습니다: [WAI-ARIA]

  • aria-checked

  • aria-describedby

  • aria-disabled

  • aria-expanded

  • aria-hidden

  • aria-invalid

  • aria-label

  • aria-level

  • aria-multiline

  • aria-multiselectable

  • aria-owns

  • aria-readonly

  • aria-required

  • aria-selected

  • aria-sort

  • aria-valuemax

  • aria-valuemin

  • aria-valuenow

콘텐트 보안 정책

다음 용어들은 콘텐트 보안 정책에 정의되어 있습니다: [CSP3]

다음 용어들은 콘텐트 보안 정책: 문서 특징에 정의되어 있습니다.

서비스 워커

다음 용어들은 서비스 워커에 정의되어 있습니다: [SERVICE-WORKERS]

  • 서비스 워커 등록 매칭

이 명세는 임의의 특정 네트워크 프로토콜, 스타일 시트 언어, 스크립팅 언어, 위 목록에 요구된 것들을 넘어선 임의의 DOM 명세의 지원을 요구하지 않습니다. 하지만, 이 명세에 설명된 언어는 스타일 언어로 CSS에, 스크립트 언어로 자바스크립트에, 네트워크 프로토콜에 HTTP에 관심을 두고 있고, 몇가지 기능들은 그 언어와 프로토콜들이 사용되고 있는 것으로 추정됩니다.

HTTP 프로토콜을 구현하는 유저 에이전트는 웹 출처 개념(Web Origin Concept) 명세와 HTTP 상태 관리 메커니즘 명세(쿠키) 역시 구현해야(must) 합니다. [HTTP] [ORIGIN] [COOKIES]

이 명세는 각각의 섹션에서 문자 인코딩, 이미지 형식, 오디오 형식, 비디오 형식에 대한 추가적인 요구사항을 가질 수 있습니다.

2.2.3. 확장성

벤더 특정 소유 유저 에이전트가 이 명세를 확장하는 것은 강력하게 지양됩니다. 문서는 사용자의 특정 유저 에이전트만이 문제의 콘텐트를 접근하는 것을 허용하여 상호 운용성을 줄이고 사용자 기반을 파편화하기 때문에 그러한 확장을 사용해서는(must) 안됩니다.

그러한 확장이 그렇더라도 필요하다면, 예를 들어 실험적인 목적으로, 벤더들은 다음 확장 메커니즘의 사용이 강력히 권장됩니다:

두 문자 x-"로 시작하는 속성(attribute)이름은 유저 에이전트가 사용하기 위해 예약 되었고 HTML 언에어 결코 공식적으로 추가되지 않을 것이 확실합니다. 유연성을 위해, 밑줄(U+005F LOW LINE 문자)을 포함하는 속성(attribute)이름 역시 실험적인 목적을 위해 예약 되었고 HTML 언어에 결코 공식적으로 추가되지 않을 것이 확실합니다.

그러한 속성(attribute)을 사용하는 페이지는 비 규범적 정의에 의합니다.

DOM 확장을 위해, 예를 들어 새로운 메서드와 IDL 속성(attribute), 새로운 멤버들은 이 명세의 미래 버전과 충돌하는 것을 방지하기 위해 벤더 특정 문자열이 앞에 붙어야(should) 합니다.

이벤트를 위해, 실험적인 이벤트 유형은 벤더 특정 문자열이 앞에 붙어야(should) 합니다.

예를 들어, 사용자가 엘레베이터에서 올라갈 때 보여주기 위한 이벤트 "Pleasold"를 호출했다면, "pleasold" 접두어를 사용할 수 있고 따라서 이벤트를 아마 "onpleasoldgoingup"라고 명명된 이벤트 핸들러가 있는 "pleasoldgoingup"로 명명합니다.

모든 확장들은 확장의 사용이 모순되거나 명세에 정의된 기능성의 비적합이 야기되지 않도록 정의되어야 합니다

예를 들어, 그렇게 하는 것이 강하게 지양되는 동안, "Foo Browser" 구현은 새로운 IDL 속성(attribute) "fooTypeTime"를 사용자가 컨트롤의 현재 값을 선택한 시간이 반환되는 컨트롤의 DOM 인터페이스에 추가할 수 있습니다(일례로). 다른 한편으로, 양식(form)의 elements 배열에 나타나는 새로운 컨트롤을 정의하는 것은 이 명세에 주어진 elements의 정의를 위반할 것이기 때문에 위 요구사항을 위반할 것입니다.

"x-vendor-feature" 형식의 콘텐트 속성에 상응하는 새로운 반영하는 IDL 속성(attribute)을 추가하는 경우, IDL 속성(attribute)은 "vendorFeature"라고 명명되어야(should) 합니다(즉, "x"는 IDL 속성(attribute)의 이름에서 빠집니다).


벤더 중립적인 확장이 이 명세에 필요한 경우, 이 명세가 그에 맞춰 업데이트 되거나, 확장 명세가 이 명세의 요구사항을 재정의하는 것이 기록될 수 있습니다. 이 명세를 그들의 액티비티에 적용하는 사람이 그러한 확장 명세의 요구사항을 인식할 것을 결정할 경우, 이 명세의 적합성 요구사항의 목적에 대해 적절한 명세가 됩니다.

누군가 임의의 적합한 바이트 스트림을 정의하는 명세를 작성하고, 이후 그들의 무작위 쓰레기가 적합하다고 주장할 수 있습니다. 하지만, 그것이 그들의 무작위 쓰레기가 실제로 모두의 목적에 대해 적합하다는 것을 의미하지 않습니다: 다른 누군가 명세가 그들의 작업에 적용하지 않는다고 결정한다면, 그들은 앞서 언급한 임의의 쓰레기가 단지 쓰레기이고 전혀 적합하지 않다고 꽤 정당하게 말할 수 있습니다. 적합성에 관한 한, 특정 커뮤니티에서 중요한 것은 그 커뮤니티가 동의하는 것이 적용된다는 것이다.

적용 가능한 명세.

문서에 대한 적합성 용어는 그러한 적용 가능한 명세에 의해 도입된 변경 사항과 문서의 콘텐트와 의도된 해석에 따라 달라집니다. 적용 가능한 명세는 새로운 문서 콘텐트(예를 들어 foobar 요소)를 정의하거나, 다른 특정 적합한 콘텐트를 금지하거나(예를 들어, <table>s의 사용을 금지), 의미(semantics), DOM 매핑, 이 명세에 정의된 콘텐트에 대한 처리 규칙을 변경할 수도 있습니다. 문서가 적합한 HTML 문서인지 아닌지는 적용 가능한 명세의 사용에 따르지 않습니다: 주어진 적합한 HTML 문서의 구문과 의미(semantics)가 적용 가능한 명세(들)의 사용에 의해 변경되지 않는다면, 그 문서는 여전히 적합한 HTML 문서 입니다. 주어진 (다른 적합한) 문서의 의미(semantics)나 처리가 적용 가능한 명세(들)의 사용에 의해 변경된다면, 그것은 적합한 HTML 문서가 아닙니다. 그러한 경우에 대해, 적용 가능한 명세는 적합성 용어를 정의해야(SHOULD) 합니다.

제안되었지만 요구된 규정이 아니기 때문에, 그러한 명세는 XXX가 적용 가능한 명세에 대한 짧은 이름 인 "적합한 HTML+XXX 문서"와 같은 적합성 용어를 정의 할 수 있습니다. (예: "적합한 HTML+AutomotiveExtensions 문서")

위에 주어진 규칙의 결과는 특정한 구문상으로 옳은 HTML 문서가 적용 가능한 명세가 있는 곳에서 적합한 HTML 문서가 아닐 수 있다는 것입니다. (예: 적용 가능한 명세는 <table>을 하나의 내용으로 정의합니다 — 그 명세에 작성되고 <table> 요소(element)를 포함하는 문서는 요소(element)가 구문적으로 옳은 HTML으로 되어 있더라도 적합한 HTML 문서가 아닙니다.)


유저 에이전트는 구문적으로 중립적인 것으로 이해할 수 없는 요소(element)와 속성(attribute)를 처리해야(must) 합니다; DOM에 그것들을 두고(DOM 처리기에 대해), CSS를 따라 스타일링 하지만 (CSS 처리기에 대해), 그것들로부터 어떠한 의미(meaning)도 끌어내지 않습니다.

기능에 대한 지원이 비활성 된 경우 (예를 들어, 보안 문제를 완화시키기 위해, 혹은 개발 지원을 위해, 혹은 성능 이유로 긴급한 조치로서), 유저 에이전트는 어떤 기능에 대해서도 지원이 없었던 것 처럼, 그리고 기능이 이 명세에 언급지 않은 것 처럼 수행해야(must) 합니다. 예를 들어, 특정 기능이 웹 IDL 인터페이스에서 속성(attribute)를 통해 접근된다면, 속성(attribute) 자체는 그 인터페이스를 구현하는 — 객체에 속성(attribute)를 두지만 null을 반환하거나 예외를 던지는(throw) 것을 불충분하게 하여 , 객체로부터 생략될 것입니다.

2.2.4. XPath와 XSLT와의 상호작용

이 명세에 설명된 방법으로(예를 들어, document.evaluate() API의 일부로) 해석되거나 생성된 HTML 문서에서 운용되는 XPath 1.0의 구현은 마치 다음 편집이 XPath 1.0 명세에 적용된 것처럼 수행해야(must) 합니다.

먼저, 이 문단을 제거합니다:

노드 테스트의 QName이 표현 맥락에서 네임스페이스 선언을 사용하여 확장된 이름으로 확장됩니다. 이것은 xmlns로 선언된 기본 네임스페이스가 사용되지 않는 것을 제외하고 시작 태그와 종료 태그의 요소 유형 이름에 대해 확장이 수행된 것과 같은 방식입니다: QName이 접두어를 가지지 않는다면, 네임스페이스 URI는 null입니다(이것은 속성 이름이 확장되는 것과 같은 방식 입니다). QName이 표현 맥락에 네임스페이스 선언이 없는 접두어를 가진다면 이것은 오류입니다.

그 후, 다음을 그 자리에 삽입합니다:

노드 테스트의 QName이 표현 맥락에서 네임스페이스 선언을 사용하여 확장된 이름으로 확장됩니다. QName이 접두어를 가진다면, 표현 맥락에 이 접두어에 대한 네임스페이스 선언이 존해해야(must) 하고, 해당하는 네임스페이스 URI는 이 접두어와 연관된 것이어야(must) 합니다. QName이 표현 맥락에 네임스페이스 선언이 없는 접두어를 가진다면 이것은 오류입니다.

QName이 접두어를 가지지 않고 주축의 주요 노드 타입이 요소(element)라면, 기본 요소(element) 네임스페이스가 사용됩니다. 그렇지 않고 QName이 접두어를 가지지 않는다면, 네임스페이스 URI는 null 입니다. 기본 요소(element) 네임스페이스는 XPath 표현에 대한 맥락의 멤버입니다. XPath 표현을 DOM3 XPath API를 통해 실행할 때 기본 요소(element) 네임스페이스의 값은 다음 방법으로 결정됩니다:

  1. 컨텍스트 노드가 HTML DOM으로부터라면, 기본 요소(element) 네임스페이스는 "https://www.w3.org/1999/xhtml" 입니다.

  2. 그렇지 않으면, 기본 요소(element) 네임스페이스 URI는 null입니다.

이것은 XPath 2.0의 기본 요소(element) 네임스페이스 기능을 XPath 1.0에 추가하는 것과, HTML 문서에 대한 기본 요소(element) 네임스페이스로서 HTML 네임스페이스를 사용하는 것과 동일합니다. 그것은 이 명세가 HTML 요소(element)에 대해 사용된 네임스페이스에 대하여 HTML에 도입하는 변경사항을 여전히 지원하는 동안 구현이 레거시 HTML 콘텐트와 호환되도록 하고자 하는 바람과, XPath 2.0보다 XPath 1.0을 사용하고자 하는 바람에 기인합니다.

이 변경은 Xpath 1.0 명세의 고의적 위반으로, 구현이 HTML 요소(element)에 대해 사용되는 네임스페이스에 대해 이 명세가 HTML에 도입하는 변경 사항을 여전히 지원하면서 레거시 콘텐트와 호환되도록 하고자 하는 바람에 기인합니다. [XPATH]


출력 메서드가 "html"인 경우 DOM으로 출력하는 XSLT 1.0 처리기는 (명시적으로 혹은 XSLT 1.0 기본 규칙을 통해) 다음과 같이 영향을 받습니다:

변환 프로그램이 네임스페이스 없이 요소(element)를 출력한다면, 처리기는, 해당 DOM 요소(element) 노드를 구성하기에 앞서, 요소(element)의 네임스페이스를 HTML 네임스페이스, 요소(element)의 ASCII-소문자 로컬 이름, 요소(element)에 네임스페이스 없는 속성(attribute)들의 ASCII-소문자 이름으로 변경해야(must) 합니다.

이; 요구사항은 XSLT 1.0 명세의 고의적 위반으로, 이 명세가 DOM 기반 XML 변경과 호환되지 않는 방법으로 네임스페이스와 대소문자를 구별하는 HTML의 규칙을 변경하기 때문입니다.(출력을 직렬화하는 처리기는 영향을 받지 않습니다.) [XSLT]


이 명세는 XSLT 처리가가 HTML 해석기 인프라와 상호작용 하는 방법을 정확하게 명시하지 않습니다(예를 들어, XSLT 처리기가 열린 요소(element) 스택에 임의의 요소(element)를 밀어 넣는 것처럼 수행하는지 여부). 하지만, XSLT 처리기는 그것이 성공적으로 완료되면 해석을 중지해야(must)하고, 현재 문서 준비상태를 먼저 "interactive"로 설정해야(must)하고 그 후 그것이 취소되면 "complete"로 설정해야(must)합니다.


이 명세는 XSLT가 탐색 알고리즘과 상호작용하는 방법, 이벤트 반복과 맞추는 방법, 오류 페이지가 처리되는 방법(예를 들어, XSLT 오류가 누적된 XSLT 출력을 대체하는 것인지 또는 인라인으로 렌더링 되는지 등)을 지정하지 않습니다.

script 요소(element) 섹션에 XSLT와 HTML의 상호작용, 그리고 template 요소(element) 섹션에 XSLT, XPath, HTML의 상호작용에 관한 추가적인 비규범적인 사족이 있습니다.

2.3. 대소문자 구별과 문자열 비교

대소문자 구분 방법으로 두 문자열을 비교하는 것은 코드 지점에 대해 코드 지점을 정확하게 비교한다는 것을 의미합니다.

ASCII 대소문자 비구분 방법으로 두 문자열을 비교하는 것은 U+0041에서 U+005A까지 범위의 문자(즉, 라틴 대문자 A부터 라틴 대문자 Z까지)와 U+0061에서 U+007A까지 범위에 해당하는 문자(즉, 라틴 소문자 A부터 라틴 소문자 Z까지)들이 모두 일치하는 것으로 간주되는 것을 제외하고, 코드 지점에 대해 코드 지점을 정확하게 비교한다는 것을 의미합니다.

호환되는 대소문자 무(無)구분 방법으로 두 문자열을 비교하는 것은 언어별 맞춤없이 두 문자열을 비교하기 위해 유니코드 호환되는 대소문자 무(無)구분 일치 연산을 사용하는 것을 의미합니다. [UNICODE]

달리 명시되지 않는 한, 문자열 비교는 대소문자 구분방법으로 수행되어야(must) 합니다.

문자열을 ASCII 대문자로 변환하는 것은 U+0061에서 U+007A 범위 (즉, 라틴 소문자 A부터 라틴 소문자 Z) 내 모든 문자를 U+0041에서 U+005A 범위 (즉, 라틴 대문자 A부터 라틴 대문자 Z) 내 해당하는 문자로 바꾸는 것을 의미합니다.

문자열을 ASCII 소문자로 변환하는 것은 U+0041에서 U+005A 범위 (즉, 라틴 대문자 A부터 라틴 대문자 Z) 내 모든 문자를 U+0061에서 U+007A 범위 (즉, 라틴 소문자 A부터 라틴 소문자 Z) 내 해당하는 문자로 바꾸는 것을 의미합니다.

문자열 patterns보다 길지 않고 spattern의 길이로 잘라내는 것이 두 문자열을 서로 일치하게 하는 경우 문자열 pattern은 문자열 s에 대한 접두어 일치입니다.

2.4. 공통 마이크로문법

HTML에는 날짜나 숫자 같은, 특정한 데이터 유형을 허용하는 다양한 위치가 있습니다. 이 섹션은 그러한 형식의 콘텐트에 대한 적합성 기준과 그것들을 해석하는 방법을 기술합니다.

구현자는 아래에 설명된 문법의 해석을 구현하기 위해 사용하는 것으로 간주될 수 있는 서드파티 라이브러리들을 주의 깊게 검토하도록 강력하게 권장됩니다. 예를 들어, 날짜 라이브러리는, 오류 처리 동작이 종종 이 명세에 사용된 것과 유사항 날짜 구문을 기술하는 명세에 정의 되어 있지 않기 때문에, 이 명세에 요구된 것과 다른 오류 처리 동작을 구현할 수 있고, 따라서 구현자는 오류를 처리하는 방법에서 크게 달라지는 경향이 있습니다.

2.4.1. 공통 해석기 표현

공백 문자는 이 명세의 목적에 따라, U+0020 공백(space), U+0009 탭 문자(tab), U+000A 라인피드 (LF), U+000C 서식 문자 (FF), and U+000D 캐리지 리턴 (CR)입니다.

여백 문자는 유니코드 PropList.txt 데이터 파일에 있는 유니코드 속성(property) "White_Space"을 가지는 문자 입니다. [UNICODE]

이 문자는 Unicode.txt 데이터 파일에 "Bidi_Class" 속성(property)의 "White_Space" 값 (약칭 "WS")과 혼동되지 않아야(should) 합니다.

제어 문자는 유니코드 "General_Category" 속성(property)이 유니코드 유니코드 UnicodeData.txt 데이터 파일의 "Cc" 값을 가지는 문자입니다. [UNICODE]

대문자 ASCII 글자는 U+0041 라틴 대문자 A부터 U+005A 라틴 대문자 Z까지 범위 내 문자입니다.

소문자 ASCII 글자는 U+0061 라틴 소문자 A부터 U+007A 라틴 소문자 Z까지 범위 내 문자입니다.

ASCII 숫자는 U+0030 숫자 0에서 U+0039 숫자 9까지 범위 내 문자입니다.

영숫자 ASCII 문자대문자 ASCII 글자, 또는 소문자 ASCII 글자, 또는 ASCII 숫자입니다.

ASCII 16진수는 U+0030 숫자 0부터 U+0039 숫자9, U+0041 라틴 대문자 A부터 U+0046 라틴 대문자 F, U+0061 라틴 소문자 A부터 U+0066 라틴 소문자 F 범위 내 문자입니다.

대문자 ASCII 16 진수는 U+0030 숫자 0부터 U+0039 숫자 9 그리고 U+0041 라틴 대문자 A부터 U+0046 라틴 대문자 F까지 범위 내 문자입니다.

소문자 ASCII 16 진수는 U+0030 숫자 0부터 U+0039 숫자 9 그리고 U+0061 라틴 소문자 A부터 U+0066 라틴 소문자 F까지 범위 내 문자입니다.

아래 설명된 일부 마이크로 해석기는 문자열이 해석되고 있도록 유지하고 있는 input 변수와 input에서 해석하기 위한 다음 문자를 가리키는 position 변수를 가지는 패턴을 따릅니다.

이 패턴을 기반으로하는 해석기의 경우, 유저 에이전트가 일련의 문자를 수집하도록 요구하는 단계는, 수집될 수 있는 문자의 집합이 되는 characters를 가지고, 다음 알고리즘을 수행해야(must) 함을 의미합니다:

  1. inputposition를 이 단계들을 호출하는 알고리즘에 동일한 이름의 것들로서 같은 변수가 되도록 합니다.

  2. result를 빈 문자열이 되게 합니다.

  3. positioninput의 끝을 지나치지 않고 position에 위치한 문자가 characters의 하나인 경우, result의 끝에 문자를 추가하고 input 내 다음 문자로 position을 전진시킵니다.

  4. result를 반환합니다.

여백 문자 건너뛰기 단계는 유저 에이전트가 공백 문자일련의 문자를 수집해야(must) 한다는 것을 의미합니다. 수집 된 문자는 사용되지 않습니다.

유저 에이전트가 문자열에서 줄 바꿈을 비워낼 경우, 유저 에이전트는 그 문자열에서 U+000A 라인피드 (LF)와 U+000D 캐리지 리턴 (CR)을 제거해야(must) 합니다.

유저 에이전트가 문자열에서 앞뒤 여백 문자를 비워낼 경우, 유저 에이전트는 문자의 시작과 끝에 있는 모든 공백 문자를 제거해야(must) 합니다.

유저 에이전트가 문자열 내 여백 문자를 들어내고 병합하는 경우, 그 문자열 내 일련의 하나 이상의 연속적인 공백 문자를 단일 U+0020 공백 문자로 바꾸고, 그 후 그 문자열에서 앞뒤 여백 문자를 비워내야(must) 합니다.

유저 에이전트가 특정 구분 문자 delimiter문자열을 엄격하게 분할해야 하는 경우, 다음 알고리즘을 사용해야(must)합니다:

  1. input을 해석되는 문자열로 둡니다.

  2. position을 초기에 문자열의 시작을 가리키는, input에 대한 포인터로 둡니다.

  3. tokens를 초기에 비어있는, 정렬된 토큰의 목록으로 둡니다.

  4. positioninput의 끝을 지나치지 않은 동안:

    1. delimiter 문자가 아닌 일련의 문자들을 수집합니다.

    2. 이전 단계에서 수집된 문자를 tokens에 추가합니다.

    3. input 내 다음 문자로 position을 전진시킵니다.

  5. tokens을 반환합니다.

공백쉼표 문자로 분할하는 특수한 경우에 대해, 이 알고리즘은 적용되지 않습니다(그러한 알고리즘은 여백 트리밍 역시 수행합니다).

2.4.2. 불리언 속성(attribute)

여러 속성(attribute)들이 불리언 속성(attribute)입니다. 요소(element)에 불리언 속성(attribute)의 존재는 true 값을 나타내고, 속성(attribute)의 부재는 false 값을 나타냅니다.

속성(attribute)이 존재한다면, 그 값은 빈 문자열 혹은 속성(attribute)의 정식 이름에 대해, 앞 뒤 여백 없이 ASCII 대소문자 구분 없이 일치하는 값이어야(must) 합니다.

"true"와 "false" 값은 불리언 속성(attribute)에 허용되지 않습니다. false 값을 나타내려면 속성을 모두 생략해야(has to) 합니다.

여기 checked와 disabled인 checkbox의 예가 있습니다. checkeddisabled 속성(attribute)은 불리언 속성(attribute)입니다.
<label><input type=checkbox checked name=cheese disabled> Cheese</label>

이것은 이렇게 동동하게 작성될 수 있습니다:

<label><input type=checkbox checked=checked name=cheese disabled=disabled> Cheese</label>

또한 혼합 방식도 가능합니다; 다음은 여전히 동등합니다:

<label><input type='checkbox' checked name=cheese disabled=""> Cheese</label>

2.4.3. 키워드와 열거 속성(attribute)

일부 속성(attribute)은 키워드의 집합에서 하나를 취하는 것으로 정의됩니다. 그러한 속성(attribute)을 열거 속성이라고 부릅니다. 키워드는 각각 특정 상태에 매핑시키기 위해 정의됩니다 (몇몇 키워드는 동일한 상태로 매핑될 수 있고, 이 경우 일부 키워드는 서로의 유의어 입니다; 추가적으로, 일부 키워드는 부적합하다 불릴 수 있고, 전통적인 이유로 이 명세에만 존재합니다.) 게다가, 두 기본 상태가 주어질 수 있습니다. 첫 번째는 유효하지 않은 기본 값, 두 번째는 누락 기본 값입니다.

열거 속성이 명시된다면, 속성의 값은 앞뒤 여백 없이, 부적합하다 불리지 않는 주어진 키워드 중 하나에 ASCII 대소문자 구분 없이 일치 되어야(must) 합니다.

속성이 명시되는 경우, 그 값이 주어진 키워드 중 하나에 ASCII 대소문자 구분 없이 일치한다면 그 키워드의 상태는 속성(attribute)이 나타내는 상태입니다. 속성(attribute) 값이 주어진 키워드 중 일치하는 것이 없고 속성이 유효하지 않은 기본 값을 가진다면, 속성(attribute)은 그 상태를 나타냅니다. 그렇지 않고, 속성(attribute) 값이 키워드에 일치하는 것이 없고 정의된 누락 기본 값 상태가 있다면, 그것은 속성(attribute)에 의해 나타내어지는 상태 입니다. 그렇지 않으면, 기본 값은 없고, 유효하지 않은 값은 어떤 상태도 나타내지 않음을 의미합니다.

속성(attribute)이 명시되지 않은 경우, 정의된 누락 기본 값 상태가 있다면, 그것은 (누락된) 속성(attribute)에 의해 나타내어지는 상태입니다. 그렇지 않으면, 속성(attribute)의 부재는 나타내어지는 상태가 없음을 의미합니다.

빈 문자열은 유효한 키워드가 될 수 있습니다.

2.4.4. 숫자

2.4.4.1. 부호있는 정수

문자열이 하나 이상의 ASCII 숫자로 구성되고, 선택적으로 U+002D HYPHEN-MINUS 문자 (-)가 접두어로 붙는다면, 유효한 정수입니다.

U+002D HYPHEN-MINUS (-) 접두어가 없는 유효한 정수는 그 숫자의 문자열에 의한 10진수 숫자를 나타냅니다. U+002D HYPHEN-MINUS (-) 접두어가 있는 유효한 정수는 0에서 뺀, U+002D HYPHEN-MINUS 다음에 있는 숫자의 문자열에 의한 10진수 숫자를 나타냅니다.

정수 해석에 대한 규칙은 다음 알고리즘에 주어진 것과 같습니다. 이 알고리즘이 호출 될 때, 단계는 값을 반환하는 첫 번째 단계에서 중단하여, 주어진 순서에 따라야(must) 합니다. 이 알고리즘은 정수나 오류를 반환할 것입니다.

  1. input을 해석되는 문자열로 둡니다.

  2. position을 초기에 문자열의 시작을 가리키게 하여, input을 가리키게 합니다.

  3. sign이 "양" 값을 가지게 합니다.

  4. 여백을 건너뜁니다.

  5. positioninput의 끝을 지났다면, 오류를 반환합니다.

  6. position에 의해 가리켜진 문자(첫번째 문자)가 U+002D HYPHEN-MINUS 문자 (-)라면:

    1. sign을 "음"으로 둡니다.

    2. position을 다음 문자로 전진시킵니다.

    3. positioninput의 끝을 지났다면, 오류를 반환합니다.

    그렇지 않고, position에 의해 가리켜진 문자(첫번째 문자)가 U+002B PLUS 부호 문자 (+) 라면:

    1. position을 다음 문자로 전진시킵니다. ("+"는 무시되지만, 이는 부적합 합니다.)

    2. positioninput의 끝을 지났다면, 오류를 반환합니다.

  7. position에 의해 가리켜진 문자가 ASCII 숫자가 아니라면, 오류를 반환합니다.

  8. ASCII 숫자일련의 문자를 수집하고, 10진수 정수로 결과로 나온 시퀀스를 해석합니다. value를 그 정수로 둡니다.

  9. sign이 "양"이라면, value를 반환하고, 그렇지 않으면 0에서 value를 뺀 결과를 반환합니다.

2.4.4.2. 음이 아닌 정수

문자열이 하나 이상의 ASCII 숫자로 구성된다면 유효한 음이 아닌 정수입니다.

유효한 음이 아닌 정수는 그 숫자의 문자열에 의해 10 진수로 나타내어지는 숫자를 나타냅니다.

음이 아닌 정수 해석에 대한 규칙은 다음 알고리즘에 주어진 것과 같습니다. 이 알고리즘이 호출될 때, 단계는 값을 반환하는 첫 번째 단계에서 중단하여, 주어진 순서에 따라야(must) 합니다. 이 알고리즘은 0이나 양의 정수, 혹은 오류를 반환할 것입니다.

  1. input을 해석된 문자열로 둡니다.

  2. value정수 해석에 대한 규칙을 사용하여 input을 해석한 결과로 둡니다.

  3. value가 오류라면, 오류를 반환합니다.

  4. value가 0보다 작다면, 오류를 반환합니다.

  5. value를 반환합니다.

2.4.4.3. 부동 소수점 수

문자열이 다음으로 구성된다면 유효한 부동소수점 수입니다:

  1. 선택적으로, U+002D HYPHEN-MINUS 문자 (-).

  2. 주어진 순서에 따라, 다음 중 하나 혹은 모두:

    1. 일련의 하나 이상의 ASCII 숫자.

    2. 주어진 순서에 따라 다음 둘 모두:

      1. 단일 U+002E 마침표 문자 (.).

      2. 일련의 하나 이상의 ASCII 숫자.

  3. 선택적으로:

    1. U+0065 라틴 소문자 E (e) 또는 U+0045 라틴 대문자 E (E).

    2. 선택적으로, U+002D HYPHEN-MINUS 문자 (-) 또는 U+002B PLUS 부호 문자 (+).

    3. 일련의 하나 이상의 ASCII 숫자.

유효한 부동소수점 수는 유효숫자에 10의 지수의 거듭 제곱과 곱하여 얻어진 숫자를 나타내고, 여기서 유효숫자는 10진수로 해석되는 (소수점과 소수점 이후 숫자가 있다면 이를 포함하여, 그리고 전체 숫자가 U+002D HYPHEN-MINUS 문자 (-)로 시작하고 숫자가 0이 아니라면 음수로서 유효숫자를 해석하여) 첫번째 숫자이고, 지수는 E 이후 숫자가 있다면 그 숫자 (E와 숫자 사이에 U+002D HYPHEN-MINUS (-) 문자가 있고 숫자가 0이 아니라면 음수로 해석되거나, E와 숫자 사이에 U+002B PLUS 부호 문자가 있다면 이를 무시하여)입니다. E가 없다면 지수는 0으로 간주됩니다.

Infinity와 Not-a-Number (NaN) 값은 유효한 부동소수점 수가 아닙니다.

부동 소수점 수로서 숫자 n의 가장 잘 표현된 표현은 ToString(n)을 수행하여 얻어진 문자열입니다. 추상 연산 ToString은 고유하게 결정되지 않습니다. 특정 값에 대해 ToString에서 얻어질 수 있는 가능한 여러 문자열이 있는 경우, 유저 에이전트는 항상 그 값에 대한 동일한 문자열을(다른 유저 에이전트에 의해 사용될 수 있는 값과 다를 수 있지만) 반환해야(must) 합니다.

부동 소수점 수 값 해석에 대한 규칙은 다음 알고리즘에 주어진 것과 같습니다. 이 알고리즘은 무언가를 반환하는 첫 번째 단계에서 중단되어야(must) 합니다. 이 알고리즘은 숫자나 오류를 반환할 것입니다.

  1. input을 해석되는 문자열로 둡니다.

  2. position을 초기에 문자열의 시작을 가리키는, input에 대한 포인터로 둡니다.

  3. value가 값 1을 가지게 합니다.

  4. divisor가 값 1을 가지게 합니다.

  5. exponent가 값 1을 가지게 합니다.

  6. 여백을 건너뜁니다.

  7. positioninput의 끝을 지났다면, 오류를 반환합니다.

  8. position에 의해 가리켜진 문자가 U+002D HYPHEN-MINUS 문자 (-) 라면:

    1. valuedivisor를 -1로 변경합니다.

    2. position을 다음 문자로 전진시킵니다.

    3. positioninput의 끝을 지났다면, 오류를 반환합니다.

    그렇지 않고, position에 의해 가리켜진 문자(첫 번째 문자)가 U+002B PLUS 부호 문자 (+) 라면:

    1. position을 다음 문자로 전진시킵니다. ("+"는 무시되지만, 이는 부적합 한 것입니다.)

    2. positioninput의 끝을 지났다면, 오류를 반환합니다.

  9. position에 의해 가리켜진 문자가 U+002E 마침표 문자 (.)이고, 그 문자가 input의 마지막 문자가 아니며, position에 의해 가리켜진 문자 이후 문자가 ASCII 숫자라면, value를 0으로 설정하고 분수로 라벨링 된 단계로 건너뜁니다.

  10. position에 의해 가리켜진 문자가 ASCII 숫자가 아니라면, 오류를 반환합니다.

  11. ASCII 숫자일련의 문자를 수집하고, 10 진수 정수로 결과로 나온 시퀀스를 해석합니다. 그 정수에 value를 곱합니다.

  12. positioninput의 끝을 지났다면, 변환으로 라벨링 된 단계로 건너뜁니다.

  13. 분수 : position에 의해 가리켜진 문자가 U+002E 마침표 문자 (.) 라면, 이 하위 단계들을 수행합니다:

    1. position을 다음 문자로 전진시킵니다.

    2. positioninput의 끝을 지났거나, position에 의해 가리켜진 문자가 ASCII 숫자, 혹은 U+0065 라틴 소문자 E (e), 혹은 U+0045 라틴 대문자 E (E)가 아니라면, 변환으로 라벨링 된 단계로 건너뜁니다.

    3. position에 의해 가리켜진 문자가 U+0065 라틴 소문자 E (e) 또는 U+0045 라틴 대문자 E (E)라면, 이 하위 단계들의 나머지를 건너뜁니다.

    4. 분수 반복: divisor에 10을 곱합니다.

    5. position에 의해 가리켜진 문자의 값을 10진수 숫자 (0..9)로 해석하고 divisor로 나누어진 값을 value에 추가합니다.

    6. position을 다음 문자로 전진시킵니다.

    7. positioninput의 끝을 지났다면, 변환으로 라벨링 된 단계로 건너뜁니다.

    8. position에 의해 가리켜진 문자가 ASCII 숫자라면, 이 하위 단계 내의 분수 반복으로 라벨링 된 단계로 건너뜁니다.

  14. position에 의해 가리켜진 문자가 U+0065 라틴 소문자 E (e) 혹은 U+0045 라틴 대문자 E (E)라면, 이 하위 단계들을 수행합니다:

    1. position을 다음 문자로 전진시킵니다.

    2. positioninput의 끝을 지났다면, 변환으로 라벨링 된 단계로 건너뜁니다.

    3. position에 의해 가리켜진 문자가 U+002D HYPHEN-MINUS 문자 (-)라면:

      1. exponent를 -1로 바꿉니다.

      2. position을 다음 문자로 전진시킵니다.

      3. positioninput의 끝을 지났다면, 변환으로 라벨링 된 단계로 건너뜁니다.

      그렇지 않고, position에 의해 가리켜진 문자가 U+002B PLUS 부호 문자(+) 라면:

      1. position을 다음 문자로 전진시킵니다.

      2. positioninput의 끝을 지났다면, 변환으로 라벨링 된 단계로 건너뜁니다.

    4. position에 의해 가리켜진 문자가 ASCII 숫자가 아니라면, 변환으로 라벨링 된 단계로 건너뜁니다.

    5. ASCII 숫자일련의 문자를 수집하고, and interpret the 10 진수 정수로 결과로 나온 시퀀스를 해석합니다. 그 정수에 exponent를 곱합니다.

    6. 10의 exponent제곱에 value를 곱합니다.

  15. 변환: S를 0을 제외한 64 비트 배정도 부동 소수점 값이고, 두 특별한 값 21024과 -21024를 포함한 IEEE 754의 집합으로 둡니다.

  16. rounded-value를, 두 개의 동일하게 가까운 값이 있다면 짝수 유효숫자를 선택하여, value에 가장 가까운 S 내의 숫자로 둡니다. (이 목적에 대해 두 개의 특별한 값 21024과 -21024는 짝수 값을 가지는 것으로 간주됩니다.)

  17. rounded-value가 21024나 -21024라면, 오류를 반환합니다.

  18. rounded-value를 반환합니다.

2.4.4.4. 백분율과 길이

치수 값 해석에 대한 규칙은 다음 알고리즘에 주어진 것과 같습니다. 이 알고리즘이 호출 될 때, 단계는 값을 반환하는 첫 번째 단계에서 중단하여, 주어진 순서에 따라야(must) 합니다. 이 알고리즘은 0.0 이상의 숫자나 오류를 반환할 것입니다. 수가 반환된다면, 백분율이나 길이와 같이 좀 더 세분화 됩니다.

  1. input을 해석되는 문자열로 둡니다.

  2. position을 초기에 문자열의 시작을 가리키는, input에 대한 포인터로 둡니다.

  3. 여백을 건너뜁니다.

  4. positioninput의 끝을 지났다면, 오류를 반환합니다.

  5. position에 의해 가리켜진 문자가 U+002B PLUS 부호 문자 (+)라면, position을 다음 문자로 전진시킵니다.

  6. positioninput의 끝을 지났다면, 오류를 반환합니다.

  7. position에 의해 가리켜진 문자가 ASCII 숫자가 아니라면, 오류를 반환합니다.

  8. ASCII 숫자일련의 문자를 수집하고, 10 진수 정수로 결과로 나온 시퀀스를 해석합니다. value를 그 수로 둡니다.

  9. positioninput의 끝을 지났다면, 길이로서 value를 반환합니다.

  10. position에 의해 가리켜진 문자가 U+002E 마침표 문자 (.)라면:

    1. position를 다음 문자로 전진시킵니다.

    2. positioninput의 끝을 지났거나, position에 의해 가리켜진 문자가 ASCII 숫자가 아니라면, 길이로서 value를 반환합니다.

    3. divisor가 값 1을 가지게 합니다.

    4. 분수 반복: divisor에 10을 곱합니다.

    5. position에 의해 가리켜진 문자의 값을 10진수 숫자 (0..9)로 해석하고 divisor로 나누어진 값을 value에 추가합니다.

    6. position을 다음 문자로 전진시킵니다.

    7. positioninput의 끝을 지났다면, 길이로서 value를 반환합니다.

    8. position에 의해 가리켜진 문자가 ASCII 숫자라면, 이 하위 단계 내의 분수 반복으로 라벨링 된 단계로 건너뜁니다.

  11. positioninput의 끝을 지났다면, 길이로서 value를 반환합니다.

  12. position에 의해 가리켜진 문자가 U+0025 PERCENT 부호 문자 (%)라면, 백분율로서 value를 반환합니다.

  13. 길이로서 value를 반환합니다.

2.4.4.5. 0이 아닌 백분율과 길이

0이 아닌 치수 값 해석에 대한 규칙은 다음 알고리즘에 주어진 것과 같습니다. 이 알고리즘이 호출 될 때, 단계는 값을 반환하는 첫 번째 단계에서 중단하여, 주어진 순서에 따라야(must) 합니다. 이 알고리즘은 0.0 이상의 숫자나 오류를 반환할 것입니다. 수가 반환된다면, 백분율이나 길이와 같이 좀 더 세분화 됩니다.

  1. input을 해석되는 문자열로 둡니다.

  2. value치수 값 해석에 대한 규칙을 사용하여 input을 해석한 결과로 둡니다.

  3. value가 오류라면, 오류를 반환합니다.

  4. value가 0이라면, 오류를 반환합니다.

  5. value가 백분율이라면, value를 백분율로서 반환합니다.

  6. value를 길이로서 반환합니다.

2.4.4.6. 부동 소수점 수 목록

부동 소수점 수의 유효한 목록은 다른 문자(예를 들어 공백 문자없이), U+002C 콤마 문자로 분리된 약간의 유효한 부동 소수점 수입니다. 또한, 주어질 수 있는 부동 소수점 수의 개수 혹은 허용된 값의 범위에 제한이 있을 수 있습니다.

부동 소수점 수 목록 해석에 대한 규칙은 다음과 같습니다:

  1. input을 해석되는 문자열로 둡니다

  2. position을 초기에 문자열의 시작을 가리키는, input에 대한 포인터로 둡니다.

  3. numbers를 초기에 빈 부동 소수점 수 목록으로 둡니다. 이 목록은 이 알고리즘의 결과가 될 것입니다.

  4. 공백 문자, U+002C 콤마, U+003B 세미콜론 문자 인 일련의 문자를 수집합니다. 이것은 앞선 선행 구분자를 건너뜁니다.

  5. positioninput의 끝을 지나지 않은 경우:

    1. 공백 문자, U+002C 콤마, U+003B 세미콜론, ASCII 숫자, U+002E 마침표, U+002D HYPHEN-MINUS 문자가 아닌 일련의 문자를 수집합니다. 이것은 앞선 선행 선행 가비지를 건너뜁니다.

    2. 공백 문자, U+002C 콤마, U+003B 세미콜론 문자가 아닌 일련의 문자를 수집하고, unparsed number를 결과로 둡니다.

    3. number부동 소수점 수 값 해석에 대한 규칙을 사용하여 unparsed number를 해석한 결과로 둡니다.

    4. number가 오류라면, number을 0으로 설정합니다.

    5. numbernumbers에 추가합니다.

    6. 공백 문자, U+002C 콤마, U+003B 세미콜론 문자 인 일련의 문자를 수집합니다. 이것은 앞선 선행 구분자를 건너뜁니다.

  6. numbers를 반환합니다.

2.4.4.7. 치수 목록

치수 목록 해석에 대한 규칙은 다음과 같습니다. 이 규칙들은 숫자와 단위로 구성된 0개 이상의 목록을 반환하고, 단위는 percentage, relative, absolute입니다.

  1. raw input을 해석될 문자열로 둡니다.

  2. raw input 내 마지막 문자가 U+002C 콤마 문자 (,) 라면, raw input에서 그 문자를 제거합니다.

  3. 콤마로 문자열 raw input를 분할합니다. raw tokens를 결과 토큰 목록으로 둡니다.

  4. result을 숫자/단위 쌍의 빈 목록으로 둡니다.

  5. raw tokens 내 각 토큰에 대해, 다음 하위 단계들을 수행합니다:

    1. input을 토큰으로 둡니다.

    2. position을 초기에 문자열의 시작을 가리키는, input에 대한 포인터로 둡니다.

    3. value를 숫자 0으로 둡니다.

    4. unitabsolute로 둡니다.

    5. positioninput의 끝을 지났다면, 단위를 relative로 설정하고 마지막 하위단계로 건너뜁니다.

    6. position에 있는 문자가 ASCII 숫자라면, ASCII 숫자일련의 문자를 수집하고, 10진수 정수로서 결과로 나온 시퀀스를 해석하고, value를 그 정수만큼 증가시킵니다.

    7. position에 있는 문자가 U+002E 마침표 문자 (.) 라면, 이 하위 단계들을 수행합니다:

      1. 공백 문자ASCII 숫자로 구성된 일련의 문자를 수집합니다. s를 결과 시퀀스로 둡니다.

      2. s 내 모든 공백 문자를 제거합니다.

      3. s가 빈 문자열이 아니라면, 이 하위 단계들을 수행합니다:

        1. lengths 내 문자(공백이 제거된 이후)의 수로 둡니다.

        2. fraction을 10 진수 정수로 s를 해석하고, 그 수를 10length로 나눈 결과로 둡니다.

        3. valuefraction 만큼 증가시킵니다.

    8. 여백을 건너뜁니다.

    9. position에 있는 문자가 U+0025 PERCENT 부호 문자 (%)라면, unitpercentage로 설정합니다.

      그렇지 않고, position에 있는 문자가 U+002A ASTERISK 문자 (*)라면, unitrelative로 설정합니다.

    10. value에 의해 주어진 수와 unit에 의해 주어진 단위로 구성된 result에 항목을 추가합니다.

  6. result 목록을 반환합니다.

2.4.5. 날짜와 시간

이 명세는 날짜에 대한 [ISO8601] 표준의 공통 부분 집합에 따라 날짜와 시간을 인코드합니다.

이는 인코드 된 날짜는 1582-03-01, 0033-03-27, 2016-03-01 와 같이 보이고, 날짜-시간은 1929-11-13T19:00Z, 0325-06-03T00:21+10:30와 같이 보이는 것을 의미합니다. 형식은, 비록 일부분은 예를 들어 생일의 월과 일, 표준 시간대 정보가 없는 시간 등과 같이 표현하기 위해 선택적이기는 하지만, 대략 YYYY-MM-DDTHH:MM:SS.DD±HH:MM 입니다.

시간은 24시간제를 사용하여 표현되고, 윤초를 표현하는 것은 오류입니다.

날짜는 역산 0000년과 9999년 사이의 역산 그레고리력으로 표현됩니다. 다른 해는 인코드될 수 없습니다.

역산 그레고리력은 1950년 이후로 전 세계적으로 가장 일반적인 달력이고, 1950년과 9999년 사이 날짜의 모든 사람들, 그리고 지난 수십 년 또는 수세기 동안 많은 사람들이 이해할 수 있습니다.

그레고리력은 교황 그레고리 13세에 의해 율리우스력에 대한 대체로서 제안된 1582년과 중국 인민 공화국에 의해 채택된 1947년 사이에, 다른 나라, 다른 시간에 공식적으로 채택되었습니다.

현재, 가까운 과거, 다음 몇 천년을 다루는, 대부분의 현실적인 목적을 위해, 이것은 문제없이 작동 할 것입니다. 그레고리력 채택 전 날짜에 대해 - 예를 들어 러시아나 터키에서 1917년에 앞선, 영국 혹은 이후 아메리카 영국 식민지에서 1752년에 앞선, 스페인, 아메리카 스페인 식민지, 세계 나머지에서 1582년에 앞선, 날짜는 그 때 쓰여진 것들과 일치하지 않을 것입니다.

그레고리력을 기본 인코딩으로 사용하는 것은 다소 임의적인 선택입니다. 많은 다른 달력이 사용 되었거나 사용되고 있고, 관심있는 독자는 웹에 대한 정보를 찾아야(should) 합니다.

(작성자를 위한) 형식에서 날짜, 시간, 숫자 형식의 논의, 폼 컨트롤의 지역화에 관한 구현 노트, time 요소(element) 또한 참고하세요.

다음 알고리즘에서, year년의 month월 내 날짜는: month가 1, 3, 5, 7, 8, 10, 12라면 31; month가 4, 6, 9, 11이라면 30; month가 2이고 year가 400으로 나누어지는 수이거나 혹은 year가 4로 나누어지지만 100으로는 나누어지지 않는 수라면 29; 그렇지 않으면 28 입니다. 이것은 그레고리력에서 윤년을 고려합니다. [GREGORIAN]

ASCII 숫자가 이 섹션에서 정의된 날짜와 시간 구문에 사용되는 경우, 그것들은 10진수 숫자로 표현됩니다.

여기에 설명된 형식은 해당하는 ISO8601의 하위 집합이 되도록 의도된 것이지만, 이 명세는 ISO8601보다 훨씬 더 자세히 해석 규칙을 정의합니다. 따라서 구현자는 아래 설명된 해석 규칙을 구현하기 위해 날짜 해석 라이브러리들을 사용하기 전에 신중하게 검토할 것이 권장됩니다; ISO8601 라이브러리는 정확히 동일한 방식으로 날짜와 시간을 해석하지 않을 수 있습니다. [ISO8601]

이 명세가 역산 그레고리력을 언급하는 경우, 그것은 거꾸로 1년까지 추론한, 현대 그레고리력을 의미합니다. 역산 그레고리력에서 날짜는, 때때로 명시적으로 역산 그레고리 날짜로 언급되는, 그 달력이 해당 시간(혹은 장소)에서 사용 중이지 않은 경우에도, 그 달력을 사용하여 설명되는 것입니다. [GREGORIAN]

2.4.5.1.

은 표준시간대 정보가 없고 연, 월을 초과하는 날짜 정보가 없는 특정한 역산 그레고리 날짜로 구성됩니다. [GREGORIAN]

문자열은 주어진 순서에 따라 다음 구성요소로 구성된다면 year년과 month월을 나타내는 유효한 월 문자열입니다.:

  1. year > 0 인 경우, year를 나타내는, 4개 이상의 ASCII 숫자

  2. U+002D HYPHEN-MINUS 문자 (-)

  3. 1 ≤ month ≤ 12 범위에서, month월을 나타내는 2개의 ASCII 숫자.

예를 들어, 2005년 2월은 2005-02로 인코드 되고, 33AD년 3월은(역산 그레고리 날짜로) 0033-03로 인코드 됩니다. 325-03 표현은 325년 3월을 의미하지 않고, 그것은 연도에 대해 4자리 숫자를 가지지 않기 때문에 오류입니다.

월 문자열을 해석하기 위한 규칙은 다음과 같습니다. 이것은 연도와 월을 반환하거나 혹은 아무 것도 반환하지 않을 것입니다. 어느 시점에 알고리즘이 "실패"라고 말한다면, 이것은 그 시점에 중단되고 아무 것도 반환하지 않음을 의미합니다.

  1. input을 해석되는 문자열로 둡니다.

  2. position을 초기에 문자열의 시작을 가리키는, input에 대한 포인터로 둡니다.

  3. yearmonth를 얻기 위해 월 컴포넌트를 해석합니다. 이것이 아무 것도 반환하지 않는다면, 실패입니다.

  4. positioninput의 끝을 지나지 않으면, 실패입니다.

  5. yearmonth를 반환합니다.

input 문자열, position이 주어진 월 컴포넌트를 해석하기 위한 규칙은 다음과 같습니다. 이것은 연도와 월을 반환하거나 아무 것도 반환하지 않을 것입니다. 어느 시점에 알고리즘이 "실패"라고 말한다면, 이것은 그 시점에 중단되고 아무 것도 반환하지 않음을 의미합니다.

  1. ASCII 숫자일련의 문자를 수집합니다. 수집된 시퀀스가 최소 4 글자가 아니라면 실패입니다. 그렇지 않으면, 10 진수 정수로 결과 시퀀스를 해석합니다. 그 숫자를 year로 둡니다.

  2. year가 0보다 큰 수가 아니면, 실패입니다.

  3. positioninput의 끝을 지났거나 position에 있는 문자가 U+002D HYPHEN-MINUS 문자가 아니라면, 실패입니다. 그렇지 않으면, position를 한 글자 앞으로 이동합니다.

  4. ASCII 숫자일련의 문자를 수집합니다. 수집된 시퀀스가 정확히 2글자가 아니라면 실패입니다. 그렇지 않으면, 10 진수 정수로 결과 시퀀스를 해석합니다. 그 숫자를 month로 둡니다.

  5. month가 1 ≤ month ≤ 12 범위의 숫자가 아니라면, 실패입니다.

  6. yearmonth를 반환합니다.

2.4.5.2. 날짜

날짜는 연, 월, 일로 구성되는 표준시간대가 없는 특정한 역산 그레고리 날짜로 구성됩니다. [GREGORIAN]

문자열은 나타내는 주어진 순서에 따라 다음 구성요소로 구성된다면, year년, month월, day일을 나타내는 유효한 날짜 문자열입니다:

  1. yearmonth를 나타내는 유효한 월 문자열

  2. U+002D HYPHEN-MINUS 문자 (-)

  3. 1 ≤ day ≤ maxday범위 내의 day를 나타내는 두 개의 ASCII 숫자로, maxdayyearmonth월의 날짜의 수.

예를 들어, 2016 2월 29일은 2016-02-29로 인코드 되고, 33AD년 3월 3일(역산 그레고리 날짜 같은)은 0033-03-03로 인코드 됩니다. 325-03-03 표현은 325년 3월 3일을 의미하지 않고, 이는 연도가 4자리 숫자를 가지지 않기 때문에 오류입니다.

날짜 문자열을 해석하기 위한 규칙은 다음과 같습니다. 이것은 날짜를 반환하거나, 아무 것도 반환하지 않을 것입니다. 어느 시점에 알고리즘이 "실패"라고 말한다면, 이것은 그 시점에 중단되고 아무 것도 반환하지 않음을 의미합니다.

  1. input을 해석되는 문자열로 둡니다.

  2. position을 초기에 문자열의 시작을 가리키는, input에 대한 포인터로 둡니다.

  3. year, month, day를 얻기 위해 날짜 컴포넌트를 해석합니다. 이것이 아무 것도 반환하지 않는다면, 실패입니다.

  4. positioninput의 끝을 지나지 않으면, 실패입니다.

  5. dateyear년, month월, day일을 가지고 날짜로 둡니다.

  6. date를 반환합니다.

input 문자열과 position가 주어진 날짜 컴포넌트를 해석하기 위한 규칙은 다음과 같습니다. 이것은 연도, 월, 일을 반환하거나 아무 것도 반환하지 않을 것입니다. 어느 시점에 알고리즘이 "실패"라고 말한다면, 이것은 그 시점에 중단되고 아무 것도 반환하지 않음을 의미합니다.

  1. yearmonth를 얻기 위해 월 컴포넌트를 해석합니다. 이것이 아무 것도 반환하지 않는다면, 실패입니다.

  2. maxdayyearmonth월의 날짜의 수로 둡니다.

  3. positioninput의 끝을 지나거나 position에 있는 문자가 U+002D HYPHEN-MINUS 문자가 아니라면, 실패입니다. 그렇지 않으면, position를 한 글자 앞으로 옮깁니다.

  4. ASCII 숫자일련의 문자를 수집합니다. 수집된 시퀀스가 정확히 두 글자가 아니라면, 실패입니다. 그렇지 않으면, 10 진수 정수로 결과 시퀀스를 해석합니다. 그 숫자를 day로 둡니다.

  5. day가 1 ≤ day ≤ maxday 내 범위의 숫자가 아니라면, 실패입니다.

  6. year, month, day를 반환합니다.

2.4.5.3. 연도 없는 날짜

연도 없는 날짜는 그레고리 월과 그 월 내의 날짜로 구성되지만, 연관된 연도는 없습니다. [GREGORIAN]

문자열이 주어진 순서에 따라 다음 컴포넌트로 구성된다면, month월과 day일을 나타내는 유효한 연도 없는 날짜 문자열입니다:

  1. 선택적으로, 두 U+002D HYPHEN-MINUS 문자 (-)

  2. 1 ≤ month ≤ 12 범위에서 month월을 나타내는 두 ASCII 숫자

  3. U+002D HYPHEN-MINUS 문자 (-)

  4. maxdaymonth월과 임의의 윤년(예를 들어, 4나 2000)의 날짜의 수인, 1 ≤ day ≤ maxday 범위에서 day를 나타내는 두 ASCII 숫자

바꿔 말하면, month이 2월을 의미하는 "02"라면, 날짜는 해가 윤년이었던 것처럼, 29가 될 수 있습니다.

예를 들어, 2월 29일은 02-29로 인코드 되고, 3월 3일은 03-03로 인코드 됩니다.

연도 없는 날짜 문자열을 해석하기 위한 규칙은 다음과 같습니다. 이것은 월과 날짜를 반환하거나 아무 것도 반환하지 않을 것입니다. 어느 시점에 알고리즘이 "실패"라고 말한다면, 이것은 그 시점에 중단되고 아무 것도 반환하지 않음을 의미합니다.

  1. input을 해석되는 문자열로 둡니다.

  2. position을 초기에 문자열의 시작을 가리키는, input에 대한 포인터로 둡니다.

  3. monthday를 얻기 위해 연도 없는 날짜 컴포넌트를 해석합니다. 이것이 아무 것도 반환하지 않는다면 실패입니다.

  4. positioninput의 끝을 지나지 않으면, 실패입니다.

  5. monthday를 반환합니다.

input 문자열과 position이 주어진 연도 없는 날짜 컴포넌트를 해석하기 위한 규칙은 다음과 같습니다. 이것은 월과 날짜를 반환하거나 아무 것도 반환하지 않을 것입니다. 어느 시점에 알고리즘이 "실패"라고 말한다면, 이것은 그 시점에 중단되고 아무 것도 반환하지 않음을 의미합니다.

  1. U+002D HYPHEN-MINUS 문자 (-)인 일련의 문자를 수집합니다. 수집된 시퀀스가 정확히 0개 혹은 두 개 글자가 아니라면, 실패입니다.

  2. ASCII 숫자일련의 문자를 수집합니다. 수집된 시퀀스가 정확히 두 글자가 아니라면, 실패입니다. 그렇지 않으면, 10 진수 정수로 결과 시퀀스를 해석합니다. 그 숫자를 month로 둡니다.

  3. month가 1 ≤ month ≤ 12 범위 내 숫자가 아니라면 실패입니다.

  4. maxday를 임의의 윤년(예를 들어, 4 또는 2000)의 month월의 날짜의 수로 둡니다.

  5. positioninput의 끝을 지나거나 position에 있는 문자가 U+002D U+002D HYPHEN-MINUS 문자가 아니라면 실패입니다. 그렇지 않으면, position를 한 글자 앞으로 이동합니다.

  6. ASCII 숫자일련의 문자를 수집합니다. 수집된 시퀀스가 정확히 두 글자가 아니라면, 실패입니다. 그렇지 않으면 10 진수 정수로 결과 시퀀스를 해석합니다. 그 숫자를 day로 둡니다.

  7. day가 1 ≤ day ≤ maxday 범위 내 숫자가 아니라면 실패입니다.

  8. monthday를 반환합니다.

2.4.5.4. 시간

time은 시, 분, 초, 소수점 초로 구성되는, 표준 시간대 정보가 없는 특정한 시간으로 구성됩니다.

문자열이 주어진 순서에 따라 다음 컴포넌트로 구성된다면, hourminutesecond를 나타내는 유효한 시간 문자열입니다:

  1. 0 ≤ hour ≤ 23 범위의 hour을 나타내는 두 ASCII 숫자

  2. U+003A 콜론 문자 (:)

  3. 0 ≤ minute ≤ 59 범위의 minute을 나타내는 두 ASCII 숫자

  4. second가 0가 아니거나, 선택적으로 second가 0이라면:

    1. U+003A 콜론 문자 (:)

    2. 0 ≤ s ≤ 59 범위의 second의 정수부를 나타내는 두 ASCII 숫자

    3. second가 정수가 아니거나, 선택적으로 second가 정수라면:

      1. 002E 마침표 문자 (.)

      2. 소수점 초 second를 나타내는 하나, 둘, 혹은 세 개의 ASCII 숫자

second 컴포넌트는 60이나 61이 될 수 없습니다; 윤초는 표현될 수 없습니다.

시간은, 선택적으로 초, 그리고 선택적으로 십진수 소수점 초를 가지고, 24시간제를 사용하여 인코드 됩니다. 따라서 7.45pm은 19:45로 인코드 됩니다. 그 시간 해석이 19:45:00 또는 7.45pm 0초를 반환 할 것이라는 것을 주목하세요. 19:45:45.456는 7.45pm 45초 이후 456 천분의 1초 입니다.

시간 문자열을 해석하기 위한 규칙은 다음과 같습니다. 이것은 시간을 반환하거나 아무 것도 반환하지 않을 것입니다. 어느 시점에 알고리즘이 "실패"라고 말한다면, 이것은 그 시점에 중단되고 아무 것도 반환하지 않음을 의미합니다.

  1. input을 해석되는 문자열로 둡니다.

  2. position을 초기에 문자열의 시작을 가리키는, input에 대한 포인터로 둡니다.

  3. hour, minute, second를 얻기 위해 시간 컴포넌트를 해석합니다. 이것이 아무 것도 반환하지 않는다면 실패입니다.

  4. positioninput의 끝을 지나지 않으면, 실패입니다.

  5. timehour 시, minute 분, second 초를 가진 시간으로 둡니다

  6. time을 반환합니다.

inputposition이 주어진 시간 컴포넌트를 해석를 해석하기 위한 규칙은 다음고 같습니다. 이것은 시, 분, 초를 반환하거나 아무 것도 반환하지 않을 것입니다. 어느 시점에 알고리즘이 "실패"라고 말한다면, 이것은 그 시점에 중단되고 아무 것도 반환하지 않음을 의미합니다.

  1. ASCII 숫자일련의 문자를 수집합니다. 수집된 시퀀스가 정확히 두 글자가 아니라면 실패입니다. 그렇지 않으면, 10진 수 정수로 결과 시퀀스를 해석합니다. 그 숫자를 hour로 둡니다.

  2. hour가 0 ≤ hour ≤ 23 범위의 숫자가 아니라면 실패입니다.

  3. positioninput의 끝을 지나거나 position에 있는 문자가 U+003A 콜론 문자가 아니라면 실패입니다. 그렇지 않으면, position를 한 글자 앞으로 이동합니다.

  4. ASCII 숫자일련의 문자를 수집합니다. 수집된 시퀀스가 정확히 두 글자가 아니라면 실패입니다. 그렇지 않으면, 10진수 정수로 결과 시퀀스를 해석합니다. 그 숫자를 minute으로 둡니다.

  5. minute이 0 ≤ minute ≤ 59 범위의 숫자가 아니라면 실패입니다.

  6. second를 "0" 값을 가진 문자열로 둡니다.

  7. positioninput의 끝을 지나지 않았고 position에 있는 문자가 U+003A 콜론 이라면, 이 하위 단계들을 수행합니다:

    1. positioninput 내 다음 문자로 전진시킵니다.

    2. positioninput의 끝 혹은 input 내 마지막 문자를 지나거나, position에서 시작하는 input 내 다음 문자가 모두 ASCII 숫자가 아니라면, 실패입니다.

    3. ASCII 숫자 혹은 U+002E 마침표 문자인 일련의 문자를 수집합니다. 수집된 시퀀스가 3개 문자거나, 3개 문자보다 길고 3번째 문자가 U+002E 마침표 문자가 아니거나, 하나보다 많은 U+002E 마침표 문자를 가진다면, 실패입니다. 그렇지 않으면, second를 수집된 문자열로 둡니다.

  8. second를 10진수(아마도 소수부를 가진) 수로 해석합니다. second를 문자열 버전 대신에 그 숫자로 둡니다.

  9. second가 0 ≤ second < 60 범위의 숫자가 아니라면, 실패입니다.

  10. hour, minute, second를 반환합니다.

2.4.5.5. 변동 날짜와 시간

변동 날짜와 시간은 연, 월, 일 그리고 시, 분, 초, 소수점 초로 , 구성되는 시간으로 구성되는 특정한 역산 그레고리 날짜로 구성되지만 표준시간대 없이 표현됩니다. [GREGORIAN]

문자열이 주어진 순서에 따라 다음 컴포넌트들로 구성된다면 날짜와 시간을 나타내는 유효한 변동 날짜와 시간 문자열입니다:

  1. 날짜를 나타내는 유효한 날짜 문자열

  2. U+0054 라틴 대문자 T (T) 혹은 U+0020 공백 문자

  3. 시간을 나타내는 유효한 시간 문자열

문자열이 주어진 순서에 따라 다음 컴포넌트로 구성된다면 날짜와 시간을 나타내는 유효한 정규화된 변동 날짜와 시간 문자열입니다:

  1. 날짜를 나타내는 유효한 날짜 문자열

  2. U+0054 라틴 대문자 T (T)

  3. 주어진 시간에 대해 가능한 가장 짧은 문자열로(예를 들어, 주어진 시간이 분 이후 0초라면 초 컴포넌트를 완전히 생략하여) 표현된 시간을 나타내는 유효한 시간 문자열

변동 날짜와 시간 문자열을 해석하기 위한 규칙은 다음과 같습니다. 이것은 날짜와 시간을 반환하거나 아무 것도 반환하지 않을 것입니다. 어느 시점에 알고리즘이 "실패"라고 말한다면, 이것은 그 시점에 중단되고 아무 것도 반환하지 않음을 의미합니다.

  1. input을 해석되는 문자열로 둡니다.

  2. position을 초기에 문자열의 시작을 가리키는, input에 대한 포인터로 둡니다.

  3. year, month, day를 얻기 위해 날짜 컴포넌트를 해석합니다. 이것이 아무 것도 반환하지 않는다면, 실패입니다.

  4. positioninput의 끝을 지났거나 position에 있는 문자가 U+0054 라틴 대문자 T (T)나 U+0020 공백 문자가 아니라면, 실패입니다. 그렇지 않으면, position를 한 글자 앞으로 이동합니다.

  5. hour, minute, second를 얻기 위해 시간 컴포넌트를 해석합니다. 이것이 아무 것도 반환하지 않는다면, 실패입니다.

  6. positioninput의 끝을 지나지 않으면, 실패입니다.

  7. dateyear년, month월, day일을 가진 날짜로 둡니다.

  8. timehour시, minute분, second초를 가진 시간으로 둡니다.

  9. datetime을 반환합니다.

2.4.5.6. 표준 시간대

표준 시간대 편차는 시간과 분의 부호 달린 숫자로 구성됩니다.

문자열이 다음으로 구성된다면, 표준 시간대 편차를 나타내는 유효한 표준 시간대 편차 문자열입니다:

이 형식은 표준 시간대 편차에 대해 -23:59에서부터 +23:59까지 허용합니다. 하지만, 실제로는, 현재 실제 표준 시간대의 편차의 범위는 -12:00에서 +14:00, 그리고 실제 표준 시간대의 편차의 분 컴포넌트는 항상 00, 또는 30, 또는 45입니다. 하지만, 이것이 영원히 지속될 것이라는 보장은 없습니다; 표준 시간대는 국가에 의해 변경되고 표준을 따르지 않습니다.

공식적인 표준 시간대의 형성에 앞선 역사적인 시간을 가진 표준 시간대 편차를 사용하는 데에 대한 자세한 내용은 아래 세계 날짜와 시간섹션의 사용법과 예제 또한 참고하세요.

표준 시간대 편차 문자열을 해석하기 위한 규칙은 다음과 같습니다. 이것은 표준 시간대 편차를 반환하거나, 아무 것도 반환하지 않을 것입니다. 어느 시점에 알고리즘이 "실패"라고 말한다면, 이것은 그 시점에 중단되고 아무 것도 반환하지 않음을 의미합니다.

  1. input을 해석되는 문자열로 둡니다.

  2. position을 초기에 문자열의 시작을 가리키는, input에 대한 포인터로 둡니다.

  3. timezonehourstimezoneminutes를 얻기 위해 표준 시간대 편차 컴포넌트를 해석합니다. 이것이 아무 것도 반환하지 않는다면, 실패입니다.

  4. positioninput의 끝을 지나지 않으면, 실패입니다.

  5. UTC로부터 timezonehours 시간 timezoneminutes 분인 표준 시간대 편차를 반환합니다.

input 문자열과 position이 주어진 표준 시간대 편차 컴포넌트를 해석하기 위한 규칙은 다음과 같습니다. 이것은 표진 시간대 시간과 표준 시간대 분을 반환하거나, 아무 것도 반환하지 않을 것입니다. 어느 시점에 알고리즘이 "실패"라고 말한다면, 이것은 그 시점에 중단되고 아무 것도 반환하지 않음을 의미합니다.

  1. position에 있는 문자가 U+005A 라틴 대문자 Z (Z)라면:

    1. timezonehours를 0으로 둡니다.

    2. timezoneminutes를 0으로 둡니다.

    3. positioninput 내 다음 문자로 전진시킵니다.

    그렇지 않고, position에 있는 문자가 U+002B PLUS 부호 (+)나 U+002D HYPHEN-MINUS (-)라면:

    1. position에 있는 문자가 U+002B PLUS 부호 (+)라면, sign를 "양"으로 둡니다. 그렇지 않고, 그것이 U+002D HYPHEN-MINUS (-)라면; sign을 "음"으로 둡니다.

    2. positioninput 내 다음 문자로 전진시킵니다.

    3. ASCII 숫자일련의 문자를 수집합니다. s를 수집된 시퀀스로 둡니다.

    4. s가 정확히 두 글자라면, 이 하위 단계들을 수행합니다:

      1. s를 10진수 정수로 해석합니다. 그 숫자를 timezonehours로 둡니다.

      2. positioninput의 끝을 지났거나, position에 있는 문자가 U+003A 콜론 문자가 아니라면 실패입니다. 그렇지 않으면, position를 한 글자 앞으로 이동합니다.

      3. ASCII 숫자일련의 문자를 수집합니다. 수집된 시퀀스가 정확히 두 글자가 아니라면 실패입니다. 그렇지 않으면, 10진 정수로 결과 시퀀스를 해석합니다. 그 수를 timezoneminutes로 둡니다.

      s가 정확히 4 글자가 아니라면, 이 하위 단계들을 수행합니다:

      1. s의 첫 번째 두 글자를 10진 정수로 해석합니다. 그 수를 timezonehours로 둡니다.

      2. s의 마지막 두 글자를 10진 정수로 해석합니다. 그 수를 timezoneminutes로 둡니다.

      그렇지 않으면 실패입니다.

    5. timezonehours가 0 ≤ timezonehours ≤ 23 범위의 숫자가 아니라면 실패입니다.

    6. sign가 "음"이라면, timezonehours를 무효화합니다.

    7. timezoneminutes가 0 ≤ timezoneminutes ≤ 59 범위의 숫자가 아니라면 실패입니다.

    8. sign이 "음"이라면, timezoneminutes를 무효화합니다.

    그렇지 않으면 실패입니다.

  2. timezonehourstimezoneminutes를 반환합니다.

2.4.5.7. 세계 날짜와 시간

세계 날짜와 시간은 시간과 분의 부호 달린 숫자로 구성되는, 표준 시간대 편차로 표현된, 연, 월, 일, 그리고 시, 분, 초, 소수점 초로 구성되는 시간으로 구성되는 특정한 역산 그레고리 날짜로 구성됩니다. [GREGORIAN]

문자열이 주어진 순서에 따라 다음 컴포넌트로 구성된다면 날짜, 시간, 표준 시간대 편차를 나타내는 유효한 세계 날짜와 시간 문자열입니다:

  1. 날짜를 나타내는 유효한 날짜 문자열

  2. U+0054 라틴 대문자 T (T) 혹은 U+0020 공백 문자

  3. 시간을 나타내는 유효한 시간 문자열

  4. 표준 시간대 편차를 나타내는 유효한 표준 시간대 편차 문자열

20 세기 중반의 UTC 형성 이전 날짜의 시간은 UTC(SI초 단위로 측정한 UT1의 근사치)가 아니라, UT1 (경도 0°에서의 현대 지구 평균 태양시)으로 표현되고 해석되어야(must)합니다. 표준 시간대의 형성 이전 시간은 적절한 현지 시간과 런던 그리니치 지역에서 관찰된 시간 사이의 차이에 가까운 명시적인 표준 시간대를 가진 UT1 시간으로 표현되고 해석되어야(must)합니다.

다음은 유효한 세계 날짜와 시간 문자열로 작성된 날짜의 몇 가지 예입니다.

"0037-12-13 00:00Z"

런던 시간 사용하는 지역에서 네로(로마 황제)의 생일의 자정. 이것이 실제로 어느 날짜에 해당하는지에 대한 자세한 설명은 아래를 참고하세요.

"1979-10-14T12:00:00.001-04:00"

일광 절약 시간제 동안 미국 동부 해안에서 사용하는 표준 시간대에서, 1979년 10월 14일 정오 이후 1밀리 초.

"8592-01-01T02:09+02:09"

8598년 1월 1일 자정 UTC. 그 시간과 관련된 표준 시간대는 현재 실제 표준 시간대가 아닌, UTC보다 2시간 9분 빠르지만, 그렇더라도 허용됩니다.

이 날짜들에 대해 몇 가지 주목할 만한 것들이 있습니다:

  • 4자리 숫자 이하의 연도는 0으로 채워져야(have to) 합니다. "37-12-13" 날짜는 유효한 날짜가 되지 않을 것입니다.

  • "T"가 공백으로 대체된다면, 이것은 하나의 공백 문자여야(must) 합니다. "2001-12-21  12:00Z" (컴포넌트 사이에 2개의 공백이 있는) 문자열은 성공적으로 해석되지 않을 것입니다.

  • 그레고리 달력의 도입에 앞선 시간의 때를 분명하게 확인하기 위해 (UTC 형성 이전 시간의 때가 분명하게 식별될 수 있는 한), 날짜는 그 때 사용되는 달력으로부터(예를 들어 율리우스력으로부터) 그레고리력으로 먼저 변환되어야(has to) 합니다. 네로의 생일 날짜는 율리우스력으로 37년 12월 15일이고, 역산 그레고리력으로는 37년 12월 13일입니다.

  • 시간과 표준 시간대 편차 컴포넌트는 선택 사항이 아닙니다.

  • 1년 이전의 날짜는 HTML의 이 버전에서 일시(datetime)로 나타낼 수 없습니다.

  • 시간은 상대적으로 최근 수십 년까지 잘 조정되거나 측정되지 않았기 때문에, 고대의 특정 사건의 시간은 잘해야 근사치입니다.

  • 표준 시간대 편차는 일광 절약 시간제에 따라 달라집니다.

지역 편차는 완전한 표준 시간대 명세가 아닙니다. 실제 날짜와 시간 값으로 작업하는 경우, 아마도 INA 시간대 ID를 사용하여, 표준 시간대에 대한 별도의 필드를 사용하는 것을 고려하세요. [TIMEZONE]

문자열이 주어진 순서에 따라 다음 컴포넌트로 구성된다면, 날짜, 시간, 표준 시간대를 나타내는 유효한 정규화 된 세계 날짜와 시간 문자열입니다:

  1. UTC 표준 시간대로 변환된 날짜를 나타내는 유효한 날짜 문자열

  2. U+0054 라틴 대문자 T (T)

  3. UTC 표준 시간대로 변환되고 주어진 시간에 대해 가능한 가장 짧은 문자열로(예를 들어, 주어진 시간이 분 이후 0초라면 초 컴포넌트를 완전히 생략하여) 표현된 시간을 나타내는 유효한 시간 문자열

  4. U+005A 라틴 대문자 Z (Z)

세계 날짜와 시간 문자열을 해석하기 위한 규칙은 다음과 같습니다. 이것은 라운드 트립 혹은 표시 목적을 위해 연관된 표준 시간대 정보를 가진 UTC 시간을 반환하거나 아무 것도 반환하지 않을 것입니다. 어느 시점에 알고리즘이 "실패"라고 말한다면, 이것은 그 시점에 중단되고 아무 것도 반환하지 않음을 의미합니다.

  1. input을 해석되는 문자열로 둡니다.

  2. position을 초기에 문자열의 시작을 가리키는, input에 대한 포인터로 둡니다.

  3. year, month, day을 얻기 위해 날짜 컴포넌트를 해석합니다. 이것이 아무 것도 반환하지 않는다면, 실패입니다.

  4. positioninput의 끝을 지나거나 position에 위치한 문자가 U+0054 라틴 대문자 T 나 U+0020 공백문자가 아니라면, 실패입니다. 그렇지 않으면, position을 한 글자 앞으로 이동합니다.

  5. hour, minute, second를 얻기 위해 시간 컴포넌트를 해석합니다. 이것이 아무 것도 반환하지 않는다면, 실패입니다.

  6. positioninput의 끝을 지났다면 실패입니다.

  7. timezonehourstimezoneminutes를 얻기 위해 표준 시간대 컴포넌트를 해석합니다. 이것이 아무 것도 반환하지 않는다면, 실패입니다.

  8. positioninput의 끝을 지나지 않으면, 실패입니다.

  9. timetimezonehours시간 timezoneminutes분을 뺀, yearmonthdayhourminutesecond초 시간의 시점으로 둡니다. 그 시간의 시점은 UTC 표준 시간대의 시점입니다.

  10. timezone을 UTC로부터 timezonehours 시간 timezoneminutes분 입니다.

  11. timetimezone를 반환합니다.

2.4.5.8. 주(weeks)

는 주-해(week-year) 수와 월요일에서 시작하여 7일 주기를 나타내는 주차 수로 구성됩니다. 아래 정의된 바와 같이, 이 달력 시스템에서의 각 주차-연도는 52 혹은 53개의 7일 주기를 가집니다. 그레고리 날짜 1969년 12월 29일 월요일((1969-12-29))에서 시작하는 7일 주기는 1970 주-해(week-year)에서의 1 주차로 정의됩니다. 연속 주차는 순차적으로 숫자가 매겨집니다. 주-해(week-year)에서의 1 주차의 이전 주는 이전 주-해(week-year)에서의 마지막 주이고, 반대도 같습니다. [GREGORIAN]

year 수를 가진 주-해(week-year)는 첫 날(1월 1일)로 목요일을 가지는 역산 그레고리력year년에 해당하거나 첫 날(1월 1일)로 수요일을 가지고 year가 400으로 나눌 수 있는 수이거나 4로 나눌 수 있지만 100으로 나눌 수 없는 수를 가지는 역산 그레고리력year년에 해당한다면 53주를 가집니다. 모든 다른 주-해(week-year)들은 52 주를 가집니다.

53주를 가진 주-해(week-year)의 마지막 날의 주차 수는 53입니다; 52주를 가진 주-해(week-year)의 마지막 날의 주차 수는 52입니다.

특정 일의 주-해(week-year) 수는 역산 그레고리력으로 그 날짜를 포함하는 해의 수와 다를 수 있습니다. y 주-해(week-year)의 첫 주는 그레고리 y년의 첫 번째 목요일을 포함하는 주입니다.

현대적인 목적을 위해, 여기 정의된 week는 ISO 8601에 정의된 대로 ISO 주와 동등합니다. [ISO8601]

문자열이 주어진 순서에 따라 다음 컴포넌트로 구성된다면 주-해(week-year) yearweek 주를 나타내는 유효한 주 문자열입니다:

  1. year > 0인, year를 나타내는 4개 이상의 ASCII 숫자

  2. U+002D HYPHEN-MINUS 문자 (-)

  3. U+0057 라틴 대문자 W (W)

  4. maxweek가 주-해(week-year) year마지막 주의 주차 수인 1 ≤ week ≤ maxweek 내 범위의 week 주를 나타내는 두 ASCII 숫자

주 문자열을 해석하기 위한 규칙은 다음과 같습니다. 이것은 주-해(week-year) 수나 주차 수를 반환하거나, 아무 것도 반환하지 않을 것 입니다. 어느 시점에 알고리즘이 "실패"라고 말한다면, 이것은 그 시점에 중단되고 아무 것도 반환하지 않음을 의미합니다.

  1. input를 해석되는 문자열로 둡니다.

  2. position을 초기에 문자열의 시작을 가리키는, input에 대한 포인터로 둡니다.

  3. ASCII 숫자일련의 문자를 수집합니다. 수집된 시퀀스가 적어도 4 글자가 아니라면 실패입니다. 그렇지 않으면, 10진수 정수로 결과 시퀀스를 해석합니다. 그 숫자를 year로 둡니다.

  4. year가 0보다 큰 수가 아니라면, 실패입니다.

  5. positioninput의 끝을 지나거나 position에 위치한 문자가 U+002D HYPHEN-MINUS 문자가 아니라면 실패입니다. 그렇지 않으면, position을 한 글자 앞으로 이동합니다.

  6. positioninput의 끝을 지나거나 position에 위치한 문자가 U+0057 라틴 대문자 W (W)라면, 실패입니다. 그렇지 않으면 position을 한 글자 앞으로 이동합니다.

  7. ASCII 숫자일련의 문자를 수집합니다. 수집된 시퀀스가 적어도 2 글자가 아니라면 실패입니다. 그렇지 않으면, 10진수 정수로 결과 시퀀스를 해석합니다. 그 숫자를 week로 둡니다.

  8. maxweekyear년의 마지막 날의 주차 수로 둡니다.

  9. week가 1 ≤ week ≤ maxweek 범위의 숫자가 아니라면, 실패입니다.

  10. positioninput의 끝을 지나지 않으면, 실패입니다.

  11. 주-해(week-year) 수 year와 주차 수week를 반환합니다.

2.4.5.9. 기간

기간은 약간의 초로 구성됩니다.

월과 초는 비교할 수 없기 때문에 (1 개월은 정확한 수의 초가 아니고, 대신 측정된 정확한 날짜에 따른 정확한 길이가 정해지는 주기입니다) 이 명세에 정의된 기간은 월(혹은 12월과 동일한 년) 을 포함할 수 없습니다. 특정한 수의 초를 기술하는 기간만이 기술 될 수 있습니다.

문자열이 다음 중 하나로 구성된다면 기간 t를 나타내는 유효한 기간 문자열입니다:

기간 문자열을 해석하기 위한 규칙은 다음과 같습니다. 이것은 기간을 반환하거나 아무 것도 반환하지 않을 것입니다. 어느 시점에 알고리즘이 "실패"라고 말한다면, 이것은 그 시점에 중단되고 아무 것도 반환하지 않음을 의미합니다.

  1. input을 해석되는 문자열로 둡니다.

  2. position을 초기에 문자열의 시작을 가리키는, input에 대한 포인터로 둡니다.

  3. months, seconds, component count을 모두 0으로 둡니다.

  4. M-disambiguatorminutes로 둡니다.

    이 플래그의 다른 값은 months입니다. 이것은 ISO8601 기간에서 월과 분에 대해 동일한 단위로 사용되는 "M" 단위를 명확하게 하기 위해 사용됩니다. 월은 허용되지 않지만, 향후 호환성을 위해 해석되고 다른 컨텍스트에서 유효할 수 있는 ISO8601 기간을 잘못 해석하는 것을 방지합니다.

  5. 여백을 건너뜁니다.

  6. positioninput의 끝을 지났다면, 실패입니다.

  7. position에 의해 가리켜진 input 내의 문자가 U+0050 라틴 대문자 P라면, position을 다음 문자로 전진시키고, M-disambiguatormonths로 설정하고, 여백을 건너뜁니다.

  8. 요구되는 반복이 끊어지거나 전체 알고리즘이 실패에 이를 때까지, 반복에서 다음 하위 단계들을 수행합니다:

    1. units를 undefined로 둡니다. 그것은 다음 값들 중 하나가 할당 될 것입니다: years, months, weeks, days, hours, minutes, seconds.

    2. next character를 undefined로 둡니다. 그것은 input로부터 문자를 가공하는데 사용됩니다.

    3. positioninput의 끝을 지났다면, 반복을 중단합니다.

    4. position에 의해 가리켜진 input 내의 문자가 U+0054 라틴 대문자 T라면, position을 다음 문자로 전진시키고, M-disambiguatorminutes으로 설정하고, 여백을 건너뛰고, 반복의 처음으로 돌아갑니다.

    5. next characterposition에 의해 가리켜진 input 내의 문자로 둡니다.

    6. next character가 U+002E 마침표 문자 (.)라면, N를 0으로 둡니다. (position를 전진시키지 않습니다. 그것은 아래에서 다루어집니다.)

      그렇지 않고, next characterASCII 숫자라면, ASCII 숫자일련의 문자를 수집하고 10진수 정수로 결과 시퀀스를 해석하고, N을 그 숫자로 둡니다.

      그렇지 않으면 next character가 숫자 부분이 아닙니다; 실패입니다.

    7. positioninput의 끝을 지났다면, 실패입니다.

    8. next characterposition에 의해 가리켜진 input 내의 문자로 설정하고, 이번에는 position을 다음 문자로 전진시킵니다. (next character가 이전에 U+002E 마침표 문자가 아니었다면, 이번에는 여전히 그 문자가 될 것입니다.)

    9. next character가 U+002E 마침표 문자 (.)라면, 이 하위 단계들을 수행합니다:

      1. ASCII 숫자일련의 문자를 수집합니다. s를 결과 시퀀스로 둡니다.

      2. s가 빈 문자열이라면 실패입니다.

      3. lengths내 문자의 개수로 둡니다.

      4. fraction을 10진수 정수로 s를 해석한 후, 그 숫자를 10length로 나눈 결과로 둡니다.

      5. Nfraction만큼 증가시킵니다.

      6. 여백을 건너뜁니다.

      7. positioninput의 끝을 지났다면, 실패입니다.

      8. next characterposition에 의해 가리켜진 input 내의 문자로 설정하고, position을 다음 문자로 전진시킵니다.

      9. next character가 U+0053 라틴 대문자 S나 U+0073 라틴 소문자 S 모두 아니라면, 실패입니다.

      10. unitsseconds로 설정합니다.

      그렇지 않으면, 이 하위 단계들을 수행합니다:

      1. next character공백 문자라면, 여백을 건너뛰고, next characterposition에 의해 가리켜진 input 내의 문자로 설정하고, position을 다음 문자로 전진시킵니다.

      2. next character가 U+0059 라틴 대문자 Y나 U+0079 라틴 소문자 Y라면, unitsyears로 설정하고 M-disambiguatormonths로 설정합니다.

        next character가 U+004D 라틴 대문자 M이거나 U+006D 라틴 소문자 M이라면, M-disambiguatormonths이고, unitsmonths로 설정합니다.

        next character가 U+0057 라틴 대문자 W이거나 U+0077 라틴 소문자 W라면, unitsweeks로 설정하고 M-disambiguatorminutes로 설정합니다.

        next character가 U+0044 라틴 대문자 D이거나 U+0064 라틴 소문자 D라면, unitsdays로 설정하고 M-disambiguatorminutes로 설정합니다.

        next character가 U+0048 라틴 대문자 H이거나 U+0068 라틴 소문자 H라면, unitshours로 설정하고 M-disambiguatorminutes로 설정합니다.

        next character가 U+004D 라틴 대문자 M이거나 U+006D 라틴 소문자 M이라면, M-disambiguatorminutes로 설정하고 unitsminutes로 설정합니다.

        next character가 U+0053 라틴 대문자 S이거나 U+0073 라틴 소문자 S라면, unitsseconds로 설정하고 M-disambiguatorminutes로 설정합니다.

        그렇지 않고 next character가 위 문자 중 어떠한 것도 아니라면, 실패입니다.

    10. component count를 증가시킵니다.

    11. multiplier를 1로 둡니다.

    12. unitsyears라면, multiplier에 12를 곱하고 unitsmonths로 설정합니다.

    13. unitsmonths라면, Nmultiplier의 곱을 months에 더합니다.

      그렇지 않으면, 이 하위 단계들을 수행합니다:

      1. unitsweeks라면, multiplier에 7을 곱하고 unitsdays로 설정합니다.

      2. unitsdays라면, multiplier에 24를 곱하고 unitshours로 설정합니다.

      3. unitshours라면, multiplier에 60을 곱하고 unitsminutes로 설정합니다.

      4. unitsminutes라면, multiplier에 60을 곱하고 unitsseconds로 설정합니다.

      5. 강제적으로, units는 이제 seconds입니다. Nmultiplier의 곱을 seconds에 더합니다.

    14. 여백을 건너뜁니다.

  9. component count가 0이라면, 실패입니다.

  10. months가 0이라면, 실패입니다.

  11. seconds 초로 구성된 기간을 반환합니다.

2.4.5.10. 시간의 모호한 때

문자열이 다음 중 하나라면 선택적인 시간을 가진 유효한 날짜 문자열입니다:


날짜나 시간 문자열을 해석하기 위한 규칙은 다음과 같습니다. 이 알고리즘은 날짜, 시간, 세계 날짜와 시간을 반환하거나, 아무 것도 반환하지 않을 것입니다. 어느 시점에 알고리즘이 "실패"라고 말한다면, 이것은 그 시점에 중단되고 아무 것도 반환하지 않음을 의미합니다.

  1. input를 해석되는 문자열로 둡니다.

  2. position을 초기에 문자열의 시작을 가리키는, input에 대한 포인터로 둡니다.

  3. start positionposition과 동일한 위치로 둡니다.

  4. date presenttime present 플래그를 true로 둡니다.

  5. year, month, day를 얻기 위해 날짜 컴포넌트를 해석합니다. 이것이 실패한다면, date present 플래그를 false로 설정합니다.

  6. date present이 true이고, positioninput의 끝을 지나지 않았고, position에 있는 문자가 U+0054 라틴 대문자 T나 U+0020 공백 문자라면, positioninput내 다음 문자로 전진시킵니다.

    그렇지 않고, date present가 true이고, positioninput의 끝을 지났거나 position에 있는 문자가 U+0054 라틴 대문자 T나 U+0020 공백 문자가 모두 아니라면, time present를 false로 둡니다.

    그렇지 않고, date present가 false라면, positionstart position과 동일한 위치로 돌립니다.

  7. time present 플래그가 true라면, hour, minute, second를 얻기 위해 시간 컴포넌트를 해석합니다. 이것이 아무 것도 반환하지 않는다면, 실패입니다.

  8. date presenttime present 플래그가 모두 true이지만, positioninput의 끝을 지났다면, 실패입니다.

  9. date presenttime present플래그가 모두 true라면, timezonehourstimezoneminutes를 얻기 위해 표준 시간대 편차 컴포넌트를 해석합니다. 이것이 아무 것도 반환하지 않는다면, 실패입니다.

  10. positioninput의 끝을 지나지 않으면, 실패입니다.

  11. date present 플래그가 true이고 time present 플래그가 false라면, dateyear년, month월, day일을 가진 날짜로 두고, date를 반환합니다.

    그렇지 않고, time present 플래그가 true이고 date present 플래그가 false라면, timehour시, minute분, second초를 가진 시간으로 두고 time을 반환합니다.

    그렇지 않으면, time을 UTC 표준 시간대 순간이 되는 시간의 순간인 timezonehours시간 timezoneminutes분을 뺀 year년, month월, day일, hour시, minute분, second초의 순간으로 둡니다; timezone을 UTC로부터 timezonehourstimezoneminutes 분으로 두고; timetimezone를 반환합니다.

2.4.6. 색상

간단한 색상은 sRGB 색상 공간에서, 각각 색상의 빨강, 초록, 파랑 컴포넌트를 나타내는 0..255 범위의 3개의 8비트 숫자로 구성됩니다. [SRGB]

문자열이 정확히 7 글자이고, 첫번째 문자가 U+0023 숫자 부호 문자 (#)이고, 나머지 여섯 글자가 모두 16진수로 첫 두 글자가 빨강 컴포넌트를 나타내고, 중간 두 글자가 초록 컴포넌트를 나타내고, 마지막 두 글자가 파랑 컴포넌트를 나타내는 ASCII 16진수라면 유효한 간단한 색상입니다.

문자열이 유효한 간단한 색상이고, U+0041 라틴 대문자 A부터 U+0046 라틴 대문자 F 범위의 문자를 사용하지 않는다면 유효한 소문자 간단한 색상입니다.

간단한 색상 값을 해석하기 위한 규칙은 다음 알고리즘에 주어진 것과 같습니다. 이 알고리즘이 호출 될 때, 값을 반환하는 첫 번째 단계에서 중단하여, 주어진 순서에 따라 단계를 따라야(must) 합니다. 이 알고리즘은 간단한 색상이나 오류를 반환할 것입니다.

  1. input을 해석되는 문자열로 둡니다.

  2. input이 정확히 7 글자가 아니라면, 오류를 반환합니다.

  3. input 내 첫 번째 문자가 U+0023 숫자 부호 문자 (#)가 아니라면, 오류를 반환합니다.

  4. input의 마지막 여섯 문자가 모두 ASCII 16진수라면, 오류를 반환합니다.

  5. result간단한 색상입니다.

  6. 두 번째와 세 번째 문자를 16진수로 해석하고 그 결과를 result의 빨강 컴포넌트로 둡니다.

  7. 네 번째와 다섯 번째 문자를 16진수로 해석하고 그 결과를 result의 초록 컴포넌트로 둡니다.

  8. 여섯 번째와 일곱 번째 문자를 16진수로 해석하고 그 결과를 result의 파랑 컴포넌트로 둡니다.

  9. result를 반환합니다.

간단한 색상이 주어지는 간단한 색상 값 직렬화를 위한 규칙은 다음 알고리즘에 주어진 것과 같습니다:

  1. result를 단일 U+0023 숫자 부호 문자 (#)로 구성되는 문자열로 둡니다.

  2. 필요하다면 0으로 채워, 소문자 ASCII 16진수를 사용하여, 빨강, 초록, 파랑 컴포넌트를 2자리 16진수 숫자로 변경하고 이 숫자들을 빨강, 초록, 파랑 순서로 result에 추가합니다.

  3. 유효한 소문자 간단한 색상이 되는 result를 반환합니다.


일부 오래된 레거시 속성은 다음 알고리즘에 주어지는 레거시 색상 값 해석을 위한 규칙을 사용하여 좀 더 복잡한 방법으로 색상을 해석합니다. 이 알고리즘이 호출 될 때, 값을 반환하는 첫 번째 단계에서 중단하여, 주어진 순서에 따라야(must) 합니다. 이 알고리즘은 간단한 색상이나 오류를 반환할 것입니다.

  1. input을 해석되는 문자열로 둡니다.

  2. input이 빈 문자열이라면, 오류를 반환합니다.

  3. input으로부터 앞뒤 여백 문자를 비워냅니다.

  4. input이 문자열 "transparent"에 ASCII 대소문자 구분 없이 일치한다면 오류를 반환합니다.

  5. input명명된 색상 중 하나에 ASCII 대소문자 구분 없이 일치한다면 그 키워드에 해당하는 간단한 색상을 반환합니다. [CSS3COLOR]

    CSS2 시스템 색상은 인정되지 않습니다.

  6. input이 4 글자이고, input의 첫 번째 문자가 U+0023 숫자 부호 문자 (#)이고, input의 마지막 세 글자가 모두 ASCII 16진수라면, 이 하위 단계들을 수행합니다:

    1. result간단한 색상으로 둡니다.

    2. input의 두 번째 문자를 16진수 숫자로 해석합니다; result의 빨강 컴포넌트를 17이 곱해진 결과로 둡니다.

    3. input의 세 번째 문자를 16진수 숫자로 해석합니다; result의 초록 컴포넌트를 17이 곱해진 결과로 둡니다.

    4. input의 네 번째 문자를 16진수 숫자로 해석합니다; result의 파랑 컴포넌트를 17이 곱해진 결과로 둡니다.

    5. result를 반환합니다.

  7. U+FFFF보다 큰 유니코드 포인트를 가지는 input의 모든 문자(즉, 기본 다국어에 없는 모든 문자)를 두 글자 문자열 "00"로 바꿉니다.

  8. input이 128개 문자보다 길다면, 처음 128개 문자만을 남겨두고, input을 잘라냅니다.

  9. input의 첫 번째 문자가 U+0023 숫자 부호 문자 (#)라면, 그것을 제거합니다.

  10. ASCII 16진수가 아닌 input의 모든 문자들을 U+0030 숫자 0 (0) 문자로 교체합니다.

  11. input의 길이가 0이나 3배수가 아닌 경우, input에 U+0030 숫자 0 (0)문자를 추가합니다.

  12. 3개의 컴포넌트를 얻기 위해 input을 동일한 길이의 세 문자열로 분할합니다. length를 그 컴포넌트들의 길이(input의 길이의 3분의 1)로 둡니다.

  13. length가 8보가 크다면, 각 컴포넌트의 앞선 length-8 문자를 제거하고 length를 8로 둡니다.

  14. length가 2보다 크고 각 컴포넌트의 첫 번째 문자가 U+0030 숫자 0 (0)문자인 경우, 그 문자를 제거하고, length를 하나 줄입니다.

  15. length여전히 2보다 크다면, 각 컴포넌트를 첫 번째 2개 문자만을 남겨 잘라냅니다.

  16. result간단한 색상으로 둡니다.

  17. 첫 번째 컴포넌트를 16진수 숫자로 해석합니다; result의 빨강 컴포넌트를 결과 숫자로 둡니다.

  18. 두 번째 컴포넌트를 16진수 숫자로 해석합니다; result의 초록 컴포넌트를 결과 숫자로 둡니다.

  19. 세 번째 컴포넌트를 16진수 숫자로 해석합니다; result의 파랑 컴포넌트를 결과 숫자로 둡니다.

  20. result를 반환합니다.

2.4.7. 공백으로 분리된 토큰

공백으로 분리된 토큰 집합은 1개 이상의 공백 문자으로 분리된 0개 이상의 단어(토큰으로 알려짐)로 구성되는 문자열이고, 단어는 어떤 것도 공백 문자가 아닌, 1개 이상의 문자의 문자열로 구성됩니다.

공백으로 분리된 토큰 집합을 포함하는 문자열은 앞 뒤 공백 문자를 가질 수도 있습니다.

공백으로 분리된 고유한 토큰의 비순차적 집합은 어떤 토큰도 중복되지 않는 공백으로 분리된 토큰 집합입니다.

공백으로 분리된 고유한 토큰의 순차적 집합은 어떤 토큰도 중복되지 않고 토큰의 순서가 의미가 있는 공백으로 분리된 토큰 집합입니다.

공백으로 분리된 토큰 집합은 때때로 정의된 허용된 값의 집합을 가집니다. 허용된 값의 집합이 정의되는 경우, 토큰은 모두 허용된 값의 목록에 있어야(must)합니다; 다른 값들은 부적합합니다. 그러한 허용된 값의 집합이 제공되지 않으면, 모든 값들이 적합합니다.

공백으로 분리된 토큰 집합의 토큰이 비교되는 방법(예를 들어, 대소문자를 구별하는지 아닌지)은 각 집합 기준으로 정의되어 있습니다.

유저 에이전트가 공백으로 문자열을 분리해야하는(has to)경우, 다음 알고리즘을 사용해야(must)합니다:

  1. input을 해석되는 문자열로 둡니다.

  2. position을 초기에 문자열의 시작을 가리키는, input에 대한 포인터로 둡니다.

  3. tokens을 초기에 비어있는, 토큰의 순차적인 목록으로 둡니다.

  4. 여백을 건너뜁니다.

  5. positioninput의 끝을 지나지 않은 경우:

    1. 공백 문자가 아닌 일련의 문자를 수집합니다.

    2. 이전 단계에서 수집된 문자열을 tokens에 추가합니다.

    3. 여백을 건너뜁니다.

  6. tokens을 반환합니다.

2.4.8. 콤마로 분리된 토큰

콤마로 분리된 토큰의 집합은 각 단일 U+002C 콤마 문자 (,)로 다음 토큰과 분리된 0개 이상의 토큰을 포함하는 문자열이고, 토큰은 공백 문자로 시작하거나 끝나지 않고, U+002C 콤마 문자(,)를 포함하지 않으며, 선택적으로 공백 문자로 둘러 싸이는, 0개 이상의 문자의 문자열로 구성됩니다.

예를 들어, 문자열 " a ,b,d d "는 4개의 토큰으로 구성됩니다: "a", "b", 빈 문자열, "d d". 각 토큰 주변의 앞 뒤 여백은 토큰의 부분으로 간주되지 않고, 빈 문자열은 토큰이 될 수 있습니다.

콤마로 분리된 토큰의 집합은 때때로 유효한 토큰으로 구성되는 것에 추가적인 제한 사항을 가집니다. 그러한 제한 사항이 정의되는 경우, 토큰은 모두 그 제한 사항에 적합해야 합니다; 다른 값들은 부적합합니다. 그러한 제한 사항이 명시되지 않는다면, 모든 값들은 적합합니다.

유저 에이전트가 콤마로 문자열을 분리해야(has to) 하는 경우, 다음 알고리즘을 수행해야(must) 합니다:

  1. input을 해석되는 문자열로 둡니다.

  2. position을 초기에 문자열의 시작을 가리키는, input에 대한 포인터로 둡니다.

  3. tokens을 초기에 비어 있는, 토큰의 순차적인 목록으로 둡니다.

  4. Token: positioninput의 끝을 지났다면, 마지막 단계로 건너뜁니다.

  5. U+002C COMMA 문자 (,)가 아닌 일련의 문자를 수집합니다. s를 결과 시퀀스(빈 문자열일 수 있습니다)로 둡니다.

  6. s에서 앞뒤 여백 문자를 비워냅니다.

  7. stokens에 추가합니다.

  8. positioninput의 끝을 지나지 않았따면, position에 있는 문자는 U+002C 콤마 문자 (,)입니다; position를 그 문자를 지나 전진시킵니다.

  9. token로 라벨링 된 단계로 돌아갑니다.

  10. tokens을 반환합니다.

2.4.9. 참조

type 유형의 요소(element)로의 유효한 해시 이름 참조는 문서에서 type 유형을 가진 요소(element)의 name 속성(attribute)의 값과 정확히 일치하는 문자열이 뒤따르는 U+0023 숫자 부호 문자 (#)로 구성되는 문자열입니다.

컨텍스트 노드 scope로 주어지는, type 유형의 요소(element)로의 해시 이름 참조 해석을 위한 규칙은 다음과 같습니다:

  1. 해석되는 문자열이 U+0023 숫자 부호 문자를 포함하지 않거나, 문자열의 첫 번째 그 문자가 문자열의 마지막 문자라면, null을 반환하고 이 단계들을 중단합니다.

  2. s를 해석되는 문자열의 첫 번째 U+0023 숫자 부호 문자 바로 뒤의 문자에서부터 그 문자열의 끝까지 문자열로 둡니다.

  3. 값이 s대소문자를 구별하여 일치하는 id 속성(attirbute)이나 값이 s호환되는 대소문자 구분이 없이 일치하는 name 속성(attirbute)을 가진 scope에 뿌리를 둔 하위 트리의 트리 순서에 따라 type유형의 첫 번째 요소(element)를 반환합니다.

2.4.10. 미디어 쿼리

문자열이 미디어 쿼리 명세의 <media-query-list> 결과물과 일치한다면 유효한 미디어 쿼리 목록입니다. [MEDIAQ]

문자열이 빈 문자열, 혹은 공백 문자로만 구성되는 문자열, 혹은 미디어 쿼리 명세에 주어진 정의에 따라 사용자의 환경에 일치하는 미디어 쿼리 목록이라면, 문자열은 사용자의 환경과 일치합니다. [MEDIAQ]

2.5. URLs

2.5.1. 용어

URL이 WHATWG URL 표준의 저작 적합성 요구사항에 준하다면 유효한 URL입니다. [URL]

문자열이 유효한 URL이고 빈 문자열이 아니라면 유효한 비어있지 않은 URL입니다.

문자열은, 문자열로부터 앞뒤 여백 문자를 비워낸 이후, 유효한 문자열이라면, 잠정적으로 공백으로 둘러싸일 수 있는 유효한 URL 입니다.

문자열은, 문자열로부터 앞뒤 여백 문자를 비워낸 이후, 유효한 비어있지 않은 URL이라면, 유효한 잠정적으로 공백으로 둘러 싸일 수 있는 비어있지 않은 URL입니다.

이 명세는 XML 도구와 호환성이 필요할 경우 HTML 문서DOCTYPE에서 사용을 위해 예약된, 비록 해결할 수 없지만, about: URL과 같이 URL about:legacy-compat를 정의합니다. [RFC6694]

이 명세는 확인 할 수 없음에도 불구하고, 예약된 URL about:과 같이 iframe srcdoc 문서문서의 주소로 사용되는 about:srcdoc를 정의합니다. [RFC6694]

객체의 폴백 기본 URL은 이 하위 단계들을 수행하여 얻어지는 절대 URL입니다:

  1. documentiframe srcdoc 문서라면, Document브라우징 컨텍스트브라우징 컨텍스트 컨테이너노드 문서문서 기본 URL을 반환합니다.

  2. documentURLabout:blank이고, document브라우징 컨텍스트생성자 브라우징 컨텍스트를 가진다면, 생성자 기본 URL을 반환합니다.

  3. documentURL을 반환합니다.

Document 객체의 문서 기본 URL은 이 하위 단계들을 수행하여 얻어지는 절대 URL입니다:

  1. Documenthref 속성(attribute)를 가진 base 요소(element)가 없다면, 문서 절대 URLDocument폴백 기본 URL입니다; 이 단계들을 중단합니다.

  2. 그렇지 않으면, 문서 기본 URL트리 순서에 따라 Document 내의 href 속성(attribute)을 가진 첫 번째 base 요소(element)의 고정(frozen) 기본 URL입니다.

2.5.2. URL 해석

URL 해석은 URL 문자열을 가져오고 그것이 의미하는 URL 레코드를 획득하는 과정입니다. 이 과정이 WAHTWG URL 표준에 정의되어 있지만, 이 명세는 편의상 래퍼를 정의합니다. [URL]

이 래퍼는 레거시 이유로 URL 해석기에 대한 문자 인코딩이 문서나 환경 설정 객체의 문자 인코딩과 일치해야(has to) 하는 경우에만 유용합니다. 문자 인코딩이 그 경우가 아닌 경우 URL 해석기가 직접적으로 사용될 수 있습니다.

documentenvironment settings object과 관련된, url URL을 해석하기 위해, 유저 에이전트는 다음 단계들을 사용해야(must) 합니다. URL 해석은 실패되거나 결과 URL 문자열결과 URL 레코드가 됩니다.

  1. document가 주어졌고, environment settings objectAPI URL 문자 인코딩은 주어지지 않았다면, encodingdocument문자 인코딩으로 둡니다.

  2. document가 주어졌고, environment settings objectbaseURLAPI 기본 URL은 주어지지 않았다면, document기본 URL로 둡니다.

  3. urlRecordbaseURLencoding과 함께, URL 해석기url에 적용한 결과로 둡니다.

  4. urlRecord가 실패라면, 오류와 함께 이 단계를 중단합니다.

  5. urlStringURL 시리얼라이저urlRecord에 적용한 결과로 둡니다.

  6. 결과 URL 문자열urlString을 반환하고 결과 URL 레코드urlRecord를 반환합니다.

2.5.3. 기본 URL로 동적 변경

문서의 문서 기본 URL이 변경되는 경우, 그 문서 내의 모든 요소(element)들은 습니다.

다음은 요소(element)가 기본 URL 변경에 의해 영향을 받는 경우 (DOM 명세에 정의된 대로), 수행되는 기본 URL 변경 단계입니다:

요소(element)가 하이퍼링크를 생성한다면
하이퍼링크에 의해 확인된 URL이 사용자에게 보여지거나, 그 URL로부터 파생된 임의의 데이터가 표현(display)에 영향을 미치고 있다면, href 속성(attribute)은 요소(element)의 노드 문서와 알맞게 갱신된 UI와 관련하여 재해석 되어야(should) 합니다.

예를 들어, CSS :link/:visited 가상 클래스는 영향을 받았을 수 있습니다.

요소(element)가 cite 속성(attribute)을 가진 q, blockquote, ins, del요소라면
cite 속성(attribute)에 의해 확인 된 URL이 사용자에게 보여지고 있거나, 그 URL로부터 파생된 임의의 데이터가 표시에 영향을 미치고 있다면, URL은 요소(element)의 노드 문서와 알맞게 갱신된 UI와 관련하여 재해석 되어야(should) 합니다.
그렇지 않으면
요소(element)는 직접적으로 영향을 받지 않습니다.

예를 들어, 기본 URL을 변경하는 것은, 스크립트에서 src IDL 속성(attribute)의 다음 접근이 보여지고 있는 이미지와 더 이상 일치하지 않을 새로운 절대 URL을 반환할 것이기는 하지만, img 요소(element)에 의해 표시된 이미지에 영향을 주지 않습니다.

2.6. 리소스 가져오기

2.6.1. 용어

유저 에이전트는 다양한 전송 프로토콜을 구현할 수 있지만, 이 명세는 주로 HTTP 관점에서 동작을 정의합니다. [HTTP]

HTTP GET 메서드는 프로토콜의 기본 검색 동작과 동일합니다. 예를 들어, FTP에서의 RETR. 그러한 동작은 HTTP 관점에서, 멱등하고 안전합니다.

멱등(idempotent)
멱등성(冪等性, 영어: idempotence)은 수학이나 전산학에서 연산의 한 성질을 나타내는 것으로, 연산을 여러 번 적용하더라도 결과가 달라지지 않는 성질을 의미.
메서드를 여러 번 호출해서 한 번만 호출한 것과 동일한 결과가 나오는 경우 이 메서드를 멱등(idempotent)이라고 할 수 있습니다. 예를 들어 읽기 전용 메서드와 같이 일반적으로 서버 측의 어떠한 상태도 변경하지 못하는 모든 메서드는 멱등(idempotent)입니다.
GET 방식과 POST로 데이터를 전송받은 URL을 재요청(refresh 등으로)할 경우, GET 페이지는 이전과 재요청 후와 동일한 결과를 응답하겠지만, POST 페이지는 재요청 시 데이터 누락으로 올바르지 않은 페이지를 응답하게 되는 것. (참고 : protocol spec)

HTTP 응답 코드는 동일한 기본 의미(meanings)를 갖는 다른 프로토콜에서의 상태와 동일합니다. 예를 들어, "file not found" 오류는 404 코드와 동일하고, 서버 오류는 5xx 코드와 동일합니다.

HTTP 헤더는 동일한 기본 의미(meanings)를 갖는 다른 프로토콜에서의 필드와 동일합니다. 예를 들어, HTTP 인증 헤더는 FTP 프로토콜의 인증 측면과 동일합니다.

리퍼러 소스DocumentURL입니다.

url, corsAttributeState, 선택적으로 동일 출처(origin) 폴백 플래그가 주어진 잠정적 CORS 요청을 생성하기 위해 이 단계들을 수행합니다:

  1. corsAttributeStateNo CORS이라면 mode를 "no-cors"로 두고, 그렇지 않으면 "cors"로 둡니다.

  2. 동일 출처(origin) 폴백 플래그가 설정되고 mode가 "no-cors"라면, mode를 "same-origin"로 설정합니다.

  3. credentialsMode를 "include"로 둡니다.

  4. corsAttributeState익명(Anonymous)이라면, credentialsMode를 "same-origin"로 설정합니다.

  5. requestURLurl이고, 목적지가 "subresource"이고, 모드mode이며 자격 증명 모드credentialsMode이고, URL 자격 증명 사용 플래그가 설정된 새로운 요청으로 둡니다.

2.6.2. 처리 모델

유저 에이전트가, 선택적으로 출처 origin으로부터, 선택적으로 오버라이드 리퍼러 소스로서 특정한 리퍼러 소스사용하여, 선택적으로 동기(synchronous) 플래그, 수동 리다이렉트 플래그, 강제 동일 출처(origin) 플래그, 쿠키 차단 플래그 중 어느 것을 가진 리소스나 URL가져오는 경우, 다음 단계들이 수행 되어야(must) 합니다. (URL을 가져올 때, URL은 얻어지는 리소스를 식별합니다.)

  1. 특정 오버라이드 리퍼러 리소스가 있고, 그것이 URL이라면, referrer오버라이드 리퍼러 리소스로 두고, clean referrer로 라벨링 된 단계로 건너 뜁니다.

  2. document를 다음 목록에 의해 주어진 대로 적절한 Document로 둡니다:

    특정한 오버라이드 리퍼러 리소스가 있다면
    오버라이드 리퍼러 리소스.
    이동 중(navigating)인 경우
    소스 브라우징 컨텍스트활성 문서.
    요소(element)에 대한 리소스를 가져오는 중인 경우
    요소(element)의 Document.
  3. documentiframe srcdoc 문서임에도 불구하고, document를 대신 document브라우징 컨텍스트브라우징 컨텍스트 컨테이너Document로 둡니다.

  4. Document출처(origin)가 scheme/host/port 튜플이 아니라면, referrer를 빈 문자열로 설정하고 Clean referrer로 라벨링 된 단계로 건너뜁니다.

  5. referrerdocument문서 주소로 둡니다.

  6. Clean referrer: URL 해석기referrer에 적용하고 parsed referrer결과 URL 레코드로 둡니다.

  7. referrer제외 프래그먼트 플래그 세트를 가지고 URL 시리얼라이저parsed referrer에 적용한 결과로 둡니다.

  8. referrer가 빈 문자열, data: URL, URL "about:blank"가 아니라면, referrer로부터 Referer (sic) 헤더에 대한 HTTP에 의해 요구된 대로 요청 UIR가 얻어지는 리소스의 주소를 생성합니다. [HTTP]

    그렇지 않으면, Referer (sic) 헤더는 그것의 값에 관계 없이 생략 되어야(must)합니다.

  9. 알고리즘이 동기(synchronous) 플래그를 가지고 작동되지 않았다면, 병렬로 나머지 단계들을 수행합니다.

  10. 이 알고리즘에 의해 대기 된 연관될 수 있는 작업들을 가진 Document가 연관된 브라우징 컨텍스트를 가지지 않는다면, 이 단계들을 중단합니다.

  11. 이것은 main step입니다.

    리소스가 어플리케이션 캐시로부터 얻어지는 것이라면, 마치 URL을 주어진 적절한 방법으로 얻어진 것처럼, 그 어플리케이션 캐시의 데이터를 사용합니다.

    리소스가 절대 URL에 의해 식별되고, 리소스가 멱등 동작 (HTTP GET이나 그와 동등한 것과 같은)을 사용하여 얻어진 것이고, 이미 다른 이유로 다운로드 되고 있고(예를 들어, 이 알고리즘의 다른 발동), 이 요청이 이전의 요청과 동일하고 (예를 들어, 동일한 AcceptOrigin헤더), 유저 에이전트가 새로운 다운로드를 개시하는 대신 기존 다운로드로부터 데이터를 다시 사용하도록 구성되어 있다면, 새로운 다운로드를 시작하는 대신 기존 다운로드의 결과를 사용합니다.

    그렇지 않고, 리소스가 리소스를 획득하기 위한 메커니즘을 정의하지 않는 스킴 (예를 들어, mailto: URL)이나 유저 에이전트가 지원하지 않는 스킴을 가진 절대 URL에 의해 식별된다면, 리소스가 다른 메타데이터가 없는 HTTP 204 콘텐트 없음 이었던 것 처럼 동작합니다.

    그렇지 않고, 리소스가 URL about:blank에 의해 식별된다면, 리소스는 메타데이터 없이 즉시 사용가능하고 빈 문자열로 구성됩니다.

    그렇지 않으면, 사용자와 유저 에이전트에게 알맞은 시간에 관련된 명세의 의미(semantics)를 적용하여 (예를 들어, HTTP GET이나 POST 연산을 수행하여, 혹은 디스크로부터 파일을 읽어, 혹은 data: URL을 확장하여, 등등) 리소스를 다운로드 (혹은 그렇지 않으면 획득)합니다.

    Referer (sic) 헤더의 목적을 위해, 이전 단계에서 생성된 요청 URI가 얻어지는 리소스의 주소 from which Request-URIs are obtained를 사용합니다.

    Origin 헤더의 목적을 위해, 페칭(fetching) 알고리즘origin에서 명시적으로 초기화 되었다면, HTTP 요청을 초기화 한 출처(origin)origin입니다. 그렇지 않으면, 이것은 "민감한 개인정보" 컨텍스트로부터의 요청입니다. [ORIGIN]

  12. 알고리즘이 쿠키 차단 플래그를 가지고 동작되지 않았고 쿠키가 설정되지 않았다면, 쿠키를 업데이트 합니다. [COOKIES] (이것은 지문 그림입니다.)

  13. 가져와진 리소스가 HTTP 리다이렉트 혹은 그와 동등한 것이라면:

    강제 동일 출처(origin) 플래그가 설정되어 있고 리다이렉트 대상의 URL페치(fetch) 알고리즘이 동작되는 URL과 같은 동일 출처(origin)를 가지지 않는다면
    원격 호스트가 연결할 수 없는 것 처럼, 이 단계들을 중단하고 이 알고리즘으로부터 실패를 반환합니다.
    수동 리다이렉트 플래그가 설정되어 있다면
    알고리즘의 결과로서 가져와진 리소스(리다이렉트)를 사용하여 계속합니다. 호출 알고리즘이 이후에 유저 에이전트가 투명하게 리다이렉트를 따르도록 요구한다면, 유저 에이전트는 main step으로부터, 원래 리소스 대신에 가져오기 위한 리소스로서 리다이렉트의 대상을 사용하여 이 알고리즘을 재개해야(must)합니다.
    그렇지 않으면
    먼저, 리다이렉트 관련 요구 사항(적절한 프롬프트를 표시하는 것 같은)을 적용합니다. 이후, main step을 원래 리소스 대신에 가져오기 위한 리소스로서 리다이렉트 대상을 사용하여 다시합니다. HTTP 요청의 경우, 새로운 요청은 다른 요구사항이 명시된 헤더(Host 헤더 같은)를 제외하고 본래 요청과 같은 동일한 헤더를 포함해야(must) 합니다. [HTTP]

    HTTP 명세는 301, 302, 307 리다이렉션이 안전한 방법 이외의 방법에 적용 될 때 사용자 확인 없이 따르지 않을 것이 요구됩니다. 그것은 위 문단에서 요구사항의 목적을 위한 적절한 프롬프트가 될 것 입니다. [HTTP]

  14. 알고리즘이 동기(synchronous) 플래그를 가지고 호출되지 않았다면: 리소스가 사용가능하거나, 어떤 설명의 오류가 있는 경우, 적절한 리소스를 사용하는 작업을 대기열에 넣습니다. 예를 들어, 순차적으로 JPEG나 HTML 파일이 섞인 것 같은 리소스가 즉시 처리될 수 있다면, 그것이 다운로드 될 때 추가적인 작업이 데이터를 처리하기 위해 대기열에 넣어질 수 있습니다. 이 작업들에 대한 작업 소스네트워킹 작업 소스입니다.

    그렇지 않으면, 리소스나 오류 정보를 호출 알고리즘에 반환합니다.

유저 에이전트가 이 알고리즘의 인스턴스에 대해 가져오는 리소스의 실제 길이를 결정할 수 있고, 그 길이가 유한하다면, 그 길이는 파일의 크기입니다. 그렇지 않으면, 알고리즘의 주제(즉, 가져오는 리소스)는 알려진 크기를 가지지 않습니다. (예를 들어, HTTP Content-Length 헤더가 이 정보를 제공할 수 있습니다.)

유저 에이전트는 이 알고리즘의 각 인스턴스에 대해 다운로드 된 바이트 수의 트랙 역시 유지해야(must) 합니다. 이 수는 HTTP 헤더와 같은, 대역 외 메타 데이터를 제외해야(must) 합니다.

이동 처리 모델은 페칭(fetching) 알고리즘에 의해 수행되는 리다이렉션 처리를 재정의 하여, 리다이렉트 자체를 처리합니다.

유형 스니핑 규칙이 가져와진 리소스에 적용되는지 여부는 규칙을 호출하는 알고리즘에 따라 달라집니다 — 그것들이 항상 적절한 것은 아닙니다.

HTTP를 참조하는 이 명세의 모든 내용은 https 스킴을 나타내는 URL로 표현되는 TLS상의 HTTP에도 적용됩니다. [HTTP]

유저 에이전트는 사용자에게 인증서 오류를 보고 해야(should)하고, 잘못된 인증서로 전송된 리소스를 다운로드하는 것을 거부해야(must)하거나 그러한 리소스가 실제로 암호화 없이 제공되는 것처럼 수행해야(must)합니다.

유저 에이전트는 페이미가 두 번째 방문 시 보안 수준이 낮은 암호화를 사용한다면 사용자가 이전에 방문했던 페이지를 방문 할 때마다 사용자에게 잠재적인 문제가 있음을 경고해야(should) 합니다.

그렇게 하지 않는 것은 사용자가 중간자(man-in-the-middle) 공격을 알아채지 못하게 할 수 있습니다.

중간자(man-in-the-middle) 공격
웹사이트와 방문자 사이에 끼어들어네트워크 통신을 조작하여 통신 내용을 도청하거나 조작하는 공격 기법
중간자 공격은 통신을 연결하는 두 사람 사이에 중간자가 침입하여, 두 사람은 상대방에게 연결했다고 생각하지만 실제로는 두 사람은 중간자에게 연결되어 있으며 중간자가 한쪽에서 전달된 정보를 도청 및 조작한 후 다른 쪽으로 전달합니다.
사용자가 자체 서명된 인증서를 가지고 서버에 연결한다면, 유저 에이전트는 암호화가 없었던 것 처럼 연결을 허용할 수 있습니다. 유저 에이전트가 대신 사용자가 문제를 무시한 후 완전히 안전하게 암호화 된 것처럼 페이지를 표시하도록 허용했다면, 사용자는 중간자(man-in-the-middle) 연결을 수용할 수 있도록 쉽게 속일 수 있습니다.

사용자가 전체 암호화 된 서버에 연결했지만, 페이지가 이후 만료 된 인증서를 가진 외부 리소스를 참조한다면, 유저 에이전트는, 어쩌면 사용자에게 문제를 보고하여, 리소스를 사용할 수 없는 것처럼 동작할 것입니다. 유저 에이전트가 대신 리소스가 사용되도록 허용했다면, 공격자는 다른 호스트의 리소스를 사용한 "보안" 사이트를 찾을 수 있고, 예를 들어 페이지의 스크립트를 넘겨받아, 그 호스트에 중간자(man-in-the-middle) 공격을 적용할 수 있습니다.

사용자가 CA 서명 인증서를 사용하는 사이트를 북마크 한 후, 그 사이트를 직접 방문하지만 해당 사이트가 자체 서명된 인증서를 사용하여 시작된다면, 유저 에이전트는 페이지가 암호화 되지 않은 것 처럼 단순하게 동작하는 대신, 중간자(man-in-the-middle) 공격이 진행 될 수 있다는 것을 사용자에게 경고할 수 있습니다.

2.6.4. 리소스 유형 결정

리소스의 Content-Type 메타데이터는 MIME 스니핑 명세의 요구사항과 일치하는 방법으로 획득되고 해석되어야(must)합니다. [MIMESNIFF]

리소스의 계산된 유형은 객체의 관련 시퀀스의 계산된 미디어 타입을 찾기 위한 주어진 요구사항과 일치하는 방법으로 찾아져야(must) 합니다. [MIMESNIFF]

명확하게 이미지를 스니핑하기 위한 규칙리소스가 텍스트인지 바이너리인지 구분하기 위한 규칙도 마임 스니핑 명세에 정의됩니다. 두 규칙의 집합 모두 그것들의 결과로 MIME 타입을 반환합니다. [MIMESNIFF]

MIME 스니핑 명세의 규칙은 정확하게 반드시 준수되어야 합니다. 유저 에이전트가 When a 유저 에이전트가 서버가 예상하는 것보다 다른 유형 감지를 위한 다른 휴리스틱을 사용하는 경우, 보안 문제가 발생할 수 있습니다. 자세한 내용은 MIME 스니핑 명세를 참고하세요. [MIMESNIFF]

2.6.5. meta 요소(element)로부터 문자 인코딩 추출하기

주어진 문자열 s인, meta 요소(element)로부터 문자 인코딩 추출하기 위한 알고리즘은, 다음과 같습니다. 이것은 문자 인코딩을 반환하거나 아무 것도 반환하지 않을 것입니다.

  1. position을 초기에 문자열의 시작을 가리키는, s에 대한 포인터로 둡니다.

  2. Loop: 단어 "charset"에 ASCII 대소문자 구분 없이 일치하는 position 이후의 s 내 처음 7개 문자를 찾습니다. 그러한 일치 항목이 발견되지 않으면, 아무 것도 반환하지 않고 이 단계들을 중단합니다.

  3. 단어 "charset"에 바로 뒤따르는 모든 공백 문자들을 건너 뜁니다.(아무 것도 없을 수도 있습니다).

  4. 다음 문자가 U+003D 등호 기호 (=)가 아니라면, position을 그 다음 문자 바로 이전 지점으로 이동시키고, loop로 라벨링 된 단계로 돌아갑니다.

  5. 등호 기호에 바로 뒤따르는 모든 공백 문자들을 건너뜁니다. (아무 것도 없을 수도 있습니다).

  6. 다음과 같이 다음 문자를 처리합니다:

    U+0022 따옴표 문자 (")이고 이후에 s에 U+0022 따옴표 문자 (")가 있다면
    U+0027 어포스트로피 문자 (')이고 이후에 s에 U+0027 어포스트로피 문자 (')가 있다면
    이 문자와 다음으로 가장 먼저 나타나는 이 문자 사이의 부분 문자열로부터 인코딩을 얻은 결과를 반환합니다.
    매치되지 않는(unmatched) U+0022 따옴표 문자 (")라면
    즉, <meta charset="""> 과 같이 pair가 없는 U+0022 따옴표 문자(")를 의미.
    매치되지 않는(unmatched) U+0027 어포스트로피 문자 (')라면
    다음 문자가 없다면
    아무 것도 반환하지 않습니다.
    그렇지 않으면
    이 문자부터 첫 공백 문자나 U+003B 세미콜론 문자 (;)을 포함하지 않고, 또는 s의 끝, 어느 쪽이든 처음 오는 문자까지 이들을 구성되는 부분 문자열로부터 인코딩을 얻은 결과를 반환합니다.
    원문이 제법 복잡하게(?) 설명이 되어 있는데 의역해 보자면,
    • 공백 문자나 세미콜론 문자가 있다면 이 공백문자나 세미콜론 문자 전까지
    • s 끝까지
    의 부분 문자열을 인코딩을 얻은 결과로 사용한다는 의미일 것으로 보입니다.

이 알고리즘은 HTTP 명세의 그것과는 다릅니다 (예를 들어, HTTP는 싱글 따옴표를 사용하는 것을 허용하지 않고 이 알고리즘에 의해 지원되지 않는 백슬래쉬 이스케이프(backslash-escape) 메커니즘을 지원하도록 요구합니다). 이 알고리즘이 역사적으로 HTTP에 연관된 컨텍스트에서 사용되는 반면, 구현에 의해 지원되는 구문은 얼마 전에 분기되었습니다. [HTTP]

2.6.6. CORS 설정 속성(attribute)

CORS 설정 속성(attribute)열거 속성입니다. 다음 표는 속성(attribute)에 대한 키워드와 상태를 나열합니다 — 왼쪽 열의 키워드는 키워드와 동일한 행의 두 번째 열의 셀에 있는 상태에 매핑됩니다.

키워드 상태 간단한 설명
anonymous 익명 요소(element)에 대한 요청은 "cors"로 설정 된 모드와 "same-origin"으로 설정 된 자격 증명 모드를 가질 것입니다.
use-credentials 자격 증명 사용 요소(element)에 대한 요청은 "cors"로 설정 된 모드와 "include"로 설정 된 자격 증명 모드를 가질 것입니다.

빈 문자열은 유효한 키워드이고 익명 상태에 매핑됩니다. 속성(attribute)의 유효하지 않은 기본 값 익명 상태입니다. 반영의 목적을 위해, Anonymous 상태에 대한 정식 사례는 anonymous 키워드입니다. 속성이 생략되었을 경우 사용되는 누락 기본 값No CORS 상태 입니다.

2.7. 공통 DOM 인터페이스

2.7.1. IDL 속성(attribute)에 콘텐트 속성(attribute) 반영하기

일부 IDL 속성(attribute)들은 특정 콘텐트 속성(attribute)을 반영하도록 정의됩니다. 이것은 가져올 때 IDL 속성(attribute)은 콘텐트 속성(attribute)의 현재 값을 반환하고, 설정할 때 IDL 속성(attribute)은 콘텐트 속성(attribute)의 값을 주어진 값으로 변경하는 것을 의미합니다.

일반적으로, 가져올 때, 콘텐트 속성(attribute)이 존재하지 않는다면, IDL 속성은 콘텐트 속성(attribute)의 값이 빈 문자열인 것 처럼 동작해야(must) 합니다; 그리고 설정할 때, 콘텐트 속성(attribute)이 존재하지 않는다면, 먼저 추가 되어야(must) 합니다.

반영하는 IDL 속성(attribute)이 콘텐트 속성이 한 개 URL을 포함하도록 정의된 DOMString 속성(attribute)이라면, 가져올 때, IDL 속성(attribute)은 콘텐트 속성(attribute)의 값을 요소(element)에 관련하여 해석해야(must)하고 그것이 성공했다면 결과로 얻어지는 절대 URL을 반환하며, 그렇지 않으면 빈 문자열을 반환해야(must) 합니다; 그리고 설정할 때, 콘텐트 속성(attribute)을 명시된 리터럴 값으로 설정해야(must) 합니다. 콘텐트 속성(attribute)이 존재하지 않는다면, IDL 속성(attribute)은 콘텐트 속성이 기본 값을 가진다면 그 기본 값을, 그렇지 않으면 빈 문자열을 반환해야(must) 합니다.

반영하는 IDL 속성(attribute)이 콘텐트 속성이 하나 이상의 URLs을 포함하도록 정의된 DOMString 속성(attribute)이라면, 가져올 때, IDL 속성(attribute)은 공백으로 콘텐트 속성(attribute)을 분할해야(must)하고 각 토큰 URL을 해석한 것의 연결을 요소에 관련하여, 각 URL 사이에 단일 U+0020 공백 문자를 가지고, 성공적으로 분해(resolve)되지 않은 토큰들은 무시하여, 절대 URL에 반환합니다. 콘텐트 속성(attribute)이 존재하지 않는다면, IDL 속성(attribute)은 콘텐트 속성이 기본 값을 가진다면 그 기본 값을, 그렇지 않으면 빈 문자열을 반환해야(must) 합니다. 설정할 때, IDL 속성(attribute)은 콘텐트 속성(attribute)을 명시된 리터럴 값으로 설정해야(must) 합니다.

반영하는 IDL 속성(attirbute)는 콘텐트 속성(attribute)이 열거 속성DOMString 속성(attribute)이고, IDL 속성이 오직 알려진 값에 제한된다면, 가져올 때, IDL 속성(attirbute)은 속성이 속한(그것의 정식 사례에 속한) 상태와 연관된 준수 값이 있다면 그 값이나 속성(attribute)이 연관된 키워드 값을 가지지 않는 상태에 있거나 속성(attribute)이 정의된 상태(예를 들어, 속성(attribute)이 누락되었고 누락 기본 값이 없는)에 속하지 않는다면 빈 문자열을 반환해야(must) 하고; 설정할 때, 콘텐트 속성은 명시된 새로운 값으로 설정 되어야(must) 합니다.

반영하는 IDL 속성(attribute)이 콘텐트 속성(attribute)이 열거 속성인 null이 될 수 있는 DOMString 속성(attribute)이라면, 가져올 때, 해당하는 콘텐트 속성(attirbute)이 누락 기본 값이라면 IDL 속성은 null을 반환해야(must)하고, 그렇지 않으면, IDL 속성(attirbute)은 속성(attribute)이 속하는 상태(그것의 정식 사례에 속한)에 연관된 준수한 값을 반환해야(must) 하며; 설정할 때, 새로운 값이 null이라면, 콘텐트 속성(attribute)은 제거되어야(must)하고, 그렇지 않으면 콘텐트 속성(attribute)은 명시된 새로운 값으로 설정되어야(must) 합니다.

반영하는 IDL 속성(attribute)이 DOMString 속성(attribute)이고 위 카테고리의 어느 범주에도 들어가지 않는다면, 가져오고 설정하는 것은 투명한, 대소문자 보존 방식으로 수행되어야(must) 합니다.

반영하는 IDL 속성(attribute)이 boolean 속성(attribute)이라면, 가져올 때 IDL 속성(attribute)은 콘텐트 속성(attribute)이 설정되었다면 true를 반환하고, 없다면 false를 반환합니다. 설정할 때, 콘텐트 속성(attribute)은 IDL 속성(attribute)이 false로 설정되어 있다면 제거되어야(must) 하고, IDL 속성이 true로 설정되어 있다면 빈 문자열로 설정되어야(must) 합니다. (이것은 불리언 콘텐트 속성(attribute)에 대한 규칙에 해당합니다.)

반영하는 IDL 속성(attribute)이 부호있는 정수 유형(long)을 가진다면, 가져올 때, 콘텐트 속성(attribute)은 부호있는 정수 해석에 대한 규칙을 따라 해석되어야(must)하고, 그것이 성공하고 값이 IDL 속성(attribute)의 유형의 범위에 있다면, 결과 값은 반환되어야(must) 합니다. 반면에, 그것이 실패 혹은 범위 밖의 값을 반환하거나, 속성(attribute)이 존재하지 않는다면, 기본 값이 대신 반환되어야(must)하고, 기본 값이 없다면 0이 반환되어야(must)합니다. 설정할 때, 주어진 값은 유효한 정수로 나타나는 가능한 가장 짧은 문자열로 변환되어야(must)하고 이후 그 문자열은 새로운 콘텐트 속성(attribute) 값으로 사용되어야(must)합니다.

반영하는 IDL 속성(attribute)이 음이 아닌 정수로만 제한된 부호있는 정수 유형 (long)을 가진다면, 가져올 때, 콘텐트 속성(attribute)은 음이 아닌 정수 해석에 대한 규칙을 따라 해석되어야(must) 하고, 그것이 성공했고 값이 IDL 속성(attribute)의 유형의 범위 내에 있다면, 결과 값이 반환되어야(must) 합니다. 반면에, 그것이 실패 혹은 범위 밖의 값을 반환하거나, 속성(attribute)이 존재하지 않는다면, 기본 값이 대신 반환되어야(must)하고, 기본 값이 없다면 -1이 반환되어야(must) 합니다. 설정할 때, 값이 음수라면, 유저 에이전트는 IndexSizeError 예외 오류를 던져야(must) 합니다. 그렇지 않으면, 주어진 값은 유효한 음이 아닌 정수로 나타내는 가능한 가장 짧은 문자열로 변환되어야(must)하고 이후 그 문자열은 새로운 콘텐트 속성(attribute) 값으로 사용되어야(must)합니다.

반영하는 IDL 속성(attribute)이 부호 없는 정수 유형 (unsigned long)을 가진다면, 가져올 때, 콘텐트 속성(attribute)은 음이 아닌 정수 해석에 대한 규칙을 따라 해석되어여(must)하고, 그것이 성공하고, 값이 0에서 2147483647까지 범위에 있다면, 결과 값이 반환되어야(must) 합니다. 반면에, 그것이 실패 혹은 범위 밖의 값을 반환하거나, 속성(attribute)이 존재하지 않는다면, 기본 값이 대신 반환되거나, 기본 값이 없다면 0이 반환되어야(must) 합니다. 설정할 때, 먼저, 새로운 값이 0에서 2147483647까지의 범위에 있다면 n를 새로운 값으로 두고, 그렇지 않으면 n를 기본 값으로 두거나 기본 값이 없다면 0으로 둡니다; 이후 n유효한 음이 아닌 정수로 나타나는 가능한 가장 짧은 문자열로 변환되어야(must)하고 그 문자열은 새로운 콘텐트 속성(attribute) 값으로 사용되어야(must) 합니다.

반영하는 IDL 속성(attribute)이 0보다 큰 음이 아닌 정수로만 제한된 부호 없는 정수 유형 (unsigned long)을 가진다면, 동작은 이전 경우와 비슷하게 동작하되 0은 허용되지 않습니다. 가져올 때, 콘텐트 속성(attribute)은 먼저 음이 아닌 정수 해석에 대한 규칙에 따라 해석되어야(must)하고, 그것이 성공하고 값이 1에서 2147483647까지 범위 내에 있다면, 결과 값이 반환되어야(must) 합니다. 반면에, 그것이 실패 혹은 범위 밖의 값을 반환하거나 속성(attribute)이 존재하지 않는다면, 기본 값이 대신 반환되어야(must) 하거나, 기본 값이 없다면 1을 반환해야(must) 합니다. 설정할 때, 값이 0이라면, 유저 에이전트는 IndexSizeError 예외를 던져야(must) 합니다. 그렇지 않으면, 먼저, 새로운 값이 1에서 2147483647 범위 내에 있다면, n을 새로운 값으로 두고, 그렇지 않으면 n을 기본 값으로, 혹은 기본 값이 없으면 1로 둡니다; 그 후, n유효한 음이 아닌 정수로 나타나는 가능한 가장 짧은 문자열로 변환되어야(must) 하고 그 문자열은 새로운 콘텐트 속성(attribute) 값으로 사용되어야(must) 합니다.

가져오는 IDL 속성(attribute)이 부동 소수점 수 유형(doubleunrestricted double)을 가진다면, 가져올 때, 콘텐트 속성(attribute)은 부동소수점 수 값 해석에 대한 규칙에 따라 해석되어야 하고 그것이 성공한다면, 결과 값이 반환되어야(must) 합니다. 반면에, 그것이 실패 혹은 속성(attribute)이 존재하지 않는다면, 기본 값이 대신 반환되어야(must) 하거나, 기본 값이 없으면 0.0이 반환되어야(must) 합니다. 설정할 때, 주어진 값은 부동 소수점 수의 가장 좋은 표현으로 변환되어야(must)하고 그 문자열은 새로운 콘텐트 속성(attribute) 값으로 사용되어야(must) 합니다.

반영하는 IDL 속성(attribute)이 0보다 큰 수로 제한된 부동 소수점 수 유형(doubleunrestricted double)를 가진다면, 이전 경우와 비슷하게 동작하되 0과 음수 값은 허용되지 않습니다. 가져올 때, 콘텐트 속성(attribute)은 부동 소수점 수 값 해석에 대한 규칙에 따라 해석되어야(must) 하고, 그것이 성공하고 값이 0.0보다 크다면, 결과 값이 반환되어야(must) 합니다. 반면에, 그것이 실패 혹은 범위 밖의 값을 반환하거나, 속성(attribute)이 존재하지 않는다면, 기본 값이 대신 반환되어야(must)하거나, 기본 값이 없다면 0.0이 반환되어야(must) 합니다. 설정할 때, 값이 0 이하라면, 값은 무시되어야(must) 합니다. 그렇지 않으면, 주어진 값은 부동 소수점 수의 가장 좋은 표현으로 변환되어야(must)하고 그 문자열은 새로운 콘텐트 속성(attribute) 값으로 사용되어야(must) 합니다.

무한대와 Not-a-Number(NaN) 값은, Web IDL 명세에 정의된 대로, 가져올 때 예외를 던집니다. [WEBIDL]

가져오는 IDL 속성(attribute)이 DOMTokenList 유형을 가진다면, 가져올 때 연관된 요소(element)가 문제의 요소이고 연관된 속성(attribute)의 지역 이름이 문제의 속성의 이름인 DOMTokenList 객체를 반환해야(must) 합니다. 동일한 DOMTokenList 객체는 각 속성(attribute)에 대해 매 번 반환되어야(must) 합니다.

반영하는 IDL 속성(attribute)이 HTMLElement 유형이나 HTMLElement의 자손 인터페이스를 가진다면, 가져올 때, 다음 알고리즘을 수행해야(must) 합니다(값을 반환하는 첫 번째 단계에서 중단하여):

  1. 해당하는 콘텐트 속성(attribute)이 존재하지 않는다면, IDL 속성(attribute)은 null을 반환해야(must) 합니다.

  2. document.getElementById() 메서드가 인수로 해당 컨텐츠 속성의 현재의 값을 건네 받았을 경우 콘텐트 속성(attribute)의 요소(element)의 노드 문서에서 호출 될 때 찾는 요소로 둡니다.

  3. candidate이 null이거나 IDL 속성(attribute)와 유형 호환되지 않는다면, IDL 속성(attribute)은 null을 반환해야(must) 합니다.

  4. 그렇지 않으면, candidate를 반환해야 합니다.

설정할 때, 주어진 요소(element)가 id 속성(attribute)을 가지고, 속성(attribute)이 설정된 요소와 동일한 홈 하위 트리를 가지며, 주어진 요소(element)가 그 홈 하위 트리에서 ID가 그 id 속성(attribtue)의 값인 첫 번째 요소(element)라면, 콘텐트 속성(attribute)은 그 id 속성(attribute)의 값으로 설정되어야(must) 합니다. 그렇지 않으면, 콘텐트 속성(attribute)은 빈 문자열로 설정되어야(must) 합니다.

2.7.2. 컬렉션

HTMLFormControlsCollectionHTMLOptionsCollection 인터페이스들은 HTMLCollection 인터페이스로부터 유래된 컬렉션입니다. 하지만 HTMLAllCollectionHTMLCollection으로부터 상속하기에 바람직하지 않은 다양한 기이한 특징을 가지기 때문에 독립적입니다.

2.7.2.1. HTMLAllCollection 인터페이스

HTMLAllCollection 인터페이스는 레거시 document.all 속성(attribtue)에 사용됩니다. HTMLCollection과 비슷하게 동작합니다; 함수처럼 호출 될 수 있는 것과 같은 웹 호환성을 위해 요구되는 다양한 다른 레거시 기능도 지원합니다(legacycaller).

모든 HTMLAllCollection 객체는 Document에 뿌리를 두고 있고 모든 요소와 일치하는 필터를 가지기 때문에, HTMLAllCollection 객체의 컬렉션에 의해 나타나는 요소(element)들은 루트 Document의 후손 요소(element)들로 구성됩니다.

[LegacyUnenumerableNamedProperties]
interface HTMLAllCollection {
  readonly attribute unsigned long length;
  getter Element? (unsigned long index);
  getter (HTMLCollection or Element)? namedItem(DOMString name);
  legacycaller (HTMLCollection or Element)? item(optional DOMString nameOrItem);
};
collection . length
컬렉션 내 요소(element)의 수를 반환합니다.
element = collection . item(index)
element = collection(index)
element = collection[index]
컬렉션으로부터 (트리 순서에 의해 결정된) 인덱스 index를 가진 항목을 반환합니다.
element = collection . item(name)
collection = collection . item(name)
element = collection . namedItem(name)
collection = collection . namedItem(name)
element = collection(name)
collection = collection(name)
element = collection[name]
collection = collection[name]
컬렉션으로부터 ID나 이름 name를 가진 항목을 반환합니다.

여러 개의 매칭되는 항목이 있다면, 그 요소들 모두를 포함하는 HTMLCollection 객체가 반환됩니다.

name 속성(attribute)의 값은 button, input, select, textarea에 대한 이름을 제공합니다. 비슷하게, iframename, objectname, metaname, mapname, formname 속성(attribute)의 값은 각 요소(element)에 대한 이름을 제공합니다. 언급된 요소(element)들만이 이 메서드의 목적을 위한 name을 가집니다.

객체의 지원되는 속성(property) 인덱스HTMLCollection 객체에 대해 정의된 것과 같습니다.

지원되는 속성(property) 이름트리 순서에 따라, 이후 중복된 것을 무시하여, idname를 모두 제공한다면, 요소(element)의 name에 앞선 id를 가지고 컬렉션에 의해 나타나는 모든 요소(element)들의 모든 idname 속성(attribute)의 비어 있지 않은 값으로 구성됩니다. idname이 모두 있을 경우, 이것들은 서로 다른 것이며 앞선 엔트리의 복제 역시 아닙니다.

가져올 때, length 속성(attribute)은 컬렉션에 의해 나타난 노드의 수를 반환합니다.

인덱싱 된 속성(property) getter는 전달받은 인덱스가 주어진 이 HTMLAllCollection로부터 모든 인덱싱 된 요소(element)를 가져온 결과를 반환해야(must) 합니다.

namedItem(name) 메서드는 name이 주어진 이 HTMLAllCollection로부터 모든 이름이 붙은 요소(element)나 요소들(elements)을 가져온 결과를 반환해야(must) 합니다.

item(nameOrIndex) 메서드는 (그리고 legacycaller 동작은) 다음 알고리즘을 따라 수행해야(must) 합니다:

  1. nameOrIndex가 제공되지 않았다면, null을 반환합니다.

  2. 자바스크립트 문자열 값으로 변환 된 nameOrIndex배열 인덱스 속성(property) 이름이라면, nameOrIndex에 의해 나타난 숫자가 주어진 이 HTMLAllCollection으로부터 인덱싱 된 모든 요소(element)를 가져온 결과를 반환합니다.

  3. nameOrIndex가 주어진 이 HTMLAllCollection으로부터 이름이 붙은 모든 요소(element) 혹은 요소들(elements)을 가져온 결과를 반환합니다.

다음 요소(element)들은 이름이 붙은 모든 요소(element)들로 간주됩니다: a, applet, button, embed, form, frame, frameset, iframe, img, input, map, meta, object, select, textarea.

인덱스 index가 주어진 HTMLAllCollection collection으로부터 "인덱싱 된 모든 요소(element)를 얻기 위해, collection내 인덱스 index를 가진 요소(element)를 반환하거나, index에 그러한 요소(element) 가 없다면 null을 반환합니다.

이름 name이 주어진 HTMLAllCollection collection으로부터 이름이 붙은 모든 요소(element) 혹은 요소들(elements)를 얻기 위해, 다음 알고리즘을 수행합니다.

  1. name이 빈 문자열이라면, null을 반환합니다.

  2. subCollection를 필터가 다음 중 하나의 요소(element)에만 일치되는, collection과 동일한 Document에 뿌리를 둔 HTMLCollection 객체로 둡니다:

  3. subCollection에 정확히 한 개 요소(element)가 존재한다면, 그 요소(element)를 반환합니다.

  4. 그렇지 않고, subCollection이 비어있다면, null을 반환합니다.

  5. 그렇지 않으면, subCollection를 반환합니다.

2.7.2.2. HTMLFormControlsCollection 인터페이스

HTMLFormControlsCollection 인터페이스는 form 요소에 나열 된 요소(element)들컬렉션으로 사용됩니다.

interface HTMLFormControlsCollection : HTMLCollection {
  // inherits length and item()
  getter (RadioNodeList or Element)? namedItem(DOMString name); // shadows inherited namedItem()
};
interface RadioNodeList : NodeList {
  attribute DOMString value;
};
collection . length
컬렉션 내 요소(element)들의 수를 반환합니다.
element = collection . item(index)
element = collection[index]
컬렉션으로부터 인덱스 index를 가진 항목을 반환합니다. 항목들은 트리 순서에 따라 정렬됩니다.
element = collection . namedItem(name)
radioNodeList = collection . namedItem(name)
element = collection[name]
radioNodeList = collection[name]
컬렉션으로부터 IDname name을 가진 항목을 반환합니다.

여러 개의 일치하는 항목이 존재한다면, 이 요소(element)들을 모두 포함하는 RadioNodeList 객체가 반환됩니다.

radioNodeList . value [ = value ]
객체에 의해 나타난 첫 번째 체크된 라디오 버튼의 값을 반환합니다.

객체에 의해 나타난 주어진 값을 가진 첫 번째 라디오 버튼을 체크하기 위해, 설정될 수 있습니다.

객체의 지원되는 속성(property) 인덱스HTMLCollection 객체에 대해 정의된 것과 같습니다.

지원되는 속성(property) 이름들트리 순서에 따라, 이후 중복을 무시하고, idname 모두를 제공한다면 요소(element)의 name에 앞서 id를 가지고, 컬렉션에 의해 나타나는 모든 요소(element)들의 모든 idname 속성(attribute)의 비어있지 않은 값으로 구성됩니다. idname은 서로 다르고, 앞선 엔트리의 복제 역시 아닙니다.

이 방법으로 노출된 속성들은 열거되어야(must) 합니다..

namedItem(name) 메서드는 다음 알고리즘을 따라 수행해야(must) 합니다:

  1. name이 빈 문자열이라면, null을 반환하고 알고리즘을 멈춥니다.

  2. 메서드가 호출되는 시점에 컬렉션에 name과 동일한 id 속성(attribute)이나 name 속성(attribute)을 가지는 정확히 한 개 노드가 존재한다면 그 노드를 반환하고 알고리즘을 멈춥니다.

  3. 그렇지 않고, 컬렉션에 name과 동일한 id 속성(attribute)이나 name 속성을 가지는 노드가 존재하지 않는다면 null을 반환하고 알고리즘을 멉춥니다.

  4. 그렇지 않으면, RadioNodeList 객체의 노드들만이 name과 동일한 id 속성(attribute)이나 name 속성(attribute)을 가지는 HTMLFormControlsCollection 객체이기 때문에 좀 더 걸러진, HTMLFormControlsCollection 객체의 존속되는 뷰를 나타내는 새로운 RadioNodeList 객체를 생성합니다. RadioNodeList 객체의 노드들은 트리 순서에 따라 정렬되어야(must) 합니다.

  5. RadioNodeList 객체를 반환합니다.


NodeList 인터페이스에서 상속된 RadioNodeList 인터페이스의 멤버들은 NodeList 객체에서와 같이 행동해야(must) 합니다.

RadioNodeList 객체의 value IDL 속성(attribute)은, 가져올 때, 다음 단계들을 수행하여 반환되는 값을 반환해야(must) 합니다.

  1. element트리 순서에 따라, type 속성(attribute)이 라디오 버튼 상태이고 체크 상태가 true인 input요소(element)인 RadioNodeList 객체에 의해 나타나는 첫 번째 요소로 둡니다. 그렇지 않으면, null로 둡니다.

  2. element가 null이라면, 빈 문자열을 반환합니다.

  3. elementvalue 속성(attribute)이 없는 요소(element)라면, "on" 문자열을 반환합니다.

  4. 그렇지 않으면, elementvalue 속성(attribute)의 값을 반환합니다.

설정할 때, value IDL 속성(attribute)은 다음 단계들을 수행해야(must) 합니다:

  1. 새로운 값이 문자열 "on"이라면 : element트리 순서에 따라, 라디오 버튼 상태인 type 속성(attribute)과 value 콘텐트 속성이 없거나 혹은 존재하면서 새로운 값과 동일한 input 요소(element)인 RadioNodeList 객체에 의해 나타난 첫 번째 요소(element)로 둡니다. 그러한 요소(element)가 존재하지 않는다면, 대신 element를 null로 둡니다.

    그렇지 않으면, element트리 순서에 따라, type 속성(attribute)이 라디오 버튼 상태이고 value 콘텐트 속성(attribute)이 존재하면서 새로운 값과 동일한 input 요소(element)인 RadioNodeList 객체에 의해 나타난 첫 번째 요소(element)로 둡니다. 그러한 요소(element)가 존재하지 않으면, 대신 element를 null로 둡니다.

  2. element가 null이 아니라면, 그 요소(element)의 체크 상태를 true로 둡니다

2.7.2.3. HTMLOptionsCollection 인터페이스

HTMLOptionsCollection 인터페이스는 option 요소(element)들의 컬렉션으로 사용됩니다. 그것은 항상 select 요소(element)에 뿌리를 두고 요소(element)의 후손을 조작하는 속성(attribute)들과 메서드들을 가집니다.

interface HTMLOptionsCollection : HTMLCollection {
  // inherits item(), namedItem()
  attribute unsigned long length; // shadows inherited length
  setter void (unsigned long index, HTMLOptionElement? option);
  void add((HTMLOptionElement or HTMLOptGroupElement) element, optional (HTMLElement or long)? before = null);
  void remove(long index);
  attribute long selectedIndex;
};
collection . length [ = value ]
컬렉션 내 요소(element)들의 수를 반환합니다.

더 적은 수로 설정하는 경우, 해당하는 컨테이너에서 option 요소(element)의 수를 잘라냅니다.

더 큰 수로 설정하는 경우, 그 컨테이너에 새로운 빈 option 요소(element)들을 추가합니다.

element = collection . item(index)
element = collection[index]
컬렉션에서부터 인덱스 index를 가진 항목을 반환합니다. 항목들은 트리 순서에 따라 정렬됩니다.
collection[index] = element
index가 컬렉션 내 항목들의 수보다 큰 경우, 해당하는 컨테이너에 새로운 빈 option 요소(element)들을 추가합니다.

null로 설정하는 경우, 컬렉션으로부터 인덱스 index에 있는 항목을 제거합니다.

option 요소(element)로 설정하는 경우, 컬렉션으로부터 인덱스 index에 있는 항목을 교체하거나 추가합니다.

element = collection . namedItem(name)
element = collection[name]
컬렉션으로부터 ID 혹은 name name을 가진 항목을 반환합니다.

일치하는 항목이 여러 개가 존재한다면, 첫 번째 것이 반환됩니다.

collection . add(element [, before ] )
before에 의해 주어진 노드 앞에 element를 삽입합니다.

before 인수는 번호가 될 수 있고, 이 경우 element는 그 숫자를 가진 항목 앞에 삽입되거나, 컬렉션의 요소(element)가 되는 경우에는, element는 그 요소 앞에 삽입됩니다.

before가 생략, 또는 null, 또는 범위 밖의 숫자라면, element는 목록의 끝에 삽입될 것입니다.

이 메서드는 element가 삽입될 요소(element)의 조상인 경우 HierarchyRequestError 예외를 던질 것입니다.

collection . remove(index)
컬렉션으로부터 인덱스 index를 가진 항목을 제거합니다.
collection . selectedIndex [ = value ]
첫 번째 선택된 항목이 있다면 그것의 인덱스를 반환하고, 선택된 항목이 없다면 -1을 반환합니다.

선택을 변경하기 위해, 설정될 수 있습니다.

객체의 지원되는 속성(property) 인덱스들HTMLCollection 객체에 대해 정의된 것과 같습니다.

가져올 때, length 속성(attribute)은 컬렉션에 의해 나타나는 노드들의 수를 반환해야(must) 합니다.

설정할 때, 행동은 새로운 값이 그 시간에 컬렉션에 의해 나타나는 노드들의 수와 같거나, 크거나, 작으냐에 따라 다릅니다. 숫자가 같다면, 속성(attribtue)을 설정하는 것은 아무 것도 하지 않아야(must)합니다. 새로운 값이 크다면, 속성(attribute)이 없고 자식 노드가 없는 n개의 새로운 option 요소(element)들은 HTMLOptionsCollection가 뿌리를 둔 select 요소(element)에 삽입되어야(must) 하고, 여기서 n은 두 수의 차이 (새로운 값에서 이전 값을 뺀) 입니다. 변경 이벤트는 새로운 option 요소(element)를 포함하는 DocumentFragment가 삽입된 것 처럼 발생되어야(must) 합니다. 새로운 값이 더 낮으면, 컬렉션의 마지막 n개 노드들은 그들의 부모 노드로부터 제거되어야(must)하고, 여기서 n은 두 수의 차이(이전 값에서 새로운 값을 뺀)입니다.

length를 설정하는 것은 어떤 optgroup 요소(element)들도 제거하거나 추가하지 않고, 새로운 자식을 기존의 optgroup 요소(element)들에 추가하지 않습니다(그것들로 부터 자식을 제거 할 수는 있지만).

지원되는 속성(property) 이름트리 순서에 따라, 이후 중복된 것을 무시하여, idname을 모두 제공한다면, 요소(element)의 name에 앞선 id를 가지고 컬렉션에 의해 나타나는 모든 요소(element)의 모든 idname 속성(attribute)들의 비어있지 않은 값으로 구성됩니다. idname이 모두 있을 경우, 이것들은 서로 다른 것이며 앞선 엔트리의 복제 역시 아닙니다.

이 방법으로 노출된 속성(property)들은 열거 되어야(must) 합니다.

유저 에이전트가 주어진 속성(property) 인덱스 index에 대한 새로운 인덱싱 된 속성(property)의 값 혹은 기존의 인덱싱된 속성(property)의 값의 설정을 새로운 값 value으로 하는 경우, 다음 알고리즘을 수행해야(must) 합니다:

  1. value가 null이라면, 인자로 index를 가진 remove 메서드에 대한 단계를 호출하고, 이 단계들을 중단합니다.

  2. length컬렉션에 의해 나타나는 노드의 수로 둡니다.

  3. nindex에서 length를 뺀 값으로 둡니다.

  4. n이 0보다 크다면, HTMLOptionsCollection에 뿌리를 둔 select 요소(element)에 속성(attribute)이 없고 자식 도느가 없는 새로운 n-1 option 개 요소(element)들로 구성된 DocumentFragment추가(append)합니다.

  5. n이 0 이상이라면, valueselect 요소(element)에 추가(append)합니다. 그렇지 않으면, 컬렉션의 index째 요소(element)를 value바꿉니다.

add(element, before) must act according 메서드는 다음 알고리즘을 따라 동작해야(must)합니다:

  1. elementHTMLOptionsCollection에 뿌리를 둔 select 요소(element)의 조상이라면, HierarchyRequestError 예외를 던지고 이 단계들을 중단합니다..

  2. before가 요소(element)이고 그 요소(element)가 HTMLOptionsCollection에 뿌리를 둔 select 그 요소(element)의 후손이 아니라면, NotFoundError 예외를 던지고 이 단계들을 중단합니다.

  3. elementbefore가 동일한 요소(element)라면, 반환하고 이 단계들을 중단합니다.

  4. before가 노드라면reference를 그 노드로 둡니다. 그렇지 않고, before가 정수이고, 컬렉션에 before 번째 노드가 있다면, reference를 그 노드로 둡니다. 그렇지 않으면, reference를 null로 둡니다.

  5. reference가 null이 아니라면, parentreference의 부모 노드로 둡니다. 그렇지 않으면, parentHTMLOptionsCollection에 뿌리를 둔 select 요소(element)로 둡니다.

  6. 첫 번째 인자로 element와 두 번째 인자로 reference를 가지고 parent 노드에서 DOM insertBefore() 메서드가 동작된 것 처럼 동작시킵니다.

remove(index) 메서드는 다음 알고리즘을 따라 동작해야(must) 합니다:

  1. 컬렉션에 의해 나타나는 노드의 수가 0이라면, 이 단계들을 중단합니다.

  2. index가 0 이상이고 컬렉션에 의해 나타나는 노드의 수보다 작은 수가 아니라면, 이 단계들을 중단합니다.

  3. element를 컬렉션의 index 번째 요소(element)로 둡니다.

  4. 부모 노드로부터 element를 제거합니다.

selectedIndex IDL 속성(attribute)은 HTMLOptionsCollection에 뿌리를 둔 select 요소(element)에서 동일하게 이름이 붙은 속성(attribute)처럼 동작해야(must) 합니다.

2.7.3. DOMStringMap 인터페이스

DOMStringMap 인터페이스는 이름-값 쌍의 세트를 나타냅니다. 이것은 속성(property) 접근을 위한 스크립팅 언어의 네이티브 메커니즘을 사용하여 이것들을 노출합니다.

DOMStringMap 객체가 인스턴스화 되는 경우, 이름-값 쌍의 목록을 가져오는 것, 이름을 특정 값으로 설정 하는 것, 이름을 삭제하는 것, 3가지 알고리즘과 연관되어집니다.

[OverrideBuiltins]
interface DOMStringMap {
  getter DOMString (DOMString name);
  setter void (DOMString name, DOMString value);
  deleter void (DOMString name);
};

임의의 인스턴스에 DOMStringMap 객체에서 지원되는 속성(property) 이름은 반환되는 순서에 따라, 그 인스턴스에서 이름-값 쌍의 목록을 가져오는 알고리즘으로부터 반환된 각 쌍의 이름입니다.

DOMStringMap에서 명명된 속성(property) name의 값을 결정하기 위해, 유저 에이전트는 이름-값 쌍의 목록을 가져오는 알고리즘에 의해 반환된 목록에서 이름 컴포넌트가 name인 이름-값 쌍의 값 컴포넌트를 반환해야(must) 합니다.

명명된 속성(property) name의 값을 value 값으로 설정하기 위해, 이름을 특정한 값으로 설정하는 알고리즘은, 이름으로 name를 그리고 값으로 value를 전달하여 수행해야(must) 합니다.

기존의 명명된 속성(property) name을 삭제하기 위해, 이름을 삭제하는 알고리즘은 이름으로 name을 전달하여 수행해야(must) 합니다.

여기 DOMStringMap 인터페이스 정의는 자바스크립트 환경에 대해서만 의도되었습니다. 다른 언어 바인딩은 DOMStringMap이 그 언어들에 대해 구현되는 방법을 정의할 필요가 있을 것입니다.

요소(element)의 dataset 속성(attribute)은 요소(element)의 data-* 속성(attribute)을 노출합니다.

유사한 구조를 가진 다음 코드 조각과 요소(element)를 고려해 볼 때:

<img class="tower" id="tower5" data-x="12" data-y="5" data-ai="robotarget" data-hp="46" data-ability="flames" src="towers/rocket.png" alt="Rocket Tower">

...하나는 일부 인수를 취하는 함수 splashDamage()를 상상해 볼 수 있고, 첫 번째 인수는 처리할 요소(element)입니다:

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
  }
}

2.7.4. DOMElementMap 인터페이스

DOMElementMap 인터페이스는 이름-요소(elememt) 매핑 세트를 나타냅니다. 이것은 속성(property) 접근을 위한 스크립팅 언어의 네이티브 메커니즘을 사용하여 이것들을 노출합니다.

DOMElementMap 객체가 인스턴스화 되는 경우, 이름-요소(element) 매핑 목록을 가져오는 것, 이름을 특정 요소(element)에 매핑하는 것, 이름으로 매핑을 삭제하는 것, 3가지 알고리즘과 연관되어집니다.

interface DOMElementMap {
  getter Element (DOMString name);
  setter creator void (DOMString name, Element value);
  deleter void (DOMString name);
};

임의의 인스턴스에 DOMElementMap 객체에서 지원되는 속성(property) 이름은 반환되는 순서에 따라, 그 인스턴스에서 이름-요소(element) 매핑 목록을 가져오는 알고리즘으로부터 반환된 각 매핑에 대한 이름입니다.

DOMElementMap에서 명명된 속성(property) name의 값을 결정하기 위해, 유저 에이전트는 이름-요소(element)매핑 목록을 가져오는 알고리즘에 의해 반환된 목록에서 이름 컴포넌트가 name인 이름-요소(element) 매핑의 요소(element) 컴포넌트를 반환해야(must) 합니다.

새로운 혹은 기존의 명명된 속성(property) name의 값을 value 값으로 설정하기 위해, 이름을 특정 요소(element)에 매팽하기 위한 알고리즘은 이름을 name 요소(element)로 value를 전달하여 수행해야(must) 합니다.

기존의 명명된 속성(property) name을 삭제하기 위해, 매핑을 삭제하기 위한 알고리즘은 삭제될 매핑의 이름 컴포넌트로 name를 전달하여 수행해야(must) 합니다.

여기 DOMElementMap 인터페이스 정의는 자바스크립트 환경에 대해서만 의도되었습니다. 다른 언어 바인딩은 DOMElementMap이 그 언어들에 대해 구현되는 방법을 정의할 필요가 있을 것입니다.

2.7.5. 가비지 컬렉션

이미 존재하는 객체를 그 객체에 돌려주는 IDL 속성(attribute)로부터의 암묵적인 강한 참조가 있습니다.

예를 들어, Window 객체의 window.document 속성(attribute)은 Window 객체로부터 그것의 Document 객체로의 강한 참조가 있음을 의미합니다. 비슷하게, Document로부터 임의의 후손 노드로, 임의의 노드로부터 그 노드의 소유자 노드 문서로의 강한 참조가 항상 있습니다.

2.8. 네임스페이스

HTML 네임스페이스: http://www.w3.org/1999/xhtml

MathML 네임스페이스: http://www.w3.org/1998/Math/MathML

SVG 네임스페이스: http://www.w3.org/2000/svg

XLink 네임스페이스: http://www.w3.org/1999/xlink

XML 네임스페이스: http://www.w3.org/XML/1998/namespace

XMLNS 네임스페이스: http://www.w3.org/2000/xmlns/


스크립트를 수행하지 않고, CSS나 XPath 표현식을 평가하지 않고, 결과 DOM을 임의의 콘텐트에 노출시키지 않고 콘텐트에 연산을 수행하는 데이터 마이닝 툴과 다른 유저 에이전트는 실제로 상기 문자열을 노출하지 않고, 그들의 DOM 노드 아날로그가 특정 네임스페이스에 있다고 당연한 것으로 가정하여 "네임스페이스를 지원"할 수도 있습니다.


HTML 구문에서, 네임스페이스 접두어와 네임스페이스 선언은 XML에서와 동일한 효과를 가지지 않습니다. 예를 들어, 콜론은 HTML 요소(element) 이름에 특별한 의미(meaning)를 가지지 않습니다.

2.9. 구조화 된 데이터의 안전한 전달

이 명세는 자바스크립트 명세의 용어와 표기법을 사용합니다. [ECMA-262]

2.9.1. 복제 가능한 객체

복제 가능한 객체이벤트 반복 전반에 걸쳐 복제되는 것을 지원합니다. 즉, 다른 출처(origin)Document 전반을 포함하여 DocumentWorker 경계 전반에 걸쳐 복제되는 것을 지원합니다. 모든 객체가 복제 가능한 객체는 아니며 복제 가능한 객체의 모든 측면이 복제될 때 반드시 보존되는 것은 아닙니다.

플랫폼 객체는 다음의 내부 메서드를 가집니다:

[[Clone]] ( targetRealm, memory )

달리 지정하지 않는 한, [[Clone]] 내부 메서드를 호출하는 것은 "DataCloneError" DOMException을 던져야 합니다. (기본적으로, 플랫폼 객체복제 가능한 객체가 아닙니다.)

복제 가능한 객체플랫폼 객체는 일련의 단계들을 수행하도록 명시된 [[Clone]] 내부 메서드를 가집니다. 그 단계들을 수행한 결과는 targetRealm에 생성된, 던져진 예외나 this의 복제여야(must) 합니다. 그것들에 대해 복제가 의미하는 바를 정의하는 것은 그 객체들에 달려있습니다.

자바스크립트 명세에 정의된 객체들은 StructuredClone 추상 연산에 의해 직접 처리됩니다.

2.9.2. 전송 가능한 객체

전송 가능한 객체이벤트 반복 전반에 걸쳐 전송 되는 것을 지원합니다. 전송은 기본 데이터로의 참조를 공유하고 전송되는 객체를 분리하는 동안 효과적으로 객체를 다시 생성합니다. 이것은 비용이 많이 드는 리소스의 소유권을 전송하는데 유용합니다. 모든 객체가 전송 가능한 객체는 아니며 전송 가능한 객체의 모든 측면이 전송 될 때 반드시 보존되는 것은 아닙니다.

전송은 되돌릴 수 없고 비멱등 연산입니다. 일단 객체가 전송되면, 다시 전송되거나, 정말로 사용될 수 없습니다.

전송 가능한 객체플랫폼 객체는 [[Detached]] 내부 슬롯(slot)과 다음 내부 메서드를 가집니다:

[[Transfer]] ( targetRealm )

모든 플랫폼 객체가 [[Clone]] 내부 메서드를 가지는 반면, 모두가 [[Detached]] 내부 슬롯(slot)과 [[Transfer]] 내부 메서드를 가지지는 않습니다.

전송 가능한 객체플랫폼 객체는 반환 값과 함께 공유된 this의 기본 데이터를 가지고 targetRealm에서 생성된, 예외를 던지거나 this의 복제를 반환하는 [[Transfer]] 내부 메서드를 정의해야(must) 하고 this의 [[Detached]] 내부 슬롯 값을 true로 설정합니다. 그것들에 대해 전송이 의미하는 바를 정의하는 것은 그 객체들에 달려있습니다.

자바스크립트 명세에 정의된 객체는 StructuredCloneWithTransfer 추상 연산에 의해 직접 처리됩니다. (기술적으로, IsTransferableTransferHelper에 의해.)

2.9.3. StructuredCloneWithTransfer ( input, transferList, targetRealm )

  1. memory를 비어있는 맵으로 둡니다.

    메모리 맵의 목적은, 여기에서와 StructuredClone 추상 연산에서, 객체를 두 번 복제하는 것을 방지하는 것입니다. 이것은 주기와 그래프에서 중복 된 객체의 식별을 보존하게 합니다.

  2. transferList의 각 객체 transferable에 대해:

    1. IsTransferable(transferable) 가 false라면, "DataCloneError" DOMException를 던집니다.

    2. placeholder를 유저 에이전트 정의 플레이스홀더(user-agent-defined) 객체로 둡니다.

    3. transferable과 값 placeholder를 가지고 memory에 엔트리를 생성합니다.

  3. clone을 ? StructuredClone(input, targetRealm, memory)의 결과로 둡니다.

  4. outputTransferList을 새로운 비어있는 List로 둡니다.

  5. transferList 내 각 객체 transferable에 대해:

    1. placeholderResult를 키가 transferablememory 내 엔트리의 값으로 둡니다.

    2. transferResult를 ? TransferHelper(transferable, targetRealm)로 둡니다.

    3. clone 내에서, placeholderResult로의 참조를 transferResult로 교체하여, placeholderResult로의 참조를 보유하는 모든 것이 이제 transferResult로의 참조를 보유합니다.

      이것은 자바스크립트에 의해 정의된 프리미티브(primitive)에 대한 매우 드문 저수준(low-level) 연산입니다.

    4. outputTransferList의 마지막 요소(element)로 transferResult를 추가합니다.

  6. { [[Clone]]: clone, [[transferList]]: outputTransferList } 를 반환합니다.

본래 StructuredCloneWithTransfer 추상 연산은 "구조화된 복제" 알고리즘으로 알려져 있습니다. StructuredClone 추상 연산은 "내부 구조화된 복제" 알고리즘으로 알려져 있습니다. 현재 StructuredCloneWithTransfer 추상 연산에 의해 처리되는, 객체 전송은 Window 객체에서의 postMessage() 메서드와 MessagePort 객체에서의 Window/postMessage() 메서드의 알고리즘의 일부분에 의해 이전에 처리됩니다.

2.9.4. StructuredClone ( input, targetRealm [ , memory ] )

  1. memory가 제공되지 않았다면, memory를 비어있는 맵으로 둡니다.

  2. memory가 키 input를 가진 엔트리를 포함한다면, 엔트리의 값을 반환합니다.

  3. Type(input) 이 Undefined, Null, Boolean, String, Number라면, input을 반환합니다.

  4. Type(input) 이 Symbol이라면, "DataCloneError" DOMException를 던집니다.

  5. deepClone을 false로 둡니다.

  6. input이 [[BooleanData]] 내부 슬롯을 가진다면, output을 [[BooleanData]] 내부 슬롯 값이 input의 [[BooleanData]] 내부 슬롯 값인 targetRealm 내의 새로운 Boolean 객체로 둡니다.

  7. 그렇지 않고, input이 [[NumberData]] 내부 슬롯을 가진다면, output을 [NumberData]] 내부 슬롯 값이 input의 [[NumberData]] 내부 슬롯 값인 targetRealm 내의 새로운 Number 객체로 둡니다.

  8. 그렇지 않고, input이 [[StringData]] 내부 슬롯을 가진다면, output을 [[StringData]] 내부 슬롯 값이 input의 [[StringData]] 내부 슬롯 슬롯 값인 targetRealm 내의 새로운 String 객체로 둡니다.

  9. 그렇지 않고, input이 [[DateValue]] 내부 슬롯을 가진다면, output을 [[DateValue]] 내부 슬롯 값이 input의 [[DateValue]] 내부 슬롯 값인 targetRealm 내의 새로운 Date 객체로 둡니다.

  10. 그렇지 않고, input이 [[RegExpMatcher]] 내부 슬롯을 가진다면, output을 [[RegExpMatcher]] 내부 슬롯 값이 input의 [[RegExpMatcher]] 내부 슬롯 값이고 [[OriginalSource]] 내부 슬롯 값이 input의 [[OriginalSource]] 내부 슬롯 값이며 [[OriginalFlags]] 내부 슬롯 값이 input의 [[OriginalFlags]] 내부 슬롯 값인 targetRealm 내의 새로운 RegExp 객체로 둡니다.

  11. 그렇지 않고, input이 [[ArrayBufferData]] 내부 슬롯을 가진다면:

    1. IsDetachedBuffer(input)가 true라면, "DataCloneError" DOMException를 던집니다.

    2. outputArrayBuffertargetRealm 내의 %ArrayBuffer% 내장 객체로 둡니다.

    3. output을 ? CloneArrayBuffer(input, 0, outputArrayBuffer)로 둡니다.

  12. 그렇지 않고, input이 [[ViewedArrayBuffer]] 내부 슬롯을 가진다면:

    1. bufferinput의 [[ViewedArrayBuffer]] 내부 슬롯의 값으로 둡니다.

    2. bufferClone을 ? StructuredClone(buffer, targetRealm, memory)}}로 둡니다.

    3. input이 [[DataView]] 내부 슬롯을 가진다면, output을 [[DataView]] 내부 슬롯 값이 true이고, [[ViewedArrayBuffer]] 내부 슬롯 값이 bufferClone이고, [[ByteLength]] 내부 슬롯 값이 input의 [[ByteLength]] 내부 슬롯 값이며, [[ByteOffset]] 내부 슬롯 값이 input의 [[ByteOffset]] 내부 슬롯 값인 targetRealm 내의 새로운 DataView 객체로 둡니다.

    4. 그렇지 않으면

      1. Assert: input은 [[TypedArrayName]] 내부 슬롯을 가집니다.

      2. constructortargetRealminput의 [[TypedArrayName]] 내부 슬롯의 값에 대한 TypedArray 생성자 표의 열 1에 나열된 내부 객체로 둡니다.

      3. byteOffsetinput의 [[ByteOffset]] 내부 슬롯 값으로 둡니다.

      4. lengthinput의 [[ArrayLength]] 내부 슬롯 값으로 둡니다.

      5. output을? TypedArrayCreate(constructor, « bufferClone, byteOffset, length »)로 둡니다.

  13. 그렇지 않고, input이 [[MapData]] 내부 슬롯을 가진다면:

    1. output을 [[MapData]] 내부 슬롯 값이 새로운 비어있는 ListtargetRealm 내의 새로운 Map 객체로 둡니다.

    2. deepClone를 true로 설정합니다.

  14. 그렇지 않고, input이 [[SetData]] 내부 슬롯을 가진다면:

    1. output을 [[SetData]] 내부 슬롯 값이 새로운 비어있는 ListtargetRealm 내의 새로운 Set 객체로 둡니다.

    2. deepClone을 true로 둡니다.

  15. 그렇지 않고, input이 배열 외래(exotic) 객체 라면:

    1. inputLenOrdinaryGetOwnProperty(input, "length")로 둡니다.[[value]].

    2. outputPrototargetRealm%ArrayPrototype% 내장 객체로 둡니다.

    3. output을 ! ArrayCreate(inputLen, outputProto)로 둡니다.

    4. deepClone을 true로 둡니다.

  16. 그렇지 않고, input이 [[Clone]] 내부 메서드를 가진다면, output을 ? input로 둡니다. [[Clone]](targetRealm, memory).

  17. 그렇지 않고, IsCallable(input)}}이 true라면, "DataCloneError" DOMException을 던집니다.

  18. 그렇지 않고, input이 [[Prototype]]나 [[Extensible]] 외 다른 어떤 내부 슬롯을 가진다면 "DataCloneError" DOMException을 던집니다.

    예를 들어, [[PromiseState]]나 [[WeakMapData]] 내부 슬롯.

  19. 그렇지 않고, input이 외래(exotic) 객체라면, "DataCloneError" DOMException을 던집니다.

    예를 들어, 프록시(proxy) 객체.

  20. 그렇지 않으면:

    1. outputtargetRealm 내 새로운 객체로 둡니다.

    2. deepClone를 true로 둡니다.

  21. memory whose 키가 input이고 값이 outputmemory 내 엔트리를 생성합니다.

  22. deepClone이 true라면:

    1. input [[MapData]] 내부 슬롯이라면:

      1. inputListinput의 [[MapData]] 내부 슬롯의 값으로 둡니다.

      2. copiedList을 새로운 비어있는 List로 둡니다.

      3. inputList의 요소(element)인 각 Record { [[key]], [[value]] } entry에 대해 반복하여,

        1. copiedEntry을 새로운 Record { [[key]]: entry.[[key]], [[value]]: entry.[[value]] }로 둡니다.

        2. copiedEntry.[[key]] 가 비어있지 않다면, copiedList의 마지막 요소(element)로 copiedEntry를 추가(append)합니다.

      4. outputListoutput의 [[MapData]] 내부 슬롯의 값으로 둡니다.

      5. copiedList의 요소(element)인 각 Record { [[key]], [[value]] } entry에 대해 반복하여,

        1. outputKey를 ? StructuredClone(entry.[[key]], targetRealm, memory)로 둡니다.

        2. outputValue를 ? StructuredClone(entry.[[value]], targetRealm, memory)로 둡니다.

        3. outputList의 마지막 요소(element)로 { [[key]]: outputKey, [[value]]: outputValue }를 추가합니다.

    2. 그렇지 않고, input이 [[SetData]] 내부 슬롯을 가진다면:

      1. copiedListinput의 [[SetData]] 내부 슬롯의 값의 복제로 둡니다.

      2. outputListoutput의 [[SetData]] 내부 슬롯의 값으로 둡니다.

      3. 비어있지 않은 copiedList의 요소(element)인 각 entry에 대해,

        1. outputEntry을 ? StructuredClone(entry, targetRealm, memory)로 둡니다.

        2. outputList의 마지막 요소(element)로 outputEntry를 추가합니다.

    3. 그렇지 않으면:

      1. enumerableKeys를 새로운 비어있는 List로 둡니다.

      2. ! input.[[OwnPropertyKeys]]() 내 각 key 에 대해:

        1. Type(key)이 String이라면:

          1. inputDesc를 ! input.[[GetOwnProperty]](key)로 둡니다.

          2. inputDesc.[[Enumerable]]가 true라면, enumerableKeys의 마지막 요소(element)로 key를 추가합니다

      3. enumerableKeys 내 각 key에 대해:

        1. ! HasOwnProperty(input, key)가 true라면:

          1. inputValue를 ? input.[[Get]](key, input)로 둡니다.

          2. outputValue를 ? StructuredClone(inputValue, targetRealm, memory)로 둡니다.

          3. ? CreateDataProperty(output, key, outputValue)를 수행합니다.

  23. output을 반환합니다.

targetRealm이 다른 이벤트 반복에 있을 수 있고 StructuredCloneWithTransferStructuredClone을 호출하는 코드에 쉽게 접근할 수 없을 수 있기 때문에, 일반적인 구현에서는 targetRealm 내 객체의 생성을 구현하기 위해 일종의 직렬화와 정리하는 것을 사용하는 것이 필요할 것입니다.

2.9.5. IsTransferable ( O )

  1. Assert: Type(O)은 객체입니다.

  2. O가 [[ArrayBufferData]] 내부 슬롯을 가진다면:

    1. IsDetachedBuffer(O)가 true라면, false를 반환합니다.

    2. true를 반환합니다.

  3. 그렇지 않고, O가 [[Detached]] 내부 슬롯을 가진다면:

    1. O의 [[Detached]] 내부 슬롯 값이 true라면, false를 반환합니다.

    2. true를 반환합니다.

  4. false를 반환합니다.

2.9.6. TransferHelper ( input, targetRealm )

  1. input가 [[ArrayBufferData]] 내부 슬롯을 가진다면:

    1. output을 [[ArrayBufferByteLength]] 내부 슬롯 값이 input의 [[ArrayBufferByteLength]] 내부 슬롯 값이고 [[ArrayBufferData]] 내부 슬롯 값이 input의 [[ArrayBufferData]] 내부 슬롯 값인 targetRealm내의 새로운 ArrayBuffer 객체로 둡니다.

    2. ! DetachArrayBuffer(input)을 수행합니다.

    3. output을 반환합니다.

  2. ? input.[[Transfer]](targetRealm)를 반환합니다.

3. HTML 문서의 의미론, 구조, API

3.1. 문서

HTML 유저 에이전트에서 모든 XML과 HTML 문서는 Document 객체로 표현됩니다. [DOM]

문서의 주소Document와 연관된 URL입니다(DOM 표준에 정의된 대로). 그것은 Document가 생성될 때 초기에 설정되지만, Document의 수명 기간 동안 변경될 수 있습니다; 예를 들어, 사용자가 페이지의 문서 조각으로 이동할 때 그리고 pushState() 메서드가 새로운 URL을 가지고 호출 될 때 변경됩니다. [DOM]

대화형 유저 에이전트들은 보통 유저 인터페이스에 문서의 주소를 노출합니다. 이것은 사이트가 다른 사람으로 가장하려하는지를 사용자가 알 수 있는 주된 메커니즘입니다.

DocumentcreateDocument()createHTMLDocument() API를 사용하여 스크립트에 의해 생성되는 경우, 문서의 주소는 스크립트의 설정 객체에 의해 명시된 신뢰할 수 있는 문서문서의 주소와 동일하고, Document는 즉시 로딩 후 작업에 대해 준비되며 완전히 로드됩니다.

문서의 리퍼러Document가 생성될 때 설정될 수 있는 절대 URL입니다. 이것이 명시적으로 설정되지 않는다면, 그 값은 빈 문자열입니다.

Document 객체는 처음에는 설정되어 있지 않은 리로드 재정의 플래그를 가집니다. 이 플래그는 특정한 상황에서 document.open()document.write() 메서드에 의해 설정됩니다. 플래그가 설정 되는 경우, Document는 리로드 될 때 문서의 소스로 사용되는 유니코드 문자열인 리로드 재정의 버퍼를 가집니다.

유저 에이전트가 소스 브라우징 컨텍스트가 주어진, 재정의 된 리로드를 수행하려면, 다음과 같이 동작해야(must) 합니다:

  1. source브라우징 컨텍스트활성 문서리로드 재정의 버퍼의 값으로 둡니다.

  2. address브라우징 컨텍스트활성 문서URL로 둡니다.

  3. HTTPS state브라우징 컨텍스트활성 문서HTTPS 상태로 둡니다.

  4. CSP list브라우징 컨텍스트활성 문서CSP 목록으로 둡니다.

  5. 브라우징 컨텍스트예외 활성화 플래그교체 활성화를 가지고 bodysource이고, CSP 목록CSP list이고 HTTP 상태HTTPS state인 새로운 응답으로 이동합니다. 소스 브라우징 컨텍스트재정의 된 리로드 알고리즘에 주어진 것입니다. 이동 알고리즘이 이 목적을 위해 Document 객체를 생성할 경우, 그 Document리로드 재정의 플래그를 설정하고 그것의 리로드 재정의 버퍼source로 설정합니다. 모든 예외를 다시 던집니다.

    이동 알고리즘에서 문서의 주소를 설정할 때가 되면, 재정의 URLaddress를 사용합니다.

3.1.1. Document 객체

DOM 명세는 Document 인터페이스를 정의하고, 이 명세는 이를 크게 확장합니다:

enum DocumentReadyState { "loading", "interactive", "complete" };

[OverrideBuiltins]
partial /*sealed*/ interface Document {
  // resource metadata management
  [PutForwards=href, Unforgeable] readonly attribute Location? location;
  attribute DOMString domain;
  readonly attribute DOMString referrer;
  attribute DOMString cookie;
  readonly attribute DOMString lastModified;
  readonly attribute DocumentReadyState readyState;

  // DOM tree accessors
  getter object (DOMString name);
  attribute DOMString title;
  attribute DOMString dir;
  attribute HTMLElement? body;
  readonly attribute HTMLHeadElement? head;
  [SameObject] readonly attribute HTMLCollection images;
  [SameObject] readonly attribute HTMLCollection embeds;
  [SameObject] readonly attribute HTMLCollection plugins;
  [SameObject] readonly attribute HTMLCollection links;
  [SameObject] readonly attribute HTMLCollection forms;
  [SameObject] readonly attribute HTMLCollection scripts;
  NodeList getElementsByName(DOMString elementName);
  readonly attribute HTMLScriptElement? currentScript;

  // dynamic markup insertion
  Document open(optional DOMString type = "text/html", optional DOMString replace = "");
  WindowProxy open(DOMString url, DOMString name, DOMString features, optional boolean replace = false);
  void close();
  void write(DOMString... text);
  void writeln(DOMString... text);

  // user interaction
  readonly attribute WindowProxy? defaultView;
  readonly attribute Element? activeElement;
  boolean hasFocus();
  attribute DOMString designMode;
  boolean execCommand(DOMString commandId, optional boolean showUI = false, optional DOMString value = "");
  boolean queryCommandEnabled(DOMString commandId);
  boolean queryCommandIndeterm(DOMString commandId);
  boolean queryCommandState(DOMString commandId);
  boolean queryCommandSupported(DOMString commandId);
  DOMString queryCommandValue(DOMString commandId);

  // special event handler IDL attributes that only apply to Document objects
  [LenientThis] attribute EventHandler onreadystatechange;
};
Document implements GlobalEventHandlers;
Document implements DocumentAndElementEventHandlers;

Document는 초기에 "none"인 HTTP 상태 (HTTPS 상태 값)를 가지고, 이것은 Document의 데이터를 전달하는데 사용된 네트워크 채널의 보안 속성(property)들을 나타냅니다.

DocumentCSP 목록을 가지고, 이것은 이 컨텍스트에서 콘텐트 보안 정책의 목록입니다. 달리 명시되지 않는 한 목록은 비어있습니다.

3.1.2. 리소스 메타데이터 관리

document . referrer
사용자가 이 문서로 이동한 문서로부터, 차단되어 있거나 그러한 문서가 없지 않은 한, Document주소를 반환하고, 그러한 경우에는 빈 문자열을 반환합니다.

noreferrer 링크 유형은 리퍼러를 차단하는 데 사용될 수 있습니다.

referrer 속성(attribute)은 문서의 리퍼러를 반환해야(must) 합니다.

document . cookie [ = value ]
Document에 적용되는 HTTP 쿠키를 반환합니다. 쿠키가 없거나 이 리소스에 쿠키가 적용될 수 없다면, 빈 문자열이 반환 될 것입니다.

새로운 쿠키를 요소(element)의 HTTP 쿠키 세트에 추가하기 위해, 설정 될 수 있습니다.

콘텐츠가 고유 출처(origin)에 샌드박스 되었다면 (예를 들어, sandbox 속성(attribute)를 가진 iframe안에), 가져올 때와 설정할 때 "SecurityError" DOMException이 던져질 것입니다.

cookie 속성(attribute)은 문서 주소에 의해 식별되는 리소스의 쿠키를 나타냅니다.

다음 조건 중 하나로 분류되는 Document 객체는 쿠키를 거부하는 Document 객체입니다:

가져올 때, 문서가 쿠키를 거부하는 Document 객체라면, 유저 에이전트는 빈 문자열을 반환해야(must) 합니다. 그렇지 않고, Document출처(origin)불분명한 출처(origin)라면, 유저 에이전트는 "SecurityError" DOMException를 던져야(must) 합니다. 그렇지 않으면, 유저 에이전트는 "non-HTTP" API를 위해 BOM 없는 UTF-8 디코드를 사용하여 디코드 된 문서의 주소에 대한 쿠키 문자열을 반환해야(must) 합니다. [COOKIES] (이것은 지문 그림입니다.)

설정할 때, 문서가 쿠키를 거부하는 Document 객체라면, 유저 에이전트는 아무 것도 하지 않아야(must) 합니다. 그렇지 않고, Document출처(origin)불분명한 출처(origin)이라면, 유저 에이전트는 "SecurityError" DOMException를 던져야 합니다. 그렇지 않으면, 유저 에이전트는 UTF-8로 인코드 된 새로운 값으로 구성하여, "non-HTTP" API를 통해 문서의 주소에 대해 설정 쿠키 문자열을 받는 경우와 같이 동작해야(must) 합니다. [COOKIES] [ENCODING]

cookie 속성(attribute)은 프레임 전반에 접근이 가능하기 때문에, 쿠키에 대한 경로 제한은 사이트의 어느 부분으로 어떤 쿠키가 전송되는지를 관리하는데 도움이 되는 도구일 뿐이고, 어떤 방식으로든 보안 기능이 아닙니다.

cookie 속성(attribute)의 getter와 setter는 동기적으로 공유 된 상태에 접근합니다. 잠금 매커니즘이 없기 때문에, 다중 프로세스 유저 에이전트에서 다른 브라우징 컨텍스트는 스크립트가 수행되는 중에 쿠키를 수정할 수 있습니다. 예를 들어, 사이트는 쿠키 값을 읽고, 그 값을 증가시키고, 세션에 대한 고유 식별자로서 쿠키의 새로운 값을 사용하여, 다시 그것을 작성하는 것을 시도할 수 있습니다; 사이트가 동시에 두 개의 다른 브라우저에서 이것을 두 번 수행한다면, 잠재적으로 형편없는 영향을 가지고, 양쪽 세션에 대해 동일한 "고유" 식별자를 사용하게 됩니다.


document . lastModified
사용자의 로컬 표준 시간대에 따라, "MM/DD/YYYY hh:mm:ss" 형식으로 서버에 의해 보고 된 대로, 문서에 대한 마지막 수정한 날짜를 반환합니다.

마지막 수정 날짜가 알 수 없다면, 현재 시간이 대신 반환됩니다.

가져올 때, lastModified 속성(attribute)은 사용자의 로컬 표준 시간대에 따라 Document의 소스 파일의 마지막 수정 날짜와 시간을 다음 형식 에 따라 반환해야(must) 합니다:
  1. 날짜의 월 컴포넌트.

  2. U+002F 슬래쉬 문자 (/).

  3. 날짜의 일 컴포넌트.

  4. U+002F 슬래쉬 문자 (/).

  5. 날짜의 연 컴포넌트

  6. U+0020 공백 문자.

  7. 시간의 시 컴포넌트.

  8. U+003A 콜론 문자 (:).

  9. 시간의 분 컴포넌트.

  10. U+003A 콜론 문자 (:).

  11. 시간의 초 컴포넌트.

연도를 제외한, 위 모든 숫자 컴포넌트는 필요하다면 0을 채워, 10 진수 숫자를 나타내는 두 ASCII 숫자로 주어져야(must) 합니다. 연도는 필요하다면 0을 채워, 10 진수 숫자를 나타내는 4개 이상의 ASCII 숫자의 가능한 가장 짧은 문자열로 주어져야 합니다.

Document의 소스 파일의 마지막 수정 날짜와 시간은 사용된 네트워크 프로토콜의 관련 기능으로부터, 예를 들어, 문서의 HTTP Last-Modified 헤더의 값으로부터, 혹은 로컬 파일에 대한 파일 시스템 메타데이터로부터 얻어져야(must) 합니다. 마지막 수정 날짜와 시간을 알 수 없다면, 속성(attribute)은 위 형식에 따라 현재 날짜와 시간을 반환해야(must) 합니다.


document . readyState
Document가 로딩되는 동안 "loading"을, 일단 해석이 끝났으나 아직 서브-리소스를 로딩 중에는 "interactive"를, 로드가 완료되었다면 "complete"를 반환합니다.

이 값이 바뀔 경우 Document 객체에서 readystatechange 이벤트가 발생합니다.

각 문서는 현재 문서 준비상태를 가집니다. Document 객체가 생성될 때, 문서가 HTML 해석기, XML 해석기, 혹은 XSLT 처리기와 연관된다면 Document는 문자열 "loading"로, 그렇지 않으면 문자열 "complete"로 설정 된 그것의 현재 문서 준비상태를 가져야(must) 합니다. 페이지 로딩 동안 다양한 알고리즘은 이 값에 영향을 끼칩니다. 값이 설정된 경우, 유저 에이전트는 Document 객체에 readystatechange로 명명된 단순한 이벤트를 발생 시켜야(must) 합니다.

Document는 아직 멈추거나 중단 되지 않은 HTML 해석기XML 해석기와 연관된다면 활성화 해석기를 가진다고 합니다.

readyState IDL 속성(attribute)은 가져올 때, 현재 문서 준비상태를 반환해야(must) 합니다.

3.1.3. DOM 트리 접근자

문서의 html 요소(element)는 문서의 루트 요소(element)가 하나 존재하고 그것이 html 요소(element)라면 문서의 루트 요소(element)이고, 그렇지 않으면 null입니다.


document . head
head 요소(element)를 반환합니다.

문서의 head 요소(element)는 html 요소(element)의 자식인 첫 번째 head 요소(element)가 하나 존재한다면 문서의 head 요소(element)이고, 그렇지 않으면 null 입니다.

head 속성(attribute)은, 가져올 때, 문서의 must return head 요소(element) (head 요소(element)나 null)를 반환해야(must) 합니다.

document . title [ = value ]
HTML에 대해 title 요소(element)에 의해 주어진 대로, SVG에 대해 SVG title 요소(element)에 의해 주어진 대로, 문서의 제목을 반환합니다.

문서의 제목을 업데이트하기 위해, 설정될 수 있습니다. 업데이트를 위한 적절한 요소(element)가 없다면, 새로운 값은 무시됩니다.

문서의 title 요소(element)는 문서에 하나만 존재한다면 문서의 첫 번째 title 요소(element)이고 (트리 순서에 따라), 그렇지 않으면 null 입니다.

title 속성(attribute)은 가져올 때, 다음 알고리즘을 수행해야(must) 합니다:
  1. 루트 요소(element)SVG 네임스페이스에 있는 svg 요소(element)라면 value루트 요소(element)의 자식인 SVG 네임스페이스에 있는 첫 번째 title 요소(element)의 모든 자식 Text 노드의 데이터의 연결로 둡니다. [SVG11]

  2. 그렇지 않으면, value트리 순서에 따라 title 요소(element)의 모든 자식 Text 노드의 데이터의 연결로 두고, title 요소(element)가 null 이라면 빈 문자열로 둡니다.

  3. value에서 여백 문자를 들어내고 병합합니다.

  4. value를 반환합니다.

설정할 때, 다음 목록의 처음 일치하는 조건에 해당하는 단계를 수행해야(must) 합니다:

루트 요소(element)SVG 네임스페이스에 있는 svg 요소(element)라면 [SVG11]
  1. element루트 요소(element)의 자식인 SVG 네임스페이스에 있는 첫 번째 title 요소(element)가 있다면, 그것으로 둡니다. 그것이 없다면, SVG 네임스페이스title 요소(element)를 생성하고, 루트 요소(element)의 첫 번째 자식으로 추가하고, element를 그 요소(element)로 둡니다. [SVG11]

  2. elementtextContent IDL 속성(attribute)이 할당되는 새로운 값으로 설정된 것 처럼 동작합니다.

루트 요소(element)HTML 네임스페이스에 있다면
  1. title 요소(element)가 null이고 head 요소(element)가 null이라면, 이 단계들을 중단합니다.

  2. title 요소(element)가 null이라면, 새로운 title 요소(element)를 생성하고 head 요소(element)에 추가(append)하고, element를 새롭게 생성된 요소(element)로 둡니다; 그렇지 않으면, elementtitle 요소(element)로 둡니다.

  3. elementtextContent IDL 속성(attribute)이 할당되는 새로운 값으로 설정된 것 처럼 동작합니다.

그렇지 않으면
아무 것도 하지 않습니다.

document . body [ = value ]
body 요소(element)를 반환합니다.

body 요소(element)를 바꾸기 위해, 설정 될 수 있습니다.

새로운 값이 bodyframeset 요소(element)가 아니라면, 이것은 HierarchyRequestError 예외를 던질 것입니다.

문서의 body 요소(element)는 html 요소(element)의 첫 번째 자식인 body 요소(element)나 frameset 요소(element)입니다. 그러한 요소(element)가 없다면, null입니다.

body 속성(attribute)은 가져올 때, 문서의 body 요소(body 요소(element)나 frameset 요소(element)나 null)를 반환해야 합니다. 설정할 때, 다음 알고리즘을 수행해야 합니다:
  1. 새로운 값이 bodyframeset 요소(element)가 아니라면, HierarchyRequestError 예외를 던지고 이 단계들을 중단합니다.

  2. 그렇지 않고, 새로운 값이 body 요소(element)와 동일하다면, 아무것도 하지 않습니다. 이 단계들을 중단합니다.

  3. 그렇지 않고, body 요소(element)가 null이 아니라면, 루트 요소(element)의 replaceChild() 메서드가 그것의 두 인자로 각각 새로운 값과 기존 body 요소(element)를 가지고 호출된 것 처럼, 그 요소(element)를 DOM에 새로운 값으로 바꾸고, 이 단계들을 중단합니다.

  4. 그렇지 않고, 루트 요소(element)가 없다면, HierarchyRequestError 예외를 던지고 이 단계들을 중단합니다.

  5. 그렇지 않으면, body 요소(element)는 null이지만, 루트 요소(element)는 존재합니다. 루트 요소(element)에 새로운 값을 추가(append)합니다.


document . images
Document에 있는 img 요소(element)들의 HTMLCollection을 반환합니다.
document . embeds
document . plugins
Document에 있는 embed 요소(element)들의 HTMLCollection을 반환합니다.
document . links
Document에 있는 href 속성(attribute)을 가진 aarea 요소(element)들의 HTMLCollection을 반환합니다.
document . forms
Document에 있는 form 요소(element)들의 HTMLCollection을 반환합니다.
document . scripts
Document에 있는 script 요소(element)들의 HTMLCollection을 반환합니다.
images 속성(attribute)은 Document 노드에 뿌리를 둔 HTMLCollection을 반환해야(must) 하고, 이 속성(attribute)의 필터는 img 요소(element)들과만 일치합니다.

embeds 속성(attribute)은 Document 노드에 뿌리를 둔 HTMLCollection을 반환해야(must) 하고, 이 속성(attribute)의 필터는 embed 요소(element)들과만 일치합니다.

plugins 속성(attribute)은 embeds 속성(attribute)에 의해 반환된 것과 동일한 객체를 반환해야(must) 합니다.

links 속성(attribute)은 Document 노드에 뿌리를 둔 HTMLCollection을 반환해야(must) 하고, 이 속성(attribute)의 필터는 href 속성(attribute)을 가진 a 요소(element)들과 href 속성(attribute)을 가진 area 요소(element)들과만 일치합니다.

forms 속성(attribute)은 Document 노드에 뿌리를 둔 HTMLCollection을 반환해야(must) 하고, 이 속성(attribute)의 필터는 form 요소(element)들과만 일치합니다.

scripts 속성(attribute)은 Document 노드에 뿌리를 둔 HTMLCollection을 반환해야(must) 하고, 이 속성(attribute)의 필터는 script 요소(element)들과만 일치합니다.


collection = document . getElementsByName(name)
Document에 있는 값 name를 가진 name 속성(attribute)을 가진 요소(element)들의 NodeList를 반환합니다.
getElementsByName(name) 메서드는 문자열 name을 사용하고, 트리 순서에 따라, 그 문서 내의 값이 인자 name과 동일한 (대소문자 구분 방법으로) name 속성(attribute)를 가진 모든 html 요소(element)들을 포함하는 존속되는 NodeList를 반환해야(must) 합니다. 메서드가 Document 객체에서 동일한 인자를 가지고 다시 호출 되는 경우, 유저 에이전트는 이전 호출에 의해 반환된 객체와 동일한 객체를 반환할 수도 있습니다. 다른 경우에는 새로운 NodeList 객체가 반환되어야(must) 합니다.

document . currentScript
현재 실행중인 script 요소(element)를 반환합니다. 재진입 script 실행의 경우, 아직 실행을 완료하지 않은 스크립트 중에서 가장 최근에 실행이 시작된 스크립트를 반환합니다.

Document가 현재 script 요소(element)를 실행 중이 아니라면 (예를 들어, 수행 중인 스크립트가 이벤트 처리기나 타임 아웃되었기 때문에) null을 반환합니다.

currentScript 속성(attribute)은 가져올 때, 가장 최근에 초기화 된 값을 반환해야(must) 합니다. Document가 생성될 때, currentScript는 null로 초기화 되어야(must) 합니다.

Document 인터페이스는 명명된 속성(property)들을 지원합니다. 어느 순간에 지원되는 속성(property) 이름들Document 안에 있는 비어 있지 않은 name 콘텐트 속성(attribute)을 가진 모든 applet, 노출 된 embed, form, iframe, img, 노출된 object 요소(element)들의 name 콘텐트 속성(attribute)들의 값들과, Document 안에 있는 비어 있지 않은 id 콘텐트 속성(attribute)을 가진 모든 applet노출된 object 요소(element)들의 id 콘텐트 속성(attribute)들의 값들과, Document 안에 있는 비어 있지 않은 name 콘텐트 속성(attribute)과 비어있지 않은 id 콘텐트 속성(attribute)을 가진 모든 img 요소(element)들의 id 콘텐트 속성(attribute)들의 값들로 구성됩니다. 지원되는 속성(property) 이름들은 동일한 요소(element)가 id 속성(attribute)과 name 속성(attribute) 모두를 제공하는 경우 name 속성(attribute)으로부터의 값 앞에 오는 id 속성(attribute)의 값을 가지고, 나중의 중복을 무시하여, 트리 순서에 따라야(must) 합니다.

Document 객체가 속성(property) 검색(retrieval)을 위해 인덱싱 되는 경우 명명된 속성(property) name의 값을 결정하기 위해, 유저 에이전트는 다음 단계들을 사용하여 얻어진 값을 반환해야(must) 합니다:

  1. elementsDocument에 이름 name을 가진 명명된 요소(element)들의 목록으로 둡니다.

    명세에 의해, 적어도 하나의 그러한 요소(element)가 존재할 것입니다.

  2. elements가 하나의 요소(element)만을 가지고, 그 요소(element)가 iframe 요소(element)라면, 그 iframe 요소(element)에 의해 나타나는 중첩된 브라우징 컨텍스트WindowProxy 객체를 반환하고, 이 단계들을 중단합니다.

  3. 그렇지 않고, elements가 하나의 요소(element)만을 가진다면, 그 요소(element)를 반환하고, 이 단계들을 중단합니다.

  4. 그렇지 않으면 Document에 뿌리를 둔, 필터가 이름 name를 가진 명명된 요소(element)들에만 일치하는 HTMLCollection를 반환합니다.

위 알고리즘의 목적을 위해 이름 name을 가진 명명된 요소(element)들은 다음 중 하나입니다:

  • 값이 namename 콘텐트 속성(attribute)을 가지는 applet, 노출 된 embed, form, iframe, img, 노출 된 object 요소(element)들, 혹은,

  • 값이 nameid 콘텐트 속성(attribute)을 가지는 applet 또는 노출 된 object 요소(element)들

  • 값이 nameid 콘텐트 속성(attribute)을 가지고, 비어 있지 않은 name 콘텐트 속성(attribute)도 가지는 img 요소(element)들

embedobject 요소(element)는 노출 된 조상 object를 가지지 않고, object 요소(element)에 대해 추가적으로 요소의 폴백 콘텐트가 보이지 않거나 후손 objectembed를 가지지 않는다면 노출 되었다라고 합니다.


Document 인터페이스에서 dir 속성(attribute)은 dir 콘텐트 속성(attribute)과 함께 정의됩니다.

3.1.4. XML 문서 로딩

partial interface XMLDocument {
  boolean load(DOMString url);
};

load(url) 메서드는 다음 단계들을 수행해야(must) 합니다:

  1. document를 메서드가 호출되는 XMLDocument 객체로 둡니다.

  2. url을, relative to the 엔트리 설정 객체에 관련하여 해석합니다. 이것이 성공적이지 않다면, "SyntaxError" DOMException를 던지고 이 단계들을 중단합니다. 그렇지 않으면, urlRecord결과 URL 레코드로 둡니다.

  3. urlRecord출처(origin)document출처(origin)와 동일한 것이 아니라면, "SecurityError" DOMException를 던지고 이 단계들을 중단합니다.

  4. 어떤 변경 이벤트도 발생시키지 않고, document의 모든 자식 노드들을 제거합니다.

  5. document현재 문서 준비상태를 "loading" 으로 설정합니다.

  6. 병렬로 이 단계들의 나머지를 수행하고, 메서드로부터 true를 반환합니다.

  7. resultDocument 객체로 둡니다.

  8. success를 false로 둡니다.

  9. requestURLurlRecord이고 클라이언트엔트리 설정 객체이고, 목적지가 "subresource"이며, 동기 플래그가 설정되고, 모드가 "same-origin", 자격 증명 모드가 "same-origin"이고, URL 자격 증명 사용 플래그가 설정 된 새로운 요청으로 둡니다

  10. responserequest가져 온 결과로 둡니다.

  11. responseContent-Type 메타데이터XML MIME 타입이라면, 이 하위 단계들을 수행합니다:

    1. result 문서와 연관된 새로운 XML 해석기를 생성합니다.

    2. 이 해석기 response본문을 전달합니다.

    3. XML well-formedness나 XML 네임스페이스 well-formedness 오류가 있다면, result로부터 모든 자식 노드들을 제거합니다. 그렇지 않으면, success를 true로 둡니다.

  12. 다음 단계들을 수행하기 위한 작업을 대기열에 넣습니다.

    1. document현재 문서 준비상태를 "complete"로 설정합니다.

    2. 새로운 자식을 포함하는 DocumentFragment가 삽입 된 것처럼 변경 이벤트를 발생하여, document의 모든 자식을 result의 자식으로 바꿉니다 (그것이 자식을 가지지 않는다 하더라도).

    3. documentload라는 단순한 이벤트를 발생시킵니다.

3.2. 요소(element)

3.2.1. 의미론(semantic)

HTML에서 요소(element), 속성(attribute), 속성 값(attribute value)은 정의 된 (이 명세에 의해) 특정한 의미(semantic)을 가집니다. 예를 들어, ol 요소(element)는 순서가 있는 목록을 나타내고, lang 속성(attribute)은 콘텐트의 언어를 나타냅니다.

이 정의는 웹 브라우저와 검색 엔진 같은 HTML 처리기가 다른 컨텍스트에서 문서와 어플리케이션을 일관되게 표현하는 것을 허용합니다.

이 예제에서 HTML 제목(heading)은 데스크탑 브라우저에서 큰 텍스트로, 또는 모바일 브라우저에서 굵은 일반 사이즈 텍스트로 보여질 수 있습니다. 두 경우 모두에서 의미론적 정보는 모두 동일하게 남겨집니다 - h1h2 요소(element)들은 제목(heading)을 나타냅니다.
<!doctype html>
<html lang="en">
  <head>
    <title>Favorite books</title>
  </head>
      <body>
    <header>
      <img src="logo.png" alt="Favorite books logo">
    </header>
    <main>
      <h1>Favorite books</h1>
      <p>These are a few of my favorite books.</p>
      <h2>The Belgariad</h2>
      <p>Five books by David and Leigh Eddings.</p>
      <h2>The Hitchhiker’s Guide to the Galaxy</h2>
      <p>A trilogy of five books by Douglas Adams.</p>
    </main>
  </body>
</html>

이 의미론적 정보는 보조 기술에 있어 매우 중요합니다. 예를 들어, 스크린 리더(screen reader)는 브라우저에 의미론적 정보를 질의하고 음성 낭독으로 문서나 어플리케이션을 표시하기 위해 그 정보를 사용합니다.

어떤 경우에 보조 기술은 추가적인 기능을 제공하기 위해 의미론적인 정보를 사용합니다. 음성 인식 도구는 예를 들어 main 요소(element)의 시작 지점으로 초점을 이동하기 위한 음성 명령을 제공 할 수 있습니다.

적절한 HTML 요소(element)나 속성(attribute)가 사용되지 않는 경우, HTML 처리기에 가치 있는 의미론적 정보를 주지 않게 됩니다.

이 예제에서 스타일링은 제목(heading)과 다른 컴포넌트의 시각적 표현을 생성하는데 사용될 수 있지만, 적절한 HTML 요소(element)가 사용 되지 않았기 때문에 웹 브라우저, 검색 엔진, 보저 기술에 사용 가능한 의미론적 정보가 거의 존재하지 않습니다.
<!doctype html>
<html lang="en">
  <head>
    <title>Favorite books</title>
  </head>
        <body>
    <div class="header">
       <img src="logo.png" alt="Favorite books logo">
    </div>
    <div class="main">
       <span class="largeHeading">Favorite books</span>
       <p>These are a few of my favorite books.</p>
       <span class="smallHeading">The Belgariad</span>
       <p>Five books by David and Leigh Eddings.</p>
       <span class="smallHeading">The Hitchhiker’s Guide to the Galaxy</span>
       <p>A trilogy of five books by Douglas Adams.</p>
    </div>
  </body>
</html>

문서는 그것이 처리되는 동안 동적으로 변경될 수 있습니다. 스크립팅과 다른 메커니즘은 속성(tattribute) 값, 텍스트, 전체 문서 구조를 변경하는데 사용될 수 있습니다. 따라서 문서의 의미론은 특정 시점의 문서의 상태에 기반하지만, 외부 이벤트에 대한 응답으로 변경될 수도 있습니다. 유저 에이전트들은 이러한 변경을 반영하기 위해 문서의 표현을 업데이트 해야(must) 합니다.

이 예제에서 audio 요소(element)는 음악 트랙을 재생하는데 사용됩니다. controls 속성(attribute)은 유저 에이전트 플레이어를 보여주는데 사용되고, 음악이 재생하는 동안 진행을 나타내기 위해 컨트롤이 업데이트 됩니다. 사용 가능한 의미론적 정보는 이러한 변경에 대한 응답으로 업데이트 됩니다.
<audio src="comfortablynumb.mp3" controls>

3.2.2. DOM에서의 요소(Element)

DOM에서 html 요소(element)들을 나타내는 노드는 이 명세의 관련 명세에 그것들에 대해 나열된 인터페이스를 구현해야(must) 하고 스크립트에 노출해야(must) 합니다. 여기에는 문서가 다른 컨텍스트(예를 들어, XSLT 변환 내부)에 있는 문서라 하더라도, XML 문서들html 요소(element)들이 포함됩니다.

DOM의 요소(element)들은 상황(things)을 나타냅니다; 즉, DOM의 요소 (element)들은 의미론(semantic)으로 알려진, 고유한 의미(meaning)를 가집니다.

예를 들어, ol 요소(element)는 순서가 있는 목록을 나타냅니다.

모든 html 요소(element)들의 인터페이스가 상속 받 고, 추가적인 요구사항이 없는 요소(element)들을 사용해야(must) 하는 기본 인터페이스는 HTMLElement 인터페이스 입니다.

interface HTMLElement : Element {
  // metadata attributes
  attribute DOMString title;
  attribute DOMString lang;
  attribute boolean translate;
  attribute DOMString dir;
  [SameObject] readonly attribute DOMStringMap dataset;

  // user interaction
  attribute boolean hidden;
  void click();
  attribute long tabIndex;
  void focus();
  void blur();
  attribute DOMString accessKey;
  attribute boolean draggable;
  [PutForwards=value] readonly attribute DOMTokenList dropzone;
  attribute HTMLMenuElement? contextMenu;
  attribute boolean spellcheck;
  void forceSpellCheck();
};
HTMLElement implements GlobalEventHandlers;
HTMLElement implements DocumentAndElementEventHandlers;
HTMLElement implements ElementContentEditable;
interface HTMLUnknownElement : HTMLElement { };

HTMLElement 인터페이스는 다수의 상이한 기능과 관련된 메서드와 속성(attribtue)들을 보유하고, 따라서 이 인터페이스의 멤버들은 이 명세의 다양한 다른 섹션에서 설명됩니다.

HTMLUnknownElement 인터페이스는 이 명세(또는 다른 적용 가능한 명세)에 정의되지 않은 html 요소(element)들에 사용되어야(must) 합니다.

3.2.3. 요소(element) 정의

이 명세에서 각 요소(element)는 다음 정보를 포함하는 정의를 가집니다:

카테고리

요소(element)가 속하는 카테고리의 목록. 이것들은 각 요소(element)에 대해 콘텐트 모델을 정의할 때 사용됩니다.

이 요소(element)가 사용될 수 있는 컨텍스트

요소(element)가 사용될 수 있는 곳의 비 규범적 설명. 이 정보는 자식으로서 이것을 허용하는 요소의 콘텐트 모델과 중복되고, 편의상으로만 제공됩니다.

간결함을 위해, 가장 구체적인 예상되는 것들만 언급됩니다. 예를 들어, 흐름(flow) 콘텐트이면서 어구(phrasing) 콘텐트인 요소(element)는 어구(phrasing) 콘텐트가 예상되는 어느 곳에서나 사용될 수 있지만, 흐름(flow) 콘텐트가 예상되는 곳은 어구(phrasing) 콘텐트도 예상되기 때문에 (모든 어구(phrasing) 콘텐트흐름(flow) 콘텐트이기 때문에), "어구(phrasing) 콘텐트가 예상되는 곳"만 언급 될 것입니다.

콘텐트 모델

요소(element)의 자식과 후손으로 포함되어야(must) 하는 콘텐트의 규범적 설명.

text/html에서 태그 생략

text/html 구문에서, 시작 태그와 종료 태그가 생략될 수 있는지 여부의 비규범적 설명. 이 정보는 선택적 태그 섹션에 주어진 규범적인 요구 사항과 중복되고, 요소(element) 정의에 편의상으로만 제공됩니다.

콘텐트 속성(attribute)

요소(element)에 명시될 수 있는 속성(attribute)의 규범적 목록과 (달리 허용되지 않는 경우를 제외하고) 그 속성(attribute)들의 비 규범적인 설명. (대시의 왼쪽의 콘텐트는 규범적이고, 대시 오른쪽의 콘텐트는 규범적이지 않습니다.)

허용된 ARIA 역학(role) 속성(attribute)

요소에 명시될 수 있는 ARIA 역할(role) 속성(attribute) 값들의 규범적 목록(달리 허용되지 않는 경우를 제외하고). 각 값은 비 규범적 설명에 연결됩니다.

허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들

범용 aria-* 속성(attribute) 목록과 허용된 역할(role), 상태(state), 속성(property) 표로의 링크

DOM 인터페이스

그 요소(element)가 구현해야(must)하는 DOM 인터페이스의 규범적 정의

이것은 요소가 작성자와 구현에 적용할 수 있는 추가적인 규범적 적합성 기준과 함께, 무엇을 나타내는지의 설명이 이후에 따라옵니다. 예제도 때때로 포함됩니다.

3.2.3.1. 속성(attribute)

달리 명시되지 않는 한, html 요소(element)들의 속성(attribute)은 빈 문자열을 포함하여 임의의 문자열 값을 가질 수 있습니다. 명시적으로 정해지지 않는 한, 그러한 속성(attribute)에 명시 될 수 있는 텍스트에 대한 제약 사항은 없습니다.

3.2.4. 콘텐트 모델(Content model)

이 명세에 정의된 각 요소(element)는 콘텐트 모델을 가집니다: 요소의 예상되는 콘텐츠의 설명. HTML 요소(element)는 요소(element)의 콘텐트 모델에 기술된 요구사항에 일치하는 콘텐트를 가져야(must) 합니다. 요소(element)의 콘텐트는 자식이 템플릿 콘텐트에 있는 template 요소(element)를 (요소가 생성될 때 요소에 대입되는 별도의 DocumentFragment) 제외하고, DOM에서 그것의 자식입니다.

공백 문자들은 항상 요소(element)들 사이에 허용됩니다. 유저 에이전트들은 소스 마크업에서 요소(element)들 사이의 이 문자들을 DOM 에서 Text 노드로 나타냅니다. 일련의 그 문자로만 구성되는 빈 Text 노드와 Text 노드는 요소(element) 간 여백으로 간주됩니다.

요소 간 여백, 주석 노드, 처리 지시 노드는 요소(element)의 콘텐트가 요소(element)의 콘텐트 모델과 일치하는지 아닌지의 여부가 수립 될 때 무시되어야(must) 하고, 문서와 요소(element) 의미론을 정의하는 알고리즘을 따를 때 무시되어야(must) 합니다.

따라서, A and B가 동일한 부모 노드를 가지고 둘 사이에 다른 요소(element) 노드나 Text 노드(요소(element) 간 여백 외)가 없다면 요소(element) A는 두 번째 요소(element) B보다 앞서거나 B가 뒤따른다고 합니다. 마찬가지로, 요소(element)가 요소(element) 간 여백, 주석 노드, 처리 지시 노드 외 다른 노드를 포함하지 않는다면 이 노드는 그 요소(element)의 유일한 자식입니다.

작성자는 html 요소(element)들을 각 요소(element)들에 대해 정의 된대로 혹은 다른 명세에 의해 명시적으로 요구 된 대로 그것들이 명시적으로 허용된 곳을 제외한 다른 어떤 곳에도 사용하지 않아야(must) 합니다. XML 복합 문서에 대해, 그 요소(element)들이 관련 컨텍스트를 제공하도록 정의되었다면, 이 상황들은 다른 네임스페이스의 내부 요소(element)가 될 수 있습니다.

예를 들어, 아톰(Atom) 명세는 content 요소(element)를 정의합니다. 그것의 type 속성(attribute)이 xhtml 값을 가지는 경우, 아톰(Atom) 명세는 단일 HTML div 요소(element)를 포함하도록 요구합니다. 따라서, div 요소(element)는 비록 이 명세에 의해 명시적으로 규범적으로 지정되지 않았지만 그 컨텍스트에서는 허용됩니다. [RFC4287]

추가적으로, html 요소(element)들은 고아 노드(즉, 부모 노드가 없는)가 될 수 있습니다.

예를 들어, td 요소(element)가 tr 요소(element) 내부에만 사용되도록 되어있다 하더라도, 스크립트에서 td 요소(element)를 생성하고 전역 변수에 저장하는 것은 적합합니다.
var data = {
  name: "Banana",
  cell: document.createElement('td'),
};
3.2.4.1. "없는(nothing)" 콘텐트 모델

요소(element)의 콘텐트 모델이 없는 경우, 요소(element)는 Text 노드 (요소(element)간 공백 외)와 요소(element) 노드를 포함하지 않아야(must) 합니다.

콘텐트 모델이 "없는" 대부분 HTML 요소(element)들은 편의상 텅 빈 요소(element) (HTML 문법에 따라 종료 태그를 가지지 않는 요소(element)). 하지만, 이것들은 완전히 분리된 개념입니다.

3.2.4.2. 콘텐트의 종류

HTML에서 각 요소(element)는 서로 유사한 특성을 가진 요소(element)를 분류한 0개 이상의 카테고리에 속합니다:

어떤 요소들은 이 명세에서 다른 부분에 정의된 다른 카테고리에도 해당됩니다.

이 카테고리들은 다음과 같이 관련됩니다:

섹션화(sectioning) 콘텐트, 제목(heading) 콘텐트, 어구(phrasing) 콘텐트, 삽입(embedded) 콘텐트, 대화형(interactive) 콘텐트는 흐름(flow) 콘텐트의 모든 유형입니다. 메타데이터는 때때로 흐름(flow) 콘텐트 입니다. 메타데이터와 대화형(interactive) 콘텐트는 때때로 어구(phrasing) 콘텐트 입니다. 삽입(embedded) 콘텐트는 또한 어구(phrasing) 콘텐트이 유형이고, 때때로 대화형(interactive) 콘텐트입니다.

다른 카테고리들은 특정 목적을 위해서도 사용됩니다, 예를 들어, 양식(form) 컨트롤들은 공통 요구사항을 정의하기 위해 여러 가지 카테고리를 사용하여 명시됩니다. 일부 요소(element)들은 고유의 요구사항을 가지고 특정 카테고리에 맞지 않습니다.

3.2.4.2.1. 메타데이터 콘텐트

메타데이터 콘텐트는 콘텐트 나머지의 표현이나 동작을 설정하거나, 다른 문서와 문서의 관계를 설정하거나, 다른 "대역 외" 정보를 전달하는 콘텐트 입니다.

3.2.4.2.2. 흐름(flow) 콘텐트

문서와 어플리케이션의 본문에 사용되는 대부분 요소(element)는 흐름(flow) 콘텐트로 분류됩니다.

3.2.4.2.3. 섹션화(sectioning) 콘텐트

섹션화(sectioning) 콘텐트제목(heading)바닥글(footer)들의 범위를 정의하는 콘텐트 입니다.

섹션화(sectioning) 콘텐트는 잠재적으로 제목(heading)과 개요(outline)를 가집니다. 더 자세한 내용을 위해 §4.3.10 제목(heading)들과 섹션들의 섹션을 참고하세요.

섹션화(sectioning) 루트인 특정 요소(element)들도 있습니다. 이것들은 섹션화(sectioning) 콘텐트와 구별되지만, 이들도 개요(outline)를 가질 수 있습니다.

3.2.4.2.4. 제목(heading) 콘텐트

제목(heading) 콘텐트는 (섹션화(sectioning) 콘텐트 요소(element)를 사용하여 명시적으로 마크업했거나, 제목(heading) 콘텐트 자체로 나타내어) 섹션의 헤더를 정의합니다.

3.2.4.2.5. 어구(phrasing) 콘텐트

어구(phrasing) 콘텐트는 문서의 텍스트 뿐만 아니라 문단 내부(intra-paragraph) 레벨에서 텍스트를 마크업 하는 요소(element) 입니다. 문단에서의 연속 된 어구(phrasing) 콘텐트.

어구(phrasing) 콘텐트로 분류된 대부분 요소(element)들은 흐름(flow) 콘텐트가 아닌 어구(phrasing) 컨텐트로 분류된 자기 자신인 요소(element)만을 포함 할 수 있습니다.

콘텐트 모델의 맥락에서 텍스트는 아무 것도 의미하지 않거나 Text 노드를 의미합니다. 텍스트는 때때로 그 자체로 콘텐트 모델로 사용되지만, 어구(phrasing) 콘텐트이기도 하며, 요소(element) 간 공백이 될 수 있습니다(Text 노드가 비어있거나 공백 문자들만을 포함한다면).

Text 노드와 속성(attribute) 값은 유니코드 문자들로 구성되어야(must) 하고, U+0000 문자는 포함하지 않아야(must) 하고, 영구적으로 정의되지 않은 유니코드 문자(비문자)를 포함하지 않아야(must) 하고, 공백 문자들제어 문자를 포함하지 않아야(must) 합니다.

이 명세는 정확한 컨텍스트에 따른 Text 노드의 정확한 값과 속성(attribtue) 값에 추가 제한 사항들을 포함합니다.

HTML에서 요소(element)들에 대해, 텍스트 콘텐트 모델의 제한 사항도 요소(element)의 종류에 따릅니다. 예를 들어, textarea 요소(element) 안에 "<"는 textarea이스케이프 될 수 있는 원시 텍스트 요소(element)이기 때문에 HTML에서 이스케이프 될 필요가 없습니다. (이것은 XHTML에 적용하지 않습니다. XHTML에서, 요소(element)의 종류콘텐트 모델: 텍스트의 제한 사항에 영향을 주지 않습니다.)

3.2.4.2.6. 삽입(embedded) 콘텐트

삽입(embedded) 콘텐트는 문서에 다른 리소스를 불러오는 콘텐트, 혹은 문서에 삽입 된 다른 표현 형식으로부터의 콘텐트 입니다.

HTML 네임스페이스와 다른 네임스페이스이고 콘텐트를 전달하지만 메타데이터는 전달하지 않는 요소(element)는 이 명세에 정의된 콘텐트 모델의 목적에 대한 삽입(embedded) 콘텐트 입니다. (예를 들어, MathML 혹은 SVG.)

일부 삽입(embedded) 콘텐트 요소(element)들은 폴백 콘텐트를 가질 수 있습니다: 외부 리소스가 사용될 수 없는 경우 (예를 들어, 지원되지 않는 형식의 콘텐트이기 때문에) 사용되는 콘텐트. 폴백이 있다면 요소(element) 정의는 폴백이 무엇인지 지정합니다.

3.2.4.2.7. 대화형(interactive) 콘텐트

대화형(interactive) 콘텐트는 유저 인터랙션을 위해 특별히 의도된 콘텐트 입니다.

tabindex 속성(attribute)은 모든 요소(element)를 대화형(interactive) 콘텐트로 만들 수 있습니다.

3.2.4.2.8. 분명한(palpable) 콘텐트

일반적인 규칙으로, 콘텐트 모델이 흐름(flow) 콘텐트어구(phrasing) 콘텐트를 허용하는 요소(element)는 분명한(palpable) 콘텐트이고 명시된 hidden 속성(attribute)을 가지지 않는 그것의 contents에 적어도 하나의 노드를 가져야(should) 합니다.

분명한(palpable) 콘텐트는 일부 비어 있지 않은 후손 텍스트를 제공하거나, 사용자가 들을 수 있거나(audio 요소(element)들) 볼 수 있거나 (videoimg 혹은 canvas 요소(element)들) 혹은 상호 작용 할 수 있는 (예를 들어, 대화형 양식(form) 컨트롤들) 것을 제공하여 요소를 비어 있지 않게 만듭니다.

하지만, 요소가 타당하게 비어 있을 수 있는 많은 경우, 예를 들어 스크립트에 의해 나중에 채워질 플레이스홀더로 사용되거나, 요소가 템플릿의 일부이고 일부 페이지에서는 아니지만 대다수 페이지에서 채워지는 경우가 있기 때문에 이 요구사항은 견고한 요구 사항이 아닙니다.

적합성 검사기는 작성 보조 도구로서, 작성자에게 이 요구 사항을 충족하는데 실패한 요소(element)들을 찾기 위한 메커니즘을 제공하도록 권장됩니다.

다음 요소(element)들은 분명한(palpable) 콘텐트입니다:

3.2.4.2.9. 스크립트 지원 요소(element)

스크립트 지원 요소(element)는 스스로 아무 것도 나타내지 않지만(즉, 렌더링 되지 않습니다), 스크립트를 지원하는데, 예를 들어 사용자를 위한 기능적 제공을 위해 사용됩니다.

다음 요소(element)들은 스크립트 지원 요소(element)들 입니다:

3.2.4.3. 투명 콘텐트 모델

일부 요소(element)들은 투명으로 기술됩니다; 그것들은 콘텐트 모델의 설명에 "투명"을 가집니다. 투명 요소(element)의 콘텐트 모델은 부모 요소의 콘텐트 모델에서 유래됩니다: "투명"인 콘텐트 모델의 부분에 요구되는 요소(element)들은 투명 요소(element)가 자신을 발견하는 투명 요소(element)의 부모 요소의 콘텐트 모델의 부분에 요구되는 것과 같은 요소(element)입니다.

예를 들어, ruby 요소(element) 안의 ins 요소(element)는, ins 요소(element)를 허용하는 ruby 요소(element)의 콘텐트 모델의 부분은 어구(phrasing) 콘텐트를 허용하는 부분이고, rt 요소(element)는 어구(phrasing) 콘텐트가 아니기 때문에, rt 요소(element)를 포함할 수 없습니다.

어떤 경우에, 투명 요소(element)가 서로 중첩되는 경우, 반복적으로 처리가 적용되어야(has to) 합니다.

다음 마크업 코드 조각을 고려해보세요:
<p><object><param><ins><map><a href="/">Apples</a></map></ins></object></p>

"Apples"가 a 요소(element) 안에 허용되는지를 확인하기 위해, 콘텐트 모델이 검사됩니다. a 요소(element)의 콘텐트 모델은 투명이고, map 요소(element)의 콘텐트 모델도, ins 요소(element)의 콘텐트 모델도, ins 요소(element)가 발견되는 object 요소의 부분도 마찬가지입니다. object 요소(element)는 콘텐트 모델이 어구(phrasing) 콘텐트p 요소(element) 안에서 발견되어집니다. 따라서, 텍스트는 어구(phrasing) 콘텐트이기 때문에, "Apples"는 허용됩니다.

투명 요소(element)가 부모가 없는 경우, "transparent"인 그것의 콘텐트 모델의 부분은 대신 모든 흐름(flow) 콘텐트를 허용하는 것으로 취급되어야(must) 합니다.

3.2.4.4. 문단(paragraphs)

이 섹션에 정의된 용어 문단p 요소(element)의 정의 이상으로 사용됩니다. 여기에 정의 된 문단 개념은 문서를 해석하는 방법을 기술하는데 사용됩니다. p 요소(element)는 문단을 마크업하는 몇 가지 방법 중 단지 한 가지일 뿐입니다.

문단은 일반적으로 타이포그라피에서와 같이, 특정 주제에 관해 논하는 하나 이상의 문장들을 가진 텍스트 블럭을 구성하거나, 좀 더 일반적인 주제 그룹에 사용될 수 있는 어구(phrasing) 콘텐트의 연속입니다. 예를 들어, 주소도 문단이고, 시(詩)의 양식의 일부나, 필자 이름을 적은 행, 혹은 연(聯)도 그러합니다.

다음 예제에서, 섹션에 두 개의 문단이 존재합니다. 문단이 아닌 어구(phrasing) 콘텐트를 포함하는 제목(heading)도 존재합니다. 주석과 요소(element) 간 여백이 문단을 구성하지 않는 방식에 주목하세요.
<section>
  <h2>Example of paragraphs</h2>
  This is the <em>first</em> paragraph in this example.
  <p>This is the second.</p>
  <!-- This is not a paragraph. -->
</section>

흐름(flow) 콘텐트 안의 문단은 문서가 문제를 복잡하게 만드는 a, ins, del, map 요소(element)들은 그들의 혼합 콘텐트 모델을 가지고 아래 처음 두 예제에서 보이는 것과 같이 문단 경계를 모호하게 할 수 있기 때문에, 이 요소(element)들이 없는 것 같이 보이는 것에 관련하여 정의됩니다.

일반적으로, 문단 경계를 모호하게 하는 요소(element)를 가지는 것을 방지하는 것이 가장 좋습니다. 그러한 마크업을 유지보수 하는 것은 어렵게 만들 수 있습니다.

다음 예제는 이전 예제에서 마크업을 가져와서 텍스트가 변경되었음을 나타내기 위해 (이 경우에서 이기는 하지만, 변경 사항은 확실히 말이 안 되기는 합니다) 일부 마크업 주변에 insdel 요소(element)를 넣습니다. 이 예제가 insdel 요소(element)에도 불구하고, 이전의 것과 정확히 동일한 문단을 가지는 방식에 주목하세요 — ins 요소(element)는 제목(heading)과 첫 번째 문단을 모호하게 하고, del 요소(element)는 두 문단 사이 경계를 모호하게 합니다.
<section>
  <ins><h1>Example of paragraphs</h1>
  This is the <em>first</em> paragraph in</ins> this example<del>.
  <p>This is the second.</p></del>
  <!-- This is not a paragraph. -->
</section>
view를 문서의 모든 a, ins, del, map 요소(element)를 그들의 콘텐츠로 바꾸는 DOM의 뷰로 둡니다. 그 후, view에서, 콘텐트의 다른 유형에 의해 연속 된 각 일련의 어구(phrasing) 콘텐트 형제 노드에 대해, 어구(phrasing) 콘텐트 뿐 아니라 어구(phrasing) 콘텐트 외 다른 콘텐트를 허용하는 요소(element) 내에서, first를 연속의 첫 번째 노드로 두고, last를 연속의 마지막 노드로 둡니다. 삽입(embedded) 콘텐트요소(element) 간 여백이 아닌 적어도 하나의 노드로 구성되는 그 각 연속에 대해, 문단은 first 바로 전부터 last 바로 이후까지 본래의 DOM에 존재합니다. (따라서 문단은 a, ins, del, map 요소(element)들 전반에 걸쳐질 수 있습니다.)

적합성 검사기는 서로 겹치는 문단을 가지는 경우의 작성자에게 경고할 수 있습니다 (이것은 object, video, audio, canvas 요소(element))들에 발생될 수 있고, HTML 안에 추가적으로 삽입되는 것을 허용하는 다른 네임스페이스에 있는 요소(element)들을, svg math 같은, 통해 간접적으로 발생될 수 있습니다).

문단은 또한 명식적으로 p 요소(element)에 의해 구성 될 수 있습니다.

p 요소(element)는 서로 문단을 구분하기 위한 어구(phrasing) 콘텐트외 다른 어떤 콘텐트도 존재하지 않을 경우 각각의 문단을 감싸는데 사용 될 수 있습니다.

다음 예제에서, 링크가 첫 번째 문단의 반, 두 번째 문단을 구분하는 제목(heading) 전부, 두 번째 문단의 반에 걸쳐 있습니다. 이는 문단과 헤딩을 모호하게 합니다.
<header>
  Welcome!
  <a href="about.html">
    This is home of...
    <h1>The Falcons!</h1>
    The Lockheed Martin multirole jet fighter aircraft!
  </a>
  This page discusses the F-16 Fighting Falcon’s innermost secrets.
</header>

여기, 이번에는 명시적으로 문단을 보여주고, 한 개 링크 요소(element)를 세개로 분할하여 이를 마크업하는 다른 방법이 있습니다:

<header>
  <p>Welcome! <a href="about.html">This is home of...</a></p>
  <h1><a href="about.html">The Falcons!</a></h1>
  <p><a href="about.html">The Lockheed Martin multirole jet
  fighter aircraft!</a> This page discusses the F-16 Fighting
  Falcon’s innermost secrets.</p>
</header>
폴백 콘텐트를 정의하는 특정 요소(element)를 사용하는 경우 문단이 중첩되는 것이 가능합니다. 예를 들어, 다음 섹션에서:
<section>
  <h2>My Cats</h2>
  You can play with my cat simulator.
  <object data="cats.sim">
    To see the cat simulator, use one of the following links:
    <ul>
      <li><a href="cats.sim">Download simulator file</a>
      <li><a href="https://sims.example.com/watch?v=LYds5xY4INU">Use online simulator</a>
    </ul>
    Alternatively, upgrade to the Mellblom Browser.
  </object>
  I’m quite proud of it.
</section>

다섯 개의 문단이 있습니다:

  1. objectobject 요소(element)인 "You can play with my cat simulator. object I’m quite proud of it." 라고 말하는 문단.

  2. "To see the cat simulator, use one of the following links:" 라고 말하는 문단.

  3. "Download simulator file" 라고 말하는 문단.

  4. "Use online simulator" 라고 말하는 문단.

  5. "Alternatively, upgrade to the Mellblom Browser." 라고 말하는 문단.

첫 번째 문단은 다른 네 개의 문단에 의해 중첩됩니다. "cats.sim" 리소스를 지원하는 유저 에이전트는 첫 번째 문단만을 보여줄 것이지만, 폴백 컨텐트를 보여주는 유저 에이전트는 혼란스럽게 첫 번째 문단의 첫 번째 문장을 두 번째 문장으로서 동일한 문단에 있었던 것 처럼 보여줄 것이고, 마지막 문단을 첫 번째 문단의 두 번째 문장의 시작에 있었던 것 처럼 보여줄 것입니다.

이 혼란을 방지하기 위해, 명시적인 p 요소(element)가 사용될 수 있습니다. 예를 들어:

<section>
  <h2>My Cats</h2>
  <p>You can play with my cat simulator.</p>
  <object data="cats.sim">
    <p>To see the cat simulator, use one of the following links:</p>
    <ul>
      <li><a href="cats.sim">Download simulator file</a>
      <li><a href="https://sims.example.com/watch?v=LYds5xY4INU">Use online simulator</a>
    </ul>
    <p>Alternatively, upgrade to the Mellblom Browser.</p>
  </object>
  <p>I’m quite proud of it.</p>
</section>

3.2.5. 범용 속성(attribute)

다음 속성(attribute)들은 모든 html 요소(element)들에 정의될 수 있습니다 (심지어 이 명세에 정의되어 있지 않더라도):

이 속성(attribute)들은 HTML 요소(element)들에 대한 속성(attribute)들로서 이 명세에 의해서만 정의됩니다. 이 명세가 이 속성(attribute)들을 가지는 요소(element)에 참조하는 경우, 이 속성(attribute)들을 가지는 것으로 정의되지 않은 네임스페이스의 요소(element)들은 이 속성(attribute)들을 가진 요소(element)들이 되는 것으로 간주되지 않아야(must) 합니다.
예를 들어, 다음 XML 코드 조각에서, "bogus" 요소(element)는 리터럴 이름 "dir"을 가진 속성(attribute)을 가짐에도 불구하고, 이 명세에 정의된 대로 dir 속성(attribute)을 가지지 않습니다. 따라서, 가장 안쪽 span 요소(element)의 방향성은 간접적으로 "bogus" 요소(element)를 통해 div 요소(element)로부터 상속 된, "rtl"입니다.
<div xmlns="https://www.w3.org/1999/xhtml" dir="rtl">
  <bogus xmlns="https://example.net/ns" dir="ltr">
    <span xmlns="https://www.w3.org/1999/xhtml">
    </span>
  </bogus>
</div>

보조 기술 제품이 HTML 요소(element)와 속성(attribute)으로 가능한 것보다 좀 더 세밀한 인터페이스를 노출할 수 있게 하기 위해, 보조 기술 제품을 위한 주석(annotation)의 세트가 명시될 수 있습니다 (ARIA rolearia-* 속성(attribute)들). [WAI-ARIA]


다음 이벤트 처리기 콘텐트 속성(attribute)들은 모든 HTML 요소(element)에 명시될 수 있습니다:

별표로 표기 된 속성(attribute)들은 body 요소(element)들에 명시되었을 경우 그 요소(element)들이 동일한 이름을 가지고 Window 객체의 이벤트 처리기를 노출하기 때문에 다른 의미(meaning)를 가집니다.

이 속성(attribute)들이 모든 요소(element)들에 적용되는데 반해, 그것들이 모든 요소(element)에 쓸모있는 것은 아닙니다. 예를 들어 미디어 요소(element)들만이 유저 에이전트에 의해 발생된 volumechange 이벤트를 받을 것입니다.


커스텀 데이터 속성(attribute)들은 (예를 들어, data-foldernamedata-msgid) 모든 HTML 요소(element)에 페이지에 특수한 커스텀 데이터를 저장하기 위해 명시 될 수 있습니다.


HTML 문서들에, HTML 네임스페이스 안에 있는 요소(element)들은 명시된 xmlns 속성(attribute)을 가질 수 있고, 이 속성(attribute)을 가진 경우에만, 정확한 값 "https://www.w3.org/1999/xhtml"을 가집니다. 이것은 XML 문서들에는 적용되지 않습니다.

HTML에서, xmlns 속성(attribute)은 전혀 영향을 가지지 않습니다. 이것은 기본적으로 마스코트 같은 것 입니다. 단지 XHTML로 그리고 XHTML로부터 약간 쉽게 마이그레이션 할 수 있도록 허용된 것입니다. HTML 해석기에 의해 해석된 경우, 속성(attribute)은 XML에서 네임스페이스 선언 속성(attribute)과 같은 "https://www.w3.org/2000/xmlns/" 네임스페이스가 아닌, 어떤 네임스페이스에도 없게 됩니다.

XML에서, xmlns 속성(attribute)은 네임스페이스 선언 메커니즘의 일부이고, 요소(element)는 실제로 명시된 네임스페이스가 없는 xmlns 속성(attribute)을 가질 수 없습니다.


XML 명세는 또한 XML 문서에 있는 모든 요소에 XML 네임스페이스에 있는 xml:space 속성(attribute)의 사용을 허용합니다. 이 속성(attribute)은 HTML에서 기본 동작이 여백을 유지하는 것이기 때문에, html 요소(element)들에 어떤 영향도 가지지 않습니다. [XML]

text/html 문법에서 html 요소(element)들xml:space 속성(attribute)을 직렬화 하는 방법은 없습니다.

3.2.5.1. id 속성(attribute)

id 속성(attribute)은 그 요소(element)의 고유 식별자 (ID)를 명시합니다. [DOM]

값은 요소(element)의 홈 하위 트리에 있는 모든 ID들 중 고유해야(must) 하고 적어도 하나의 문자를 포함해야(must) 합니다. 값은 어떠한 공백 문자들도 포함하지 않아야(must) 합니다.

ID가 취할 수 있는 형식에는 다른 제약사항이 없습니다; 특별히, 숫자로 구성 될 수도, 숫자로 시작할 수도, 밑줄로 시작할 수도, 구두점으로 구성 될 수도, 기타 등등이 가능합니다.

요소(element)의 고유 식별자는 가장 명백하게는 부분 식별자를 사용하여 문서의 특정 부분으로 연결하기 위한 방법으로, 스크립팅의 경우 요소(element)를 목표로 삼기 위한 방법으로, CSS에서 특정 요소(element)를 스타일하기 위한 방법 등 다양한 목적으로 사용될 수 있습니다.

식별자는 분명하지 않은 문자열입니다. 특별한 의미(meanings)가 id 속성(attribute)의 값으로부터 파생되지 않아야(should) 합니다.
3.2.5.2. title 속성(attribute)

title 속성(attribute)은 툴팁에 적절할 것 같은 조언 정보를 나타냅니다. 링크에서, 이것은 제목(title)이나 대상 리소스의 설명이 될 수 있고; 이미지에서, 이미지 제공자(image credit)나 이미지의 설명; 문단에서, 텍스트에 각주나 주석; 인용구에서, 소스에 대한 추가적인 정보; 대화형(interactive) 콘텐트에서, 요소(element)의 사용에 대한 레이블이나 지시사항 등등이 될 수 있습니다. 값은 텍스트입니다.

title 속성(attribute)에 의존하는 것은 많은 유저 에이전트들이 이 명세에 의해 요구된 대로 접근 가능한 방법으로 속성을 노출하지 않기 때문에 (예를 들어, 현대의 폰이나 태블릿을 가진 사람들 같이, 키보드만 사용하는 유저와 터치만 사용하는 유저들을 배제하고, 툴팁이 나타나도록 하기 위해 마우스 같은 포인팅 디바이스를 요구하는 것) 현재 지양됩니다.

이 속성(attribute)이 요소(element)에 생략되었다면, title 속성(attribute) 설정을 가진 가장 가까운 조상 HTML 요소title 속성(attribute)이 이 요소(element)에도 관련 됨을 암시합니다. 속성(attribute)이 이것을 재정의하도록 설정하는 것은, 명시적으로 모든 조상 요소(element)의 조언 정보가 이 요소에 관련되지 않음을 지정하는 것입니다. 속성(attribute)을 빈 문자열로 설정하는 것은 요소(element)가 조언 정보를 가지지 않는 다는 것을 나타냅니다.

title 속성(attribute)의 값이 U+000A 라인피드 (LF) 문자를 포함한다면, 콘텐트는 여러 줄로 나뉘어 집니다. 각 U+000A 라인피드 (LF) 문자는 개행을 나타냅니다.

주의해야 할 것은 title 속성(attribute)에 새로운 행을 사용하는 점에 대해 신중해야 합니다.

예를 들어, 다음 코드 조각은 실제로 개행이 있는 축약어의 본딧말을 정의합니다:

<p>My logs show that there was some interest in <abbr title="Hypertext
Transport Protocol">HTTP</abbr> today.</p>

마치 <br> 이 있는 것과 같이 표현되며, 스크린 리더로 읽을 시에도 <br> 처리가 된 것 처럼 "Hypertext"를 한 개 행으로, "Transport Protocol"를 한 개 행으로 읽습니다.
즉, "Hypertext Transport Protocol" 이라는 하나의 용어를 의미하지 않게 됩니다.

link, abbr, input 같은 어떤 요소(element)들은 위에서 설명된 의미(semantics) 이외에 title 속성(attribute)에 대한 추가적인 의미(semantics)를 정의합니다.

요소(element)의 조언 정보는 일단 값이 반환되면 알고리즘이 중단되는 다음 알고리즘이 반환하는 값입니다. 알고리즘이 빈 문자열을 반환하는 경우, 조언 정보는 없습니다.
  1. 요소(element)가 link, style, dfn, abbr, menuitem 요소(element)라면: 요소(element)가 title 속성(attribute)을 가진다면, 그 속성(attribute)의 값을 반환하고, 그렇지 않으면 빈 문자열을 반환합니다.

  2. 그렇지 않고, 요소(element)가 속성(attribute)을 가진다면, 그 값을 반환합니다.

  3. 그렇지 않고, 요소(element)가 부모 요소를 가진다면, 부모 요소(element)의 조언 정보를 반환합니다.

  4. 그렇지 않으면, 빈 문자열을 반환합니다.

유저 에이전트들은 요소(element)가 조언 정보를 가지는 경우, 사용자에게 알려야(should) 하고, 그렇지 않으면 정보는 인지될 수 없을 것입니다.


title IDL 속성(attribute)은 title 콘텐트 속성(attribute)을 반영해야(must) 합니다.

3.2.5.3. langxml:lang 속성(attribute)

lang 속성(attribute)은 (네임스페이스에 없는) 요소(element)의 콘텐츠와 텍스트를 포함하는 요소(element)의 속성(attribute)에 대한 주 언어를 명시합니다. 그 값은 유효한 BCP 47 언어 태그나 빈 문자열이어야(must) 합니다. 속성(attribute)을 빈 문자열로 설정하는 것은 주 언어가 알 수 없는 것임을 나타냅니다. [BCP47]

XML 네임스페이스에 있는 lang 속성(attribute)은 XML에서 정의됩니다. [XML]

요소(element)에서 이 속성(attribute)들이 생략되었다면, 이 요소(element)의 언어는 부모 요소(element)의 언어가 있다면 그것과 동일합니다.

네임 스페이스가 없는 lang 속성(attribute)은 모든 HTML 요소(element)에 사용 될 수 있습니다.

XML 네임스페이스에 있는 lang 속성(attribute)은 XML 문서html 요소(element)들 뿐만 아니라, 관련 명세가 그것을 허용한다면 (특히, MathML과 SVG는 그들의 요소(elemenet)에 XML 네임스페이스lang 속성(attribute)이 명시되는 것을 허용합니다) 다른 네임스페이스에 있는 요소(element)들에 사용될 수 있습니다. 네임 스페이스가 없는 lang 속성(attribute)과 XML 네임스페이스에 있는 lang 속성(attribute)이 모두 동일한 요소(element)에 명시되었다면, 그것들은 ASCII 대소문자 비구분 방식으로 비교되는 경우 정확히 동일한 값을 가져야(must) 합니다.

작성자는 HTML 문서들html 요소(element)들XML 네임스페이스에 있는 lang 속성(attribute)을 사용하지 않아야(must) 합니다. XHTML로 그리고 XHTML로부터 쉬운 마이그레이션을 위해, 작성자는 XML 네임스페이스가 없는 속성(attribute)을 HTML 문서html 요소(element)들에 지역 이름 "xml:lang"를 가지고 접두어 없이 명시할 수 있지만, 그러한 속성(attribute)들은 네임스페이스가 없는 lang 속성(attribute)도 명시된 경우에만 명시되어야(must) 하고, 두 속성(attribute) 모두 ASCII 대소문자 비구분 방법으로 비교될 경우 동일한 값을 가져야(must) 합니다.

접두어가 없고 리터럴 지역 이름 "xml:lang"을 가진 네임스페이스가 없는 속성(attribute)은 언어 처리에 영향을 가지지 않습니다.

HTML 문서들의 언어는 (문서의 주 언어를 나타내기 위해 HTML 요소(element) 자신에, 언어의 변경을 나타내기 위해 각 요소(element)들에) lang 속성(attribute)을 사용하여 나타납니다. 그것은 콘텐트의 언어에 대해 유저 에이전트들에 명시적인 표시를 제공하기 때문에, 적절한 언어 사전이 사용될 수 있고, 스크린 리더와 음성 출력을 가진 비슷한 보조 기술의 경우에, 콘텐트는 올바른 음성 / 언어 라이브러리를 (사용 가능한 경우) 사용하여 발음됩니다. 문서나 문서 일부의 언어와 일치하지 않는 lang 속성(attribute)을 사용하여 언어를 설정하는 것은 일부 사용자가 내용을 이해할 수 없게 만들 것입니다.


노드의 언어를 결정하기 위해, 유저 에이전트들은 XML 네임스페이스에 있는 lang 속성(attribute) 세트를 가지거나 네임스페이스가 없는 lang 속성(attribute) 세트를 가진 HTML 요소(element)인 가장 가까운 조상 요소(element)를 (노드가 요소(element)라면 그 요소(element)를 포함하여) 고려해야(must) 합니다. 그 속성(attribute)은 노드의 언어를 명시합니다(그 값에 상관하지 않고).

네임 스페이스가 없는 lang 속성(attribute)과 XML 네임스페이스에 있는 lang 속성(attribute)이 둘 모두 요소(element)에 설정된 경우, 유저 에이전트들은 XML 네임스페이스에 있는 lang 속성(attribute)을 사용해야(must)하고, 네임 스페이스가 없는 lang 속성(attribute)은 요소(element)의 언어 결정의 목적에 대해 무시되어야(must) 합니다.

루트 요소(element)를 포함하여 노드나 노드의 조상 중 어떠한 것도 속성(attribute) 세트를 가지지 않지만, 선처리 설정 기본 언어 세트가 존재한다면, 그것은 노드의 언어입니다. 선처리 설정 기본 언어 세트가 없다면, 상위 레벨 프로토콜(HTTP 같은)의 언어 정보가 있다면 대신 마지막 폴백 언어로서 그것이 사용되어야(must) 합니다. 그러한 언어 정보가 없고, 상위 레벨 프로토콜이 여러 언어를 출력하는 경우, 노드의 언어는 알 수 없고, 해당하는 언어 태그는 빈 문자열입니다.

예를 들어, 문서가 HTTP로 전송되고 Content-Language HTTP 헤더가 "en"로 정의되어 있다면 (그리고 선처리 설정 기본 언어가 없다면), 그 자체에 lang 속성이나 해당 요소(element)의 어떤 조상도 가지지 않는 문서 내 모든 요소(element)에 대해, 요소에 대한 폴백 언어는 영어가 될 것입니다. Content-Language 헤더의 값이 "de, fr, it" 였다면, 노드의 언어는 알 수 없습니다. 이 글은 HTTP 헤더와 언어 정보를 제공하는 meta 요소(element) 사용에 대한 몇 가지 추가적인 지침을 제공합니다.

결과 값이 알려진 언어 태그가 아니라면, 모든 다른 언어들와 별개의, 주어진 언어 태그를 가지는 알 수 없는 언어로 취급되어야(must) 합니다. 언어 태그를 기대하는 다른 서비스와 왕복하거나 통신하는 목적을 위해, 유저 에이전트들은 BCP 47 언어 태그가 되도록 태그 되고, 수정되지 않은 채로 알 수 없는 언어를 전달해야(should) 하기 때문에, 차후 서비스들은 언어 설명의 다른 유형으로 데이터를 해석하지 않습니다. [BCP47]

따라서, 예를 들어, lang="xyzzy"를 가진 요소(element)는, 둘 모두 동일하게 유효하지 않기는 하지만, 선택자 :lang(xyzzy)에 (예를 들어, CSS에서) 매칭될 것이지만 :lang(abcde)에는 매칭되지 않을 것입니다. 비슷하게, 웹 브라우저와 스크린 리더가 요소(element)의 언어에 대해 합력하여 통신했다면, 그것이 유효하지 않다는 것을 알았을 지라도, 결국에는 스크린 리더는 실제로 그 태그를 가지고 언어가 지원된 경우에 한하여, 브라우저는 스크린 리더에 언어가 "xyzzy"라고 알려줄 것입니다. 스크린 리더가 BCP 47과 인코딩 언어 이름을 위한 다른 문법이 모두 지원되고 그 다른 문법에서 문자열 "xyzzy"가 벨라루스어를 나타내는 방법이었다 하더라도, "xyzzy"는 벨라루스어가 BCP 47 코드로 기술 된 방식이 아니기 때문에 (BCP 47은 벨라루스어에 대해 코드 "be"를 사용합니다), 그것은 스크린리더가 텍스트를 벨라루스어로 취급하기 시작하는 것은 옳지 않게 될 것입니다.

결과 값이 빈 문자열이라면, 노드의 언어가 명시적으로 알 수 없음을 의미하는 것으로 해석 되어야(must) 합니다.


유저 에이전트들은 요소의 언어를 적절한 처리나 렌더링을 결정하는데 사용할 수 있습니다 (예를 들어, 적절한 폰트나 발음의 선택으로, 혹은 사전 선택을 위해, 혹은 날짜 선택기 같은 양식 컨트롤의 유저 인터페이스를 위해).


lang IDL 속성(attribute)은 네임 스페이스가 없는 lang 콘텐트 속성(attribute)을 반영해야(must) 합니다.

3.2.5.4. translate 속성(attribute)

translate 속성(attribute)은 페이지가 지역화 될 때 요소(element)의 속성(attribute) 값과 그것의 자식 Text 노드의 값이 번역될지 여부를 지정하는데 사용되는 열거 속성(attribute)입니다.

속성(attribute)의 키워드는 빈 문자열, yes, no입니다. 빈 문자열과 yes 키워드는 yes 상태에 매핑됩니다. no 키워드는 no 상태에 매핑됩니다. 게다가, 세번째 상태가 있는데, 누락 기본 값인 (그리고 유효하지 않은 기본 값인) inherit 상태입니다.

각 요소(element)는 (비 HTML 요소(element) 조차) 번역 가능 상태 혹은 번역 안함 상태에 속하는, 번역 모드를 가집니다. HTML 요소(element)translate 속성(attribute)이 yes 상태에 있다면, 요소(element)의 번역 모드번역 가능 상태에 있습니다; 그렇지 않고 요소(element)의 translate 속성(attribute)이 no 상태에 있다면, 요소(element)의 번역 모드번역 안함 상태에 있습니다; 그렇지 않으면, 요소(element)의 translate 속성(attribute)은 inherit 상태에 있거나 요소(element)는 HTML 요소(element)가 아니고 따라서 translate 속성(attribute)을 가지지 않습니다; 어느 경우에나, 요소(element)의 번역 모드는 그 부모 요소(element)의 상태가 있다면 그것과 동일한 상태에 있거나, 요소가 루트 요소(element)라면, 번역 가능 상태에 있습니다.

요소(element)가 번역 가능 상태에 있다면, 요소(element)의 번역 가능 속성(attribute)들과 자식 Text 노드의 값들은 페이지가 지역화 될 경우 번역 되어야 합니다.

요소(element)가 번역 안함 상태에 있는 경우, 예를 들어, 요소(element)가 사람의 이름이나 컴퓨터 프로그램의 이름을 포함하기 때문에, 요소(elment)의 속성(attribure)값과 자식 Text 노드의 값들은 페이지가 지역화 될 때 그대로 남습니다.

다음 속성(attribute)들은 번역 가능 속성(attribute)입니다:


translate IDL 속성(attribute)은 가져올 때 요소(element)의 번역 모드번역 가능이라면 true를 반환하고, 그렇지 않으면 false를 반환해야(must) 합니다. 설정할 때, 새로운 값이 true라면 콘텐트 속성(attribute)의 값을 "yes"로 설정하고, 그렇지 않으면 콘텐트 속성(attribute)의 값을 "no"로 설정해야(must) 합니다.

이 예제에서, 키보드 입력 견본과 프로그램 출력 견본을 제외하고, 페이지가 지역화 될 때 문서의 모든 것이 번역됩니다:
<!DOCTYPE HTML>
<html> <!-- default on the root element is translate=yes -->
  <head>
    <title>The Bee Game</title> <!-- implied translate=yes inherited from ancestors -->
  </head>
  <body>
    <p>The Bee Game is a text adventure game in English.</p>
    <p>When the game launches, the first thing you should do is type
      <kbd translate=no>eat honey</kbd>. The game will respond with:</p>
  <pre><samp translate=no>Yum yum! That was some good honey!</samp></pre>
  </body>
</html>
3.2.5.5. xml:base 속성(attribute) (XML만)

xml:base 속성(attribute)은 XML 기반에서 정의됩니다. [XMLBASE]

xml:base 속성(attribute)은 XML 문서들html 요소(element)에 사용될 수 있습니다. 작성자는 HTML 문서들에 있는 html 요소(element)에 must not use the xml:base를 사용하지 않아야(must) 합니다.

3.2.5.6. dir 속성(attribute)

dir 속성(attribute)은 요소(element)의 텍스트 방향성을 명시합니다. 속성(attribute)은 다음 키워드와 상태를 가진 열거 속성 입니다:

ltr 상태에 일치하는 ltr 키워드

요소(element)의 콘텐트가 명시적으로 방향성이 왼쪽에서 오른쪽으로 구분 된 텍스트임을 나타냅니다.

rtl 상태에 일치하는 rtl 키워드

요소(element)의 콘텐트가 명시적으로 방향성이 오른쪽에서 왼쪽으로 구분 된 텍스트임을 나타냅니다.

auto 상태에 일치하는 auto 키워드

요소(element)의 콘텐트가 명시적으로 방향성이 구분 된 텍스트임을 나타내지만, 방향은 요소(element)의 콘텐츠를 사용하여 (아래 설명된 대로) 프로그램적으로 결정됩니다.

이 상태에 의해 사용되는 휴리스틱은 매우 조잡합니다 (양방향 알고리즘에서 문단 레벨 결정과 유사한 방식으로, 강한 방향성을 가진 첫 번째 문자를 살필 뿐입니다). 작성자는 텍스트의 방향이 정말로 알 수 없고 적용 될 수 있는 더 나은 서버 사이드 휴리스틱이 없을 경우, 최후의 수단으로만 이 값을 사용하도록 권장됩니다. [BIDI]

textareapre 요소(element)에 대해, 휴리스틱은 문단별 레벨에 적용됩니다.

속성(attribute)은 유효하지 않은 기본 값누락 기본 값이 없습니다.


요소(element)의 방향성은 (HTML 요소(element)가 아닌 모든 요소) "ltr" 혹은 "rtl"이고, 다음 목록의 단계들의 첫 번째 적절한 설정에 따라 결정됩니다:

요소(element)의 dir 속성(attribute)이 ltr 상태에 있다면
요소(element)가 루트 요소(element)이고 dir 속성(attribute)이 정의된 상태에 있지 않다면 (즉, 존재하지 않거나 유효하지 않은 값을 가지는 경우)
요소(element)가 type 속성(attribute)이 Telephone 상태에 있고 dir 속성(attribute)이 정의된 상태에 있지 않은 (즉, 존재하지 않거나 유효하지 않은 값을 가지는 경우) input 요소(element)라면
요소(element)의 방향성이 "ltr"입니다.
요소(element)의 dir 속성(attribute)이 rtl 상태에 있다면
요소(element)의 방향성이 "rtl"입니다.
요소(element)가 type 속성(attribute)이 Text, Search, Telephone, URL, E-mail 상태에 있고, dir 속성(attribute)이 auto 상태에 있는 input 요소(element)라면
요소(element)가 textarea 요소(element)이고 dir 속성(attribute)이 auto 상태에 있다면
요소(element)의 이 양방향성 문자 유형 AL이나 R의 문자를 포함하고 요소의 의 그 문자에 앞서 양방향성 문자 유형 L의 문자가 없다면, 요소(element)의 방향성은 "rtl"입니다. [BIDI]

그렇지 않고, 요소(element)의 이 빈 문자열이 아니거나, 요소(element)가 루트 요소(element)라면, 요소(element)의 방향성은 "ltr"입니다.

그렇지 않으면, 요소(element)의 방향성은 요소(element)의 부모 요소(element)의 방향성과 같습니다.

요소(element)의 dir dir 속성(attribute)이 auto 상태에 있다면
요소(element)가 bdi 요소(element)이고 dir 속성(attribute)이 정의된 상태에 있지 않다면 (즉, 존재하지 않거나 유효하지 않은 값을 가지는 경우)
트리 순서에 따라 다음 기준에 일치하는 첫 번째 문자를 찾습니다:
  • 문자가 방향성이 결정되어야 할 요소(element)의 후손인 Text 노드에 있습니다.

  • 문자는 양방향성의 문자 유형 L, AL, 또는 R 입니다. [BIDI]

  • 문자가 방향성이 결정되어야 할 요소(element)의 후손이면서 다음 중 하나인 조상 요소(element)를 가진 Text 노드에 없습니다:

    • bdi 요소(element).

    • script 요소(element).

    • style 요소(element).

    • textarea 요소(element).

    • 정의된 상태에 있는 dir 속성(attribute)을 가진 요소(element).

그러한 문자가 발견되고 그것이 양방향성의 문자 유형 AL나 R의 것이라면, 요소(element)의 방향성은 "rtl"입니다.

그러한 문자가 발견되고 그것이 양방향성의 문자 유형 L의 것이라면, 요소(element)의 방향성은 "ltr"입니다.

그렇지 않고, 요소(element)가 루트 요소(element)라면, 요소(element)의 방향성은 "ltr"입니다.

그렇지 않으면, 요소(element)의 방향성은 부모 요소(element)의 방향성과 같습니다.

요소(element)가 부모 요소(element)를 가지고 dir 속성(attribute)이 정의된 상태에 있지 않다면 (즉, 존재하지 않거나 유효하지 않은 값을 가지는 경우)
요소(element)의 방향성은 요소(element)의 부모 요소(element)의 방향성과 같습니다.

속성(attribute)은 html 요소(element)에만 사용될 수 있기 때문에, 다른 네임스페이스의 요소(element)들에는 존재할 수 없습니다. 따라서, 다른 네임스페이스의 요소(element)들은 그들의 부모 요소(element)에서 방향성을 상속 받거나, 부모 요소(element)를 가지지 않는다면, 기본으로 "ltr"가 됩니다.


속성(attribute)의 텍스트가 렌더링 되는 어떤 방식에 포함되는 경우, HTML 요소(element)속성(attribute)의 방향성은 다음 목록의 단계들의 첫 번째 적절한 설정에 따라 결정됩니다:

속성(attribute)이 방향성이 가능한 속성(attribute)이고 요소(element)의 dir 속성(attribute)이 auto 상태에 있다면
양방향성의 문자 유형 L, AL, R의 것인 속성(attribute) 값의 첫 번째 문자(논리 순서에 따라)를 찾습니다 [BIDI]

그 문자가 발견되고 양방향성의 문자 유형 AL이나 R의 것이라면, 속성(attribute)의 방향성은 "rtl"입니다.

그렇지 않으면, 속성(attribute)의 방향성은 "ltr"입니다.

그렇지 않으면
속성(attribute)의 방향성요소(element)의 방향성과 동일합니다.

다음 속성(attribute)들은 방향성이 가능한 속성(attribute)들:


document . dir [ = value ]
html 요소(element)의 dir 속성(attribute)의 값이 있다면 이를 반환합니다.

html 요소(element)의 dir 속성(attribute)을 바꾸기 위해 "ltr"나 "rtl" 혹은 "auto"로 설정 될 수 있습니다.

html 요소(element)가 없다면, 빈 문자열을 반환하고 새로운 값을 무시합니다.

요소(element)의 dir IDL 속성(attribute)은 알려진 값으로만 제한된 그 요소(element)의 dir 콘텐트 속성(attribute)을 반영해야(must) 합니다.

Document 객체의 dir IDL 속성(attribute)은 html 요소(element)가 있다면 알려진 값으로만 제한된 그 요소의 dir 콘텐트 속성(attribute)을 반영해야(must) 합니다. 그러한 요소(element)가 없다면, 속성(attribute)은 빈 문자열을 반환해야(must)하고 설정 할 때 아무 것도 하지 않아야(must) 합니다.

작성자는 텍스트 방향성을 나타내기 위해 CSS를 사용하는 것 보다 dir 속성(attribute)을 사용하도록 강력히 권장되는데, 이는 CSS가 없는 경우에도 (예를 들어, 검색 엔진에 의해 해석되는 것 같은) 문서가 올바르게 계속해서 렌더링 되는 방법이기 때문입니다.

이 마크업 코드 조각은 IM 대화 내용의 것입니다.
<p dir=auto class="u1"><b><bdi>Student</bdi>:</b> How do you write "What’s your name?" in Arabic?</p>
<p dir=auto class="u2"><b><bdi>Teacher</bdi>:</b> ما اسمك؟</p>
<p dir=auto class="u1"><b><bdi>Student</bdi>:</b> Thanks.</p>
<p dir=auto class="u2"><b><bdi>Teacher</bdi>:</b> That’s written "شكرًا".</p>
<p dir=auto class="u2"><b><bdi>Teacher</bdi>:</b> Do you know how to write "Please"?</p>
<p dir=auto class="u1"><b><bdi>Student</bdi>:</b> "من فضلك", right?</p>

p 요소(element)에 대한 주어진 적절한 스타일 시트와 기본 정렬 스타일, 즉, 텍스트를 문단의 시작 모서리에 정렬하기 위해, 결과 렌더링은 다음과 같을 수 있습니다:

오른쪽으로 정렬 될 두 번째 문단과 마지막 문단을 제외하고, 왼쪽으로 콜론, 그 왼쪽으로 텍스트 처음이 있는 오른쪽에 정렬된 사용자 이름을 (이 예제에서는 'Student'와 'Teacher') 가진 왼쪽 정렬된 문단을 가진 별개의 블럭으로 렌더링 된 각 문단

앞서 언근한 바와 같이, auto 값은 만병통치약이 아닙니다. 이 예제에서 마지막 문단은 아랍 문자를 가지고 시작되었기 때문에, "right?"가 아랍어 텍스트의 왼쪽에 있도록 되어, 오른쪽에서 왼쪽 텍스트가 되는 것으로 잘못 해석됩니다

3.2.5.7. class 속성(attribute)

HTML 요소(element)는 명시된 class 속성(attribute)을 가질 수 있습니다.

속성(attribute)이 명시되었다면 이 속성(attribute)은 요소(element)가 속하는 다양한 클래스를 나타내는 공백으로 분리된 토큰의 세트인 값을 가져야(must) 합니다.

HTML 요소(element)가 할당한 클래스는 class 속성(attribute)의 값이 공백으로 분리될 때 반환되는 모든 클래스로 구성됩니다 (중복은 무시합니다).

요소(element)에 클래스를 할당하는 것은 클래스가 CSS에서 선택자에, DOM에서 getElementsByClassName() 메서드에, 다른 그러한 기능들에 매칭하는데 영향을 줍니다.

작성자가 class 속성(attribute)에 사용할 수 있는 토큰에 추가적인 제한 사항은 없지만, 콘텐트의 희망 표현을 기술하는 값보다 콘텐트의 특징을 기술하는 값을 사용하도록 권장됩니다.


DOM 명세에 정의된 classNameclassList IDL 속성(attribute)은 class 콘텐트 속성(attribute)을 반영합니다. [DOM]

3.2.5.8. style 속성(attribute)

CSP3 지시자에 기반한 style 콘텐트 속성(attribute)를 차단하는 네이티브 구현은 알려진 것이 없습니다. 따라서 이 기능은 신뢰되지 않아야(should) 합니다.

모든 html 요소(element)들style 콘텐트 속성(attribute) 세트를 가질 수 있습니다. 이것은 CSS 스타일링 속성(attribute) 구문 명세에 의해 정의된 CSS 스타일링 속성(attribute)입니다. [CSS-STYLE-ATTR]

CSS를 지원하는 유저 에이전트들에서, 속성(attribute)의 값은 속성(attribute)이 추가되거나 그 값이 변경되는 경우, CSS 스타일링 속성(attribute)에 대해 주어진 규칙을 따라 해석되어야(must) 합니다. [CSS-STYLE-ATTR]

그러나, 요소(element)의 인라인 동작은 콘텐트 보안 정책에 의해 차단되어야(should) 하는가? 알고리즘이 속성(attribute)의 요소(element)와 "style attribute"에서 실행되는 경우 "Blocked"를 반환한다면, 속성(attribute))의 값에 정의된 스타일 규칙은 요소(element)에 적용되지 않아야(must) 합니다. [CSP3]

요소(element)들에 style 속성(attribute)들을 사용하는 문서는 그 속성(attribute)이 제거된 경우에도 여전히 이해될 수 있고 사용될 수 있어야(must) 합니다.

특히, 콘텐트를 숨기고 보여주기 위해, 혹은 문서에 포함되지 않은 의미(meaning)를 전달하기 위해 style 속성(attribute)을 사용하는 것은 적합하지 않습니다. (콘텐트를 숨기고 보여주기 위해서는, hidden 속성(attribute)을 사용하세요.)


element . style
요소(element)의 style 속성(attribute)에 대한 CSSStyleDeclaration 객체를 반환합니다.
style IDL 속성(attribute)은 CSS 객체 모델 (CSSOM) 명세에서 정의됩니다. [CSSOM]
다음 예제에서, 색상을 참조하는 단어가 시각 매체에 관련 색상으로 표시되도록 하기 위해 span 요소(element)와 style 속성(attribute)을 사용하여 마크업 됩니다.
<p>My sweat suit is <span style="color: green; background:
transparent">green</span> and my eyes are <span style="color: blue;
background: transparent">blue</span>.</p>
3.2.5.9. data-* 속성(attribute)들로 보이지 않는 커스텀 데이터 삽입하기

커스텀 데이터 속성(attribute)은 이름이 하이픈 뒤에 적어도 하나의 문자를 가지고, XML 호환 가능하며, 대문자 ASCII 문자를 포함하는, 문자열 "data-"로 시작하는 네임스페이스 없는 속성(attribute)입니다.

HTML 문서들html 요소(element)들의 모든 속성(attribute) 이름은 자동적으로 ASCII 소문자로 얻어지기 때문에, ASCII 대문자에 대한 제한 사항은 그 문서들에 영향을 주지 않습니다.

커스텀 데이터 속성(attribute)들은 페이지나 어플리케이션에 대해 더 이상 적절한 속성(attribute)들이나 요소(element)들이 없는 커스텀 데이터를 저장하기 위해 의도됩니다.

이 속성(attribute)들은 속성(attribute)들을 사용하는 사이트의 관리자가 모르는 소프트웨어에서 사용을 위해 의도되지 않습니다. 여러 독립적인 도구에 의해 사용되는 일반적인 확장을 위해, 이 명세는 명시적으로 기능을 제공하도록 확장되어야(should) 하거나, 마이크로데이터 같은 기술이 (표준화 된 표현 형식을 사용하는) 사용되어야(should) 합니다.

예를 들어, 음악 관련 사이트는 각 트랙의 길이를 포함하는 커스텀 데이터 속성(attribute)을 가진 앨범의 트랙을 나타내는 목록 항목을 표시할 수 있습니다. 이 정보는 이후에 사이트에 의해 사용자가 트랙 길이로 목록을 정렬하거나 특정 길이의 트랙에 대한 목록을 필터링하는 것을 허용하는데 사용될 수 있습니다.
<ol>
  <li data-length="2m11s">Beyond The Sea</li>
  ...
</ol>

하지만, 사용자가 이 데이터를 살펴봄으로 특정 길이의 트랙을 찾기 위해 그 음악 사이트와 관련되지 않은 일반 소프트웨어를 사용하는 것은 적절하지 않을 것입니다.

이것은 이 속성(attribute)들이 사이트의 자체 스크립트에 의해 사용되도록 의도되었고, 범용적으로 사용가능한 메타데이터에 대한 일반적인 확장 메커니즘이 아니기 때문입니다.

비슷하게, 페이지 작성자는 사용하려는 번역 도구에 대한 정보를 제공하는 마크업을 작성할 수 있습니다:
<p>The third <span data-mytrans-de="Anspruch">claim</span> covers the case of
<span translate="no">HTML</span> markup.</p>

이 예제에서, "data-mytrans-de" 속성(attribute)은 "claim"이라는 문구를 독일어로 번역 하는 MyTrans 제품에 사용할 특정 텍스트를 제공합니다. 하지만, 표준 translate 속성(attribute)은 모든 언어에서 "HTML"은 변경되지 않고 남기기 위한 것임을 알리기 위해 사용됩니다. 표준 속성(attribute)이 사용 가능한 경우, 커스텀 데이터 속성(attribute)이 사용될 필요가 없습니다.

HTML 요소(element)는 임의의 값을 가지고 명시된 커스텀 데이터 속성(attribute)들을 얼마든지 가질 수 있습니다.


element . dataset
요소(element)의 data-* 속성(attribute)들에 대한 DOMStringMap 객체를 반환합니다.

하이픈으로 연결된 이름들은 카멜-케이스가 됩니다. 예를 들어, data-foo-bar=""element.dataset.fooBar가 됩니다.

dataset IDL 속성(attribute)은 요소의 모든 data-* 속성(attribute)들에 대한 편리한 접근자를 제공합니다. 가져올 때, dataset IDL 속성(attribute)은 그들의 요소(element)에 이 속성(attribtue)들을 노출하는 다음 알고리즘과 연관된 DOMStringMap 객체를 반환해야(must) 합니다:

이름-값 쌍의 목록을 가져오기 위한 알고리즘

  1. list를 이름-값 쌍의 빈 목록으로 둡니다.

  2. 첫 다섯 문자가 문자열 "data-"이고 나머지 문자들이 (있다면) 대문자 ASCII 글자들을 포함하지 않는 요소(element)의 각 콘텐트 속성(attribute)에 대해, 그 속성(attribute)들이 요소(element)의 속성(attribute) 목록에 나열된 순서에 따라, 이름이 처음 다섯 글자가 삭제 된 속성(attribute)의 이름과 값이 속성(attribute)의 값인 이름-값 쌍을 list에 추가합니다.

  3. list의 각 이름에 대해, 이름에 소문자 ASCII 글자가 뒤따르는 각 U+002D HYPHEN-MINUS 문자 (-)에 대해, U+002D HYPHEN-MINUS 문자 (-)를 삭제하고 그 뒤에 오는 글자를 ASCII 대문자로 변환 된 동일한 글자로 변경합니다.

  4. list를 반환합니다.

이름을 특정 값으로 설정하기 위한 알고리즘

  1. name을 알고리즘에 전달되는 이름으로 둡니다.

  2. value를 알고리즘에 전달되는 값으로 둡니다.

  3. name소문자 ASCII 글자가 뒤따르는 U+002D HYPHEN-MINUS 문자 (-)를 포함한다면, "SyntaxError" DOMException을 던지고 이 단계들을 중단합니다.

  4. name에 각 대문자 ASCII 글자에 대해, 글자 앞에 U+002D HYPHEN-MINUS 문자 (-)를 추가하고 글자를 ASCII 소문자로 변환 된 동일한 글자로 바꿉니다.

  5. name의 맨 앞에 문자열 data-를 추가합니다.

  6. 이름 name을 가진 속성(attribute)의 값을 속성이 이미 존재한다면 이전 값을 교체하여, 값 value으로 설정합니다. setAttribute()가 속성을 이름 name으로 설정할 때 예외를 던졌다면, 이것은 동일한 예외를 던져야(must) 합니다.

이름을 삭제하기 위한 알고리즘

  1. name을 알고리즘에 전달될 이름으로 둡니다.

  2. name의 각 대문자 ASCII 글자에 대해, 글자 앞에 U+002D HYPHEN-MINUS 문자 (-)를 추가하고 글자를 ASCII 소문자로 변환 된 동일한 글자로 바꿉니다.

  3. name의 맨 앞에 문자열 data-를 추가합니다.

  4. 이름 name을 가진 속성(attribute)가 있다면, 그 속성(attribute)을 제거합니다. 달리 아무 것도 하지 않습니다.

이 알고리즘은 이름-값 쌍의 목록을 가져오는 앞선 알고리즘에 의해 주어진 이름에 대해서만 웹 IDL 명세에 의해 호출 될 것입니다. [WEBIDL]

웹 페이지가 우주선을 나타내기 위한 요소(element)를 원한다면, 예를 들어 게임의 일부분으로, data-* 속성(attribute)들과 함께 class 속성(attribute)을 사용해야(have to) 할 것입니다:
<div class="spaceship" data-ship-id="30">
  <button class="fire" onclick="spaceships[this.parentNode.dataset.shipId].fire()">
    Fire
  </button>
</div>

API에서 하이픈으로 연결된 속성(attribute)이름이 카멜 케이스로 되는 방식에 주목하세요.

작성자는 속성(attribute)들이 무시되고 관련된 CSS가 사라지는 경우, 페이지가 여전히 사용 가능 하도록 이러한 확장을 신중하게 설계해야 합니다.

유저에이전트들은 이 속성(attribute)들이나 값들로부터 구현 행동을 파생하지 않아야(must) 합니다. 유저 에이전트들을 위해 의도된 명세는 이 속성(attribute)들이 의미있는 값을 가지도록 정의하지 않아야(must) 합니다.

자바스크립트 라이브러리들은 그것들이 사용 되는 페이지의 일부로 간주되기 때문에 커스텀 데이터 속성(attribute)들을 사용할 수 있습니다. 많은 작성자들에 의해 재사용되는 라이브러리의 작성자는 충돌 위험을 줄이기 위해 속성(attribute) 이름에 그들의 이름을 포함하도록 권장됩니다. 그것이 말이 된다면, 라이브러리 작성자는 또한 정확한 이름이 커스텀 가능한 속성(attribute) 이름으로 사용되도록 권장되기 때문에, 모르고 동일한 이름을 고른 작성자의 라이브러리가 같은 페이지에 사용될 수 있고, 특정 라이브러리의 여러 버전이, 그 버전이 서로 호환이 되지 않는 경우에서 조차 동일한 페이지에서 사용 될 수 있습니다.

예를 들어, "DoQuery"라 불리는 라이브러리는 data-doquery-range와 같은 속성(attribute) 이름을 사용할 수 있고, "jJo"라 불리는 라이브러리는 data-jjo-range와 같은 속성(attribute) 이름을 사용할 수 있습니다. jJo 라이브러리는 사용할 접두어를 설정하기 위한 API를 제공 할 수도 있습니다 (예를 들어, data-j2-range와 같은 이름을 가진 속성(attribute)을 만드는 J.setDataPrefix("j2")).

3.2.6. 양방향 알고리즘에 관한 요구사항

3.2.6.1. 양방향 알고리즘 서식 문자에 대한 작성 적합성 기준

콘텐츠Text 노드들이 있는 html 요소(element)들텍스트 콘텐트와 자유 형식 텍스트를 허용하는 html 요소(element)들의 속성(attribute)의 텍스트는 U+202A부터 U+202E까지 그리고 U+2066부터 U+2069까지 범위의 문자들을 (양방향 알고리즘 서식 문자들) 포함할 수 있습니다. 하지만, 이 문자들의 사용은 이 문자들에 의해 생성된 모든 삽입 혹은 재정의들이 다른 부모 요소(element)로 시작하고 끝나지 않도록 제한되기 때문에, 모든 그러한 삽입과 재정의들은 명시적으로 U+202C POP 방향성 형식 문자로 끝납니다. 이것은 양방향 알고리즘에 예기치 않은 영향을 가지는 방법으로 재사용되는 텍스트의 발생을 줄일 수 있습니다. [BIDI]

앞서 언급된 제한사항들은 문서의 특정 부분이 양방향 알고리즘 서식 문자 범위들을 구성하는 것을 명시하는 것에 의해 정의되고, 그러한 범위에 요구사항을 도입하고 있습니다.

다음 알고리즘을 HTML 요소(element) element에 적용한 결과 문자열은 양방향 알고리즘 서식 문자 범위들 입니다:

  1. output을 문자열의 빈 목록으로 둡니다.

  2. string을 빈 문자열로 둡니다.

  3. nodeelement의 첫 번째 자식 노드가 있다면 그것으로, 그렇지 않으면 null로 둡니다.

  4. Loop: node가 null이라면, end로 라벨링 된 단계로 건너뜁니다.

  5. 다음 목록에 처음 매칭되는 단계에 따라 node를 처리합니다:

    nodeText 노드라면
    node의 텍스트 데이터를 string에 추가(append)합니다.
    nodebr 요소(element)라면
    node흐름 콘텐트이고 어구 콘텐트는 아닌 HTML 요소(element)라면
    string이 빈 문자열이 아니라면, outputstring을 넣고(push) string를 빈 문자열로 둡니다.
    그렇지 않으면
    아무 것도 하지 않습니다.
  6. nodenode의 다음 형제가 있다면 그것으로, 그렇지 않으면 null로 둡니다.

  7. loop로 라벨링 된 단계로 건너 뜁니다.

  8. End: string이 빈 문자열이 아니라면, outputstring를 넣습니다(push).

  9. 양방향 알고리즘 서식 문자 범위들로서 output를 반환합니다.

HTML 요소(element)의 네임스페이스 없는 속성(attribute)의 값은 양방향 알고리즘 서식 문자 범위입니다.

위에 설명된 대로, 양방향 알고리즘 서식 문자 범위인 모든 문자열은 다음 유니코드인 문자 세트인 ABNF의 string 문자열과 일치해야(must) 합니다. [ABNF]

string        = *( plaintext ( embedding / override / isolation ) ) plaintext
embedding     = ( lre / rle ) string pdf
override      = ( lro / rlo ) string pdf
isolation     = ( lri / rli / fsi ) string pdi
lre           = %x202A ; U+202A LEFT-TO-RIGHT EMBEDDING
rle           = %x202B ; U+202B RIGHT-TO-LEFT EMBEDDING
lro           = %x202D ; U+202D LEFT-TO-RIGHT OVERRIDE
rlo           = %x202E ; U+202E RIGHT-TO-LEFT OVERRIDE
pdf           = %x202C ; U+202C POP DIRECTIONAL FORMATTING
lri           = %x2066 ; U+2066 LEFT-TO-RIGHT ISOLATE
rli           = %x2067 ; U+2067 RIGHT-TO-LEFT ISOLATE
fsi           = %x2068 ; U+2068 FIRST STRONG ISOLATE
pdi           = %x2069 ; U+2069 POP DIRECTIONAL ISOLATE
plaintext     = *( %x0000-2029 / %x202F-2065 / %x206A-10FFFF )
                ; 양방향 서식 문자가 없는 모든 문자열

U+2069 POP 방향성 구분 문자가 열린 삽입과 재정의를 암묵적으로 종료하는데 반해, 이 암묵적 범위 클로저에 의존하는 텍스트는 이 명세에 적합하지 않습니다. 이 섹션의 요구사항에 따르기 위해 삽입, 재정의, 구분의 모든 문자열은 암묵적으로 종료될 필요가 있습니다.

작성자는 양방향 알고리즘 서식 문자를 수동으로 관리하는 것 보다 dir 속성(attribute), bdo 요소(element), bdi 요소(bdi)를 사용하도록 권장됩니다. 양방향 알고리즘 서식 문자는 CSS와 충분히 상호작용 하지 않습니다.

3.2.6.2. 유저 에이전트 적합 기준

유저 에이전트들은 문서와 문서의 일부를 렌더링 할 때 문자의 적절한 순서를 결정하기 위해 유니코드 양방향성 알고리즘을 구현해야 합니다. [BIDI]

HTML의 유니코드 양방향 알고리즘으로의 매핑은 3가지 방법 중 하나로 수행 되어야(must) 합니다. 유저 에이전트는 특별한 CSS unicode-bidi, direction, content 속성(property)들을 사용하여 CSS를 구현해야(must) 하고 그것의 유저 에이전트 스타일 시트에 이 명세의 §10 Rendering 섹션에 주어진 그 속성(property)들을 사용하는 규칙을 가져야(must) 하거나, 혹은 그 대신에, 유저 에이전트는 앞서 언급된 속성(property)들이 구현되고 모든 앞서 언급된 규칙들을 포함하는 유저 에이전트 스타일 시트를 가지면서 문서에 명시된 스타일 시트가 그것들을 재정의 하도록 두지 않는 것 처럼 동작해야(must) 하거나, 혹은 그 대신에, 유저 에이전트는 동등한 의미(semantics)를 가진 다른 스타일링 언어를 구현해야(must) 합니다. [CSS-WRITING-MODES-3] [CSS3-CONTENT]

다음 요소(element)들과 속성(attribute)들은 §10 Rendering 섹션에 의해 정의된, 이 섹션의 요구사항 때문에 모든 유저 에이전트들에 대한 요구사항인 (제안된 기본 렌더링을 지원하는 것뿐 아니라), 요구사항을 가집니다:

  • dir 속성(attribute)

  • bdi 요소(element)

  • bdo 요소(element)

  • br 요소(element)

  • pre 요소(element)

  • textarea 요소(element)

  • wbr 요소(element)

3.2.7. WAI-ARIA와 HTML 접근성 API 매핑

3.2.7.1. ARIA 작성 요구사항들
작성자는 HTML 요소(element)들에 ARIA in HTML [html-aria]에 명시된 요구사항과 충돌하는 것들을 제외하고 ARIA 명세에 기술된 요구사항에 부합되게 ARIA rolearia-* 속성(attribute)을 사용할 수 있습니다. 이 예외 사항들은 보조 기술 제품이 문서의 실제 상태를 나타내지 않는 무의미한 상태를 보고하는 것으로부터 작성자를 방지하기 위한 것입니다. [WAI-ARIA]

대부분의 경우에 기본 암묵적 ARIA 의미(semantics)에 일치하는 ARIA role과/혹은 aria-* 속성(attribute)을 설정하는 것은 불필요하고 이 속성(property)들은 이미 브라우저에 의해 설정되어 있기 때문에 권장되지 않습니다.

작성자들은 이 섹션에 제공된 것 이상으로 ARIA in HTML 사용에 대한 지침을 위해 다음 문서의 사용이 권장됩니다:

  • Notes on Using ARIA in HTML - 접근 가능한 리치 인터넷 어플리케이션 명세를 사용하여 HTML 요소(element)들에 접근성 정보를 추가하는 방법에 대한 개발자를 위한 실질적인 지침 [WAI-ARIA].
  • WAI-ARIA 1.1 Authoring Practices - 접근 가능한 리치 인터넷 어플리케이션을 이해하고 구현하기 위한 작성자의 지침.
3.2.7.2. 적합성 검사기 구현 요구사항들

적합성 검사기는 ARIA in HTML에 정의된 대로 HTML 요소(element)들에 ARIA rolearia-* 속성(attribute)들의 사용에 대한 문서 적합성 요구사항을 구현하도록 요구됩니다. [html-aria]

3.2.7.3. 유저 에이전트 구현 요구사항들

유저 에어전트들은 ARAI 명세 [WAI-ARIA][core-aam-1.1]에 정의된 대로, 모든 HTML 요소(element)들에 ARIA 의미론을 구현하도록 요구됩니다.

유저 에어전트들은 HTML 접근성 API 매핑 명세 [html-aam-1.0]에 정의된 대로, 모든 HTML 요소(element)들에 접근성 API 의미론을 구현하도록 요구됩니다.

ARIA 명세에 정의된 ARIA 속성(attribute)들은 CSS 가상 클래스 매칭이나, 보조 기술을 사용하지 않는 유저 인터페이스 양상이나, 이 명세어 정의된 유저 인터랙션 이벤트의 기본 동작에 어떠한 영향도 가지지 않습니다.

3.2.7.3.1. ARIA 역할(Role) 속성(Attribute)
모든 HTML 요소(element)는 명시된 ARIA role 속성(attribute)을 가질 수 있습니다. 이것은 [WAI-ARIA]에 의해 정의된 ARIA 역할(Role) 속성(attribute) 입니다.

속성(attribute)이 명시되었다면, 공백으로 구분된 토큰의 세트인 값을 가져야(must)합니다; 각 토큰은 WAI-ARIA 명세 [WAI-ARIA]에 정의된 비 추상 역살(role)이어야(must) 합니다.

HTML 요소(element)에 할당 된 WAI-ARIA 역할(role)은 role 속성(attribute)이 공백으로 분리되는 경우 생성된 값의 목록에서 발견 된 첫 번째 비 추상 역할(role) 입니다.
3.2.7.3.2. 상태(State)와 속성(Property) 속성(Attribute)들
모든 HTML 요소(element)는 명시된 ARIA 상태(state)와 속성(property) 속성(attribute)들을 가질 수 있습니다. 이 속성(attribute)들은 [WAI-ARIA]에 의해 정의됩니다.

ARIA 상태(State)와 속성(Property) 속성(attribute)들의 부분 집합은 [WAI-ARIA] 명세의 "범용 상태(State)들과 속성(Property)들"로 정의된 것입니다.

이 속성(attribute)들이 명시되었다면 [WAI-ARIA]에 따라 적절한 HTML 값 유형에 매핑된, 상태(state) 혹은 속성(property)에 대한 정의의 "Value" 필드에 있는 ARIA 값 유형인 값을 가져야(must) 합니다.

ARIA 상태(State)와 속성(Property) 속성(attribute)들은 모든 요소(element)에 사용될 수 있습니다. 하지만, 그것들이 항상 의미있는 것은 아니며, 그러한 경우 유저 에어전트들은 DOM에 그것들을 포함하는 것과 별개로 처리하는 것을 수행하지 않을 수 있습니다. 상태(State)와 속성(Property) 속성(attribute)들은 [WAI-ARIA] 뿐만 아니라 HTML 접근성 API 매핑 명세 [html-aam-1.0]의 요구사항, 그리고 ARIA 명세들 [WAI-ARIA][core-aam-1.1]에 정의된 대로 처리 됩니다.

3.2.7.4. 허용된 ARIA 역할(role)들, 상태(state)들, 속성(property)들

이 섹션은 비 규범적입니다.

다음 표는 HTML에 사용에 대해 허용된 ARIA 역할(role)들, 상태(state)들, 속성(property)들에 대한 유용한 참고 사항을 제공합니다. 모든 ARIA 역할(role)들, 상태(state)들, 속성(property)들은 규범적으로 [WAI-ARIA] 명세에 정의됩니다. 표의 ARIA 역할(role)들, 상태(state)들, 속성(property)들에 대한 링크는 규범적인 [WAI-ARIA] 정의를 참조합니다.

ARIA 역할(role)들, 상태(state)들, 속성(property)들
역할(role) 설명 요구되는 속성(property)들 지원되는 속성(property)들
any ARIA 범용 상태(state)들과 속성(property)들은 모든 HTML 요소(element)에 사용될 수 있습니다. 없음
  • aria-atomic

  • aria-busy (state)

  • aria-controls

  • aria-describedby

  • aria-disabled (state)

  • aria-dropeffect

  • aria-flowto

  • aria-grabbed (state)

  • aria-haspopup

  • aria-hidden (state)

  • aria-invalid (state)

  • aria-label

  • aria-labelledby

  • aria-live

  • aria-owns

  • aria-relevant

alert 중요한 메세지, 그리고 대개 시간에 민감한 정보. 관련된 alertdialogstatus를 참고하세요. 없음
  • aria-expanded (state)

alertdialog 초기 초점이 대화상자 안의 요소(element)에 가는, 경고 메세지를 포함하는 대화상자 유형. 관련된 alertdialog를 참고하세요. 없음
  • aria-expanded (state)

application 웹 문서와 다른, 웹 어플리케이션으로 선언된 영역 없음
  • aria-expanded (state)

article 문서, 페이지, 사이트의 독립적인 부분을 구성하는 구성 요소로 구성된 페이지의 섹션. 없음
  • aria-expanded (state)

banner 페이지에 한정된 콘텐트 보다는 대부분 사이트 지향적인 콘텐트를 포함하는 영역. 없음
  • aria-expanded (state)

button 클릭되거나 눌려질 경우 사용자 발생 동작을 허용하는 입력. 관련된 link를 참고하세요. 없음
  • aria-expanded (state)

  • aria-pressed (state)

checkbox 세 가지 가능한 값을 가지는 체크 가능한 입력: true, false, 혹은 mixed.
  • aria-checked (state)

columnheader 컬럼에 대한 제목(header) 정보를 포함하는 셀. 없음
  • aria-sort

  • aria-readonly

  • aria-required

  • aria-selected (state)

  • aria-expanded (state)

combobox 선택의 표현; 일반적으로 사용자가 옵션을 선택하기 위해 앞서 타이핑 할 수 있는 텍스트 상자와 유사하거나, 혹은 목록 내 새로운 항목으로 임의의 텍스트를 입력하기 위한 유형. 관련된 listbox를 참고하세요.
  • aria-expanded (state)

  • aria-autocomplete

  • aria-required

  • aria-activedescendant

complementary DOM 계층에서 비슷한 수준에 있는 주 콘텐트를 보완하도록 설계되고, 주 콘텐트와 분리되는 경우에도 여전히 의미가 있는, 문서의 지원 섹션. 없음
  • aria-expanded (state)

contentinfo 부모 문서에 대한 정보를 포함하는 인식 가능한 큰 영역. 없음
  • aria-expanded (state)

definition 용어나 개념의 정의. 없음
  • aria-expanded (state)

dialog 대화상자는 사용자가 정보를 입력하거나 응답할 것을 요구하도록 유도하기 위해 어플리케이션의 현재 처리를 중단시키도록 설계된 어플리케이션 윈도우 입니다. 관련된 alertdialog를 참고하세요. 없음
  • aria-expanded (state)

directory 콘텐트의 정적 테이블과 같은, 그룹의 멤버들에 대한 참조 목록. 없음
  • aria-expanded (state)

document 웹 어플리케이션과 다른, 문서 콘텐트로서 선언된 연관된 정보를 포함하는 영역. 없음
  • aria-expanded (state)

form 전체적으로 양식을 생성하기 위해 결합하는 항목들과 객체들의 컬렉션을 포함하는 랜드마크(landmark) 영역. 관련된 search를 참고하세요. 없음
  • aria-expanded (state)

grid 그리드는 표 처럼, 행과 열로 배치되는 표로 나타낸 데이터의 칸들을 포함하는 대화형(interactive) 컨트롤 입니다. 없음
  • aria-level

  • aria-multiselectable

  • aria-readonly

  • aria-activedescendant

  • aria-expanded (state)

gridcell grid나 treegrid에 있는 칸. 없음
  • aria-readonly

  • aria-required

  • aria-selected (state)

  • aria-expanded (state)

group 보조 기술에 의해 페이지 요약이나 콘텐트 목차에 포함되도록 의도되지 않은 사용자 인터페이스 객체의 집합 없음
  • aria-activedescendant

  • aria-expanded (state)

heading 페이지의 섹션에 대한 제목(heading) 없음
  • aria-level

  • aria-expanded (state)

img 이미지를 구성하는 요소(element)의 컬렉션에 대한 컨테이너. 없음
  • aria-expanded (state)

link 내부 혹은 외부 리소스가 활성화 될 때 유저 에이전트가 그 리소스를 탐색하도록 하는 내부 혹은 외부 리소스에 대한 대화형(interactive) 참조. 관련된 button을 참고하세요. 없음
  • aria-expanded (state)

list 비 대화형(non-interactive) 목록 항목들의 그룹. 관련된 listbox를 참고하세요. 없음
  • aria-expanded (state)

listbox 사용자가 선택 목록으로부터 하나 이상의 항목을 선택하도록 허용하는 위젯. 관련된 comboboxlist를 참고하세요. 없음
  • aria-multiselectable

  • aria-required

  • aria-expanded (state)

  • aria-activedescendant

  • aria-expanded (state)

listitem listdirectory의 단일 항목. 없음
  • aria-level

  • aria-posinset

  • aria-setsize

  • aria-expanded (state)

log 새로운 정보가 의미있는 순서로 추가되고 오래된 정보가 사라질 수 있는 라이브 영역의 유형. 관련된 marquee를 참고하세요. 없음
  • aria-expanded (state)

main 문서의 주요 콘텐트. 없음
  • aria-expanded (state)

marquee 중요하지 않은 정보가 자주 변경되는 라이브 영역의 유형. 관련된 log를 참고하세요. 없음
  • aria-expanded (state)

math 수학적 표현을 나타내는 콘텐트. 없음
  • aria-expanded (state)

menu 사용자에게 선택 목록을 제공하는 위젯 유형. 없음
  • aria-expanded (state)

  • aria-activedescendant

  • aria-expanded (state)

menubar 대개 보이는 상태로 유지되고 대개 가로로 표현되는 메뉴의 표현. 없음
  • aria-expanded (state)

  • aria-activedescendant

  • aria-expanded (state)

menuitem menumenubar에 의해 포함되는 선택 그룹의 옵션. 없음
menuitemcheckbox 3가지 가능한 값을 가지는 체크 가능한 menuitem: true, false, 혹은 mixed.
  • aria-checked (state)

menuitemradio 한 번에 하나만 체크될 수 있는, menuitemradio 역할(role)들의 그룹에 있는 체크 가능한 menuitem
  • aria-checked (state)

  • aria-posinset

  • aria-selected (state)

  • aria-setsize

navigation 문서를 탐색하거나 문서에 관련된 탐색 요소(대개 링크들)의 컬렉션. 없음
  • aria-expanded (state)

note 콘텐트가 설명적이거나 리소스의 주요 콘텐트에 보조적인 섹션. 없음
  • aria-expanded (state)

option 선택 목록 내 선택 가능한 항목. 없음
  • aria-checked (state)

  • aria-posinset

  • aria-selected (state)

  • aria-setsize

presentation 암묵적 네이티브 역할(role) 의미(semantics)가 접근성 API에 매핑되지 않는 요소(element) 없음
progressbar 오랜 시간이 걸리는 작업에 대한 진행 상태를 표시하는 요소(element). 없음
  • aria-valuemax

  • aria-valuemin

  • aria-valuenow

  • aria-valuetext

radio 한 번에 하나만 체크 될 수 있는, radio 역할(role)들의 그룹의 체크 가능한 입력.
  • aria-checked (state)

  • aria-posinset

  • aria-selected (state)

  • aria-setsize

radiogroup 라디오 버튼들의 그룹. 없음
  • aria-required

  • aria-activedescendant

  • aria-expanded (state)

region 작성자가 페이지 요약이나 콘텐트 목록에 포함되기에 충분히 중요하다고 느끼는, 예를 들어, 라이브 스포츠 경기 이벤트 통계를 포함하는 페이지의 영역, 웹 페이지나 문서의 큰 인식 가능한 섹션. 없음
  • aria-expanded (state)

row grid에 있는 칸의 행. 없음
  • aria-level

  • aria-selected (state)

  • aria-activedescendant

  • aria-expanded (state)

rowgroup grid에 있는 하나 이상의 행 요소(element)를 포함하는 그룹. 없음
  • aria-activedescendant

  • aria-expanded (state)

rowheader grid에 있는 행에 대한 제목(header) 정보를 포함하는 칸. 없음
  • aria-sort

  • aria-readonly

  • aria-required

  • aria-selected (state)

  • aria-expanded (state)

scrollbar 콘텐트가 뷰 영역에 꽉 차게 보이는지에 관계 없이, 뷰 영역에 있는 콘텐트의 스크롤을 제어하는 그래픽 객체.
  • aria-controls

  • aria-orientation

  • aria-valuemax

  • aria-valuemin

  • aria-valuenow

  • aria-expanded (state)

search 전체적으로 검색 기능을 생성하기 위해 결합하는 항목들과 객체들의 컬렉션을 포함하는 랜드마크(landmark) 영역. 관련된 form를 참고하세요. 없음
  • aria-expanded (state)

  • aria-orientation

separator 콘텐트의 섹션이나 메뉴항목들의 그룹을 분리하고 구별하는 구분자. 없음
  • aria-valuetext

slider 주어진 범위에서 사용자가 값을 선택하는 사용자 입력.
  • aria-valuemax

  • aria-valuemin

  • aria-valuenow

  • aria-orientation

  • aria-valuetext

spinbutton 사용자가 이산 선택 중에서 선택할 것이라고 예상하는 범위의 형식.
  • aria-valuemax

  • aria-valuemin

  • aria-valuenow

  • aria-required

  • aria-valuetext

status 종종 상태 표시줄로 필연적으로 표시되지 않는, 콘텐트가 사용자를 위한 조언 정보이지만 경고를 합리화 할 만큼 중요하지 않은 컨테이너. 관련된 alert를 참고하세요. 없음
  • aria-expanded (state)

tab 사용자에게 렌더링 될 수 있는 탭 콘텐트를 선택하기 위한 메커니즘을 제공하는 그루핑 레이블. 없음
  • aria-selected (state)

  • aria-expanded (state)

tablist 탭 패널 요소(element)를 참조하는 탭 요소(element)의 목록. 없음
  • aria-level

  • aria-activedescendant

  • aria-expanded (state)

tabpanel tabtablist에 포함 된 tab과 연관된 리소스에 대한 컨테이너. 없음
  • aria-expanded (state)

textbox 값으로 자유 형식 텍스트를 허용하는 입력. 없음
  • aria-activedescendant

  • aria-autocomplete

  • aria-multiline

  • aria-readonly

  • aria-required

timer 시작점으로부터 지나간 시간의 양이나 종료점까지 남은 시간을 나타내는 숫자 카운터를 포함하는 라이브 영역의 유형. 없음
  • aria-expanded (state)

toolbar 소형 시각적 양식으로 표현 된 이란저그올 사용되는 기능 버튼의 컬렉션. 없음
  • aria-activedescendant

  • aria-expanded (state)

tooltip 요소(element)에 대한 설명을 나타내는 문맥상의 팝업. 없음
  • aria-expanded (state)

tree 접히고 확장될 수 있는 중첩된 그룹 하위 수준을 포함할 수 있는 목록의 유형. 없음
  • aria-multiselectable

  • aria-required

  • aria-activedescendant

  • aria-expanded (state)

treegrid tree에 대한 것과 동일한 방법으로 확장되고 접힐 수 있는 행의 grid 없음
  • aria-level

  • aria-multiselectable

  • aria-readonly

  • aria-activedescendant

  • aria-expanded (state)

  • aria-required

treeitem tree의 선택 항목. 이것은 treeitem들의 하위 수준 그룹을 포함한다면, 확장되거나 접힐 수 있는 tree 안의 요소(element)입니다. 없음
  • aria-level

  • aria-posinset

  • aria-setsize

  • aria-expanded (state)

  • aria-checked (state)

  • aria-selected (state)

4. HTML의 요소(element)들

4.1. 루트 요소(root element)

4.1.1. html 요소(element)

카테고리:
없음.
이 요소(element)가 사용될 수 있는 컨텍스트:
문서의 루트 요소(element)로서.
복합 문서에 하위 문서 조각이 허용되는 곳.
콘텐트 모델:
body 요소(element)가 뒤따르는 head 요소(element).
text/html에서 태그 생략:
html 요소(element)의 시작 태그html 요소(element) 안의 첫 번째 것이 주석이 아니라면 생략될 수 있습니다.
html 요소(element)의 종료 태그html 요소(element)가 주석이 즉시 뒤따르지 않는다면 생략될 수 있습니다.
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
없음
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
DOM 인터페이스:
interface HTMLHtmlElement : HTMLElement {};

html 요소(element)는 HTML 문서의 루트를 나타냅니다.

작성자들은 루트 html 요소(element)에 문서의 언어를 제공하는 lang 속성(attribute)을 명시하도록 권장됩니다. 이것은 음성 합성 도구가 사용할 발음을 결정하는 것, 번역 도구가 사용하는 규칙을 결정하는 것 등등을 지원합니다.

처음 1024바이트 내에서 문자 인코딩 선언의 적절한 감지를 허용하기 위해 html 요소(element)에 정의된 속성(attribute)들과 그 값들의 사용을 최소한으로 유지하는 것이 권장됩니다.

다음 예제에서 html 요소(element)는 문서의 언어를 영어로 선언합니다.
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Swapping Songs</title>
  </head>
  <body>
    <h1>Swapping Songs</h1>
    <p>Tonight I swapped some of the songs I wrote with some friends, who
    gave me some of the songs they wrote. I love sharing my music.</p>
  </body>
</html>

4.2. 문서 메타데이터

4.2.1. head 요소(element)

카테고리:
없음.
이 요소(element)가 사용될 수 있는 컨텍스트:
html 요소(element) 내 첫 번째 요소(element).
콘텐트 모델:
문서가 iframe srcdoc 문서이거나 제목(title) 정보가 상위 프로토콜에서 사용 가능하다면: title 요소(element)가 한 개를 초과하지 않고 base 요소(element)가 한 개를 초과하지 않는, 메타데이터 콘텐트의 0개 이상의 요소(element).
그렇지 않으면: 정확히 하나가 title 요소(element)와 base 요소(element)가 한 개를 초과하지 않는, 메타데이터 콘텐트의 한 개 이상의 요소(element).
text/html에서 태그 생략:
head 요소(element)의 시작 태그는 요소(element)가 비어있거나 head 요소(element) 내의 첫 번째 것이 요소(element)라면 생략될 수 있습니다.
head 요소(element)의 종료 태그head 요소(element)에 공백 문자주석이 즉시 따르지 않는다면 생략될 수 있습니다.
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
없음
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
DOM 인터페이스:
interface HTMLHeadElement : HTMLElement {};

head 요소(element)는 Document에 대한 메타데이터의 컬렉션을 나타냅니다.

head 요소(element) 내 메타데이터의 컬렉션은 많거나 적을 수 있습니다. 여기 매우 짧은 것의 예가 있습니다:
<!doctype html>
<html>
  <head>
    <title>A document with a short head</title>
  </head>
  <body>
    ...

여기 긴 것의 예가 있습니다:

<!DOCTYPE HTML>
  <HTML>
  <HEAD>
    <META CHARSET="UTF-8">
    <BASE HREF="https://www.example.com/">
    <TITLE>An application with a long head</TITLE>
    <LINK REL="STYLESHEET" HREF="default.css">
    <LINK REL="STYLESHEET ALTERNATE" HREF="big.css" TITLE="Big Text">
    <SCRIPT SRC="support.js"></SCRIPT>
    <META NAME="APPLICATION-NAME" CONTENT="Long headed application">
  </HEAD>
  <BODY>
    ...

title 요소(element)는 대부분 상황에서 요구된 자식이지만, 상위 레벨 프로토콜이 제목(title) 정보를 제공하는 경우, 예를 들어 HTML이 이메일 작성 서식으로 사용되는 경우 이메일의 제목 줄에, title 요소(element)는 생략 될 수 있습니다.

처음 1024바이트 내에서 문자 인코딩 선언의 적절한 감지를 허용하기 위해 head 요소(element)에 정의된 속성(attribute)들과 그 값들의 사용을 최소한으로 유지하는 것이 권장됩니다.

4.2.2. title 요소(element)

카테고리:
메타데이터 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
다른 title 요소(element)를 포함하지 않는 head요소(element) 안.
콘텐트 모델:
요소(element) 간 여백이 아닌 텍스트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다.
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
없음
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
DOM 인터페이스:
interface HTMLTitleElement : HTMLElement {
  attribute DOMString text;
};

title 요소(element)는 문서의 제목(title)이나 이름을 나타냅니다. 작성자는 문서가 문맥 밖에서, 예를 들어 사용자의 방문 기록이나 북마크에 혹은 검색 결과에 사용될 때 조차도 문서를 알아보게 하는 제목을 사용해야(should) 합니다. 문서의 첫 번째 제목(heading)은 문맥에서 벗어날 경우 혼자 있을 필요가 없기 때문에, 문서의 제목(title)은 종종 문서의 첫 번째 제목(heading)과 다릅니다.

문서 당 하나의 title 요소(element)만 있어야(must) 합니다.

Document가 제목을 가지 않는 것이 타당하다면, title 요소(element)는 아마도 요구 되지 않습니다. 요소(element)가 요구되는 경우의 설명에 대한 head 요소(element)의 콘텐트 모델을 참고하세요.

title . text [ = value ]
Text 노드가 아닌 자식 노드들을 무시하여, 요소(element)의 콘텐트를 반환합니다.

주어진 값으로 요소(element)의 자식을 바꾸기 위해, 설정 될 수 있습니다.

IDL 속성(attribute) text트리 순서에 따라 title 요소(element)의 자식인 (주석이나 요소(element) 같은 다른 노드들은 무시하여) 모든 Text 노드의 콘텐트의 연결을 반환해야(must) 합니다. 설정할 때, textContent IDL 속성(attribute)과 동일한 방법으로 동작해야(must) 합니다.
여기 최상위 동일한 페이지에 사용될 수 있는 제목(heading)과 대조되는 적절한 제목의 몇 가지 예가 있습니다.
<title>Introduction to The Mating Rituals of Bees</title>
...
<h1>Introduction</h1>
<p>This companion guide to the highly successful
<cite>Introduction to Medieval Bee-Keeping</cite> book is...

다음 페이지는 동일한 사이트의 일부입니다. 첫 번째 제목(heading)이 독자가 문맥이 무엇인지 알고 따라서 춤이 살사인지 알츠인지 궁금해하지 않는다고 가정하면서 제목(title)이 주제를 분명하게 설명하는 방법에 주목하세요:

<title>Dances used during bee mating rituals</title>
...
<h2>The Dances</h2>

문서의 제목(title)로 사용하기 위한 문자열은 document.title IDL 속성(attribute)에 의해 주어집니다.

유저 에이전트들은 유저 인터페이스에서 문서로 참조할 때 문서의 제목(title)을 사용해야(should) 합니다. title 요소(element)의 콘텐트가 이 방법으로 사용되는 경우, 그 title 요소(element)의 방향성은 유저 인터페이스에서 문서의 제목(title)의 방향성을 설정하는데 사용되어야(should) 합니다.

4.2.3. base 요소(element)

카테고리:
메타데이터 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
다른 base 요소(element)들을 포함하지 않는 head 요소(element) 안.
콘텐트 모델:
없음.
text/html에서 태그 생략:
종료 태그 없음.
콘텐트 속성(attribute)들:
범용 속성(attribute)들
href문서 기본 URL
target하이퍼링크 탐색(navigation)§4.10.22 Form submission에 대한 기본 브라우징 컨텍스트
허용된 ARIA 역할(role) 속성(attribute) 값들:
없음
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들.
DOM 인터페이스:
interface HTMLBaseElement : HTMLElement {
  attribute DOMString href;
  attribute DOMString target;
};

base 요소(element)는 작성자가 상대 URL들 해석의 목적에 대한 문서 기본 URL하이퍼링크들을 따라가는 것의 목적에 대한 기본 브라우징 컨텍스트의 이름을 명시하는 것을 허용합니다. 요소(element)는 이 정보를 넘어 어떤 컨텐트도 나타내지 않습니다.

문서 당 하나의 base 요소(element)만 있어야(must) 합니다.

base 요소(element)는 href 속성(attribute)이나 target 속성(attribute), 혹은 둘 모두를 가져야(must) 합니다.

href 콘텐트 속성(attribute)이 명시되었다면, 이 속성(attribute)은 유효한 잠정적으로 공백으로 둘러 싸일 수 있는 URL을 포함해야(must) 합니다.

base 요소(element)가 href 속성(attribute)을 가진다면 base 요소(element)는 html 요소를 제외하고 URL들을 취하는 것으로 정의된 속성을 가지는 트리 내의 다른 요소들(element) 앞에 와야(must) 합니다.

href 속성(attribute)들을 가진 여러 개의 base 요소(element)들이 있다면, 첫 번째를 제외하고 모두 무시됩니다.

target 속성(attribute)가 명시되었다면, 이 속성은 Document하이퍼링크들과 양식들탐색(navigation)을 야기하는 경우 어느 브라우징 컨텍스트가 기본으로 사용되는지를 명시하는 유효한 브라우징 컨텍스트 이름이나 키워드를 포함해야(must) 합니다.

base 요소(element)가 target 속성(attribute)을 가진다면 base 요소(element)는 elements in the tree that represent 하이퍼링크들을 나타내는 트리 내 모든 요소(element)들 앞에 와야(must) 합니다.

target 속성(attribute)들을 가진 여러 개의 base 요소(element)들이 있다면, 첫 번째를 제외하고 모두 무시됩니다.

특정 Documenthref 콘텐트 속성(attribute)을 가진 첫 번째 base 요소(element)인 base 요소(element)는 고정(frozen) 기본 URL을 가집니다. 고정(frozen) 기본 URL은 다음 상황의 어떤 것이 발생될 때에든지 요소(element)에 대해 즉시 설정되어야(must) 합니다:

  • base 요소(element)가 그것의 Document트리 순서에 따라 href 콘텐트 속성(attribute)을 가진 첫 번째 base 요소(element)가 되는 경우.

  • base 요소(element)가 그것의 Document트리 순서에 따라 href 콘텐트 속성(attribute)을 가진 첫 번째 base 요소(element)이고, 그것의 href콘텐트 속성(attribute)이 변경되는 경우.

요소(element) element에 대해, 고정(frozen) 기본 URL을 설정하기 위해:

  1. documentelement노드 문서로 둡니다.

  2. urlRecordelementdocument폴백 기본 URLdocument문자 인코딩을 가진 href 콘텐트 속성(attribute)의 값을 해석한 결과로 둡니다. (따라서 base 요소(element)는 자신에 의해 영향을 받지 않습니다.)

  3. elements고정(frozen) 기본 URLurlRecord이 실패하거나 결과 URL 레코드기본(base)이 문서에 대해 허용되는가?를 실행 중이고 document가 "Blocked"를 반환한다면 document폴백 기본 URL로 설정하고, 그렇지 않으면 urlRecord로 설정합니다.

href IDL 속성(attribute)은 가져올 때 다음 알고리즘을 수행한 결과를 반환해야(must) 합니다:

  1. documentelement노드 문서로 둡니다.

  2. urlbase 요소(element)의 href 속성(attribute)의 값을 가진다면 그 값으로 두고, 그렇지 않으면 빈 문자열로 둡니다.

  3. urlRecordurldocument폴백 기본 URLdocument문자 인코딩을 가지고 해석한 결과로 둡니다. (따라서, base 요소(element)는 다른 base 요소(element)나 자신에 의해서 영향을 받지 않습니다.)

  4. urlRecord이 실패라면, url을 반환합니다.

  5. urlRecord직렬화를 반환합니다.

href IDL 속성(attribute)은 설정할 때 href 콘텐트 속성(attribute)을 주어진 새로운 값으로 설정해야(must) 합니다.

target IDL 속성(attribute)은 동일한 이름의 콘텐트 속성(attribute)을 반영해야(must) 합니다.

이 예제에서, base 요소(element)는 문서 기본 URL을 설정하는데 사용됩니다:
<!DOCTYPE html>
<html>
  <head>
    <title>This is an example for the &lt;base&gt; element</title>
    <base href="https://www.example.com/news/index.html">
  </head>
  <body>
    <p>Visit the <a href="archives.html">archives</a>.</p>
  </body>
</html>

위 예제에서 링크는 "https://www.example.com/news/archives.html"로의 링크가 될 것입니다.

카테고리:
메타데이터 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
메타데이터 콘텐트가 기대되는 곳.
head 요소(element)의 자식인 noscript 요소(element) 안.
콘텐트 모델:
없음.
text/html에서 태그 생략:
종료 태그 없음.
콘텐트 속성(attribute)들:
범용 속성(attribute)들
href하이퍼링크의 주소
crossorigin — 요소(element)가 교차출처(crossorigin) 요청들을 처리하는 방법
rel — 이 문서 (또는 하위 섹션/주제)에서 목적지 리소스로의 관계
rev — 목적지 리소스에서 이 문서 (또는 하위 섹션/주제)로의 역방향 링크 관계
media — 적용가능한 매체
hreflang — 연결된 리소스의 언어
type — 참조된 리소스의 유형에 대한 힌트
sizes — 아이콘의 (for rel="icon"에 대한) 크기
또한, title 속성(attribute)은 이 요소(elemnt)에 특별한 의미(semantics)를 가집니다: 링크의 제목(title); 대체 스타일 시트의 이름을 설정합니다.
허용된 ARIA 역할(role) 속성(attribute) 값들:
link (기본 값 - 설정 하지 마세요).
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
role 값에 대한
DOM 인터페이스:
interface HTMLLinkElement : HTMLElement {
  attribute DOMString href;
  attribute DOMString? crossOrigin;
  attribute DOMString rel;
  attribute DOMString rev;
  [SameObject, PutForwards=value]readonly attribute DOMTokenList relList;
  attribute DOMString media;
  attribute DOMString hreflang;
  attribute DOMString type;
  [SameObject, PutForwards=value] readonly attribute DOMTokenList sizes;
};
HTMLLinkElement implements LinkStyle;

link 요소(element)는 작성자가 그들의 문서를 다른 리소스들에 연결시키는 것을 허용합니다.

링크(들)의 목적지는 href 속성(attribute)에 의해 주어지고, 이 속성(attribute)는 존재해야(must) 하고 유효한 잠정적으로 공백으로 둘러 싸일 수 있는 비어있지 않은 URL을 포함해야(must) 합니다. href 속성이 존재하지 않ㄴ흔다면, 요소(element)는 링크를 정의하지 않습니다.

link 요소(element)는 rel 속성(attribute)을 가져야(must) 합니다.

rel 속성(attribute)이 사용되었다면, 요소(element)는 head 요소(element)에 제한됩니다.

표현된 링크의 유형 (관계)는 rel 속성(attribute)의 값에 의해 주어지고, 이것이 존재한다면, 공백으로 분리된 토큰 집합인 값을 가져야(must) 합니다. 허용된 키워드와 그것들의 의미(meanings)는 이후 섹션에서 정의됩니다. rel 속성(attribute)이 존재하지 않는다면 키워드를 가지지 않거나, 사용된 어떤 키워드도 이 명세에서의 정의를 따라 허용된 것이 아니라면, 요소(element)는 어떤 연결도 생성하지 않습니다.

링크의 두 카테고리들은 link 요소(element)를 사용하여 생성될 수 있습니다: 외부 리소스들로의 링크들하이퍼링크들. §4.8.6 Link types 섹션은 특정 링크 유형이 외부 리소스인지 하이퍼링크인지를 정의합니다. 한 개 link 요소(element)는 여러 개의 링크들을 (일부는 외부 리소스 링크일 수 있고 일부는 하이퍼링크일 수 있습니다) 생성할 수 있습니다; 정확히 어떤 그리고 몇 개의 링크들이 생성 되는지는 rel 속성(attribute)에 주어진 키워드에 달려 있습니다. 유저 에이전트들은 요소(element) 단위가 아닌 링크 단위로 처리해야(must) 합니다.

link 요소(element)에 대해 생성 된 각 링크는 별도로 처리됩니다. 예를 들어, rel="stylesheet"를 가진 두 개의 link 요소(element)가 있따면, 각각은 독립적으로 자신의 속성(attbribute)에 의해 영향을 받습니다. 마찬가지로, next stylesheet 값을 가진 rel 속성(attribute)을 가진 단일 link 요소(element)가 있다면, 이것은 (next 키워드에 대한) 하이퍼링크와 (stylesheet 키워드에 대한) 외부 리소스 링크를 생성하고, 그것들은 다른 속성(attribute)들에 의해 (mediatitle 같은) 다르게 영향을 받습니다.

예를 들어, 다음 link 요소(element)는 두 하이퍼링크들을 (동일한 페이지에 대한) 생성합니다 :
<link rel="author license" href="/about">

이 요소(element)에 의해 생성된 두 링크들은 의미(semantic)가 현재 페이지의 작성자에 대한 정보를 가진 대상 페이지인 하나와, 의미(semantic)가 현재 페이지가 어떤 라이센스 하에 제공되는지에 관한 정보를 가지는 대상 페이지인 하나입니다.

linka 요소(element)들은 href에 의해 명시된 리소스로부터 현재 문서로의 역방향 연결 관계를 설명하는데 사용되는 rev 속성(attribute)도 가질 수 있습니다. 이것이 존재한다면 이 속성(attribute)의 값은 공백으로 분리된 토큰 집합이어야 합니다. rel 속성(attribute)처럼, §4.8.6 Link typesrev 속성(attribute)에 대한 허용된 키워드와 그것들의 의미(meanings)를 설명합니다. relrev 속성(attribute)들은 동일 요소(element)에 모두 존재할 수 있습니다.

역방향 링크는 링크의 역방향 관계를 나타내는 방법입니다. 값이 정방향 관계를 ("링크가 나에게 관계되는 방법") 전달하는 rel 속성(attribute)과는 대조적으로, rev 속성(attribute)은 유사한 관계들이 역방향으로 ("내가 이 링크에 관계되는 방법") 노출되도록 허용합니다. 이 값들은 유저 에이전트들이 연결된 문서의 보다 포괄적인 지도를 만들 수 있게 할 수 있습니다.

책의 챕터를 각각 포함하는 두 개의 문서가 주어지면, 그것들 사이의 링크는 다음과 같이 relrev 속성(attribute)들을 가지고 기술될 수 있습니다:

"chapter1.html" URL를 가진 문서

<link href="chapter2.html" rel="next" rev="prev">

"chapter2.html" URL를 가진 문서

<link href="chapter1.html" rel="prev" rev="next">
<link href="chapter3.html" rel="next" rev="prev">

chapter1.html에서 chapter2.html로의 연결은 정방향으로 시리즈에서 "next" 챕터이고, 역방향으로는 (chapter2.html에서 chapter1.html으로) "previous" 챕터 입니다.

콘텐트 목록 문서에서 링크들은 relrev를 사용하여 다음과 같이 기술 될 수 있습니다:
<ol>
  <li><a href="chapter1.html" rev="toc" rel="next">chapter 1</a></li>
  <li><a href="chapter2.html" rev="toc"></a>chapter 2</li>
  <li><a href="chapter3.html" rev="toc"></a>chapter 3</li>
</ol>

콘텐트 목록에서 "next" 논리 경로는 rel을 사용하여 노출 된 첫 번째 챕터 입니다. 각 챕터 링크는 현재 문서가 매 챕터에 대한 콘텐트 목록 문서 임을 나타내는 "toc" rev 값을 가집니다.

crossorigin 속성(attribute)은 CORS 설정 속성(attribute)입니다. 이것은 외부 리소스 링크와 함께 사용하도록 의도된 것입니다.

외부 리소스로의 링크에 대한 정확한 동작은 관련 링크 유형에 대해 정의된 정확한 관계에 달려있습니다. 일부 속성(attribute)들은 외부 리소스가 적용 될지 (아래 정의된 대로) 여부를 제어합니다.

DOM에 표현되는 외부 리소스에 대해 (예를 들어, 스타일시트), DOM 표현은 리스소가 적용 되지 않는다 하더라도 사용 가능 하게 되어야(must) 합니다 (모듈 교차 출처 제한). 리소스를 획득하기 위해, 유저 에이전트는 다음 단계들을 수행해야(must) 합니다:

  1. href 속성(attribute)의 값이 빈 문자열이라면, 이 단계들을 중단합니다.

  2. 요소(element)의 노드 문서에 관련하여, href 속성(attribute)에 의해 주어진 URL해석합니다. 그것이 실패한다면, 이 단계들을 중단합니다. 그렇지 않으면, url결과 URL 레코드로 둡니다.

  3. corsAttributeState를 요소(element)의 crossorigin 콘텐트 속성(attribute)의 현재 상태로 둡니다.

  4. requesturlcorsAttributeState가 주어진 잠재적 CORS 요청 생성의 결과로 둡니다.

  5. request클라이언트link 요소(element)의 노드 문서Window 객체의 환경 설정 객체로 둡니다.

  6. request가져옵니다.

유저 에이전트들은 적용되지 않은 모든 리소스들을 능동적으로 가져오는 대신, 그것들이 필요할 경우 그 리소스를 얻기 위해 시도하기로 선택할 수 있습니다.

외부 리소스를 가져올 때 사용된 프로토콜의 (예를 들어, HTTP) 의미(semantics)를 따라야(must) 합니다. (예를 들어, 리다이렉트가 뒤따르는 것과 404 응답은 외부 리소스가 적용되지 않는 것을 야기합니다.)

일단 리소스를 얻으려는 시도와 그것의 중요한 하위 리소스들이 완료되면, 유저 에이전트는 로드가 성공적이었다면, link 요소(element)에 load라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣거나, 리소스나 그것의 중요한 하위 리소스들의 하나가 어떤 이유로 (예를 들어, DNS 오류, HTTP 404 응답, 너무 빨리 닫히는 연결, 지원되지 않은 Content-Type) 완전한 로드가 실패되었다면, link 요소(element)에 error라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣습니다. 리소스나 하위 리소스들 처리에 비 네트워크 오류들은 (예를 들어, CSS 해석 오류, PNG 디코딩 오류) 이 문단의 목적을 위한 실패가 아닙니다.

작업들에 대한 작업 소스DOM 조작 작업 소스입니다.

요소(element)는 리소스와 그것의 중요한 하위 리소스들을 얻기 위한 모든 시도가 완료될 때까지 요소(element)의 노드 문서로드 이벤트를 지연시켜야(must) 합니다. (유저 에이전트가 아직 얻으려고 시도하지 않은 리소스는, 예를 들어 리소스가 필요하기를 기다리고 있기 때문에, 로드 이벤트를 지연시키지 않습니다.)


대화형 유저 에이전트들은 유저 인터페이스의 어딘가에서 link 요소(element)를 사용하여 생성된 하이퍼링크들을 따르기 위한 방법을 사용자에게 제공할 수 있습니다. 정확한 인터페이스는 이 명세에 정의되지 않지만, 문서 내 각 link 요소(element)를 가지고 생성된 각 하이퍼링크에 대해, 일부 형식이나 다른 것에서 (아마도 간소화 된), 다음 정보를 (아래 정의된 대로, 요소(element)의 속성으로부터 얻어진) 포함할 수 있습니다.

  • 이 문서와 리소스 (rel 속성(attribute)에 의해 주어진) 사이의 관계

  • 리소스의 제목 (title 속성(attribute)에 의해 주어진).

  • 리소스의 주소 (href 속성(attribute)에 의해 주어진).

  • 리소스의 언어 (hreflang 속성(attribute)에 의해 주어진).

  • 리소스에 대한 최고의 매체 (media 속성(attribute)에 의해 주어진).

유저 에이전트들은 리소스의 유형과 같은 (type 속성(attribute)에 의해 주어진), 다른 정보를 포함할 수 있습니다.

link 요소(element)와 그것의 rel 속성(attribute)을 가지고 생성된 하이퍼링크들은 전체 페이지에 적용됩니다. 이것은 컨텍스트가 문서 안의 링크의 위치에 의해 주어진 위치인 링크의 유형을 나타내는, aarea 요소(element)의 rel 속성(attribute)과 대조를 이룹니다.

media 속성(attribute)은 리소스가 적용될 매체를 말해줍니다. 값은 유효한 미디어 쿼리 목록이어야(must) 합니다.

링크가 하이퍼링크라면 media 속성(attribute)은 순수하게 조언적이고, and 문제의 문서가 어떤 매체에 대해 설계되었는지를 설명합니다.

하지만, 링크가 외부 리소스 링크라면, media 속성(attribute)은 지시적인 것입니다. 유저 에이전트는 media 속성(attribute)의 값이 환경과 일치하고 다른 관련 조건들이 적용되는 경우 외부 리소스를 적용해야(must)하고, 그렇지 않으면 적용하지 않아야(must) 합니다.

외부 리소스는 그것의 적용 가능성 제한 내에서 정의된 추가 제한 사항을 가질 수 있습니다. 예를 들어, CSS 스타일 시트는 일부 @media 블럭을 가질 수 있습니다. 이 명세는 그러한 추가 제한 사항이나 요구사항을 재정의 하지 않습니다.

media 속성(attribute)이 생력되었다면 기본 값은 기본값에 의해 링크가 모든 매체에 적용 됨을 의미하는 "all" 입니다.

link 요소(element)의 hreflang 속성(attribute)은 a 요소(element)의 hreflang 속성(attribute)과 동일한 의미를 가집니다.

type 속성(attribute)은 링크되는 리소스의 MIME 타입을 제공합니다. 이것은 순수하게 조언적입니다. 값은 유효한 MIME 타입이어야(must) 합니다.

외부 리소스 링크에 대해, type 속성(attribute)은 유저 에이전트가 지원하지 않는 리소스를 가져오는 것을 방지할 수 있도록 유저 에이전트에 대한 힌트로 사용됩니다. 속성(attribute)이 존재하지 않는다면, 유저 에이전트는 (그것이 유효한 MIME 타입, 예를 들어, 빈 문자열이라 하더라도) 리소스가 주어진 유형의 것으로 추정해야(must) 합니다. 속성(attribute)이 생략되었고, 외부 리소스 링크 유형이 정의된 기본 유형을 가진다면, 유저 에이전트는 리소스를 그 유형의 것으로 추정해야(must) 합니다. 유저 에이전트가 주어진 링크 관계에 대해 주어진 MIME 타입을 지원하지 않는다면, 유저 에이전트는 리소스를 획득하지 않아야(should) 합니다; 유저 에이전트가 주어진 링크 관계에 대해 주어진 MIME 타입을 지원하지 않는다면, 유저 에이전트는 외부 리소스 링크의 특정 유형에 대해 명시된 대로 적절한 시간에 리소스를 획득해야(should) 합니다. 속성(attribute)이 생략되었고, 외부 리소스 링크 유형이 정의된 기본 유형을 가지지 않고, 유형이 알려져 있고 지원되는 경우 유저 에이전트가 리소스를 획득 한다면, 유저 에이전트는 그것이 지원된다는 가정 하에 리소스를 획득 해야(should) 합니다.

유저 에이전트들은 type 속성(attribute)을 믿을만한 것으로 간주하지 않아야(must) 합니다 — 리소스를 가져오는데에, 유저 에이전트들은 type 속성(attribute)을 그것의 실제 유형을 결정하기 위해 사용하지 않아야(must) 합니다. 오직 실제 유형은 (다음 문단에 정의된 것과 같이) 리소스에 적용 할지 여부를 결정짓기 위해서 사용되는 것이지, 앞서 언급된 가정된 유형이 아닙니다.

외부 리소스 링크 유형이 리소스의 Content-Type 메타데이터 처리에 대한 규칙을 정의한다면, 그 규칙은 적용됩니다. 그렇지 않고, 리소스가 이미지가 예상된다면, 유저 에이전트들은 리소스의 Content-Type 메타데이터로부터 유형이 결정된 official type을 가지고 이미지 스니핑 규칙들을 적용할 수 있고, 결과로 나온 계산 된 리소스의 유형을 그것이 실제 유형인것 처럼 사용할 수 있습니다. 그렇지 않고, 이 조건들을 적용하거나 유저 에이전트가 이미지 스니핑 규칙을 적용하지 않기로 한다면, 유저 에이전트는 리소스의 유형을 결정하기 위해 리소스의 Content-Type 메타데이터를 사용해야(must) 합니다. 유형 메타데이터가 없고 외부 리소스 링크 유형이 정의된 기본 유형을 가진다면, 유저 에이전트는 리소스를 그 유형의 것으로 추정해야(must) 합니다.

stylesheet 링크 유형은 리소스의 Content-Type 메타데이터 처리에 대한 규칙을 정의합니다.

유저 에이전트가 리소스의 유형을 설정 할 때, 유저 에이전트는 지원되는 유형의 것이고 다른 관련 조건이 적용된다면 리소스를 적용해야(must)하고, 그렇지 않으면 리소스를 무시해야(must) 합니다.

문서가 다음과 같이 라벨링 된 스타일 시트 링크를 포함한다면:
<link rel="stylesheet" href="A" type="text/plain">
<link rel="stylesheet" href="B" type="text/css">
<link rel="stylesheet" href="C">

...CSS 스타일 시트만을 지원하는 호환 유저 에이전트는 B와 C파일을 가져오고, A파일은 생략할 것입니다 (text/plain은 CSS 스타일 시트에 대한 MIME 타입이 아니기 때문에).

B와 C 파일에 대해, 이것은 이후 서버에 의해 반환된 실제 유형을 검사할 것입니다. text/css로 보내어진 것들에 대해, 이것은 스타일 시트를 적용할 것이지만, text/plain으로 라벨링 된 것들에 대해 혹은 다른 유형에 대해서는 그렇지 않을 것입니다.

두 파일 중 하나가 Content-Type 메타데이터 없이 혹은, Content-Type: "null"과 같은 구문적으로 틀린 유형을 가지고 반환된다면, stylesheet 링크들에 대한 기본 유형이 효과를 낼 것입니다. 그 기본 유형이 text/css이기 때문에, 스타일 시트는 그럼에도 불구하고 적용 것입니다.

title 속성(attribute)은 링크의 제목(title)을 제공합니다. 한 가지 예외를 가지고, 이것은 순수하게 조언적입니다. 값은 텍스트입니다. 예외 사항은 title 속성(attribute)이 대체 스타일 시트 세트를 정의하는 스타일 시트에 대한 것입니다.

link 요소(element)들의 title 속성(attribute)은 제목이 부모 요소(element)의 제목을 상속 받지 않는 링크라는 점에서 대다수 다른 요소(element)들의 범용 title 속성(attribute)과는 차이가 있습니다: 그것은 단지 제목을 가지지 않습니다.

sizes 속성(attribute)은 icon 링크 유형과 함께 사용됩니다. 속성(attribute)은 icon 키워드를 명시한 rel 속성(attribute)을 가지지 않는 link 요소(element)들에 명시되지 않아야(must) 합니다.

하이퍼링크들을 생성하는 link 요소(element)들의 활성화 동작은 다음 단계들을 수행하는 것입니다:
  1. link 요소(element)의 노드 문서가, 완전히 활성화가 아니라면, 이 단계들을 중단합니다.

  2. link 요소(element)에 의해 생성된 하이퍼링크를 따라갑니다.

HTTP Link: 헤더가 지원된다면, HTTP 메세지에 주어진 순서에 따라, 문서 내 모든 링크들 앞에 오는 것으로 추정되어야(must) 합니다. 이 헤더들은 관련 명세에 주어진 규칙을 따라 처리 됩니다. [HTTP] [RFC5988]

HTTP 링크의 등록 관계 유형: 헤더는 HTML 링크 유형들과 구별되고, 따라서 그것들의 의미는 동일한 이름의 HTML 유형들과 다를 수 있습니다.

IDL 속성(attribute)들 href, rel, rev, media, hreflang, type, sizes는 동일한 이름의 각 콘텐트 속성(attribute)들을 반영해야(must) 합니다.

crossOrigin IDL 속성(attribute)은 콘텐트 속성(attribute)을 반영해야(must) 합니다.

IDL 속성(attribute) relListrel 콘텐트 속성을 반영 해야(must) 합니다.

relListDOMTokenList지원되는 토큰들link 요소(element)들에 허용되고 유저 에이전트에 의해 지원된 HTML 링크 유형들에 정의된 키워드들입니다.

rel지원되는 토큰들link 요소(element)들에 허용되고, 처리 모델에 영향을 주고, 유저 에이전트에 의해 지원되는 HTML 링크 유형들에 정의된 키워드들입니다. 가능한 지원되는 토큰들은 alternate, dns-prefetch, icon, preconnect, prefetch, prerender, stylesheet 입니다. rel지원되는 토큰들은 유저 에이전트가 처리 모델에 대해 구현하는 이 목록의 토큰들을 포함해야(must) 합니다.

다른 명세들은 [RESOURCE-HINTS]과 같은, 다른 링크 유형들에 정의 된 HTML 링크 유형들을 추가할 수 있습니다. 이 명세들은 그들의 링크 유형들이 rel의 지원되는 토큰들에 포함되도록 요구할 수 있습니다.

LinkStyle 인터페이스는 또한 이 요소(element)에 의해 구현됩니다. [CSSOM]

여기, link 요소(element)들의 세트가 일부 스타일 시트들을 제공합니다:
<!-- a persistent style sheet -->
<link rel="stylesheet" href="default.css">

<!-- the preferred alternate style sheet -->
<link rel="stylesheet" href="green.css" title="Green styles">

<!-- some alternate style sheets -->
<link rel="alternate stylesheet" href="contrast.css" title="High contrast">
<link rel="alternate stylesheet" href="big.css" title="Big fonts">
<link rel="alternate stylesheet" href="wide.css" title="Wide screen">
다음 예제는 대체 형식을 사용하고 다른 언어를 대상으로하며 다른 매체에 대해 의도된 페이지의 버전을 지정할 수 있는 방법을 보여줍니다:
<link rel=alternate href="/en/html" hreflang=en type=text/html title="English HTML">
<link rel=alternate href="/fr/html" hreflang=fr type=text/html title="French HTML">
<link rel=alternate href="/en/html/print" hreflang=en type=text/html media=print title="English HTML (for printing)">
<link rel=alternate href="/fr/html/print" hreflang=fr type=text/html media=print title="French HTML (for printing)">
<link rel=alternate href="/en/pdf" hreflang=en type=application/pdf title="English PDF">
<link rel=alternate href="/fr/pdf" hreflang=fr type=application/pdf title="French PDF">

4.2.5. meta 요소(element)

카테고리:
메타데이터 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
charset 속성(attribute)이 존재하거나, 요소(element)의 http-equiv 속성(attribute)이 인코딩 선언 상태에 있다면: head 요소(element) 안.
http-equiv 속성(attribute)이 존재하지만 인코딩 선언 상태에 있지 않다면: head 요소(element) 안.
http-equiv 속성(attribute)이 존재하지만 인코딩 선언 상태에 있지 않다면: head 요소(element)의 자식인 noscript 요소(element) 안.
name 속성(attribute)이 존재한다면: 메타데이터 콘텐트가 기대되는 곳.
콘텐트 모델:
없음.
text/html에서 태그 생략:
종료 태그 없음.
콘텐트 속성(attribute)들:
범용 속성(attribute)들
name — 메타데이터 이름
http-equiv — 선처리(pragma) 지시자
content — 요소(element)의 값
charset문자 인코딩 선언
허용된 ARIA 역할(role) 속성(attribute) 값들:
없음
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
DOM 인터페이스:
interface HTMLMetaElement : HTMLElement {
  attribute DOMString name;
  attribute DOMString httpEquiv;
  attribute DOMString content;
};

meta 요소(element)는 title, base, link, style, script 요소(element)들을 사용하여 나타낼 수 없는 메타데이터의 다양한 종류를 나타냅니다.

meta 요소(element)는 name 속성(attribute)으로 문서 수준의 메타데이터를, http-equiv 속성(attribute)으로 선처리(pragma) 지시자들을, charset 속성(attribute)으로 HTML 문서가 문자열 형식으로 직렬화 될 때 (예를 들어, 네트워크나 디스크 기억 장치를 통한 전송에 대해) 파일의 문자 인코딩 선언을 나타낼 수 있습니다.

name, http-equiv, charset 속성(attribute)들 중 정확히 하나는 명시 되어야(must) 합니다.

namehttp-equiv가 명시되었다면, content 속성(attribute)도 명시되어야(must) 합니다. 그렇지 않으면 생략 되어야(must) 합니다.

charset 속성(attribute)은 문서에 사용된 문자 인코딩을 명시합니다. 이것이 문자 인코딩 선언 입니다. 속성(attribute)이 XML 문서에 존재한다면, 그 값은 문자열 "utf-8"에 ASCII 대소문자 구분 없이 일치해야(must) 합니다 (그리고 문서는 따라서 그 인코딩으로 UTF-8을 사용하도록 강제됩니다).

meta 요소(element)의 charset 속성(attribute)은 XML 문서들에 영향을 가지지 않고, XHTML로부터 그리고 XHMTL로의 마이그레이션을 가능하게 하기 위해서만 허용됩니다.

문서 당 charset 속성(attribute)을 가진 meta 요소(element)는 하나를 초과하여 존재하지 않아야(must) 합니다.

content 속성(attribute)은 요소(element)가 그 목적에 대해 사용될 때 문서 메타데이터의 값이나 선처리(pragma) 지시자의 값을 제공합니다. 허용된 값은 이 명세의 다음 섹션에 설명된 대로, 정확한 컨텍스트에 달려 있습니다.

meta 요소(element)가 name 속성(attribute)을 가진다면, 문서 메테데이터를 설정합니다. 문서 메타데이터는, 이름을 제공하는 meta 요소(element)의 name 속성(attribute)과, 값을 제공하는 동일한 요소(element)의 content 속성, 이름-값 쌍의 용어로 표현됩니다. 이름은 메타데이터의 측면이 설정하는 것을 명시합니다; 유효한 이름들과 그 값의 의미가 다음 섹션에 설명되어 있습니다. meta 요소(element)가 content 속성을 가지지 않는다면, 메타데이터 이름-값 쌍의 값은 빈 문자열 입니다.

namecontent IDL 속성(attribute)들은 동일한 이름의 각각의 콘텐트 속성(attribute)들을 반영해야(must) 합니다. IDL 속성(attribute) httpEquiv는 콘텐트 속성(attribute) http-equiv반영해야(must) 합니다.

4.2.5.1. 표준 메타데이터 이름들

이 명세는 meta 요소(element)의 name 속성(attribute)에 대한 몇 가지 이름들을 정의합니다.

이름들은 ASCII 대소문자 구분이 없고, ASCII 대소문자 비구분 방법으로 비교되어야(must) 합니다.

application-name

값은 페이지가 나타내는 웹 어플리케이션의 이름을 제공하는 짧은 자유 형식의 문자열이어야(must) 합니다. 페이지가 웹 어플리케이션이 아니라면, application-name 메타데이터 이름은 사용되지 않아야(must) 합니다. 각 이름의 언어를 명시하기 위한 lang 속성을 사용하여 웹 어플리케이션의 이름의 번역이 제공될 수 있습니다.

주어진 언어application-name 값으로 설정하는 name 속성(attribute)을 가진 meta 요소(element)는 문서 당 하나를 초과하여 존재하지 않아야(must) 합니다.

제목(title)은 어플리케이션의 이름이 되는 것 대신에 특정 순간의 상태 메세지와 페이지의 상태와 유사한 것을 포함할 수 있기 때문에, 유저 에이전트들은 페이지의 title보다 우선적으로 UI에서 어플리케이션 이름을 사용할 수 있습니다.

주어진 언어의 정렬된 목록을 (예를 들어, 영국 영어, 미국 영어, 영어) 사용하기 위한 어플리케이션 이름을 찾기 위해, 유저 에이전트들은 다음 단계들을 수행해야(must) 합니다:

  1. languages를 언어의 목록으로 둡니다.

  2. default languageDocument루트 요소(element)언어가 있다면 그것으로두고, 그 언어는 알 수 없는 것이 아닙니다.

  3. default language가 있다면, 그리고 그것이 languages의 언어 중 어떠한 것과도 동일한 언어가 아니라면, languages에 그것을 추가(append) 합니다.

  4. winning language를 값 application-name로 설정된 name 속성(attribute)을 가지고 언어가 문제의 언어인 Documentmeta 요소(element)에 있는 languages의 첫 번째 언어로 둡니다.

    언어들어 어떠한 것도 그러한 meta 요소(element)를 가지지 않는다면, 이 단계들을 중단합니다; 주어진 어플리케이션 이름이 없습니다.

  5. 트리 순서에 따라 값 application-name로 설정된 name 속성(attribute)을 가지고 언어winning languageDocument의 첫 번째 meta 요소(element)의 content 속성(attribute)의 값을 반환합니다.

이 알고리즘은 페이지에 대한 이름이 요구될 때, 예를 들어 북마크에 라벨을 붙이기 위해, 브라우저에 의해 사용됩니다. 알고리즘에 제공될 언어는 사용자가 선호하는 언어가 될 것입니다.

author

값은 페이지의 작성자 하나의 이름을 제공하는 자유 형식의 문자열이어야(must) 합니다.

description

값은 페이지를 설명하는 자유 형식의 문자열이어야(must)합니다. 값은 페이지의 디렉토리에서 사용하기에, 예를 들어, 검색엔진에서, 적절해야(must) 합니다. 문서 당 값 description로 설정된 name 속성(attribute)을 가진 meta 요소(element)는 하나를 초과하여 존재하지 않아야(must) 합니다.

generator

값은 문서를 생성하는데 사용된 소프트웨어 패키지들의 하나를 확인하는 자유 형식의 문자열이어야(must) 합니다. 이 값은 소프트웨어에 의행 생성되지 않은 마크업의 페이지에는, 예를 들어, 텍스트 에디터로 사용자에 의해 작성된 마크업의 페이지에는 사용되지 않아야(must) 합니다.

여기 "Frontweaver"라고 불리는 도구가, 페이지의 head 요소(element)에서, 페이지를 생성하는데 사용된 것으로 그 자신을 식별하기 위해, 그것의 출력물에 포함할 수 있는 것이 있습니다.
<meta name=generator content="Frontweaver 8.2">

keywords

값은 각각이 페이지에 관련된 키워드인, 콤마로 분리된 토큰의 집합이어야(must) 합니다.

영국 고속도로의 서체에 대한 이 페이지는 meta 요소(element)를 사용자가 페이지를 찾는데 사용할 수 있는 몇 가지 키워드를 명시하기위해 사용합니다:
<!DOCTYPE HTML>
<html lang="en-GB">
  <head>
    <title>Typefaces on UK motorways</title>
    <meta name="keywords" content="british,type face,font,fonts,highway,highways">
  </head>
  <body>
  ...

이 기능은 역사적으로 신뢰할 수 없고 사용자에게 도움이 되지 않는 방법으로 결과를 내는 스팸 검색 엔진을 위한 방법으로 오해시킬 만큼 사용되어 왔기 때문에 많은 검색 엔진들은 그 키워드들을 고려하지 않습니다.

작성자가 페이지에 대해 적절한 것으로서 명시한 키워드들의 목록을 얻기 위해 , 유저 에이전트는 다음 단계들을 수행해야(must) 합니다:
  1. keywords을 빈 목록으로 둡니다.

  2. name 속성(attribute)과 name 속성(attribute)의 값이 keywordscontent 속성(attribute)을 가진 각 meta 요소(element)에 대해, 다음 하위 단계들을 수행합니다:

    1. 요소(element)의 content 속성(attribute)의 값을 콤마로 분리합니다.

    2. 결과 토큰들이 있다면 keywords에 추가(add) 합니다.

  3. keywords로부터 중복을 제거합니다.

  4. keywords를 반환합니다. 이것은 작성자가 페이지에 적절한 것으로 명시한 키워드의 목록입니다.

유저 에이전트들은 값의 신뢰성에 대한 확신이 불충분 할 경우 이 정보를 사용하지 않아야(should) 합니다.

예를 들어, 사이트 별 검색 엔진의 색인을 덧붙이기 위해 시스템에 페이지의 키워드 정보를 사용하기 위한 콘텐츠 관리 시스템은 타당할 것이지만, 이 정보를 사용하는 대규모 콘텐트 제공 웹사이트는 특정 사용자가 부적절한 키워드의 사용을 통해 랭킹 메커니즘을 희롱하는 시도를 하는 것을 발견할 가능성이 있습니다.

4.2.5.2. 다른 메타데이터 이름들

미리 정의된 메타데이터 이름들의 세트에 대한 확장들WHATWG Wiki MetaExtensions 페이지에 등록될 수 있습니다. [WHATWGWIKI]

누구든지 유형을 추가하기 위해 언제든지 WHATWG Wiki MetaExtensions 페이지를 자유롭게 수정할 수 있습니다. 이 새로운 이름들은 다음 정보를 가지고 명시되어야(must) 합니다:

키워드(keyword)

정의되는 실제 이름. 이름은 다른 정의된 이름과 혼란스럽게 유사하지 않아야(should) 합니다 (예를 들어, 대소문자만 다른).

간단한 설명(brief description)

그 안에 값이 요구되는 형식을 포함하여, 메타데이터의 이름이 의미하는 것의 짧은 비규범적 설명

명세(specification)

메타데이터 이름의 의미와 요구사항들의 더 자세한 설명으로의 링크. 다른 위키의 페이지나 외부 페이지로의 링크가 될 수 있습니다.

동의어(synonyms)

정확히 동일한 처리 요구사항을 가지는 다른 이름들의 목록. 작성자는 동의어로 정의된 이름을 사용하지 않아야(should)합니다. 그것들은 유저 에이전트들이 레거시 콘텐트를 지원하는 것을 허용하도록 의도되었을 뿐입니다. 누구나 실제로 사용되지 않는 동의어를 제거 할 수 있습니다; 레거시 콘텐트와 호환성을 위한 동의어로서 처리되도록 요구되는 이름들만 이 방법으로 등록됩니다.

상태(status)

다음 중 하나:

제안 됨(proposed)

폭넓은 검토와 승인을 받지 않은 이름. 누군가 그것을 제한했고 곧 사용하게 될 것입니다.

승인 됨(ratified)

폭넓은 검토와 승인을 받은 이름. 이것은 올바르지 않은 방법으로 사용되는 경우를 포함하여 이름을 사용하는 페이지를 처리하는 방법을 분명하게 정의하는 명세를 가집니다.

중단 됨(discontinued)

폭넓은 검토를 받고 불충분함이 발견된 메타데이터 이름. 기존 페이지들이 이 메티데이터 이름을 사용하고 있지만, 새로운 페이지들은 그것을 방지해야(should) 합니다. "간단한 설명"과 "명세" 항목은 어떠한 것이라도, 작성자가 대신 사용해야 하는 것의 자세한 내용을 제공할 것입니다.

메타데이터 이름이 기존 값과 중복된 것으로 발견되면, 그것은 제거되고 기존 값에 대한 동의어로 포함되어야(should) 합니다.

메타데이터 사용되거나 명시되지 않고 이름이 한 달 이상 "제안 됨" 상태에 등록되어있다면, 레지스트리로부터 제거될 수 있습니다.

메타데이터 이름이 "제안 됨" 상태로 추가되었고 기존 값과 중복되는 것이 발견된다면, 그것은 제거되고 기존 값에 대한 동의어로 포함되어야(should) 합니다. 메타데이터 이름이 "제안 됨" 상태로 추가되었고 위험한 것으로 발견된다면, 그것은 "중단 됨" 상태로 변경되어야(should) 합니다.

누구든 언제든지 상태를 변경할 수 있지만, 위 정의에 따라서 그렇게만 해야(should) 합니다.

적합성 검사기는 값이 허용되었는지 아닌지를 확증하기 위해 WHATWG Wiki MetaExtensions 페이지에 주어진 정보를 사용할 수 있습니다: "중단 됨"으로 표기된 값이나 이 명세나 앞서 언급된 페이지에 포함되지 않은 값은 유효하지 않은 것으로 보고되어야(must) 하는데 반하여, 이 명세에 정의된 값이나 "제안 됨"이나 "승인 됨"으로 표시된 값은 받아들여져야(must) 합니다. 적합성 검사기는 이 정보를 캐시할 수 있습니다 (예를 들어, 성능상의 이유나 신뢰할 수 없는 네트워크 접속의 사용을 방지하기 위해).

작성자가 이 명세 혹은 위키 페이지에 의해 정의되지 않은 새로운 메타데이터 이름을 사용하는 경우, 적합성 검사기는 위에 기술된 상세 내용을 가지고, "제안 됨" 상태로 위키에 값을 추가하도록 제안해야(should) 합니다.

값들이 URL들이 되는 메타데이터 이름들은 제안되거나 받아들여지지 않아야(must) 합니다. 링크들은 meta 요소(element)가 아니라, link 요소(element)를 사용해서 표현되어야(must) 합니다.

4.2.5.3. 선처리(pragma) 지시자들

meta 요소(element)에 http-equiv 속성(attribute)이 명시되어 있다면, 요소(element)는 선처리(pragma) 지시자입니다.

http-equiv 속성(attribute)은 열거 속성입니다. 다음 표는 이 속성(attribute)에 대해 정의된 키워드들을 나열합니다. 키워드와 함께 행들의 첫 번째 칸에 주어진 상태는 그 키워드가 일치하는 상태를 제공합니다. 마지막 열에 언급된 바와 같이 키워드의 일부는 부적합 합니다.

상태 키워드 메모
Content Language content-language 부적합
Encoding declaration content-type
Default style default-style
Refresh refresh
Cookie setter set-cookie 부적합
meta 요소(element)가 문서에 삽입되는 경우, 그것의 http-equiv 속성(attribute)이 존재하고 위 상태 중 하나를 나타낸다면, 유저 에이전트는 다음 목록에 정의된 대로, 그 상태에 대해 적절한 알고리즘을 수행해야(must) 합니다:

콘텐트 언어 상태 (http-equiv="content-language")

이 기능은 부적합합니다. 작성자들은 대신 lang 속성(attribute)을 사용하도록 권장됩니다.

이 선처리(pragma)는 선처리 설정 기본 언어를 설정합니다. 그 선처리(pragma)가 성공적으로 처리될 때까지, 선처리 설정 기본 언어가 존재하지 않습니다.

  1. meta 요소(element)가 content 속성(attribute)을 가지지 않는다면, 이 단계들을 중단합니다.

  2. 요소(element)의 content 속성(attribute)이 U+002C 콤마 문자 (,)를 포함한다면, 이 단계들을 중단합니다.

  3. input을 요소(element)의 content 속성(attribute)의 값으로 둡니다.

  4. positioninput의 첫 번째 문자를 가리키게 합니다.

  5. 여백을 건너뜁니다.

  6. 공백 문자들이 아닌 일련의 문자를 수집합니다.

  7. candidate를 이전 단계로부터 결과로 나온 문자열로 둡니다.

  8. candidate가 빈 문자열이라면, 이 단계들을 중단합니다.

  9. 선처리 설정 기본 언어candidate로 설정합니다.

    값이 공백으로 구분된 토큰들로 구성된다면, 첫 번째 이후 토큰들은 무시됩니다.

이 선처리(pragma)는 동일한 이름의 HTTP Content-Language 헤더와 동일하지 않습니다. 한 개 언어 태그를 초과한 HTTP Content-Language 값들은 이 선처리(pragma)에 의해 비유효한 것으로 거부될 것입니다. [HTTP]

인코딩 선언 상태 (http-equiv="content-type")

인코딩 선언 상태는 단지 charset 속성(attribute) 설정의 대체 형식입니다: 이것이 문자 인코딩 선언입니다. 이 상태의 유저 에이전트 요구사항들은 모두 명세의 해석 섹션에 의해 처리됩니다.

인코딩 선언 상태에 있는 http-equiv 속성(attribute)을 가진 meta 요소(elements)들에 대해, content 속성(attribute)은 ASCII 대소문자 구분 없이 다음으로 구성된 문자열에 일치하는 값을 가져야 합니다: 리터럴 문자열 "text/html;", 그 뒤로 선택적으로 얼마든지의 공백 문자들, 그 뒤로 리터럴 문자열 "charset=", 그 뒤로 문자 인코딩 선언문자 인코딩레이블들 중 하나.

문서는 인코딩 선언 상태에 있는 http-equiv 속성(attribute)을 가진 meta 요소(element)와 charset 속성(attribute)을 가진 meta 요소(element)를 모두 포함하지 않아야(must) 합니다.

인코딩 선언 상태HTML 문서들XML 문서들에서 사용될 수 있습니다. 인코딩 선언 상태XML 문서들에서 사용된다면, 문자 인코딩의 이름은 문자열 "UTF-8"에 대해 ASCII 대소문자 구분 없이 일치해야(must) 합니다 (그리고 문서는 따라서 그것의 인코딩으로 UTF-8을 사용하도록 강제 됩니다).

인코딩 선언 상태는 XML 문서들에서 어떤 영향도 가지지 않고, XHTML로 그리고 XHTML로부터 마이그레이션을 가능하게 하기 위하여만 허용됩니다.

기본 스타일 상태 (http-equiv="default-style")

이 선처리(pragma)는 기본 대체 스타일 시트 세트의 이름을 설정합니다.

  1. meta 요소(element)가 content 속성(attribute)을 가지지 않거나, 그 속성(attribute)의 값이 빈 문자열이라면, 이 단계들을 중단합니다.

  2. 우선되는 스타일 시트 세트를 요소(element)의 content 속성(attribute)의 값으로 설정합니다. [CSSOM]

새로고침 상태 (http-equiv="refresh")

이 선처리(pragma)는 시한(일정 시간 후 작동하도록 장치된) 리다이렉트로 동작합니다.

  1. 새로고침 상태에 있는 http-equiv 속성(attribute)을 가진 다른 meta 요소(element)는 이미 성공적으로 처리되었다면 (즉, 그것이 삽입될 때 유저 에이전트가 그것을 처리하고 end라고 라벨링 된 단계에 도달할 경우), 이 단계들을 중단합니다.

  2. meta 요소(element)가 content 속성(attribute)을 가지지 않거나, 그 속성(attribute)의 값이 빈 문자열이라면, 이 단계들을 중단합니다.

  3. input을 요소(element)의 content 속성(attribute)의 값으로 둡니다.

  4. positioninput의 첫 번째 문자를 가리키게 합니다.

  5. 여백을 건너뜁니다.

  6. ASCII 숫자들일련의 문자를 수집하고, 음이 아닌 정수 해석에 대한 규칙을 사용하여 결과 문자열을 해석합니다. 수집된 일련의 문자들이 빈 문자열이라면, 번호가 해석되지 않을 것입니다; 이 단계들을 중단합니다. 그렇지 않으면, time을 해석된 숫자로 둡니다.

  7. ACSII 숫자들이고 U+002E 마침표 문자 (.)인 일련의 문자를 수집합니다. 수집된 모든 문자들을 무시합니다.

  8. urlmeta 요소(element)의 노드 문서URL로 둡니다.

  9. positioninput의 끝을 지났다면, end라고 라벨링 된 단계로 건너뜁니다.

  10. position에 의해 가리켜진 input 내 문자가 U+003B 세미콜론 문자 (;)나, U+002C 콤마 문자 (,)나, 공백 문자가 아니라면, 이 단계들을 중단합니다.

  11. 여백을 건너뜁니다.

  12. position에 의해 가리켜진 input 내 문자가 U+003B 세미콜론 문자 (;)나, U+002C 콤마 문자 (,) 라면, position을 다음 문자로 전진시킵니다.

  13. 여백을 건너뜁니다.

  14. positioninput의 끝을 지났다면, end라고 라벨링 된 단계로 건너뜁니다.

  15. urlposition에 있는 문자로부터 문자열의 끝까지 input의 부분 문자열과 같게 합니다.

  16. position에 의해 가리켜진 input 내 문자가 U+0055 라틴 대문자 U (U)이거나 U+0075 라틴 소문자 U (u)라면, position을 다음 문자로 전진시킵니다. 그렇지 않으면, skip quotes로 라벨링 된 단계로 건너뜁니다.

  17. position에 의해 가리켜진 input 내 문자가 U+0052 라틴 대문자 R (R)이거나 U+0072 소문자 R (r)이라면, position을 다음 문자로 전진시킵니다. 그렇지 않으면, Parse라고 라벨링 된 단계로 건너뜁니다.

  18. position에 의해 가리켜진 input 내 문자가 U+004C 라틴 대문자 L (L)이거나 U+006C 라틴 소문자 L (l)이라면, position을 다음 문자로 전진시킵니다. 그렇지 않으면 Parse라고 라벨링 된 단계로 건너뜁니다.

  19. 여백을 건너뜁니다.

  20. position에 의해 가리켜진 input 내 문자가 U+003D 등호 기호 (=)라면, position를 다음 문자로 전진시킵니다. 그렇지 않으면, Parse로 라벨링 된 단계로 건너뜁니다.

  21. 여백을 건너뜁니다.

  22. Skip quotes: position에 의해 가리켜진 input 내 문자가 U+0027 어포스트로피 문자 (')나 U+0022 따옴표 문자 (")라면, quote를 그 문자로 두고, position을 다음 문자로 전진시킵니다. 그렇지 않으면, quote를 빈 문자열로 둡니다.

  23. urlposition에 있는 문자부터 문자열의 끝까지 input의 부분 문자열과 같게 합니다.

  24. quote가 빈 문자열이 아니고, url 내에 quote와 동일한 문자가 있다면, 그 문자에서 url을 버리기 때문에, 그것과 모든 다음의 문자들은 제거됩니다.

  25. Parse: meta 요소(element)의 노드 문서에 관련하여 url해석합니다. 그것이 실패한다면, 이 단계들을 중단합니다. 그렇지 않으면, urlRecord결과 URL 레코드로 둡니다.

  26. End: 다음 단계들 중 하나 이상을 수행합니다:

    그밖에, 유저 에이전트는, 어떠한 것이라도, 모든 타이머의 상태, 시간이 초과된 모든 리다이렉션의 목적지 등등을 포함하여 작동의 모든 측면을 예외 없이 사용자에게 알릴 수 있습니다.

새로고침 상태 상태에 있는 http-equiv 속성(attribute)을 가진 meta 요소(element)들에 대해, content 속성(attribute)은 다음으로 구성되는 값을 가져야(must) 합니다:

전자의 경우, 정수는 페이지가 리로드 되기 전 몇 초를 나타냅니다; 후자의 경우 정수는 주어진 URL로 페이지가 교체되기 몇 초 전을 나타냅니다.

뉴스 조직의 프론트 페이지는 매 5분 마다 서버로부터 페이지가 자동으로 리로드 되는 것을 보장하기 위해, 페이지의 head 요소(element)에 다음 마크업을 포함할 수 있습니다:
<meta http-equiv="Refresh" content="300">
일련의 페이지는 다음과 같은 마크업을 사용하여, 순서에 따라 각 페이지가 다음 페이지로 새로고침 되도록 만드는 것에 의해 자동적인 슬라이드 쇼로 사용될 수 있습니다:
<meta http-equiv="Refresh" content="20; URL=page4.html">

쿠키 설정자 (http-equiv="set-cookie")

이 선처리(pragma)는 HTTP 쿠키를 설정합니다. [COOKIES]

이것은 부적합 합니다. 실제 HTTP 헤더들이 대신 사용되어야(should) 합니다.

  1. meta 요소(element)가 content 속성(attribute)을 가지지 않거나 그 속성(attribute)의 값이 빈 문자열이라면, 이 단계들을 중단합니다.

  2. "비 HTTP" API를 통해 UTF-8로 인코드 된 요소(element)의 content 속성(attribute) 값으로 구성되는, 문서의 주소에 대해 쿠키 설정 문자열을 수신하는 것 처럼 행동합니다. [COOKIES] [ENCODING]

콘텐트 보안 정책 상태 (http-equiv="content-security-policy")

이 선처리(pragma)는 Document콘텐트 보안 정책강제 합니다. [CSP3]

  1. meta 요소(element)가 head 요소(element)의 자식이 아니라면, 이 단계들을 중단합니다.

  2. meta 요소(element)가 content 속성(attribute)을 가지지 않거나, 그 속성(attribute)의 값이 빈 문자열이라면, 이 단계들을 중단합니다.

  3. policymeta 요소(element)의 content 속성(attribute)의 값에 콘텐트 보안 정책의 직렬화 된 콘텐트 보안 정책 해석을 실행한 결과로 둡니다.

  4. policy부터의 report-uri, frame-ancestors, sandbox 지시자들의 모든 발생들을 제거합니다.

  5. policy 정책을 강제합니다.

콘텐트 보안 정책 상태에 있는 http-equiv 속성(attribute)을 가진 meta 요소(element)들에 대해, content 속성(attribute)은 유효한 콘텐트 보안 정책으로 구성되는 값을 가져야(must) 하고, 어떤 report-uri나, frame-ancestors나, sandbox 지시자들을 포함하지 않아야(must) 합니다. content 속성(attribute)에 주어진 콘텐트 보안 정책은 현재 문서에 강제될 것입니다.

페이지는 다음과 같은 정책을 사용하여, 모든 플러그인 콘텐트를 차단할 뿐 아니라, 인라인 자바스립트의 실행을 막음으로써 교차 사이트 스크립팅 공격의 위험성을 완화시키기 위해 선택할 수 있습니다:
<meta http-equiv="Content-Security-Policy" content="script-src 'self'; object-src 'none'">

한 번에 문서에 어떤 특정 상태를 가진 meta 요소(element)는 하나를 초과하여 존재하지 않아야(must) 합니다.

4.2.5.4. 다른 선처리(pragma) 지시자들

선처리(pragrm) 지시자들의 미리 정의된 세트에 대한 확장들은 특정 조건 하에, WHATWG Wiki PragmaExtensions 페이지에 등록될 수 있습니다.

그 확장들은 영구 메시지 헤더 필드 레지스트리에 등록된 HTTP 헤더와 같은 이름을 사용해야(must) 하고, HTTP 헤더에 대해 기술된 것과 같은 동작을 가져야(must) 합니다. [IANAPERMHEADERS]

메타데이터를 설명하는 헤더에 해당하는 선처리(Pragma) 지시자들이나, 특정 유저 에이전트 처리를 요구하지 않는 선처리(Pragma) 지시자들은 등록되지 않아야(must) 합니다; 대신에, 메타데이터 이름들을 사용하세요. HTTP 처리 모델에 (예를 들어, 캐싱) 영향을 주는 헤더에 해당하는 선처리(Pragma) 지시자들은 그것들은 HTTP 수준 동작에서 HTML을 구현하는 유저 에이전트들과 그렇지 않은 유저 에이전트들에 차이가 발생될 것이기 때문에, 등록되지 않아야(must) 합니다.

누구든지 이 조건들을 만족하는 선처리(pragma) 지시자를 추가하기 위해 언제든지 WHATWG Wiki PragmaExtensions 페이지를 자유롭게 수정할 수 있습니다. 그 등록들은 다음 정보를 명시해야(must) 합니다:

키워드(keyword)

정의되는 실제 이름. 이름은 동일한 요구사항을 가진 앞서 등록된 HTTP 이름과 일치해야(must) 합니다.

간단한 설명(brief description)

선처리(pragma) 지시자의 목적에 대한 짧은 비 규범적 설명.

명세(specification)

해당하는 HTTP 헤더를 정의하는 명세로의 링크.

적합성 검사기는 값이 허용되었는지 아닌지를 확증하기 위해 WHATWG Wiki PragmaExtensions 페이지에 주어진 정보를 사용해야(must) 합니다: 이 명세나 앞서 언급된 페이지에 언급되지 않은 값들이 유효하지 않은 것으로 거부되어야(must) 하는데 반하여, 이 명세에 정의된 값이나 앞서 언급된 페이지에 언급된 값들은 허용되어야(must)합니다. 적합성 검사기는 이 정보를 캐시할 수 있습니다 (예를 들어, 성능상의 이유나 신뢰할 수 없는 네트워크 접속의 사용을 방지하기 위해).
4.2.5.5. 문서의 문자 인코딩 명시하기

문자 인코딩 선언은 문서를 저장하거나 전송하는데 사용되는 명시된 문자 인코딩에 의한 메커니즘입니다.

다음 제약 사항들이 문자 인코딩 선언에 적용됩니다:

  • 주어진 문자 인코딩 이름은 파일 직렬화에 사용된 문자 인코딩레이블들 중 하나에 ASCII 대소문자 구분 없이 일치해야(must) 합니다. [ENCODING]

  • 문자 인코딩 선언은 문자 참조들이나 어떤 종류의 문자 이스케이프의 사용 없이 직렬화 되어야(must) 합니다.

  • 문자 인코딩 선언을 포함하는 요소(element)는 문서의 처음 1024 바이트 내에서 완전히 직렬화 되어야(must) 합니다.

게다가, meta 요소(element)들에 몇 가지 제약 사항 때문에, 문서 당 하나의 meta 기반 문자 인코딩 선언만 존재 할 수 있습니다.

HTML 문서가 BOM으로 시작하지 않고 그것의 인코딩이 명시적으로 Content-Type 메타데이터에 의해 주어지지 않고, 문서가 iframe srcdoc 문서가 아니라면, 사용된 문자 인코딩은 ASCII 호환 인코딩이어야(must) 하고, 인코딩은 charset 속성(attribute)을 가진 meta 요소(element)나 인코딩 선언 상태에 있는 http-equiv 속성(attribute)을 가진 meta 요소(element)를 사용하여 명시되어야(must) 합니다.

인코딩이 US-ASCII일 지라도, 문자 인코딩이 양식, 스크립트에 의해 생성된 URL들 등에서 사용자에 의해 입력된 비 ASCII 문자들을 처리하기 위해 필요하기 때문에, 문자 인코딩 선언은 (Content-Type 메타데이터나 파일에 명시적으로) 요구됩니다.

문서가 iframe srcdoc 문서라면, 문서는 문서 인코딩 선언을 가지지 않아야(must) 합니다. (이 경우에는, iframe가 포함된 문서의 일부이기 때문에 소스는 이미 디코드 되어있습니다).

HTML 문서charset 속성(attribute)을 가진 meta 요소(element)나 문자 인코딩 상태에 있는 http-equiv 속성(attribute)을 가진 meta 요소(element)를 포함한다면, 사용된 문자 인코딩은 ASCII 호환 인코딩이어야(must) 합니다.

작성자들은 UTF-8을 사용해야(should) 합니다. 적합성 검사기들은 작성자들이 레거시 인코딩을 사용하지 않도록 조언할 수 있습니다. [ENCODING]

작성 도구들은 새롭게 생성되는 문서들에 대해 UTF-8 사용을 기본으로 해야(should) 합니다. [ENCODING]

작성자들은 WHATWG 인코딩 표준에 정의되지 않은 인코딩을 사용하지 않아야(must) 합니다. 추가적으로, 작성자들은 ISO-2022-JP를 사용하지 않아야(should) 합니다. [ENCODING]

WHATWG 인코딩 표준에 정의되지 않은 일부 인코딩들은, U+0020부터 U+007E까지 범위에 해당하는 문자들과 다른 문자들을 인코드하기 위해, 0x20부터 0x7E까지의 범위의 바이트를 사용하고, 잠재적인 보안 취약점을 나타냅니다: 유저 에이전트는 아마도 정상적인 평문 콘텐트를 HTML 태그와 자바스크립트로 해석하게 될 수도 있습니다.

위 Note 부분은 일부 번역이 잘못 되었을 수 있습니다.

비 UTF-8 인코딩을 사용하는 것은 기본 값으로 문서의 문자 인코딩을 사용하는 양식 제출과 URL 인코딩에서 예기치 않은 결과를 가져 올 수 있습니다.

XHTML에서, 필요하다면, XML 선언은 인라인 문자 인코딩 정보에 사용되어야(should) 합니다.

HTML에서, 문자 인코딩이 UTF-8임을 선언하기 위해, 작성자는 문서의 상단 가까이에 (head 요소(element) 안에) 다음 마크업을 포함할 수 있습니다:
<meta charset="utf-8">

XML에서, 마크업의 최 상단에, XML 선언이 대신 사용될 것입니다:

<?xml version="1.0" encoding="utf-8"?>

4.2.6. style 요소(element)

카테고리:
메타데이터 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
메타데이터 콘텐트가 기대 되는 곳.
head 요소(element)의 자식인 noscript 요소(element) 안.
콘텐트 모델:
type 속성(attribute)의 값에 달려있지만, 아래 본문에 기술된 요구사항들에 일치해야(must) 합니다.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다.
콘텐트 속성(attribute)들:
범용 속성(attribute)들
media — 적용 가능한 매체
nonce - 콘텐트 보안 정책 검사에 사용되는 암호화 임시값 [CSP3]
type — 삽입된 리소스의 유형
또한, title 속성(attribute)은 이 요소(element)에서 특별한 의미를 가집니다: 대체 스타일 시트 세트 이름.
허용된 ARIA 역할(role) 속성(attribute) 값들:
없음
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
DOM 인터페이스:
interface HTMLStyleElement : HTMLElement {
  attribute DOMString media;
  attribute DOMString nonce;
  attribute DOMString type;
};
HTMLStyleElement implements LinkStyle;

CSP3 지시자에 기반한 style 요소(element)를 차단하는 네이티브 구현은 알려진 것이 없습니다. 따라서 이 기능은 신뢰되지 않아야(should) 합니다.

style 요소(element)는 작성자들이 그들의 문서에 스타일 정보를 삽입시키는 것을 허용합니다. style 요소(element)는 스타일링 처리 모델에 몇 가지 입력 중 하나입니다. 요소(element)는 사용자에게 콘텐트를 나타내지 않습니다.

type 속성(attribute)은 스타일링 언어를 제공합니다. 속성(attribute)이 존재한다면, 그 값은 스타일링 언어를 지정하는 유효한 MIME 타입이어야(must) 합니다. charset 파라미터는 명시되지 않아야(must) 합니다. 속성(attribute)이 존재하지 않는다면 사용되는 type 속성(attribute)에 대한 기본 값은 "text/css"입니다. [RFC2318]

언어를 지원하는지를 결정하기 위해 유형들을 검토할 경우, 유저 에이전트들은 알려지지 않은 MIME 파라미터들을 무시하지 않아야(must) 합니다 — 알려지지 않은 파라미터들을 가진 유현들은 지원되지 않는 것으로 간주되어야(must) 합니다. charset 파라미터는 여기 MIME 타입들과 비교할 목적을 위해 알려져지 않은 파라미터로 취급되어야(must) 합니다.

media 속성(attribute)은 스타일이 적용되는 매체를 알립니다. 값은 유효한 미디어 쿼리 목록이어야(must)합니다. 유저 에이전트는 media 속성(attribute)의 값이 환경과 일치하고 다른 관련 조건들이 적용되는 경우 스타일을 적용해야(must)하고, 그렇지 않으면 적용하지 않아야(must) 합니다.

스타일은 범위에 따라, 예를 들어 @media 블럭을 사용하는 CSS에서, 더 제한될 수 있습니다. 이 명세는 그러한 추가적인 제약 사항이나 요구사항들을 재정의 하지 않습니다.

media 속성(attribute)이 생략되었다면, 기본 값은 기본적으로 스타일이 모든 매체에 적용 됨을 의미하는 "all"입니다.

style 요소(element)는 문서의 head에 나타나도록 제한됩니다.

nonce 속성(attribute)은 요소(element)에 의해 명시된 스타일이 문서에 적용될 것인지 아닌지를 결정하기 위해 콘텐트 보안 정책으로 사용될 수 있는 암호화 임시 값("한 번 사용되는 숫자")을 나타냅니다. 값은 텍스트 입니다. [CSP3]

style 요소(element)들의 title 속성(attribute)은 대체 스타일 시트 세트들을 정의합니다. style 요소(element)가 title 속성(attribute)을 가지지 않는다면, 제목(title)을 가지지 않습니다; 조상들의 title 속성(attribute)은 style 요소(element)에 영향을 주지 않습니다. [CSSOM]

style 요소(element)들의 title 속성(attribute)은 link 요소(element)들의 title 속성(attribute)과 같이, 제목(title)이 없는 style 블럭이 부모 요소(element)의 제목(title)을 상속하지 않는 점에서 범용 title 속성(attribute)과 다릅니다: 그것은 단지 제목(title)을 가지지 않습니다.

style 요소(element)의 textContent는 유니코드인 문자 세트인 다음 ABNF의 style 산출물과 일치해야(must) 합니다. [ABNF]

style         = no-c-start *( c-start no-c-end c-end no-c-start )
no-c-start    = < any string that doesn’t contain a substring that matches c-start >
c-start       = "<!--"
no-c-end      = < any string that doesn’t contain a substring that matches c-end >
c-end         = "-->"

유저 에이전트는 다음 조건들 중 하나가 발생할 때 마다, 요소(element)의 스타일 데이터를 전달하여, style 요소(element)의 type 속성(attribute)에 의해 명시된 스타일 시트 언어에 대해 적용하는 style 블럭 업데이트 알고리즘을 수행해야(must) 합니다:

순수 텍스트로 구성된 스타일링 언어에 대한 (XML과 반대로), style 요소(element)의 스타일 데이터트리 순서에 따라, style 요소(element)의 자식인 모든 Text 노드들의 (주석들이나 요소(element)들 같은 다른 노드들이 아닌) 콘텐트의 연결입니다. XML 기반 스타일링 언어에 대한, 스타일 데이터style 요소(element)의 모든 자식 노드들로 구성됩니다.

CSS(text/css)에 대한 style 블럭 업데이트 알고리즘은 다음과 같습니다:

  1. elementstyle 요소(element)로 둡니다.

  2. element연관된 CSS 스타일 시트를 가진다면, 문제의 CSS 스타일 시트를 제거합니다.

  3. elementDocument 안에 없다면, 이 단계들을 중단합니다.

  4. 요소(element)의 인라인 동작은 콘텐트 보안 정책에 의해 차단되어야(should) 하는가? 알고리즘이 style 요소(element)에서 실행된 경우 "Blocked"와, "style", 그리고 style 요소(element)의 스타일 데이터를 반환한다면, 이 단계들을 중단합니다. [CSP3]

  5. 다음 속성(property)들을 가지고 CSS 스타일 시트를 생성합니다:

    type

    text/css

    소유자 노드

    element

    media

    elementmedia 속성(attribute) .

    이것은 속성(attribute)의 현재 값의 복사본 보다는, 속성(attribute)에 대한 (아마도 현재는 없을 수도 있습니다) 참조입니다. CSSOM 명세는 속성(attribute)이 동적으로 설정, 변경, 제거될 때 일어나는 것을 정의합니다.

    title

    elementtitle 속성(attribute).

    다시, 이것은 속성(attribute)에 대한 참조입니다.

    대체 플래그

    해제.

    origin-clean 플래그

    설정.

    부모 CSS 스타일 시트

    소유자 CSS 규칙

    null

    비활성 플래그

    기본 값으로 남음.

    CSS 규칙들

    초기화되지 않은 채로 남음.

이 명세는 다른 스타일링 언어의 style 블럭 업데이트 알고리즘을 정의하지 않습니다.

스타일 시트의 중요한 하위 리소스들이 있는 경우 이를 얻기 위한 시도가 완료되거나, 스타일 시트가 중요한 하위 리소스들을 가지지 않는 경우 스타일 시트가 해석되고 처리될 때, 유저 에이전트는 로드가 성공적이거나 중요한 하위 리소스들이 없었다면 style 요소(element)에 load라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣어야(must) 하거나, 스타일 시트의 중요한 하위 리소스들 중 하나가 어떤 이유로 (예를 들어, DSN 오류, HTTP 404 응답, 너무 빨리 닫히는 연결, 지원되지 않은 Content-Type) 완전한 로드가 실패되었다면 style 요소(element)에 error라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣어야(must) 합니다. 스타일 시트나 그것의 하위 리소스들 처리에서 비 네트워크 오류는 (예를 들어, CSS 해석 오류들, PNG 디코딩 오류들) 이 단락의 목적에 대한 실패가 아닙니다.

작업들에 대한 작업 소스DOM 조작 작업 소스입니다.

요소(element)는 스타일 시트의 하위 리소스들이 있다면 이들을 획득하기 위한 모든 시도가 완료될 때까지, 요소(element)의 노드 문서로드 이벤트를 지연시켜야(must) 합니다.

이 명세는 스타일 시스템을 명시하지 않지만, CSS는 대다수 브라우저에 의해 지원되는 것으로 예상됩니다. [CSS-2015]

media, nonce, type IDL 속성(attribute)들은 각각의 동일한 이름의 콘텐트 속성(attribute)들을 반영해야(must) 합니다.

LinkStyle 인터페이스 또한 이 요소(element)에 의해 구현됩니다. [CSSOM]

다음 문서는 작품의 제목(title)들과 라틴어 단어들이 기본 이탤릭체로 남겨지는 것에 반해, 그것의 이탤릭체 텍스트보다 밝은 붉은 텍스트로 스타일 된 강조를 가집니다. 그것은 적절한 요소(element)들을 사용하여 문서들의 재스타일링을 쉽게 가능하게 하는 방법을 보여줍니다.
<!DOCTYPE html><html>
  <head>
    <title>My favorite book</title>
    <style>
      body { color: black; background: white; }
      em { font-style: normal; color: red; }
    </style>
  </head>
  <body>
    <p>My <em>favorite</em> book of all time has <em>got</em> to be
    <cite>A Cat’s Life</cite>. It is a book by P. Rahmel that talks
    about the <i lang="la">Felis Catus</i> in modern human society.</p>
  </body>
</html>

4.2.7. 스타일링과 스크립팅의 상호작용

스타일 시트들은, link 요소(element)나, style 요소(element)나, <?xml-stylesheet?> PI나, HTTP Link 헤더나 어떤 다른 메커니즘에 의해 추가되었든지 간에, 초기에 해제되어 있는 스타일 시트 준비 플래그를 가집니다.

스타일 시트가 적용될 준비가 될 경우, 그것의 스타일 시트 준비 플래그가 설정됩니다. 스타일 시트가 다른 리소스들을 참조하지 않았다면 (예를 들어, @import 규칙들 없는 style 요소(element)에 의해 주어진 내부 스타일 시트였다면), 스타일 규칙들은 즉시 스크립트에 사용할 수 있게 되어야(must) 합니다; 그렇지 않으면, 스타일 규칙들은 이벤트 반복이 그것의 렌더링 업데이트 단계에 도달할 때에만 스크립트에 사용할 수 있게 되어야(must) 합니다.

HTML 해석기XML 해석기Document의 컨텍스트에서 스타일 시트는 요소(element)가 그 Document의 해석기에 의해 생성되었고, 요소(element)가 style 요소(element)나 요소(element)가 해석기에 의해 생성 되었을 때 외부 리소스 링크link 요소(element)이고, 요소(element)의 스타일 시트가 요소(element)가 해석기에 의해 생성되었을 때 활성화 되었고, 요소(element)의 스타일 시트 준비 플래그가 아직 설정되지 않았고, 마지막에 이벤트 반복이 단계 1에 도달했을 때 요소(element)가 그 Document에 있었고 유저 에이전트가 아직 그 특정 스타일 시트를 포기하지 않았다면, 스크립트들을 차단하는 스타일 시트라고 알려집니다. 유저 에이전트는 언제든지 스타일 시트를 포기할 수 있습니다.

스타일 시트가 로드되기 전에 스타일 시트를 포기하는 것은, 스타일 시트가 결국 여전히 로드한다면, 스크립트가 잘못된 정보를 가지고 작동되는 결과를 초래할 수 있음을 의미합니다. 예를 들어, 스타일 시트가 요소(element)의 색상을 녹색으로 설정하지만, 결과 스타일을 검사하는 스크립트는 시트가 로드되기 전에 실행된다면, 스크립트는 요소(element)가 검정색임을 (혹은 기본 색상인 어떤 색상) 발견하게 될 것이고, 따라서 잘못된 선택을 (예를 들어, 녹색 대신, 페이지의 다른 곳에서 검정색을 사용하도록 결정한) 만들 수 있습니다. 구현자는 잘못된 정보를 사용하는 스크립트의 가능성과 느린 네트워크 요청이 끝나기를 기다리는 동안 아무 것도 하지 않는 것의 성능 영향을 조정해야(must) 합니다.

Document는 그 Document의 컨텍스트에서 스크립트들을 차단하는 스타일 시트가 있거나, 그 Document부모 브라우징 컨텍스트를 가지고 그 부모 브라우징 컨텍스트활성 문서스크립트들을 차단하는 스타일 시트를 가지는 브라우징 컨텍스트에 있다면 스크립트들을 차단하는 스타일 시트를 가집니다.

Document는 위 단락에서 기술된 바와 같은 스크립트들을 차단하는 스타일 시트를 가지지 않는다면 스크립트들을 차단하는 스타일 시트를 가지지 않습니다.

4.3. 섹션

4.3.1. body 요소(element)

카테고리:
섹션화(sectioning) 루트.
이 요소(element)가 사용될 수 있는 컨텍스트:
html 요소(element) 내의 두 번째 요소(element)로서.
콘텐트 모델:
흐름(flow) 콘텐트.
text/html에서 태그 생략:
body 요소(element)의 시작 태그는 요소(element)가 비어있거나 body 요소(element) 안의 첫 번째 것이 meta, link, script, style, template를 제외하고, 공백 문자주석이 아니라면 생략될 수 있습니다.
body 요소(element)의 종료 태그body 요소(element)에 주석이 즉시 뒤따르지 않는다면 생략될 수 있습니다.
콘텐트 속성(attribute)들:
범용 속성(attribute)들
onafterprint
onbeforeprint
onbeforeunload
onhashchange
onlanguagechange
onmessage
onoffline
ononline
onpagehide
onpageshow
onpopstate
onrejectionhandled
onstorage
onunhandledrejection
onunload
허용된 ARIA 역할(role) 속성(attribute) 값들:
document 역할(role) (기본 값 - 설정하지 마세요), application.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
interface HTMLBodyElement : HTMLElement {
};
HTMLBodyElement implements WindowEventHandlers;

body 요소(element)는 문서의 콘텐트를 나타냅니다.

적합한 문서들에서, body 요소(element)는 오직 하나만 존재합니다. document.body IDL 속성은 문서의 body 요소(element)로의 쉬운 접근을 가진 스크립트를 제공합니다.

일부 DOM 연산들은 (예를 들어 드래그 앤 드랍 모델의 일부) "body 요소(element)"의 측면에서 정의됩니다. 이것은 독단적인 body 요소(element)가 아니라 용어의 정의마다, DOM의 특정 요소(element)를 참조합니다.

body 요소(element)는 이벤트 처리기 콘텐트 속성(attribute)들로서 Window 객체의 많은 이벤트 처리기들을 노출시킵니다. 그것은 또한 그것들의 이벤트 처리기 IDL 속성(attribute)들을 반영합니다.

body 요소(element)에 노출된 Window 객체의 onblur, onerror, onfocus, onload, onresize, onscroll 이벤트 처리기들은 일반적인 이벤트 처리기들을 보통 html 요소(element)들에 의해 지원되는 동일한 이름으로 교체합니다.

따라서, 예를 들어, Documentbody 요소(element)의 자식에서 보내진 버블링 error 이벤트는 처음 그 요소(element)의 onerror 이벤트 처리기 콘텐트 속성(attribute)들을 작동시키고, 이후 루트 html 요소(element)의 그것을 작동시키고, 그 이후에야 body 요소(element)에서 onerror 이벤트 처리기 콘텐트 속성(attribute)을 작동 시킬 것입니다. 이것은 이벤트가 대상으로부터 body로, html로, Document로, Window로 버블되고, body이벤트 처리기body가 아닌 Window를 바라보고 있기 때문입니다. 하지만, addEventListener()를 사용하여 body에 할당 된 보통의 이벤트 리스너는 이벤트가 Window 객체에 도달했을 때가 아닌 body를 통해 버블되었을 때 수행될 것입니다.

이 페이지는 사용자가 온라인인지 아닌 지를 보여주는 표시기를 갱신합니다:
<!DOCTYPE HTML>
<html>
  <head>
    <title>Online or offline?</title>
    <script>
      function update(online) {
        document.getElementById('status').textContent =
        online ? 'Online' : 'Offline';
      }
    </script>
  </head>
  <body ononline="update(true)"
    onoffline="update(false)"
    onload="update(navigator.onLine)">
    <p>You are: <span id="status">(Unknown)</span></p>
  </body>
</html>

4.3.2. article 요소(element)

카테고리:
main 요소(element) 후손들이 없는 흐름(flow) 콘텐트.
섹션화(sectioning) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
흐름(flow) 콘텐트가 예상 되는 곳.
콘텐트 모델:
흐름(flow) 콘텐트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
article (기본 값 - 설정하지 마세요), application, documentmain.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLElement를 사용합니다.

article 요소(element)는 완전한 혹은 독립적인 문서, 페이지, 어플리케이션, 혹은 사이트 내의 구성요소를 나타냅니다. 이것은 잡지, 뉴스, 기술적 혹은 전문적 아티클, 에세이나 보고서, 블로그나 다른 소셜 미디어 게시물 일 수 있습니다.

일반적인 규칙은 article 요소(element)가 요소(element)의 콘텐트가 문서의 아웃라인 내에 명시적으로 나열되는 경우에만 적절하다는 것입니다. 각 article은 일반적으로 article 요소(element)의 자식으로 제목(heading)(h1-h6 요소(element))을 포함하는 것에 의해 식별되어야(should) 합니다.

보조 기술은 article의 의미를 사용자에게 전달 할 수 있습니다. 이 정보는 콘텐트의 유형으로 사용자에게 힌트를 제공할 수 있습니다. 예를 들어 사용자가 article 요소(element)로 탐색할 경우, 요소(element) 이름 "article"에 일치하는 요소(element)의 role은 스크린리더 소프트웨어에 의해 알려질 수 있습니다. 유저 에이전트들은 또한 article 요소(element)로 탐색하기 위한 메서드들을 제공할 수 있습니다.

article 요소(element)들이 중첩되는 경우, 내부 article 요소(element)들은 원칙적으로 바깥 아티클의 콘텐츠와 연관된 아티클들임을 의미합니다. 예를 들어, 사이트의 블로그 항목은 블로그 항목에 대한 article 요소(element) 내에 중첩 된 article 요소들(element)에 다른 블로그 항목들의 요약들로 구성될 수 있습니다.

article 요소(element)와 연관된 작성자 정보는 (참조. address 요소(element)) 중첩된 article 요소(element) 들에 적용되지 않습니다.

다음은 article 요소(element)를 사용하여 마크업 된, 블로그 게시물 발췌의 예입니다:

<article>
 <header>
  <h2><a href="https://herbert.io">Short note on wearing shorts</a></h2>
   <p>Posted on Wednesday, 10 February 2016 by Patrick Lauke.
   <a href="https://herbert.io/short-note/#comments">6 comments</a></p>
 </header>
 <p>A fellow traveller posed an interesting question: Why do you wear shorts rather than
 longs? The person was wearing culottes as the time, so I considered the question equivocal in nature,
 but I attempted to provide an honest answer despite the dubiousness of the questioner’s dress.</p>
 <p>The short answer is that I enjoy wearing shorts, the long answer is...</p>
 <p><a href="https://herbert.io/short-note/">Continue reading: Short note on
 wearing shorts</a></p>
</article>

schema.org 표현 형식은 창작 - 아티클 하위 유형을 사용하여 아티클의 유형에 대한 좀 더 세밀한 정보를 제공하는데 사용될 수 있고, 아티클에 대한 발행 날짜와 같은 다른 정보들도 역시 제공될 수 있습니다.

이 예제는 일부 schema.org 주석을 가지고 article 요소(element)를 사용하여 블로그 게시물을 보여줍니다:

<article itemscope itemtype="https://schema.org/BlogPosting">
  <header>
    <h2 itemprop="headline">The Very First Rule of Life</h2>
    <p><time itemprop="datePublished" datetime="2016-02-28">3 days ago</time></p>
  </header>
  <p>If there’s a microphone anywhere near you, assume it’s hot and
  sending whatever you’re saying to the world. Seriously.</p>
  <p>...</p>
  <footer>
    <a itemprop="discussionUrl" href="?comments=1">Show comments...</a>
  </footer>
</article>

여기 동일한 게시물이지만, 댓글들의 일부를 보여주는 것이 있습니다:

     <article itemscope itemtype="https://schema.org/BlogPosting">  <header>
    <h2 itemprop="headline">The Very First Rule of Life</h2>
    <p><time itemprop="datePublished" datetime="2009-10-09">3 days ago</time></p>
  </header>
   <p>If there’s a microphone anywhere near you, assume it’s hot and
   sending whatever you’re saying to the world. Seriously.</p>
   <p>...</p>
  <section>
    <h3>Comments</h3>
    <ol>
     <li itemprop="comment" itemscope itemtype="https://schema.org/UserComments" id="c1">
        <p>Posted by: <span itemprop="creator" itemscope itemtype="https://schema.org/Person">
        <span itemprop="name">George Washington</span>
        </span></p>
        <p><time itemprop="commentTime" datetime="2009-10-10">15 minutes ago</time></p>
        <p>Yeah! Especially when talking about your lobbyist friends!</p>
     <li itemprop="comment" itemscope itemtype="https://schema.org/UserComments" id="c2">
        <p>Posted by: <span itemprop="creator" itemscope itemtype="https://schema.org/Person">
        <span itemprop="name">George Hammond</span>
        </span></p>
        <p><time itemprop="commentTime" datetime="2009-10-10">5 minutes ago</time></p>
        <p>Hey, you have the same first name as me.</p>
     </li>
   </ol>
  </section>
</article>

댓글들을 구조화하기 위한 순서가 있는 목록 ol의 사용에 주목하세요. 또한 댓글들이 section 요소(element)를 사용하여 식별된 아티클의 하위 섹션임을 참고하세요.

4.3.3. section 요소(element)

카테고리:
흐름(flow) 콘텐트.
섹션화(sectioning) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
흐름(flow) 콘텐트가 기대 되는 곳.
콘텐트 모델:
흐름(flow) 콘텐트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
region 역할(role) (기본 값 - 설정하지 마세요), alert, alertdialog, application, contentinfo, dialog, document, log, main, marquee, presentation, search, status.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLElement를 사용합니다.

section 요소(element)는 문서나 어플리케이션의 일반적인 섹션을 나타냅니다. 이 맥락에서, 섹션은 콘텐트의 주제별 그룹 입니다. 각 section은 일반적으로 section 요소(element)의 자식으로 제목(heading)을 (h1-h6 요소(element)) 포함하는 것으로 식별되어야(should) 합니다.

섹센의 예제들은 챕터들, 탭 대화상자의 여러 탭 페이지들, 논문의 번호가 매겨진 섹션들이 될 것입니다. 웹 사이트의 홈페이지는 소개, 뉴스 항목들, 연락 정보에 대한 섹션들로 분할 될 수 있습니다.

작성자들은 콘텐트가 완전하거나 독립적인 구성 요소인 경우 section 요소(element) 대신 article 요소(element)를 사용하도록 권장됩니다.

section 요소(element)는 일반적인 컨테이너 요소(element)가 아닙니다. 요소(element)가 단지 스타일링 목적이나 스크립팅을 위한 편의로 요구되는 경우, 작성자는 대신 div 요소(element)를 사용하도록 권장됩니다. 일반적인 규칙은 section 요소(element)는 요소(element)의 콘텐트가 문서의 개요(outline)에 명시적으로 나열되는 경우에만 적절합니다.

보조 기술은 요소(element)가 명시적인 레이블을 가지는 경우 사용자들에게 section의 의미를 전달 할 수 있습니다. 이 정보는 사용자에게 콘텐트의 유형에 관하여 힌트를 제공할 수 있습니다. 예를 들어 이 경우에 "region"인 요소(element)의 role은 사용자가 section 요소(element)로 탐색할 때 스크린리더 소프트웨어에 의해 알려질 수 있습니다. 유저 에이전트들은 또한 section 요소(element)들에 탐색하기 위한 메서드들을 제공할 수 있습니다.

다음 예제에서, 우리는 두 개의 짧은 섹션들을 포함하는 사과에 대한 아티클(큰 웹 페이지의 부분)을 볼 수 있습니다.

section은 콘텐츠의 간단한 설명을 제공하는 aria-label 속성(attribute)을 가집니다. 보조 기술은 사용자들에게 힌트로서 aria-label 값과 마찬가지로 region 역할(role)을 전달할 수 있습니다.

<article>
  <header>
    <h2>Apples</h2>
    <p>Tasty, delicious fruit!</p>
  </header>
  <p>The apple is the pomaceous fruit of the apple tree.</p>
  <section aria-label="Red apples.">
    <h3>Red Delicious</h3>
    <p>These bright red apples are the most common found in many
    supermarkets.</p>
  </section>
  <section aria-label="Green apples.">
    <h3>Granny Smith</h3>
    <p>These juicy, green apples make a great filling for
    apple pies.</p>
  </section>
</article>
여기 하나는 졸업하는 사람들의 목록이고, 다른 하나는 식의 설명인, 두 개의 섹션들을 가진 졸업식 프로그램이 있습니다. (이 예제에서 마크업은 대부분의 요소(element) 간 여백을 최소화하는데 종종 사용되는 흔하지 않은 스타일을 특징으로 합니다.)
<!DOCTYPE Html>
<html
  ><head
    ><title
      >Graduation Ceremony Summer 2022</title
    ></head
  ><body
    ><h1
      >Graduation</h1
    ><section
      ><h2
        >Ceremony</h2
      ><p
        >Opening Procession</p
      ><p
        >Speech by Validactorian</p
      ><p
        >Speech by Class President</p
      ><p
        >Presentation of Diplomas</p
      ><p
        >Closing Speech by Headmaster</p
    ></section
    ><section
      ><h2
        >Graduates</h2
      ><ul
        ><li
          >Molly Carpenter</li
        ><li
          >Anastasia Luccio</li
        ><li
          >Ebenezar McCoy</li
        ><li
          >Karrin Murphy</li
        ><li
          >Thomas Raith</li
        ><li
          >Susan Rodriguez</li
      ></ul
    ></section
  ></body
></html>
이 예에서, 책 저자는 챕터와 일부 부록으로 몇 개의 섹션들을 마크업했고, 이 두 종류의 섹션에 제목들을 다르게 하기 위해 CSS를 사용합니다. 책 전체는 아른 책들을 포함하는 큰 문서의 일부로서 article 요소(element)로 감싸집니다.
<style>
  section { border: double medium; margin: 2em; }
  section.chapter h3 { font: 2em Roboto, Helvetica Neue, sans-serif; }
  section.appendix h3 { font: small-caps 2em Roboto, Helvetica Neue, sans-serif; }
</style>
...
<article class="book">
  <header>
    <h2>My Book</h2>
    <p>A sample with not much content</p>
    <p><small>Published by Dummy Publicorp Ltd.</small></p>
  </header>

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

4.3.4. nav 요소(element)

카테고리:
흐름(flow) 콘텐트.
섹션화(sectioning) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
흐름(flow) 콘텐트가 기대되는 곳.
콘텐트 모델:
후손 main 요소(element)가 없는 흐름(flow) 콘텐트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
navigation 역할(role) (기본 값 - 설정하지 마세요) 혹은 presentation.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLElement를 사용합니다.

nav 요소(element)는 다른 페이지들이나 페이지 내의 부분으로 연결하는 페이지의 섹션을 나타냅니다: 탐색 링크들을 가진 섹션.

보조 기술은 사용자에게 nav의 의미(semantic)를 전달 할 수 있습니다. 이 정보는 사용자에게 콘텐트의 유형에 관하여 힌트를 제공할 수 있습니다. 예를 들어 이 경우에 "navigation"인, 요소(element)의 role은 사용자가 nav 요소(element)로 탐색할 때 스크린리더 소프트웨어에 의해 알려질 수 있습니다. 유저 에이전트들은 또한 nav 요소(element)들로 탐색하기 위한 메서드들을 제공할 수 있습니다.

nav 요소(element)의 콘텐트가 항목들의 목록을 나타내는 경우, 이해와 탐색을 돕기 위해 목록 마크업을 사용하세요.

페이지의 모든 링크 그룹들이 nav 요소(element)에 요구되지 않습니다 — 요소(element)는 주로 주요한 탐색 블럭으로 구성되는 섹션들을 위해 의도된 것입니다. 특히, 서비스 약관, 홈페이지, 저작권 페이지과 같은 사이트의 다양한 페이지로의 링크들의 짧은 목록을 가지는 푸터가 일반적입니다. footer 요소(element)만으로도 그러한 경우에 충분합니다; 그러한 경우에 nav 요소(element)가 사용될 수 있지만, 일반적으로는 불필요합니다.

최초 렌더링에서 생략되는 탐색 정보로부터 혜택을 받을 수 있는 사용자 혹은 즉시 사용 가능한 탐색 정보로부터 혜택을 받을 수 있는 사용자를 대상으로 하는, 유저 에이전트들은 (스크린 리더들 같은) 페이지의 콘텐트가 초기에 건너 뛸지 혹은 요청 할 때 제공할지 (혹은 둘 다일지)를 결정하기 위한 방법으로 이 요소(element)를 사용할 수 있습니다.

다음 예제에서 기본적으로 사이트 주변 탐색과, 부차적으로 페이지 자체 주변 탐색, 두 개의 nav 요소(element)들이 있습니다.
<body>
  <h1>The Wiki Center Of Exampland</h1>
  <nav>
    <ul>
      <li><a href="/">Home</a></li>
      <li><a href="/events">Current Events</a></li>
      ...more...
    </ul>
  </nav>
  <article>
    <header>
      <h2>Demos in Exampland</h2>
      <p>Written by A. N. Other.</p>
    </header>
    <nav>
      <ul>
        <li><a href="#public">Public demonstrations</a></li>
        <li><a href="#destroy">Demolitions</a></li>
        ...more...
      </ul>
    </nav>
    <div>
      <section id="public">
        <h2>Public demonstrations</h2>
        <p>...more...</p>
      </section>
      <section id="destroy">
        <h2>Demolitions</h2>
        <p>...more...</p>
      </section>
      ...more...
    </div>
    <footer>
      <p><a href="?edit">Edit</a> | <a href="?delete">Delete</a> | <a href="?Rename">Rename</a></p>
    </footer>
  </article>
  <footer>
    <p><small>© copyright 1998 Exampland Emperor</small></p>
  </footer>
</body>
다음 예제에서, 페이지는 링크가 존재하는 여러 위치를 가지지만, 그 위치 중 하나만 탐색 섹션으로 간주됩니다.
<body typeof="schema:Blog">
  <header>
    <h1>Wake up sheeple!</h1>
    <p><a href="news.html">News</a> -
    <a href="blog.html">Blog</a> -
    <a href="forums.html">Forums</a></p>
    <p>Last Modified: <span property="schema:dateModified">2009-04-01</span></p>
    <nav>
      <h2>Navigation</h2>
      <ul>
        <li><a href="articles.html">Index of all articles</a></li>
        <li><a href="today.html">Things sheeple need to wake up for today</a></li>
        <li><a href="successes.html">Sheeple we have managed to wake</a></li>
      </ul>
    </nav>
  </header>
  <main>
    <article property="schema:blogPosts" typeof="schema:BlogPosting">
      <header>
        <h2 property="schema:headline">My Day at the Beach</h2>
      </header>
      <main property="schema:articleBody">
        <p>Today I went to the beach and had a lot of fun.</p>
        ...more content...
      </main>
      <footer>
        <p>Posted <time property="schema:datePublished" datetime="2009-10-10">Thursday</time>.</p>
      </footer>
    </article>
    ...more blog posts...
  </main>
  <footer>
    <p>Copyright ©
      <span property="schema:copyrightYear">2010</span>
      <span property="schema:copyrightHolder">The Example Company</span>
    </p>
    <p><a href="about.html">About</a> -
      <a href="policy.html">Privacy Policy</a> -
      <a href="contact.html">Contact Us</a></p>
  </footer>
</body>

main 요소(element)가 페이지의 주요 콘텐트를 감싸기 위해 사용되는 것에 주목하세요. 이 경우, 페이지 헤더와 푸터와 다른 모든 콘텐트입니다.

블로그 게시물에 대한 발행 날짜와 다른 메타데이터를 제공하기 위해 schema.org 표현 형식을 사용하는 위 예제의 마이크로데이터 주석을 볼 수 있습니다.

nav 요소(element)는 목록을 포함할 필요가 없고, 그것은 다른 종류의 콘텐트도 포함할 수 없습니다. 이 탐색 블럭에서, 링크들은 본문에 제공됩니다:
<nav>
  <h2>Navigation</h2>
  <p>You are on my home page. To the north lies <a href="/blog">my
  blog</a>, from whence the sounds of battle can be heard. To the east
  you can see a large mountain, upon which many <a
  href="/school">school papers</a> are littered. Far up thus mountain
  you can spy a little figure who appears to be me, desperately
  scribbling a <a href="/school/thesis">thesis</a>.</p>
  <p>To the west are several exits. One fun-looking exit is labeled <a
  href="https://games.example.com/">"games"</a>. Another more
  boring-looking exit is labeled <a
  href="https://isp.example.net/">ISP™</a>.</p>
  <p>To the south lies a dark and dank <a href="/about">contacts
  page</a>. Cobwebs cover its disused entrance, and at one point you
  see a rat run quickly out of the page.</p>
</nav>
이 예제에서, nav는 사용자가 폴더를 전환하도록, 이메일 어플리케이션에서 사용됩니다:
<p><input type=button value="Compose" onclick="compose()"></p>
<nav>
  <h2>Folders</h2>
  <ul>
    <li> <a href="/inbox" onclick="return openFolder(this.href)">Inbox</a> <span class=count></span>
    <li> <a href="/sent" onclick="return openFolder(this.href)">Sent</a>
    <li> <a href="/drafts" onclick="return openFolder(this.href)">Drafts</a>
    <li> <a href="/trash" onclick="return openFolder(this.href)">Trash</a>
    <li> <a href="/customers" onclick="return openFolder(this.href)">Customers</a>
  </ul>
</nav>

4.3.5. aside 요소(element)

카테고리:
흐름(flow) 콘텐트.
섹션화(sectioning) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
흐름(flow) 콘텐트가 기대되는 곳.
콘텐트 모델:
후손 main 요소(element)가 없는 흐름(flow) 콘텐트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
complementary 역할(role) (기본 값 - 설정하지 마세요), note, search, presentation.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLElement를 사용합니다.

aside 요소(element)는 부모 위치의 섹션화(sectioning) 콘텐트의 콘텐트에 별로 관계 없이 관련되고, 그 콘텐트와 별개로 간주 될 수 있는 콘텐트로 구성되는 페이지의 섹션을 나타냅니다. 그 섹션들은 종종 인쇄된 표기법에서 사이드바(sidebar)들로 표현됩니다.

요소(element)는 발췌한 인용구나 사이드바 같은 인쇄 효과, 광고, nav 요소(element)들의 그룹, 가장 가까운 조상 섹션화(sectioning) 콘텐트의 주요 콘텐트에서 독립된 것으로 간주되는 다른 콘텐트로 사용될 수 있습니다.

보조 기술은 사용자에게 aside의 의미(semantic)를 전달 할 수 있습니다. 이 정보는 콘텐트의 유형에 관하여 사용자에게 힌트를 전달 할 수 있습니다. 예를 들어 이 경우에 "complementary"인 요소(element)의 role은 사용자가 aside 요소(element)로 탐색할 때 스크린리더 소프트웨어에 의해 알려질 수 있습니다. 유저 에이전트들은 또한 aside 요소(element)들로 탐색하기 위한 메서드들을 제공할 수 있습니다.

단순히 삽입구에 aside 요소(element)를 사용하는 것은, 그것이 문서의 주요 흐름의 부분이기 때문에 적절하지 않습니다.

다음 예제는 유럽에서 훨씬 더 긴 뉴스 기사에서 스위스의 배경 자료를 마크업하는데 aside가 사용되는 방법을 보여줍니다.
<aside>
  <h2>Switzerland</h2>
  <p>Switzerland, a land-locked country in the middle of geographic
  Europe, has not joined the geopolitical European Union, though it is
  a signatory to a number of European treaties.</p>
</aside>
다음 예제는 긴 기사에 인용구를 마크업하기 위해 aside가 어떻게 사용되는지를 보여줍니다.
...

<p>He later joined a large company, continuing on the same work.
<q>I love my job. People ask me what I do for fun when I’m not at
work. But I’m paid to do my hobby, so I never know what to
answer. Some people wonder what they would do if they didn’t have to
work... but I know what I would do, because I was unemployed for a
year, and I filled that time doing exactly what I do now.</q></p>

<aside>
  <q> People ask me what I do for fun when I’m not at work. But I’m
  paid to do my hobby, so I never know what to answer. </q>
</aside>

<p>Of course his work — or should that be hobby? —      isn’t his only passion. He also enjoys other pleasures.</p>

...
다음 발췌는 aside가 블로그의 블로그롤(blogroll)들과 기타 부수 콘텐트에 어떻게 사용되는지를 보여줍니다:
<body>
  <header>
    <h1>My wonderful blog</h1>
    <p>My tagline</p>
  </header>
  <aside>
    <!-- this aside contains two sections that are tangentially related
    to the page, namely, links to other blogs, and links to blog posts
    from this blog -->
    <nav>
      <h2>My blogroll</h2>
      <ul>
        <li><a href="https://blog.example.com/">Example Blog</a>
      </ul>
    </nav>
    <nav>
      <h2>Archives</h2>
      <ol reversed>
        <li><a href="/last-post">My last post</a>
        <li><a href="/first-post">My first post</a>
      </ol>
    </nav>
  </aside>
  <aside>
    <!-- this aside is tangentially related to the page also, it
    contains twitter messages from the blog author -->
    <h2>Twitter Feed</h2>
    <blockquote cite="https://twitter.example.net/t31351234">
      I’m on vacation, writing my blog.
    </blockquote>
    <blockquote cite="https://twitter.example.net/t31219752">
      I’m going to go on vacation soon.
    </blockquote>
  </aside>
  <article>
    <!-- this is a blog post -->
    <h2>My last post</h2>
    <p>This is my last post.</p>
    <footer>
      <p><a href="/last-post" rel=bookmark>Permalink</a>
    </footer>
  </article>
  <article>
    <!-- this is also a blog post -->
    <h2>My first post</h2>
    <p>This is my first post.</p>
    <aside>
      <!-- this aside is about the blog post, since it’s inside the
      <article> element; it would be wrong, for instance, to put the
        blogroll here, since the blogroll isn’t really related to this post
        specifically, only to the page as a whole -->
        <h1>Posting</h1>
        <p>While I’m thinking about it, I wanted to say something about
        posting. Posting is fun!</p>
    </aside>
    <footer>
      <p><a href="/first-post" rel=bookmark>Permalink</a>
    </footer>
  </article>
  <footer>
    <nav>
      <a href="/archives">Archives</a><a href="/about">About me</a><a href="/copyright">Copyright</a>
    </nav>
  </footer>
</body>

4.3.6. h1, h2, h3, h4, h5, h6 요소(element)들

카테고리:
흐름(flow) 콘텐트.
제목(heading) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
흐름(flow) 콘텐트가 기대되는 곳.
콘텐트 모델:
어구(phrasing) 콘텐트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
heading 역할(role) (기본 값 - 설정하지 마세요), tab 또는 presentation.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들..
DOM 인터페이스:
interface HTMLHeadingElement : HTMLElement {};

이 요소(element)들은 그들의 섹션들의 제목(heading)들을 나타냅니다.

이 요소(element)들은 그들의 이름에 숫자로 주어진 등급을 가집니다. h1 요소(element)는 가장 상위 등급을 가지고, h6 요소(element)는 가장 낮은 등급을 가지며, 동일한 이름을 가진 두 요소(element)들은 동일한 등급을 가집니다.

문서 개요(outline)을 생성하기 위해 제목(heading) 요소(element)들의 등급을 사용하세요.

다음 코드는 제목(heading)들의 6개 수준들을 가진 문서 개요(outline)을 마크업하는 방법을 보여줍니다.
<body>
<h1>top level heading</h1>
 <section><h2>2nd level heading</h2>
  <section><h3>3nd level heading</h3>
   <section><h4>4th level heading</h4>
    <section><h5>5th level heading</h5>
     <section><h6>6th level heading</h6>
     </section>
    </section>
 </section>
</section>
</section>
</body>

문서 개요(outline)은 section 요소(element)가 사용되지 않았다면 동일할 것입니다.

h2h6 요소(element)들은 새로운 섹션이나 하위 섹션에 대한 제목(heading)으로 의도되지 않은 한, 하위 제목(subheading)들, 부제(subtitle)들, 대체 제목(alternative title)들, 태그 라인들을 마크업하는데 사용되지 않아야(must) 합니다. 대신 명세의 §4.13 Common idioms without dedicated elements 섹션의 마크업 패턴을 사용하세요.

보조 기술은 종종 사용자에게 문서의 구조를 이해하고 그것의 개요(ouline)의 '심적 모델(mental model)'을 구성하기 위해 힌트로서, 제목(heading)의 존재와 수준을 알립니다. 예를 들어, 이 경우에 "heading"이고 제목(heading) 수준 "1"부터 "6"까지인, 요소(element)의 role은 사용자가 h1h6 요소(element)로 탐색할 때 스크린리더 소프트웨어에 의해 알려질 수 있습니다. 유저 에이전트들은 또한 h1h6 요소(element)로 탐색하기 위한 메서드들을 제공할 수 있습니다.

그들의 각 문서 개요(outline)들이 (그들의 제목(heading)과 섹션 구조들) 영향을 미치는 한, 이 두 코드 조각들은 의미적으로 동등합니다:
<body>
  <h1>Let’s call it a draw(ing surface)</h1>
  <h2>Diving in</h2>
  <h2>Simple shapes</h2>
  <h2>Canvas coordinates</h2>
  <h3>Canvas coordinates diagram</h3>
  <h2>Paths</h2>
</body>
<body>
  <h1>Let’s call it a draw(ing surface)</h1>
  <section>
    <h2>Diving in</h2>
  </section>
  <section>
    <h2>Simple shapes</h2>
  </section>
  <section>
    <h2>Canvas coordinates</h2>
    <section>
      <h3>Canvas coordinates diagram</h3>
    </section>
  </section>
  <section>
    <h2>Paths</h2>
  </section>
</body>

작성자들은 그것의 간결성을 위해 전자의 스타일이나, 혹은 많은 편집에도 불구하고 그것의 편의를 위해 후자의 스타일을 선호할 수 있습니다; 무엇이 가장 좋으냐는 순수하게 선호되는 작성자 스타일의 문제입니다.

레거시 도구와의 호환성을 위해 두 스타일들은 결합될 수 있는 동시에 그 호환성이 더 이상 요구되지 않는 경우를 위해 여전히 미래를 보장할 수 있습니다.

h1h6 요소(element)들의 의미론과 의미는 §4.3.10 제목(heading)들과 섹션들의 섹션에서 더 자세히 설명됩니다.

4.3.7. header 요소(element)

카테고리:
흐름(flow) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
흐름(flow) 콘텐트가 기대되는 곳.
콘텐트 모델:
후손 main 요소(element) 혹은 header의 후손인 섹션화(sectioning) 콘텐트의 후손들이 아닌 header, footer 요소(element)들이 없는 흐름(flow) 콘텐트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
banner 역할(role) (기본 값 - 설정하지 마세요) 혹은 presentation.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLElement를 사용합니다.

header 요소(element)는 그것의 가장 가까운 조상 섹션화(sectioning) 콘텐트섹션화(sectioning) 루트 요소(element)에 대한 서두의 콘텐트를 나타냅니다. header는 일반적으로 서두 혹은 탐색 도구의 그룹을 포함합니다.

가장 가까운 조상 섹션화(sectioning) 콘텐트섹션화(sectioning) 루트 요소(element)가 body 요소(element)인 경우, 그것은 전체 페이지에 적용됩니다.

header 요소(element)는 보통 섹션의 제목(heading)을 (h1h6 요소(element)) 포함하도록 의도되지만, 이것은 필수는 아닙니다. header 요소(element)는 또한 섹션의 콘텐츠 목차, 검색 양식, 관련 로고들을 감싸는데 사용될 수 있습니다.

가장 가까운 조상 섹션화(sectioning) 콘텐트섹션화(sectioning) 루트 요소(element)가 body 요소(element)인 경우 보조 기술은 사용자들에게 header의 의미(semantic)를 전달할 수 있습니다. 이 정보는 콘텐트의 유형에 관하여 사용자에게 힌트를 제공할 수 있습니다. 예를 들어 이 경우에 "banner"인, 요소(element)의 role은 사용자가 범위를 body 요소(element)로 하는 header 요소(element)들로 탐색할 때 스크린리더 소프트웨어에 의해 알려질 수 있습니다. 유저 에이전트들은 또한 범위를 body 요소(element)로 하는 header 요소(element)들로 탐색 하기 위한 메서드들을 제공할 수 있습니다.

여기 일부 샘플 헤더들이 있습니다. 이 첫 번째 것은 게임에 대한 것입니다:
<header>
  <p>Welcome to...</p>
  <h1>Voidwars!</h1>
</header>

다음 코드 조각은 요소(element)가 명세의 헤더를 마크업하는데 사용될 수 있는 방법을 보여줍니다:

<header>
  <h1>Scalable Vector Graphics (SVG) 1.2</h1>
  <p>W3C Working Draft 27 October 2004</p>
  <dl>
    <dt>This version:</dt>
    <dd><a href="https://www.w3.org/TR/2004/WD-SVG12-20041027/">https://www.w3.org/TR/2004/WD-SVG12-20041027/</a></dd>
    <dt>Previous version:</dt>
    <dd><a href="https://www.w3.org/TR/2004/WD-SVG12-20040510/">https://www.w3.org/TR/2004/WD-SVG12-20040510/</a></dd>
    <dt>Latest version of SVG 1.2:</dt>
    <dd><a href="https://www.w3.org/TR/SVG12/">https://www.w3.org/TR/SVG12/</a></dd>
    <dt>Latest SVG Recommendation:</dt>
    <dd><a href="https://www.w3.org/TR/SVG/">https://www.w3.org/TR/SVG/</a></dd>
    <dt>Editor:</dt>
    <dd>Dean Jackson, W3C, <a href="mailto:dean@w3.org">dean@w3.org</a></dd>
    <dt>Authors:</dt>
    <dd>See <a href="#authors">Author List</a></dd>
  </dl>
  <p class="copyright"><a href="https://www.w3.org/Consortium/Legal/ipr-notic ...
</header>

header 요소(element)는 섹션화(sectioning) 콘텐트가 아닙니다; 이것은 새로운 섹션을 도입시키지 않습니다.

이 예제에서, 페이지는 h1 요소(element)에 의해 주어진 페이지 제목(heading)과, h2 요소(element)들에 의해 주어지는 제목(heading)의 두 하위 섹션들을 가집니다. header 요소(element) 이후의 콘텐트는 header 요소(element)가 개요(outline) 알고리즘에 참여하지 않기 때문에, 여전히 header 요소(element) 내에서 시작된 마지막 하위 섹션의 일부입니다.
<body>
  <header>
    <h1>Little Green Guys With Guns</h1>
    <nav>
      <ul>
      <li><a href="/games">Games</a>
      <li><a href="/forum">Forum</a>
      <li><a href="/download">Download</a>
      </ul>
    </nav>
    <h2>Important News</h2> <!-- this starts a second subsection -->
    <!-- this is part of the subsection entitled "Important News" -->
    <p>To play today’s games you will need to update your client.</p>
    <h2>Games</h2> <!-- this starts a third subsection -->
    </header>
    <p>You have three active games:</p>
    <!-- this is still part of the subsection entitled "Games" -->
    ...

개발자가 다른 header 안에 headerfooter를 중첩시키기 원하는 경우들에 대해: header 요소(element)는 headerfooter섹션화(sectioning) 콘텐트 내에 포함된 것들인 경우에만 headerfooter를 포함할 수 있습니다.

이 예제에서, articleheader를 포함하는 aside를 포함한 header를 가집니다. 후손 headeraside 요소(element) 내에 포함되기 때문에 이것은 적합합니다.

<article>
  <header>
    <h1>Flexbox: The definitive guide</h1>
    <aside>
      <header>
        <h2>About the author: Wes McSilly</h2>
        <p><a href="./wes-mcsilly/">Contact him! (Why would you?)</a></p>
      </header>
      <p>Expert in nothing but Flexbox. Talented circus sideshow.</p>
    </aside>
  </header>
  <p><ins>The guide about Flexbox was supposed to be here, but it
    turned out Wes wasn’t a Flexbox expert either.</ins></p>
</article>
카테고리:
흐름(flow) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
흐름(flow) 콘텐트가 기대되는 곳.
콘텐트 모델:
후손 main 요소(element) 혹은 footer의 후손인 섹션화(sectioning) 콘텐트의 후손들이 아닌 header, footer 요소(element)들이 없는 흐름(flow) 콘텐트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
contentinfo 역할(role) (기본 값 - 설정하지 마세요) 또는 presentation.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLElement를 사용합니다.

footer 요소(element)는 가장 가까운 조상 섹션화(sectioning) 콘텐트섹션화(sectioning) 루트에 대한 푸터를 나타냅니다. 푸터는 일반적으로 누가 작성하였는지, 관련된 문서로의 링크, 저작권 데이터 등과 같은 그것의 섹션에 대한 정보를 포함합니다.

footer 요소(element)가 전체 섹션들을 포함할 경우, 그것들은 부록, 색인, 긴 출판사 이름들, 장황한 사용권 동의서들, 기타 그러한 콘텐트들을 나타냅니다.

가장 가까운 조상 섹션화(sectioning) 콘텐트섹션화(sectioning) 루트body 요소(element)인 경우 보조 기술은 사용자에게 footer의 의미(semantic)를 전달할 수 있습니다. 이 정보는 콘텐트의 유형에 관하여 사용자에게 힌트로 제공할 수 있습니다. 예를 들어, 이 경우 "콘텐트 정보"인 요소(element)의 role은 사용자가 범위를 body 요소(element)로 하는 footer 요소(element)로 탐색할 때 스크린리더 소프트웨어에 의해 알려질 수 있습니다. 유저 에이전트들은 또한 범위를 body 요소(element)로 하는 footer 요소(element)들로 탐색하기 위한 메서드들을 제공할 수 있습니다.

섹션의 작성자나 편집자에 대한 연락 정보는 아마도 footer 내부에 있는, address 요소(element)에 속합니다. headerfooter 모두에 적합할 수 있는 필자의 이름을 적은 행들과 다른 정보는 둘 중 하나에 배치 될 수 (혹은 둘 중 어디에도 배치되지 않을 수) 있습니다. 이 요소(element)들의 주된 목적은 단순히 작성자가 유지보수와 스타일이 쉬운 자명한 마크업을 작성하는 것을 돕는 것입니다; 그것들은 작성자에게 특정한 구조들을 강요하기 위한 것이 아닙니다.

푸터들은 보통 그렇기는 하지만, 섹션의 에 나타날 필요는 없습니다.

가장 가까운 조상 섹션화(sectioning) 콘텐트섹션화(sectioning) 루트 요소(element)가 body 인 경우, 그것은 전체 페이지에 적용됩니다.

footer 요소(element)는 섹션화(sectioning) 콘텐트가 아닙니다; 그것은 새로운 섹션을 도입하지 않습니다.

여기 동일한 컨텐트를 가진 상단과 바닥에 있는 두 개의 푸터들을 가진 페이지가 있습니다:
<body>
  <footer><a href="../">Back to index...</a></footer>
  <div>
    <h1>Lorem ipsum</h1>
    <p>The ipsum of all lorems</p>
  </div>
  <p>A dolor sit amet, consectetur adipisicing elit, sed do eiusmod
  tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
  veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex
  ea commodo consequat. Duis aute irure dolor in reprehenderit in
  voluptate velit esse cillum dolore eu fugiat nulla
  pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
  culpa qui officia deserunt mollit anim id est laborum.</p>
  <footer><a href="../">Back to index...</a></footer>
</body>
여기 사이트 전반 푸터와 섹션 푸터 둘 모두에 사용되는 footer 요소(element)를 보여주는 예가 있습니다.
<!DOCTYPE HTML>
<HTML><HEAD>
<TITLE>The Ramblings of a Scientist</TITLE>
<BODY>
<h1>The Ramblings of a Scientist</h1>
<MAIN>
  <ARTICLE>
  <H2>Episode 15</H2>
  <VIDEO SRC="/fm/015.ogv" CONTROLS PRELOAD>
  <P><A HREF="/fm/015.ogv">Download video</A>.</P>
  </VIDEO>
  <FOOTER> <!-- footer for article -->
  <P>Published <TIME DATETIME="2009-10-21T18:26-07:00">on 2009/10/21 at 6:26pm</TIME></P>
  </FOOTER>
</ARTICLE>
<ARTICLE>
  <H2>My Favorite Trains</H2>
  <P>I love my trains. My favorite train of all time is a Köf.</P>
  <P>It is fun to see them pull some coal cars because they look so
  dwarfed in comparison.</P>
  <FOOTER> <!-- footer for article -->
  <P>Published <TIME DATETIME="2009-09-15T14:54-07:00">on 2009/09/15 at 2:54pm</TIME></P>
  </FOOTER>
  </ARTICLE>
</MAIN>
<FOOTER> <!-- site wide footer -->
  <NAV>
  <P><A HREF="/credits.html">Credits</A><A HREF="/tos.html">Terms of Service</A><A HREF="/index.html">Blog Index</A></P>
  </NAV>
  <P>Copyright © 2009 Gordon Freeman</P>
</FOOTER>
</BODY>
</HTML>
일부 사이트 디자인들은 "넓은 푸터들" — 이미지, 다른 아티클들로의 링크, 피드백을 보내기 위한 페이지로의 링크, 특별한 제안... 어떤 점에서는 푸터 내 전체 "프론트 페이지"를 포함하는 많은 자료들을 포함하는 푸터들 같은 것에 종종 참조되는 것을 가집니다.

이 코드 조각은 "넓은 푸터"를 가진 사이트의 페이지의 바닥을 보여줍니다:

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

4.3.9. address 요소(element)

카테고리:
흐름(flow) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
흐름(flow) 콘텐트가 기대되는 곳.
콘텐트 모델:
후손 제목(heading) 콘텐트들을 가지지 않고, 후손 섹션화(sectioning) 콘텐트들을 가지지 않으며, 후손 header, footer 혹은 address 요소(element)를 가지지 않는 흐름(flow) 콘텐트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
contentinfo 역할(role).
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLElement를 사용합니다.

address 요소(element)는 가장 가까운 조상 article이나 body 요소(element)에 대한 연락 정보를 나타냅니다. 그것이 body 요소(element)라면 연락 정보는 전체 문서에 적용됩니다.

예를 들어, HTML에 관련된 W3C 웹 사이트에 있는 페이지는 다음 연락 정보를 포함할 수 있습니다:
<ADDRESS>
  <A href="../People/Raggett/">Dave Raggett</A>,
  <A href="../People/Arnaud/">Arnaud Le Hors</A>,
  contact persons for the <A href="Activity">W3C HTML Activity</A>
</ADDRESS>

address 요소(element)는 그 주소들이 실제로 관련 연락 정보가 아닌 한, 임의의 주소를 (예를 들어, 우편 주소들) 나타내는데 사용되지 않아야(must) 합니다. (일반적으로 p 요소(element)가 우편 주소들을 마크업하기 위한 적절한 요소(element)입니다.)

address 요소(element)는 연락 정보 외 다른 정보를 포함하야 않아야(must) 합니다.

예를 들어, 다음은 address 요소(element) 사용의 부적합한 사용입니다:
<ADDRESS>Last Modified: 1999/12/24 23:37:50</ADDRESS>

일반적으로, address 요소(element)는 footer 요소(element)에 다른 정보와 함께 포함될 것입니다.

노드 node에 대한 연락 정보는 다음 목록 중 첫 번째 적용가능한 항목에 의해 정의된 address 요소(element)들의 컬렉션입니다:
nodearticle 요소(element)라면
nodebody 요소(element)라면
연락 정보는 조상으로 node를 가지고 node의 후손인 다른 조상 bodyarticle 요소(element)를 가지지 않는 모든 address 요소(element)들로 구성됩니다.
nodearticle 요소(element)인 조상 요소(element)를 가진다면
nodebody 요소(element)인 조상 요소(element)를 가진다면
node의 연락 정보는 가장 가까운 조상 articlebody 요소(element) 중 가장 가까운 것의 연락 정보와 동일합니다.
node노드 문서body 요소(element)를 가진다면
node의 연락 정보는 Documentbody 요소(element)의 연락 정보와 동일합니다.
그렇지 않으면
node에 대한 연락 정보는 없습니다.

유저 에이전트들은 사용자에게 노드의 연락 정보를 노출하거나, 섹션의 연락 정보를 기반으로 섹션들을 색인하는 것 같은 다른 목적으로 사용할 수 있습니다.

이 예제에서 푸터는 연락 정보와 저작권 공고를 포함합니다.
<footer>
  <address>
  For more details, contact
  <a href="mailto:js@example.com">John Smith</a>.
  </address>
  <p><small>© copyright 2038 Example Corp.</small></p>
</footer>

4.3.10. 제목(heading)들과 섹션들

h1h6 요소(element)들은 제목(heading)들입니다.

섹션화(sectioning) 콘텐트의 요소(element) 내 제목(heading) 콘텐트의 첫 번째 요소(element)는 그 섹션에 대한 제목(heading)을 나타냅니다. 동일한 혹은 상위 등급의 다음 제목(heading)들은 새로운 (암묵적인) 섹션들을 시작하고, 하위 등급의 제목(heading)들은 이전 것의 일부인 암묵적인 하위 섹션들을 시작합니다. 두 경우에, 요소(element)는 암묵적인 섹션의 제목(heading)을 나타냅니다.

h1h6 요소(element)들은 새로운 섹션이나 하위 섹션에 대한 제목(heading)으로 의도되지 않은 한, 하위 제목(subheading)들, 부제(subtitle)들, 대체 제목(alternative title)들, 태그 라인들을 마크업하는데 사용되지 않아야(must) 합니다. 대신 명세의 §4.13 Common idioms without dedicated elements 섹션의 마크업 패턴을 사용하세요.

특정 요소(element)들은 blockquotetd 요소(element)들을 포함하여, 섹션화(sectioning) 루트들로 불립니다. 이 요소(element)들은 그들 자신의 개요(outline)들을 가질 수 있지만, 이 요소(element)들 안의 섹션들과 제목(heading)들은 그들 조상들의 개요(outline)들에 영향을 주지 않습니다.

섹션화(sectioning) 콘텐트는, 다른 제목(heading)들이 생성할 수 있는 암묵적 섹션에 상관없이, 항상 그들의 가장 가까운 조상 섹션화(sectioning) 루트나 그들의 가장 가까운 섹션화(sectioning) 콘텐트의 중 가장 가까운 것의 하위 섹션들로 간주됩니다.

다음 코드 조각에 대한:
<body>
  <h1>Foo</h1>
  <h2>Bar</h2>
  <blockquote>
    <h3>Bla</h3>
  </blockquote>
  <p>Baz</p>
  <h2>Quux</h2>
  <section>
    <h3>Thud</h3>
  </section>
  <p>Grunt</p>
</body>

...구조는 이러할 것입니다:

  1. Foo ("Grunt" 문단을 포함하는, 명시적인 body 섹션의 제목(heading))

    1. Bar (인용구와 "Baz" 문단을 포함하는, 암묵적 섹션을 시작하는 제목(heading))

    2. Quux (제목(heading) 자체 외 다른 콘텐트가 없는 암묵적 세션을 시작하는 제목(heading))

    3. Thud (명시적인 section 섹션의 제목(heading))

section이 이전의 암묵적 섹션을 종료하기 때문에 마지막 문단("Grunt")이 최 상위 수준으로 돌아가는 방식에 주목하세요.

섹션들은 그들의 섹션 중첩 수준과 동일한 등급의 제목(heading)들을 포함할 수 있습니다. 작성자들은 섹션의 중첩 수준에 대한 적절한 등급의 제목(heading)들을 사용해야(should) 합니다.

작성자들은 또한 하나의 섹션화(sectioning) 콘텐트의 요소(element)에 여러 제목(heading)들을 가지는 것에 의해 생성되는 암묵적 섹션들에 의존하는 대신, 섹션화(sectioning) 콘텐트의 요소(element)들 안의 섹션들을 명시적으로 감싸도록 권장됩니다.

예를 들어, 다음은 정확합니다:
<body>
  <h1>Apples</h1>
  <p>Apples are fruit.</p>
  <section>
    <h2>Taste</h2>
    <p>They taste lovely.</p>
    <h3>Sweet</h3>
    <p>Red apples are sweeter than green ones.</p>
    <h3>Color</h3>
    <p>Apples come in various colors.</p>
  </section>
</body>

하지만, 동일한 문서가 다음과 같이 좀 더 명확하게 표현될 수 있습니다:

<body>
  <h1>Apples</h1>
  <p>Apples are fruit.</p>
  <section>
    <h2>Taste</h2>
    <p>They taste lovely.</p>
    <section>
      <h3>Sweet</h3>
      <p>Red apples are sweeter than green ones.</p>
    </section>
  </section>
  <section>
    <h3>Color</h3>
    <p>Apples come in various colors.</p>
  </section>
</body>

위 문서들 모두 의미론적으로 동일하고 규칙을 준수하는 유저 에이전트들에서 동일한 개요(outline)를 생성할 것입니다.

위 예제는 잘못 되었습니다. 실제로 두 코드는 서로 다른 개요(outline)을 생성합니다.
이 내용은 W3C HTML Github Issue를 통해 확인 되었고, 수정된 내용이 HTML 5.2에 반영됩니다.
전자의 코드와 동일한 개요(outline)을 가지는 것은 다음 코드가 됩니다.
<body>
  <h1>Apples</h1>
  <p>Apples are fruit.</p>
  <section>
  <h2>Taste</h2>
  <p>They taste lovely.</p>
  <section>
    <h3>Sweet</h3>
    <p>Red apples are sweeter than green ones.</p>
  </section>
  <section>
    <h3>Color</h3>
    <p>Apples come in various colors.</p>
  </section>
  </section>
</body>
4.3.10.1. 개요(outline) 생성

개요(outline) 알고리즘이 적합성 검사기들과 브라우저 확장들 같은 다른 소프트웨어에 구현되기는 하지만, 그래픽 브라우저들이나 보조 도구 유저 에이전트들에 현재 알려진 개요(outline) 알고리즘의 네이티브 구현은 없습니다. 따라서 개요 알고리즘은 사용자들에게 문서 구조를 전달하는데 신뢰될 수 없습니다. 작성자들은 문서 구조를 전달하기 위해 제목(heading) 등급을 (h1-h6) 사용해야(should) 합니다.

이 섹션은 비 규범적입니다.

이 섹션은 섹션화(sectioning) 콘텐트 요소(element)나 섹션화(sectioning) 루트에 대한 개요(outline) 생성을 위한 알고리즘을 정의합니다. 이것은 순회 하는 동안 입장할 때와 퇴장할 때 방문되는 각 노드들을 가지고, 트리 순서에 따라 DOM 트리의 노드들을 순회하는 측면에서 정의됩니다.

섹션화(sectioning) 콘텐트 요소(element)나 섹션화(sectioning) 루트 요소(element)에 대한 개요(outline)는 하나 이상의 잠재적으로 중첩되는 섹션들의 목록으로 구성됩니다. 개요(outline)이 생성되는 요소(element)는 개요(outline)의 소유자라고 합니다.

섹션은 원래 DOM 트리의 일부 노드에 해당하는 컨테이너 입니다. 각 섹션은 그것에 연관된 제목(heading)을 가질 수 있고, 추가적인 중첩된 섹션들을 얼마든지 포함할 수 있습니다. 개요(outline)에 대한 알고리즘은 또한 특정 섹션과 잠재적으로 제목(heading)을 가진 DOM 트리의 각 노드를 연관시킵니다. (개요(outline)의 섹션들은 섹션 요소(element)들에 해당 할 수 있기는 하지만 섹션 요소(element)들은 아닙니다 — 그것들은 단지 개념적인 섹션들입니다.)

다음 마크업 조각은:
<body>
  <h1>A</h1>
  <p>B</p>
  <h2>C</h2>
  <p>D</p>
  <h2>E</h2>
  <p>F</p>
</body>

...body 노드에 대해 (그리고 따라서 전체 문서에 대해) 생성되는 다음 개요(outline)를 낳습니다:

  1. body 노드에 대해 생성된 섹션. 제목(heading) "A"와 연관됨. 또한 문단 "B"와 연관됨. 중첩된 섹션들:

    1. 첫 번째 h2 요소(element)에 대한 암묵적 섹션. 제목(heading) "C"와 연관됨. 또한 문단 "D"와 연관됨. 중첩된 섹션들 없음.

    2. 두 번째 h2 요소(element)에 대한 암묵적 섹션. 제목(heading) "E"와 연관됨. 또한 문단 "F"와 연관됨. 중첩된 섹션들 없음.

요소(element)의 개요(outline)를 결정하기 위해 섹션화(sectioning) 콘텐트 요소(element)나 섹션화(sectioning) 루트에 뿌리를 둔 DOM 하위트리의 순회 동안 따라야(must)하는 알고리즘은 다음과 같습니다:
  1. current outline target를 null로 둡니다. (이것은 생성 되는 중인 개요(outline)의 요소(element)를 보유합니다.)

  2. current section를 null로 둡니다. (이것은 섹션에 대한 포인터를 보유하고, 따라서 DOM의 요소(element)들은 모두 섹션에 연관될 수 있습니다.)

  3. 중첩을 처리하는데 사용되는 요소(element)들을 보유하기 위한 스택을 생성합니다. 이 스택을 빈 것으로 초기화 합니다.

  4. 개요(outline)가 생성되는 하위 트리의 루트에 있는 섹션화(sectioning) 콘텐트 요소(element)나 섹션화(sectioning) 루트를 가지고 시작하여 트리 순서에 따라 DOM을 순회하고, 입장하고 퇴장할 때 각 요소(element)에 대해 아래 첫 번째 관련 단계를 작동시킵니다.

    요소를 퇴장 중일때, 그 요소(element)가 스택의 최 상단에 있는 요소(element)라면

    퇴장 되는 중인 요소(element)는 제목(heading) 콘텐트 요소(element)나 hidden 속성(attribute)을 가진 요소(element)입니다.

    스택으로부터 그 요소(element)를 꺼냅니다.

    스택의 최 상단이 제목(heading) 콘텐트 요소나 hidden 속성(attribute)을 가진 요소(element)입니다.
    아무 것도 하지 않습니다.
    hidden 속성(attribute)를 가진 요소(element)를 입장 중일 때
    스택에 입장 되는 중인 요소(element)를 넣습니다. (이것은 그 요소(element)와 요소(element)의 모든 후손들을 건너 뛰기 위한 알고리즘을 발생시킵니다.)
    섹션화(sectioning) 콘텐트 요소(element)에 입장 중일 때
    이 단계들을 수행합니다:
    1. current outline target가 null이 아니라면, 이 단계들을 수행합니다:

      1. current section가 제목(heading)을 가지지 않는다면, 암묵적 제목(heading)을 생성하고 그것을 current section에 대한 제목(heading)으로 둡니다.

      2. 스택에 current outline target를 넣습니다.

    2. current outline target를 입장 되는 중인 요소(element)로 둡니다.

    3. current sectioncurrent outline target 요소(element)에 대해 새롭게 생성된 섹션으로 둡니다.

    4. current outline targetcurrent section과 연관시킵니다.

    5. 개요(outline)의 유일한 섹션으로서 새로운 current section으로 초기화 된, 새로운 current outline target에 대한 새로운 개요(outline)이 있게 합니다.

    섹션화(sectioning) 콘텐트 요소(element)를 퇴장 중일 때, 스택이 비어있지 않다면
    이 단계들을 수행합니다:
    1. current section가 제목(heading)을 가지지 않는다면, 암묵적 제목(heading)을 생성하고 그것을 current section에 대한 제목(heading)으로 둡니다.

    2. 스택으로부터 최 상단 요소(element)를 꺼내고, current outline target를 그 요소(element)로 둡니다.

    3. current sectioncurrent outline target 요소(element)의 개요(outline) 내의 마지막 섹션으로 둡니다.

    4. 퇴장하는 섹션화(sectioning) 콘텐트 요소(element)의 개요(outline)current section에 추가(append)합니다. (이것은 어떤 섹션이 개요(outline) 내의 마지막 섹션인지를 변경하지 않습니다.)

    섹션화(sectioning) 루트 요소(element)를 입장 중일 때
    이 단계들을 수행합니다:
    1. current outline target가 null이 아니라면, 스택에 current outline target를 넣습니다.

    2. current outline target를 입장하는 요소(element)로 둡니다.

    3. current outline target부모 섹션current section로 둡니다.

    4. current sectioncurrent outline target 요소(element)에 대해 새롭게 생성된 섹션으로 둡니다.

    5. 개요(outline)의 유일한 섹션으로서 새로운 current section으로 초기화 된, 새로운 current outline target에 대한 새로운 개요(outline)를 있게 합니다.

    섹션화(sectioning) 루트 요소(element)를 퇴장 중일 때, 스택이 비어있지 않다면
    이 단계들을 수행합니다:
    1. current section가 제목(heading)을 가지지 않는다면, 암묵적 제목(heading)을 생성하고 그것을 current section에 대한 제목(heading)으로 둡니다.

    2. current sectioncurrent outline target부모 섹션으로 둡니다.

    3. 스택에서 최 상단 요소(element)를 꺼내고, current outline target를 그 요소(element)로 둡니다.

    섹션화(sectioning) 콘텐트섹션화(sectioning) 루트 요소(element)를 퇴장 중일 때 (스택이 비어있는 경우)

    current outline target는 퇴장되는 중인 요소(element)이고, 그것은 개요(outline)가 생성되는 하위 트리의 루트에 있는 섹션화(sectioning) 콘텐트섹션화(sectioning) 루트 요소(element)입니다.

    current section가 제목(heading)을 가지지 않는다면, 암묵적 제목(heading)을 생성하고 그것을 current section에 대한 제목(heading)으로 둡니다.

    전체 단계들의 세트의 다음 단계들로 건너뜁니다. (순회가 끝납니다.)

    제목(heading) 콘텐트 요소(element)로 입장 중일 때
    current section가 제목(heading)을 가지지 않는다면, 입장 되는 중인 요소(element)를 current section에 대한 제목(heading)으로 둡니다.

    그렇지 않고, 입장 되는 중인 요소(element)가 current outline target개요(outline)의 마지막 섹션의 제목(heading)과 동일 또는 상위의 등급을 가지거나, current outline target개요(outline)의 마지막 섹션의 제목(heading)이 암묵적 제목(heading)이라면, 새로운 섹션을 생성하고 current outline target 요소(element)를 추가(append)하며, 따라서 이 새로운 섹션은 그 개요(outline)의 새로운 마지막 섹션입니다. current section를 그 새로운 섹션으로 둡니다. 입장하는 요소(element)를 current section에 대한 새로운 제목(heading)으로 둡니다.

    그렇지 않으면, 이 하위 단계들을 수행합니다:

    1. candidate sectioncurrent section로 둡니다.

    2. Heading loop: 입장 되는 중인 요소(element)가 candidate section의 제목(heading)의 등급보다 낮은 등급을 가진다면, 새로운 섹션을 생성하고, candidate section에 그것을 추가(append) 합니다. (이것은 개요(outline)의 마지막 섹션이 어떤 섹션인지를 변경하지 않습니다.) current section를 이 새로운 섹션으로 둡니다. 입장 되는 중인 요소(element)를 current section에 대한 새로운 제목(heading)으로 둡니다. 이 하위 단계들을 중단합니다.

    3. new candidate sectioncurrent outline target개요(outline) 내의 candidate section를 포함하는 섹션으로 둡니다.

    4. candidate sectionnew candidate section로 둡니다.

    5. heading loop로 라벨링 된 단계로 돌아갑니다.

    입장 되는 중인 요소(element)를 스택에 넣습니다. (이것은 요소(element)의 모든 후손들을 건너 뛰기 위한 알고리즘을 발생시킵니다.)

    h1가장 상위 등급을 가지고, h6가 가장 하위 등급을 가진다는 것을 상기하세요.

    그렇지 않으면
    아무 것도 하지 않습니다.

    덧붙여, 순회를 종료 할 때마다, 위 단계들을 수행 한 뒤, 노드가 아직 섹션과 연관된 것이 아니라면, current section 섹션과 노드를 연관시킵니다.

  5. 개요(outline)가 생성되는 하위 트리에 있는 모든 비 요소(non-element) 노드들은 부모 요소(element)가 연관된 섹션과 연관시킵니다.

  6. 하위 트리의 모든 노드들을 그것들이 연관된 섹션의 제목(heading)이 있다면 그것들과 연관시킵니다.

위 알고리즘에 의해 생성된 섹션들의 트리나 그것의 올바른 하위 세트는 문서 개요(outline)들을 생성할 때, 예를 들어 콘텐츠 목차를 생성할 때, 사용되어야(must) 합니다.

Documentbody 요소(element)에 대해 생성된 개요(outline)은 전체 문서의 개요(outline)입니다.

콘텐츠의 상호 작용 목차를 생성할 경우, 섹션이 원본 문서의 실제 요소(element)에 대해 생성되었다면 항목들은 관련 섹션화(sectioning) 콘텐트로, 또는 트리 내 섹션이 위 프로세스에서 제목(heading)에 대해 생성되었다면 관련 제목(heading) 콘텐트 요소(element)로 사용자를 건너뛰게 해야(should) 합니다.

따라서 문서의 첫 번째 섹션을 선택하는 것은 body 내 첫 번째 제목(heading)이 발견되는 곳에 상관없이, 항상 사용자를 문서의 최 상단으로 데려갑니다.

섹션 section과 연관된 제목(heading) 콘텐트 요소(element)의 개요 깊이(outline depth)section이 그것의 Document의 요소(element)들의 개요(outline)들이 생성될 때 자신을 발견하는 가장 바깥쪽의 개요(outline) 내의 section의 조상들인 섹션들의 수에 1을 더한 것입니다. 섹션과 연관되지 않은 제목(heading) 콘텐트 요소(element)의 개요 깊이(outline depth)는 1입니다.

유저 에이전트는 명시적인 섹션 제목(heading)을 가지지 않는 섹션들에 대한 기본 제목(heading)들을 제공해야(should) 합니다.

다음 코드 조각을 고려해보세요:
<body>
  <nav>
    <p><a href="/">Home</a></p>
  </nav>
  <p>Hello world.</p>
  <aside>
    <p>My cat is cute.</p>
  </aside>
</body>

비록 제목(heading)들을 포함하지 않지만, 이 코드 조각은 세 개의 섹션들을 가집니다: 두 하위 섹션을 (navaside) 가진 문서 (body). 유저 에이전트는 다음과 같이 개요(outline)을 표현할 수 있습니다:

  1. Untitled document

    1. Navigation

    2. Sidebar

이 기본 제목(heading)들은 ("Untitled document", "Navigation", "Sidebar")은 이 명세에 의해 명시되지 않고, 사용자의 언어, 페이지의 언어, 사용자의 환경 설정, 유저 에어전트 구현자의 선호도 등등에 의해 변할 수 있습니다.

다음 자바스크립트 함수는 트리 순회가 구현될 수 있는 방법을 보여줍니다. root 인수는 순회하기 위한 트리의 루트 (섹션화(sectioning) 콘텐트 요소(element)나 섹션화(sectioning) 루트 요소(element)), enterexit 인수들은 입장 되고 퇴장 될 때 노드들을 가지고 호출되는 콜백 함수들 입니다. [ECMA-262]
function (root, enter, exit) {
  var node = root;
  start: while (node) {
    enter(node);
    if (node.firstChild) {
      node = node.firstChild;
      continue start;
    }
    while (node) {
      exit(node);
      if (node == root) {
        node = null;
      } else if (node.nextSibling) {
        node = node.nextSibling;
        continue start;
      } else {
        node = node.parentNode;
      }
    }
  }
}

4.3.11. 사용법 요약

이 섹션은 비 규범적입니다.

요소(element) 용도(purpose)
예시
body
<!DOCTYPE HTML>
<html>
  <head> <title>Steve Hill’s Home Page</title> </head>
  <body> <p>Hard Trance is My Life.</p> </body>
</html>
article
<article>
  <img src="/tumblr_masqy2s5yn1rzfqbpo1_500.jpg" alt="Yellow smiley face with the caption 'masif'">
  <p>My fave Masif tee so far!</p>
  <footer>Posted 2 days ago</footer>
</article>
<article>
  <img src="/tumblr_m9tf6wSr6W1rzfqbpo1_500.jpg" alt="">
  <p>Happy 2nd birthday Masif Saturdays!!!</p>
  <footer>Posted 3 weeks ago</footer>
</article>
section
<h1>Biography</h1>
<section>
  <h1>The facts</h1>
  <p>1500+ shows, 14+ countries</p>
</section>
<section>
  <h1>2010/2011 figures per year</h1>
  <p>100+ shows, 8+ countries</p>
</section>
nav
<nav>
  <ul>
    <li><a href="/">Home</a>
    <li><a href="/biog.html">Bio</a>
    <li><a href="/discog.html">Discog</a>
  </ul>
</nav>
aside
<h1>Music</h1>
<p>As any burner can tell you, the event has a lot of trance.</p>
<aside>You can buy the music we played at our <a href="buy.html">playlist page</a>.</aside>
<p>This year we played a kind of trance that originated in Belgium, Germany, and the Netherlands in the mid 90s.</p>
h1h6 섹션 제목(heading)
<h1>The Guide To Music On The Playa</h1>
<h2>The Main Stage</h2>
<p>If you want to play on a stage, you should bring one.</p>
<h2>Amplified Music</h2>
<p>Amplifiers up to 300W or 90dB are welcome.</p>
header
<article>
  <header>
  <h1>Hard Trance is My Life</h1>
  <p>By DJ Steve Hill and Technikal</p>
  </header>
  <p>The album with the amusing punctuation has red artwork.</p>
</article>
footer
<article>
  <h1>Hard Trance is My Life</h1>
  <p>The album with the amusing punctuation has red artwork.</p>
  <footer>
  <p>Artists: DJ Steve Hill and Technikal</p>
  </footer>
</article>
address
<address>
To book DJ Steve Hill and Technikal, contact our
<a href="mailto:management@example.com">management</a>.
</address>
4.3.11.1. Article or section?

이 섹션은 비 규범적입니다.

section은 다른 무언가의 일부를 구성합니다. article은 그 자체의 것입니다. 하지만 어떤 것이 어떤 것인지 어떻게 알까요? 대부분 실제 대답은 "그것은 작성자 의도에 달려있다"입니다.

예를 들어, "이 과즙이 풍부한 초록 사과는 사과 파이를 꽉 채웁니다."라고 말하는 "Granny Smith" 챕터를 가진 책을 떠올릴 수 있습니다; 그것은 사과들의 다른 종류에 (아마도) 다른 많은 챕터가 있을 것이기 때문에 section이 될 수 있습니다.

반면에, "그래니 스미스. 이 과즙이 풍부한 초록 사과는 사과 파이를 꽉 채웁니다."라고 말하는 트윗이나 텀블러 게시물 혹은 신문 광고를 연상할 수 있습니다; 그것은 그것이 전부였기 때문에 article들 일 것입니다.

아티클의 댓글들은 댓글을 달고 있는 article의 일부가 아니지만 관련된 것이므로 그것들 자신의 중첩 된 article에 포함 될 수 있습니다.

4.4. 섹션화(sectioning) 콘텐트

4.4.1. p 요소(element)

카테고리:
흐름(flow) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
흐름(flow) 콘텐트가 예상 되는 곳.
콘텐트 모델:
어구(phrasing) 콘텐트.
text/html에서 태그 생략:
p 요소(element)가 address, article, aside, blockquote, details, div, dl, fieldset, figcaption, figure, footer, form, h1, h2, h3, h4, h5, h6, header, hr, main, menu, nav, ol, p, pre, section, table, ul 요소(element)가 즉시 뒤따르거나, 부모 요소(element)에 더 이상의 콘텐트가 존재하지 않고 부모 요소(element)가 a, audio, del, ins, map, noscript, video 요소(element)가 아닌 HTML 요소(element)가 아니라면, p 요소(element)의 종료 태그는 생략될 수 있습니다.
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
interface HTMLParagraphElement : HTMLElement {};

p 요소(element)는 문단나타냅니다.

문단들이 보통 빈 줄들을 통해 인접한 블럭들로부터 물리적으로 분리된 텍스트 블럭들에 의해 시각 매체에 표현되는 반면, 스타일 시트나 유저 에이전트는 다른 방법으로, 예를 들어 인라인 단락 기호 (¶)를 사용하여, 문단 구분을 표현하는 것이 동일하게 당연할 것입니다.

다음 예제들은 적합한 HTML 코드 조각들 입니다:
<p>The little kitten gently seated itself on a piece of
carpet. Later in his life, this would be referred to as the time the
cat sat on the mat.</p>
<fieldset>
  <legend>Personal information</legend>
  <p>
    <label>Name: <input name="n"></label>
    <label><input name="anon" type="checkbox"> Hide from other users</label>
  </p>
  <p><label>Address: <textarea name="a"></textarea></label></p>
</fieldset>
<p>There was once an example from Femley,<br>
Whose markup was of dubious quality.<br>
The validator complained,<br>
So the author was pained,<br>
To move the error from the markup to the rhyming.</p>

p 요소(element)는 더 명시적인 요소(element)가 적합할 경우 사용되지 않아야(should) 합니다.

다음 예제는 기술적으로는 맞습니다:
<section>
  <!-- ... -->
  <p>Last modified: 2001-04-23</p>
  <p>Author: fred@example.com</p>
</section>

하지만, 다음 마크업이 더 좋을 것입니다:

<section>
  <!-- ... -->
  <footer>Last modified: 2001-04-23</footer>
  <address>Author: fred@example.com</address>
</section>

혹은:

<section>
  <!-- ... -->
  <footer>
  <p>Last modified: 2001-04-23</p>
  <address>Author: fred@example.com</address>
  </footer>
</section>
목록 요소(element)들은 (특히, olul요소(element)들) p 요소(element)들의 자식이 될 수 없습니다. 따라서, 문장이 글머리 기호 목록을 포함하는 경우, 누군가는 그것이 어떻게 마크업 되어야(should) 하는지 궁금해 할 수 있습니다.
예를 들어, 이 기이한 문장은 관련되는 글머리 기호들을 가집니다
  • wizards,

  • faster-than-light travel, and

  • telepathy,

그리고 아래에서 더 논의됩니다.

해결책은 HTML 관점에서, 문단이 논리적 개념이 아니라, 구조적 개념이라는 것을 인식하는 것입니다. 위 기이한 예제에서, 이 명세에 의해 정의된 대로 실제로 다섯 개의 문단들이 있습니다: 목록 앞 하나, 각 글머리 기호에 대해 하나, 목록 후 하나.

따라서 위 예제에 대한 마크업은 다음이 될 수 있습니다:
<p>For instance, this fantastic sentence has bullets relating to</p>
<ul>
  <li>wizards,
  <li>faster-than-light travel, and
  <li>telepathy,
</ul>
<p>and is further discussed below.</p>

여러 "구조적" 문단들로 구성되는 "논리적" 문단들을 편리하게 스타일을 하고자하는 작성자는 p 요소(element) 대신에 div 요소(element)를 사용할 수 있습니다.

따라서 예를 들어 위 예제는 다음과 같이 될 수 있습니다:
<div>For instance, this fantastic sentence has bullets relating to
  <ul>
    <li>wizards,
    <li>faster-than-light travel, and
    <li>telepathy,
  </ul>
and is further discussed below.</div>

이 예제는 여전히 5개의 구조적 문단들을 가지지만, 이제 작성자는 예제의 각 부분을 별도로 간주해야 하는 대신 단지 div을 사용할 수 있습니다.

4.4.2. hr 요소(element)

카테고리:
흐름(flow) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
흐름(flow) 콘텐트가 예상 되는 곳.
콘텐트 모델:
없음.
text/html에서 태그 생략:
종료 태그 없음.
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
separator (기본 값 - 설정하지 마세요) 또는 presentation.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
interface HTMLHRElement : HTMLElement {};

hr 요소(element)는 문단 수준의 주제별 구분을, 예를 들어 스토리에서 장면 변화, 또는 참고 서적의 섹션 내에서 다른 주제로의 전환, 나타냅니다.

다음 가상의 프로젝트 메뉴얼의 발췌문은 섹션에서 주제들을 구분하기 위해 hr 요소(element)를 사용하는 두 섹션들을 보여줍니다.
<section>
  <h1>Communication</h1>
  <p>There are various methods of communication. This section
  covers a few of the important ones used by the project.</p>
  <hr>
  <p>Communication stones seem to come in pairs and have mysterious
  properties:</p>
  <ul>
    <li>They can transfer thoughts in two directions once activated
    if used alone.</li>
    <li>If used with another device, they can transfer one’s
    consciousness to another body.</li>
    <li>If both stones are used with another device, the
    consciousnesses switch bodies.</li>
  </ul>
  <hr>
  <p>Radios use the electromagnetic spectrum in the meter range and
  longer.</p>
  <hr>
  <p>Signal flares use the electromagnetic spectrum in the
  nanometer range.</p>
</section>
<section>
  <h1>Food</h1>
  <p>All food at the project is rationed:</p>
  <dl>
    <dt>Potatoes</dt>
    <dd>Two per day</dd>
    <dt>Soup</dt>
    <dd>One bowl per day</dd>
  </dl>
  <hr>
  <p>Cooking is done by the chefs on a set rotation.</p>
</section>

section 요소(element)들과 h1 요소(element)들은 암묵적으로 스스로 주제별로 변경하기 때문에, 섹션들끼리 사이에 hr 요소(element)가 필요하지 않습니다.

다음 피터 F. 해밀턴의 판도라의 별에서의 발췌문은 장면 전환 전과 장면 전환 뒤에 따르는 두 문단들을 보여줍니다. 두 번째와 세 번째 문단 사이에 중앙에 위치한 혼자 있는 별을 포함하는 간격으로 표현된 장면 전환은 여기에서 hr 요소(element)를 사용하여 표현됩니다.
<p>Dudley was ninety-two, in his second life, and fast approaching
time for another rejuvenation. Despite his body having the physical
age of a standard fifty-year-old, the prospect of a long degrading
campaign within academia was one he regarded with dread. For a
supposedly advanced civilization, the Intersolar Commonwealth could be
appallingly backward at times, not to mention cruel.</p>
<p><i>Maybe it won’t be that bad</i>, he told himself. The lie was
comforting enough to get him through the rest of the night’s
shift.</p>
<hr>
<p>The Carlton AllLander drove Dudley home just after dawn. Like the
astronomer, the vehicle was old and worn, but perfectly capable of
doing its job. It had a cheap diesel engine, common enough on a
semi-frontier world like Gralmond, although its drive array was a
thoroughly modern photoneural processor. With its high suspension and
deep-tread tyres it could plough along the dirt track to the
observatory in all weather and seasons, including the metre-deep snow
of Gralmond’s winters.</p>

hr 요소(element)는 문서의 개요(outline)에 영향을 주지 않습니다.

4.4.3. pre 요소(element)

카테고리:
흐름(flow) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
흐름(flow) 콘텐트가 예상 되는 곳.
콘텐트 모델:
어구(phrasing) 콘텐트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
interface HTMLPreElement : HTMLElement {};

pre 요소(element)는 구조가 요소(element)들에 의해서 보다 인쇄 방식에 의해 표현되는 미리 서식화 된(preformatted) 텍스트의 블럭을 나타냅니다.

pre 요소(element) 시작 태그에 즉시 뒤따르는 선행 개행 문자는 제거됩니다.

pre 요소(element)가 사용될 수 있는 경우의 몇 가지 예들:

  • 빈 줄들로 나타나는 문단, 글머리 기호가 앞에 붙은 행들로 나타나는 목록들 등을 가진 이메일을 포함하는 경우.

  • 언어의 규약을 따라 보여지는 구조를 가진 컴퓨터 코드의 코드 조각을 포함하는 경우.

  • ASCII 아트 표현.

작성자들은 미리 서식화된 텍스트가 음성 합성기들, 점자 표시기들 같은 것의 사용자에 대한 경우가 되는 것과 같은 서식을 잃어버릴 경우 경험 될 방법을 고려하도록 권장됩니다. ASCII 아트 같은 경우, 텍스트 형식의 설명 같은 대체 표현이 문서의 독자들에게 좀 더 보편적인 접근 가능하게 될 것입니다.

컴퓨터 코드 블럭을 표현하기 위해, pre 요소(element)가 code 요소(element)와 함께 사용될 수 있습니다; 컴퓨터 출력 블럭을 표현하기 위해 pre 요소(element)가 samp 요소(element)와 함께 사용될 수 있습니다. 유사하게, 사용자가 입력하는 텍스트를 나타내기 위해 kbd 요소(element)가 pre 요소(element)와 함께 사용될 수 있습니다.

다음 코드 조각에서, 컴퓨터 코드의 견본이 제시됩니다.
<p>This is the <code>Panel</code> constructor:</p>
<pre><code>function Panel(element, canClose, closeHandler) {
  this.element = element;
  this.canClose = canClose;
  this.closeHandler = function () { if (closeHandler) closeHandler() };
}</code></pre>
다음 코드 조각에서, sampkbd 요소(element)들은 Zork I의 세션을 보여주기 위해 pre 요소(element)의 콘텐트에 혼합되어 있습니다.
<pre><samp>You are in an open field west of a big white house with a boarded
front door.
There is a small mailbox here.

></samp> <kbd>open mailbox</kbd>

<samp>Opening the mailbox reveals:
A leaflet.

></samp></pre>
다음은 시의 고유한 부분을 형성하는 그것의 일반적이지 않은 형식을 보존하기 위해 pre 요소(element)를 사용하는 현대 시를 보여줍니다.
<pre>                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</pre>

4.4.4. blockquote 요소(element)

카테고리:
흐름(flow) 콘텐트.
섹션화(sectioning) 루트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
흐름(flow) 콘텐트가 예상 되는 곳.
콘텐트 모델:
흐름(flow) 콘텐트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
cite - 인용구 소스로의 링크.
허용된 ARIA 역할(role) 속성(attribute) 값들:
모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
interface HTMLQuoteElement : HTMLElement {
  attribute DOMString cite;
};

HTMLQuoteElement 인터페이스는 q 요소(element)에 의해서도 사용됩니다.

blockquote 요소(element)는 선택적으로, footercite 요소(element) 내에 있어야 하는 출처(citation)를 가지고, 그리고 선택적으로, 주석(annotation)들과 축약어들 같은 인라인 변경사항들을 가지고, 다른 소스로부터 인용(quote)되는 콘텐트를 나타냅니다.

출처(citation)와 인라인 변경 사항들과 다른 blockquote 안의 콘텐트는 다른 소스로부터 인용(quote)되어야(must) 하고, 그것이 주소를 가진다면, 주소는 cite 속성(attribute)에 언급될 수 있습니다.

페이지가 블로그 게시물의 댓글들 같이, 여러 사람들로부터의 의견을 포함하는 경우에, '다른 소스'는 다른 사람에 의해 작성된 동일한 페이지의 텍스트를 포함할 수 있습니다.

cite 속성(attribute)이 존재한다면, 그것은 유효한 잠정적으로 공백으로 둘러 싸일 수 있는 URL이어야(must) 합니다. 해당하는 출처(citation) 링크를 얻기 위해, 속성(attribute)의 값은 요소에 관련하여 해결(resolve) 되어야(must) 합니다. 유저 에이전트는 사용자가 그 출처(citation) 링크들을 따라가는 것을 허용할 수 있지만, 그것은 독자들을 위한 것이 아니라, 주로 특정한 사용을 위해 (예를 들어, 사이트의 인용구(quotation)들의 사용에 대한 통계를 수집하는 서버 사이드 스크립트들에 의해) 의도된 것입니다.

cite IDL 속성(attribute)은 요소(element)의 cite 콘텐트 속성(attribute)을 반영해야(must) 합니다.

blockquote의 콘텐트는 축약 되거나, 추가된 콘텐트를 가지거나, 주석(annotation)들을 가질 수 있습니다. 인용된 텍스트에 대한 모든 그러한 추가 사항들이나 변경 사항들은 텍스트로 나타나야(must) (텍스트 수준에서) 합니다. 이것은 "emphasis mine" 같은, 관습적인 규약들이나 명시적인 언급들의 사용을 의미할 수 있습니다.

"emphasis mine"
작성자가 제시한 인용구가 원문 출처에서 언급한 인용구보다 우선시 된다는 것을 강조하기 위해 사용하는 표기

예를 들어, 영어에서, 축약어들은 전통적으로 대괄호들을 사용하여 식별됩니다. "Fred ate the cracker. He then said he liked apples and fish." 라는 문장을 가진 페이지를 고려해보세요; 이것은 다음과 같이 인용(quote)될 수 있습니다:
<blockquote>
  <p>[Fred] then said he liked [...] fish.</p>
</blockquote>

따옴표 표기는 blockquote 내에서 인용(quote)된 텍스트와 주석(annotation)들 사이를 구별하기 위해 사용될 수 있습니다.

예를 들어, 작성자에 의해 인라인 메모가 제공됩니다:
<figure>
<blockquote>
"That monster custom, who all sense doth eat
Of habit’s devil," <abbr title="et cetera">&c.</abbr> not in Folio

"What a falling off was there !
From me, whose love was of that dignity
That it went hand in hand even with the vow
I made to her in marriage, and to decline
Upon a wretch."
</blockquote>
<footer><cite class="title">Shakespeare manual</cite> by <cite class="author">Frederick Gard Fleay</cite>,
p19 (in Google Books)
</footer>
</figure>

위 예제에서, 출처(citation)는 figure 요소(element)의 footer에 포함되고, 이것은 인용구와 인용에 대한 정보를 그룹핑하고 연관시킵니다. 이 경우에, figcaption 요소(element)는 출처(citation)가 캡션이 아니기 때문에 출처(citation)에 대한 컨테이너로 사용되지 않았습니다.

인용구(quotation)에 대한 속성(attribution)은 blockquote 요소(element)내에 위치할 수 있을 것이지만, 텍스트 내의 속성(attribution)들을 위한 cite 요소(element) 안이나 footer 요소(element) 안에 있어야(must)합니다.

예를 들어, 여기 인용구(quote)를 이 속성(attribution)에 분명하게 관련시기키 위해, 인용(quote)된 텍스트 뒤에 footer에 주어진 속성(attribution)이 있습니다:
<blockquote>
  <p>I contend that we are both atheists. I just believe in one fewer
  god than you do. When you understand why you dismiss all the other
  possible gods, you will understand why I dismiss yours.</p>
  <footer><cite>Stephen Roberts</cite></footer>
</blockquote>
여기 속성(attribution)은 인용(quote)된 텍스트의 마지막 행에 cite 요소(element)에 주어집니다. 작성자로의 링크도 포함되는 것에 주목하세요.
<blockquote>
  The people recognize themselves in their commodities; they find their
  soul in their automobile, hi-fi set, split-level home, kitchen equipment.
  — <cite><a href="https://en.wikipedia.org/wiki/Herbert_Marcuse">Herbert Marcuse</a></cite>
</blockquote>

blockquote의 마크업이 인용(quote)된 소스로부터임을 나타내는 공식적인 방법은 없습니다. footercite 요소(element)들이 포함되고 이 요소(element)들이 blockquote 내에 출처(citation)들을 식별하기 위해 사용된다면, 인용된 소스의 요소(element)들이 그들의 원본을 식별하기 위한 메타데이터를 가지고, 예를 들어 class 속성(attribute)를 사용하여 (정의된 확장 가능한 메커니즘) 주석이 달릴 수 있는 것이 제안됩니다.

이 예제에서 인용(quote)의 소스는 class 속성(attribute)를 사용하여 주석이 달린 cite 요소(element)를 포함합니다:
<blockquote>
  <p>My favorite book is <cite class="from-source">At Swim-Two-Birds</cite></p>
  <footer>- <cite>Mike[tm]Smith</cite></footer>
</blockquote>

아래 다른 예제들은 속성(attribution)을 보여주는 다른 방법들을 보여줍니다.

여기 blockquote 요소(element)는 figure 요소(element)와 그것의 figcaption과 함께 사용됩니다:
<figure>
  <blockquote>
  <p>The truth may be puzzling. It may take some work to grapple with.
  It may be counterintuitive. It may contradict deeply held
  prejudices. It may not be consonant with what we desperately want to
  be true. But our preferences do not determine what’s true. We have a
  method, and that method helps us to reach not absolute truth, only
  asymptotic approaches to the truth — never there, just closer
  and closer, always finding vast new oceans of undiscovered
  possibilities. Cleverly designed experiments are the key.</p>
  </blockquote>
  <figcaption><cite>Carl Sagan</cite>, in "<cite>Wonder and Skepticism</cite>", from
  the <cite>Skeptical Inquirer</cite> Volume 19, Issue 1 (January-February
  1995)</figcaption>
</figure>
이 다음 예제는 cite와 함께 blockquote의 사용을 보여줍니다:
<p>His next piece was the aptly named <cite>Sonnet 130</cite>:</p>
<blockquote cite="https://quotes.example.org/s/sonnet130.html">
  <p>My mistress' eyes are nothing like the sun,<br>
  Coral is far more red, than her lips red,<br>
  ...
이 예제는 사용자가 댓글을 달고 있는 게시물를 보여주기 위해 포럼 게시물이 blockquote를 사용할 수 있는 방법을 보여줍니다. article 요소(element)는 쓰레딩을 마크업하기 위해 각 게시물에 사용됩니다.
<article>
  <h1><a href="https://bacon.example.com/?blog=109431">Bacon on a crowbar</a></h1>
  <article>
    <header><strong>t3yw</strong> 12 points 1 hour ago</header>
    <p>I bet a narwhal would love that.</p>
    <footer><a href="?pid=29578">permalink</a></footer>
    <article>
      <header><strong>greg</strong> 8 points 1 hour ago</header>
      <blockquote><p>I bet a narwhal would love that.</p></blockquote>
      <p>Dude narwhals don’t eat bacon.</p>
      <footer><a href="?pid=29579">permalink</a></footer>
      <article>
        <header><strong>t3yw</strong> 15 points 1 hour ago</header>
        <blockquote>
          <blockquote><p>I bet a narwhal would love that.</p></blockquote>
          <p>Dude narwhals don’t eat bacon.</p>
        </blockquote>
        <p>Next thing you’ll be saying they don’t get capes and wizard
        hats either!</p>
        <footer><a href="?pid=29580">permalink</a></footer>
        <article>
          <header><strong>boing</strong> -5 points 1 hour ago</header>
          <p>narwhals are worse than ceiling cat</p>
          <footer><a href="?pid=29581">permalink</a></footer>
        </article>
      </article>
    </article>
    <article>
      <header><strong>fred</strong> 1 points 23 minutes ago</header>
      <blockquote><p>I bet a narwhal would love that.</p></blockquote>
      <p>I bet they’d love to peel a banana too.</p>
      <footer><a href="?pid=29582">permalink</a></footer>
    </article>
  </article>
</article>
이 예제는 blockquote 요소(element)들 내에 p 요소(element)들을 사용할 필요가 없다는 것을 보여주는, 짧은 코드 조각들에 대한 blockquote의 사용을 보여줍니다:
<p>He began his list of "lessons" with the following:</p>
<blockquote>One should never assume that his side of
the issue will be recognized, let alone that it will
be conceded to have merits.</blockquote>
<p>He continued with a number of similar points, ending with:</p>
<blockquote>Finally, one should be prepared for the threat
of breakdown in negotiations at any given moment and not
be cowed by the possibility.</blockquote>
<p>We shall now discuss these points...

대화를 표현하는 방법의 예들은 이후 섹션에 보여집니다; 이것은 이 목적을 위해 citeblockquote 요소(element)들을 사용하는 것은 적절하지 않습니다.

4.4.5. ol 요소(element)

카테고리:
흐름(flow) 콘텐트.
요소(element)의 자식이 적어도 하나의 li 요소(element)를 포함한다면: 분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
흐름(flow) 콘텐트가 예상 되는 곳.
콘텐트 모델:
0개 이상의 li스크립트 지원 요소(element)들.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
reversed - 목록에 번호를 거꾸로 지정.
start - 첫 번째 항목의 서수 값
type - 목록 표식의 종류.
허용된 ARIA 역할(role) 속성(attribute) 값들:
list 역할(role) (기본 값 - 설정하지 마세요), directory, group, listbox, menu, menubar, presentation, radiogroup, tablist, toolbar, tree.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
interface HTMLOListElement : HTMLElement {
  attribute boolean reversed;
  attribute long start;
  attribute DOMString type;
};

ol 요소(element)는 의도적으로 정렬된 항목들의 목록을 나타내기 때문에, 순서를 변경하는 것은 문서의 의미를 변경할 것입니다.

목록의 항목들은 트리 순서에 따라 ol 요소(element)의 li 요소(element) 자식 노들입니다.

reversed 속성(attribute)은 불리언 속성(attribute)입니다. 이것이 존재한다면, 목록인 내림차순 목록 (..., 3, 2, 1) 임을 나타냅니다. 속성(attribtue)가 생략되었다면, 목록은 오름차순 목록 (1, 2, 3, ...)입니다.

start 속성(attribute)가 존재한다면 이 속성(attribute)은 첫 번째 목록 항목의 서수 값을 제공하는 유효한 정수이어야(must) 합니다.

start 속성(attribute)이 존재한다면, 유저 에이전트들은 속성(attribute)의 값을 결정하기 위해 순서에 따라 정수로 그것을 해석해야(must) 합니다. 속성(attribute)이 누락되거나 값이 참조된 알고리즘을 따라 숫자로 변환될 수 없는 경우에 사용되는 기본 값은 요소(element)가 reversed 속성(attribute)를 가지지 않는다면 1이고, 그렇지 않으면 li 자식 요소(element)들의 수입니다.

목록의 첫 번째 항목은 그 li 요소(element)가 성공적으로 해석될 수 있는 값을 가지는 경우 그 value 속성(attribtue)에 의해 주어진 서수 값을 가지고, 그렇지 않는 한, ol 요소(element)의 start 속성(attribtue)에 의해 주어진 서수 값을 가집니다.

목록의 각 이후 항목들은 그것이 value 속성(attribute)을 가진다면 value 속성(attribute)에 의해 주어진 서수 값을 가지거나, value 속성(attribute)을 가지지 않는다면, reversed가 없다면 이전 항목의 서수 값에 1을 더한 값을, reversed가 있다면 1을 뺀 값을 가집니다.

type 속성(attribute)은 목록에서 사용되는 표식 종류가 중요한 경우에 (예를 들어, 항목들이 그들의 숫자/문자에 의해 참조되는 것이기 때문에) 이를 명시하는데 사용될 수 있습니다. 속성(attribute)이 명시된다면 속성(attribute)은 대소문자를 구분하여 다음 표의 행의 하나의 첫 번째 칸에 주어진 문자의 하나와 일치하는 값을 가져야(must) 합니다. type 속성(attribtue)은 첫 번째 칸이 속성(attribute)의 값에 일치하는 행의 두 번째 열의 칸에 주어진 상태를 나타냅니다; 일치하는 칸들이 없거나, 혹은 속성(attribute)이 생략되었다면, 속성(attribute)은 decimal 상태를 나타냅니다.

키워드 상태 설명 values 1-3과 3999-4001 값에 대한 예제들
1 (U+0031) decimal 십진수 1. 2. 3. ... 3999. 4000. 4001. ...
a (U+0061) lower-alpha 소문자 라틴 알파벳 a. b. c. ... ewu. ewv. eww. ...
A (U+0041) upper-alpha 대문자 라틴 알파벳 A. B. C. ... EWU. EWV. EWW. ...
i (U+0069) lower-roman 소문자 로마 숫자들 i. ii. iii. ... mmmcmxcix. i̅v̅. i̅v̅i. ...
I (U+0049) upper-roman 대문자 로마 숫자들 I. II. III. ... MMMCMXCIX. I̅V̅. I̅V̅I. ...
유저 에이전트는 목록의 항목들을 ol 요소(element)의 type 속성(attribute)의 상태와 일치하는 방법으로 표현해야(should) 합니다. 0보다 작거나 같은 숫자는 type 속성(attribute)에 상관없이 항상 십진법을 사용해야(should) 합니다.

CSS 유저 에이전트에 대해, 이 속성(attribute)를 list-style-type CSS 속성(property)에 매핑시키는 것은 §10 Rendering 섹션에서 주어집니다(매핑은 간단합니다: 위 상태들은 그들의 해당하는 CSS 값들과 동일한 이름들을 가집니다).

CSS 유저 에이전트들에서 이 속성(attribute)를 구현하는데 사용되는 기본 CSS 목록 스타일들을 재정의하는 것이 가능합니다; 그렇게 하는 것은 목록 항목들이 표시되는 방법에 영향을 줄 것입니다.

reversed, start, type IDL 속성(attribute)들은 동일한 이름의 각 콘텐트 속성(attribute)들을 반영해야(must) 합니다. start IDL 속성(attribute)은 그것의 콘텐트 속성과 동일한 기본 값을 가집니다.
다음 마크업은 순서가 중요한 목록을 보여주고, 따라서 ol 요소(element)가 적절한 위치를 보여줍니다. 이 목록과 ul 요소(element)를 사용하는 동일한 항목들의 예제들을 참고하여 ul 섹션 내의 동등한 목록을 비교해보세요.
<p>I have lived in the following countries (given in the order of when
I first lived there):</p>
<ol>
  <li>Switzerland
  <li>United Kingdom
  <li>United States
  <li>Norway
</ol>

목록의 순서를 변경하는 것이 문서의 의미를 어떻게 변경하는지 주목하세요. 다음 예제에서, 처음 두 개 항목들의 상대적인 순서를 변경하는 것은 작성자의 출생지를 변경시켰습니다:

<p>I have lived in the following countries (given in the order of when
I first lived there):</p>
<ol>
  <li>United Kingdom
  <li>Switzerland
  <li>United States
  <li>Norway
</ol>

4.4.6. ul 요소(element)

카테고리:
흐름(flow) 콘텐트.
요소(element)의 자식이 적어도 하나의 li 요소(element)를 포함한다면: 분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
흐름(flow) 콘텐트가 예상 되는 곳.
콘텐트 모델:
Zero or more li and script-supporting elements.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
list 역할(role) (기본 값 - 설정하지 마세요), directory, group, listbox, menu, menubar, presentation, radiogroup, tablist, toolbar, tree.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
interface HTMLUListElement : HTMLElement {};

ul 요소(element)는 항목들의 순서가 중요하지 않은 — 즉, 순서를 변경하는 것이 문서의 의미(meaning)를 실질적으로 변경하지 않는 항목들의 목록을 나타냅니다.

목록의 항목들은 ul 요소(element)의 li 요소(element) 자식 노드들입니다.

다음 마크업은 순서가 중요하지 않고, 따라서 ul 요소(element)가 적절한 목록을 보여줍니다. 이 목록과 ol 요소(element)를 사용하는 동일한 항목들의 예를 참고하여 ol 섹션 내의 동등한 목록을 비교해보세요.
<p>I have lived in the following countries:</p>
<ul>
  <li>Norway
  <li>Switzerland
  <li>United Kingdom
  <li>United States
</ul>

목록의 순서를 변경하는 것이 문서의 의미(meaning)을 변경하지 않는 것에 주목하세요. 위 코드 조각의 항목들은 알파벳 순서로 주어지지만, 아래 코드 조각에서는 전혀 문서의 의미(meaning)의 변경 없이, 2007년 경상수지의 크기의 순서로 주어집니다:

<p>I have lived in the following countries:</p>
<ul>
  <li>Switzerland
  <li>Norway
  <li>United Kingdom
  <li>United States
</ul>

4.4.7. li 요소(element)

카테고리:
없음.
이 요소(element)가 사용될 수 있는 컨텍스트:
ol 요소(element)들 안에.
ul 요소(element)들 안에.
콘텐트 모델:
흐름(flow) 콘텐트.
text/html에서 태그 생략:
li 요소(element)의 종료 태그li 요소(element)에 다른 li 요소(element)가 즉시 뒤따르거나 부모 요소에 더 이상의 콘텐트가 존재하지 않는다면 생력될 수 있습니다.
콘텐트 속성(attribute)들:
범용 속성(attribute)들
If the element is not a child of an ul or menu element: value
허용된 ARIA 역할(role) 속성(attribute) 값들:
listitem 역할(role) (기본 값 - 설정하지 마세요), menuitem, menuitemcheckbox, menuitemradio, option, presentation, radio, separator, tab, treeitem.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
interface HTMLLIElement : HTMLElement {
  attribute long value;
};

li 요소(element)는 목록 항목을 나타냅니다. 그것의 부모 요소(element)가 ol, ul, menu 요소(element)라면, 요소(element)는 이 요소(element)에 대해 정의된 부모 요소(element) 목록의 항목입니다. 그렇지 않으면, 목록 항목은 어떤 다른 li 요소(element)에도 정의된 목록 관련 관계를 가지지 않습니다.

부모 요소(element)가 ol 요소(element)라면, li 요소(element)는 서수 값을 가집니다.

value 속성(attribute)이 존재한다면, 목록 항목의 서수 값을 제공하는 유효한 정수이어야(must) 합니다.

value 속성(attribute)이 존재한다면, 유저 에이전트들은 속성(attribute)의 값을 결정하기 위해 정수로 해석해야(must)합니다. 속성(attribute)의 값이 숫자로 변환될 수 없다면, 속성(attribute)은 그것이 존재하지 않는 것 처럼 취급되어야(must) 합니다. 속성(attribute)은 기본 값을 가지지 않습니다.

value 속성(attribute)은 요소(element)의 부모 ol 요소(element)가 있다면 그것에 관련하여 처리됩니다. 부모 ol 요소(element)가 없다면, 속성(attribute)은 영향을 가지지 않습니다. ( ol 요소(element) 참조)

value IDL 속성(attribute)은 value 콘텐트 속성(attribute)의 값을 반영해야(must) 합니다.

다음 예는, top 10 영화들이 나열 된 (역순으로) 것입니다. 목록이 figure 요소(element)와 그것의 figcaption 요소(element)를 사용하여 제목이 주어지는 방식에 주목하세요.
<figure>
  <figcaption>The top 10 movies of all time</figcaption>
  <ol>
    <li value="10"><cite>Josie and the Pussycats</cite>, 2001</li>
    <li value="9"><cite lang="sh">Црна мачка, бели мачор</cite>, 1998</li>
    <li value="8"><cite>A Bug’s Life</cite>, 1998</li>
    <li value="7"><cite>Toy Story</cite>, 1995</li>
    <li value="6"><cite>Monsters, Inc</cite>, 2001</li>
    <li value="5"><cite>Cars</cite>, 2006</li>
    <li value="4"><cite>Toy Story 2</cite>, 1999</li>
    <li value="3"><cite>Finding Nemo</cite>, 2003</li>
    <li value="2"><cite>The Incredibles</cite>, 2004</li>
    <li value="1"><cite>Ratatouille</cite>, 2007</li>
  </ol>
</figure>

마크업은 ol 요소(element)에 reversed 속성(attribtue)를 사용하여 다음과 같이 작성될 수도 있습니다:

<figure>
  <figcaption>The top 10 movies of all time</figcaption>
  <ol reversed>
    <li><cite>Josie and the Pussycats</cite>, 2001</li>
    <li><cite lang="sh">Црна мачка, бели мачор</cite>, 1998</li>
    <li><cite>A Bug’s Life</cite>, 1998</li>
    <li><cite>Toy Story</cite>, 1995</li>
    <li><cite>Monsters, Inc</cite>, 2001</li>
    <li><cite>Cars</cite>, 2006</li>
    <li><cite>Toy Story 2</cite>, 1999</li>
    <li><cite>Finding Nemo</cite>, 2003</li>
    <li><cite>The Incredibles</cite>, 2004</li>
    <li><cite>Ratatouille</cite>, 2007</li>
  </ol>
</figure>

li 요소(element)들 안에 제목(heading) 요소(element)들을 (예를 들어, h1) 포함시키는 경우, 작성자가 의도한 의미(semantics)를 전달하지 않을 것입니다. 제목(heading)은 새로운 섹션을 시작하고, 따라서 목록 내의 제목(heading)은 암묵적으로 여러 섹션들로 목록을 분리시킵니다.

4.4.8. dl 요소(element)

카테고리:
흐름(flow) 콘텐트.
요소(element)의 자식이 적어도 하나의 이름-값 그룹을 포함한다면: 분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
흐름(flow) 콘텐트가 예상 되는 곳.
콘텐트 모델:
선택적으로 스크립트 지원 요소(element)들과 섞어서, 하나 이상의 dd 요소(element)들이 뒤따르는 하나 이상의 dt 요소(element)들로 각각 구성되는 0개 이상의 그룹들.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
list 역할(role) (기본 값 - 설정하지 마세요), directory, group, listbox, menu, menubar, presentation, radiogroup, tablist, toolbar, tree.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
interface HTMLDListElement : HTMLElement {};

dl 요소(element)는 0개 이상의 용어-설명 그룹들의 설명 목록을 나타냅니다. 각 용어-설명 그룹은 하나 이상의 용어들과 (dt 요소(element)들에 의해 표현 된), 하나 이상의 설명들 (dd 요소(element)들에 의해 표현 된)로 구성됩니다.

용어-설명 그룹들은 이름과 정의, 질문과 답, 범주와 주제, 혹은 다른 용어-설명 쌍의 그룹들이 될 수 있습니다.

이 예제에서 dl은 이름과 설명의 간단한 목록을 나타내는데 사용됩니다:

<dl>
  <dt>Blanco tequila</dt>
  <dd>The purest form of the blue agave spirit...</dd>
  <dt>Reposado tequila</dt>
  <dd>Typically aged in wooden barrels for between two and eleven months...</dd>
</dl>

용어-설명 그룹 내의 각 용어는 단일 dt 요소(element)에 의해 나타나져야(must) 합니다. 용어-설명 그룹 내의 설명들은 선택 가능한 것들입니다. 각 설명은 단일 dd 요소(element)로 나타나져야(must) 합니다.

이 예에서 dl 요소(element)는 여러 설명들을 가지는 용어들의 세트를 나타냅니다:

<p>Information about the rock band Queen:</p>
<dl>
  <dt>Members</dt>
  <dd>Brian May</dd>
  <dd>Freddie Mercury</dd>
  <dd>John Deacon</dd>
  <dd>Roger Taylor</dd>
  <dt>Record labels</dt>
  <dd>EMI</dd>
  <dd>Parlophone</dd>
  <dd>Capitol</dd>
  <dd>Hollywood</dd>
  <dd>Island</dd>
</dl>

dl 요소(element) 내의 용어-설명 그룹들의 순서와 각 그룹 내의 용어들과 설명들의 순서는 중요할 수 있습니다.

이 예에서 dl은 지시들의 순서가 중요한 지시들의 세트를 보여주는데 사용됩니다:

<p>Determine the victory points as follows (use the first matching case):</p>
<dl>
  <dt> If you have exactly five gold coins </dt>
  <dd> You get five victory points </dd>
  <dt> If you have one or more gold coins, and you have one or more silver coins </dt>
  <dd> You get two victory points </dd>
  <dt> If you have one or more silver coins </dt>
  <dd> You get one victory point </dd>
  <dt> Otherwise </dt>
  <dd> You get no victory points </dd>
</dl>

dl 요소(element)가 dtdd 자식 요소(element)들을 포함하지 않는다면, 용어-설명 그룹들을 포함하지 않습니다.

dl 요소(element)가 하나 이상의 비 여백 텍스트 노드 자식을 가지거나, dtdd 요소(element)들 둘 모두 아닌 자식을 가진다면, 모든 그 텍스트 노드들과 요소(element)들 뿐만 아니라 그것들의 후손들은 (모든 dtdd 요소(element)들을 포함하여) dl 내의 모든 용어-설명 그룹의 부분을 구성하지 않습니다.

dl 요소(element)가 하나 이상의 dt 자식 요소(element)를 가지지만 dd 자식 요소(element)를 가지지 않는다면, 그것은 용어들은 있지만 설명들이 없는 하나의 그룹으로 구성됩니다.

dl 요소(element)가 하나 이상의 dd 자식 요소(element)를 가지지만 dt 자식 요소(element)를 가지지 않는다면, 그것은 설명들은 있지만 용어들이 없는 하나의 그룹으로 구성됩니다.

dd 요소(element)가 dl 요소(element)의 첫 번째 자식이라면 (스크립트 지원 요소(element)를 제외하고), 첫 번째 그룹은 연관된 용어를 가지지 않습니다.

dt 요소(element)가 dl 요소(element)의 마지막 자식이라면 (스크립트 지원 요소(element)를 제외하고), 마지막 그룹은 연관된 설명들을 가지지 않습니다.

주목: dl 요소(element)가 그것의 콘텐트 모델과 일치하지 않는 경우, 그것은 종종 dd 요소(element)가 dt 요소(element) 대신 사용되거나, 그 반대이기 때문입니다.

4.4.9. dt 요소(element)

카테고리:
없음.
이 요소(element)가 사용될 수 있는 컨텍스트:
dl 요소(element)들 내의 dddt 요소(element)들 앞에.
콘텐트 모델:
후손 header, footer, 섹션화(sectioning) 콘텐트, 제목(heading) 콘텐트를 가지지 않는 흐름(flow) 콘텐트
text/html에서 태그 생략:
dt 요소(element)에 다른 dt 요소(element)나 dd 요소(element)가 즉시 뒤따른다면, dt 요소(element)의 종료 태그는 생략될 수 있습니다.
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
없음.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
어떤 aria-* 속성(attribute)들도 없음.
DOM 인터페이스:
HTMLElement를 사용.

dt 요소(element)는 설명 목록 (dl 요소(element)) 내의 용어-설명 그룹의 부분인 용어를 나타냅니다.

이 예에서 dt 요소(element)들은 질문들을 나타내고 dd 요소(element)들은 답들을 나타냅니다:

<dl>
  <dt>What is my favorite drink?</dt>
  <dd>Tea</dd>
  <dt>What is my favorite food?</dt>
  <dd>Sushi</dd>
  <dt>What is my favourite film?</dt>
  <dd>What a Wonderful Life</dd>
</dl>

dl 요소(element)에 사용되는 경우, dt 요소(element)는 반드시 용어에 대한 정의를 나타내는 것은 아닙니다. dfn 요소(element)가 정의를 나타내는데 사용되어야(should) 합니다.

이 예에서 dfn 요소(element)는 dt 요소(element)는 정의되는 용어를 포함하고, 이에 대한 정의가 dd 요소(element)에 의해 표현됨을 나타냅니다:

<dl>
  <dt lang="en-us"><dfn>Color</dfn></dt>
  <dt lang="en-gb"><dfn>Colour</dfn></dt>
  <dd>A sensation which (in humans) derives from the ability of the fine structure of the eye to distinguish three differently filtered analyses of a view.</dd>
</dl>

4.4.10. dd 요소(element)

카테고리:
없음.
이 요소(element)가 사용될 수 있는 컨텍스트:
dl 요소(element)들 내의 dtdd 요소(element)들 이후에 .
콘텐트 모델:
흐름(flow) 콘텐트.
text/html에서 태그 생략:
dd 요소(element)에 다른 dd 요소(element)나 dt 요소(element)가 즉시 뒤따르거나, 부모 요소에 더 이상의 콘텐트가 없다면 dd 요소(element)의 종료 태그는 생략될 수 있습니다.
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
없음
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLElement를 사용.

dd 요소(element)는 설명 목록 (dl 요소(element)) 내의 용어-설명 그룹의 부분인 설명을 나타냅니다 .

이 예에서 dd 요소(element)들은 dt 요소(element)들에 나타난 키코드들을 동작시키는 키들을 나타냅니다:

<dl>
  <dt>37</dt>
  <dd>Left</dd>
  <dt>38</dt>
  <dd>Right</dd>
  <dt>39</dt>
  <dd>Up</dd>
  <dt>40</dt>
  <dd>Down</dd>
</dl>

4.4.11. figure 요소(element)

카테고리:
흐름(flow) 콘텐트.
섹션화(sectioning) 루트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
흐름(flow) 콘텐트가 예상 되는 곳.
콘텐트 모델:
선택적으로 figcaption 자식 요소(element)를 포함하는 흐름(flow) 콘텐트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
Any role value.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLElement를 사용.

figure 요소(element)는 선택적으로 캡션을 가지고, 독립적이고 (완전한 문장 같은) 문서의 주요 흐름에서 단일 개체로서 참조되는 일부 흐름(flow) 콘텐트나타냅니다.

이 컨텍스트에서 독립은 반드시 독립적임을 의미하지는 않습니다. 예를 들어, 문단 내 각 문장은 독립적입니다; 문장의 일부인 이미지는 figure에 대해 적절하지 않을 것이지만, 이미지들로 만들어진 전체 문장은 적절할 것입니다.

요소(element)는 삽화, 도표, 사진, 코드 목록 등등에 주석을 다는데(annotate) 사용될 수 있습니다.

figure가 그것의 캡션으로 식별하는 것에 의해 (예를 들어, 삽화 번호에 의해) 문서의 주요 콘텐트로부터 참조되는 경우, 그러한 콘텐트가 문서의 흐름에 영향을 주지 않고 그 주요한 콘텐트로부터, 예를 들어, 페이지의 사이드로 혹은 전용 문서로 혹은 부록으로 쉽게 이동하는 것이 가능합니다.

figure 요소(element)가 그것의 관련된 위치에 의해 참조된다면, 예를 들어 "사진 위에" 혹은 "다음 삽화가 보여주는 바와 같이", 삽화를 이동시키는 것은 페이지의 의미(meaning)를 방해할 것입니다. 작성자는 그러한 참조들을 사용하는 것보다 삽화를 참조하기 위해 레이블들을 사용하여 페이지가 페이지의 의미(meaning)에 영향을 주는 것 없이 쉽게 재 스타일링 될 수 있도록 하는 것이 권장됩니다.

figure의 후손 figcaption가 있다면, 이것은 figure 요소(element)의 콘텐츠의 캡션을 나타냅니다. 자식 figcaption 요소(element)가 없다면, 캡션이 존재하지 않습니다.

figure 요소(element)의 콘텐츠는 주변 흐름의 일부입니다. 페이지의 목적이 삽화를, 예를 들어 이미지 공유 사이트에서 사진을, 보여주는 것이라면, figurefigcaption 요소(element)들이 그 삽화에 대한 캡션을 명시적으로 제공하는데 사용될 수 있습니다. 단지 살짝 연관되거나 주변 흐름보다는 별도의 목적을 제공하는 콘텐트를 위해서는 aside 요소(element)가 사용되어야(should) 합니다 (그리고 그것이 figure를 감쌀 수 있습니다). 예를 들어, article에서 콘텐트를 반복하는 인용구(pull quote)는 콘텐트의 일부가 아니라, 그것은 독자를 유인하거나 주요 주제들을 강조하는 목적에 대한 콘텐트의 반복이기 때문에, figure 안에 보다는 aside 안이 더 적절할 것입니다.

이 예제는 코드 나열을 마크업하기 위한 figure 요소(element)를 보여줍니다.
<p>In <a href="#l4">listing 4</a> we see the primary core interface
API declaration.</p>
<figure id="l4">
  <figcaption>Listing 4. The primary core interface API declaration.</figcaption>
  <pre><code>interface PrimaryCore {
  boolean verifyDataLine();
  void sendData(in sequence&lt;byte> data);
  void initSelfDestruct();
}</code></pre>
</figure>
<p>The API is designed to use UTF-8.</p>
여기 페이지의 주요 콘텐트인 사진을 (갤러리에서 처럼) 마크업 하기 위한 figure 요소(element)를 볼 수 있습니다.
<!DOCTYPE HTML>
<title>Bubbles at work — My Gallery™</title>
<figure>
  <img src="bubbles-work.jpeg"
      alt="Bubbles, sitting in his office chair, works on his
            latest project intently.">
  <figcaption>Bubbles at work</figcaption>
</figure>
<nav><a href="19414.html">Prev</a><a href="19416.html">Next</a></nav>
이 예에서, 삽화가 아닌 이미지 뿐만 아니라 삽화인 이미지와 비디오를 볼 수 있습니다. 첫 번째 이미지는 사실상 예제의 두 번째 문장의 일부이므로 그것은 독립적인 개체가 아니며, 따라서 figure가 적절하지 않을 것입니다.
<h2>Malinko’s comics</h2>

<p>This case centered on some sort of "intellectual property"
infringement related to a comic (see Exhibit A). The suit started
after a trailer ending with these words:

<blockquote>
  <img src="promblem-packed-action.png" alt="ROUGH COPY! Promblem-Packed Action!">
</blockquote>

<p>...was aired. A lawyer, armed with a Bigger Notebook, launched a
preemptive strike using snowballs. A complete copy of the trailer is
included with Exhibit B.

<figure>
  <img src="ex-a.png" alt="Two squiggles on a dirty piece of paper.">
  <figcaption>Exhibit A. The alleged <cite>rough copy</cite> comic.</figcaption>
</figure>

<figure>
  <video src="ex-b.mov"></video>
  <figcaption>Exhibit B. The <cite>Rough Copy</cite> trailer.</figcaption>
</figure>

<p>The case was resolved out of court.
여기, 시의 일부가 figure를 사용하여 마크업 됩니다.
<figure>
  <p>'Twas brillig, and the slithy toves<br>
  Did gyre and gimble in the wabe;<br>
  All mimsy were the borogoves,<br>
  And the mome raths outgrabe.</p>
  <figcaption><cite>Jabberwocky</cite> (first verse). Lewis Carroll, 1832-98</figcaption>
</figure>
성(castle)에 대하여 논하는 매우 큰 저작물의 일부일 수 있는 이 예에서, 중첩된 figure 요소(element)들은 그룹 캡션과 그룹 내 각 삽화에 대한 개별 캡션들 모두를 제공하는데 사용됩니다:
<figure>
  <figcaption>The castle through the ages: 1423, 1858, and 1999 respectively.</figcaption>
  <figure>
    <figcaption>Etching. Anonymous, ca. 1423.</figcaption>
    <img src="castle1423.jpeg" alt="The castle has one tower, and a tall wall around it.">
  </figure>
  <figure>
    <figcaption>Oil-based paint on canvas. Maria Towle, 1858.</figcaption>
    <img src="castle1858.jpeg" alt="The castle now has two towers and two walls.">
  </figure>
  <figure>
    <figcaption>Film photograph. Peter Jankle, 1999.</figcaption>
    <img src="castle1999.jpeg" alt="The castle lies in ruins, the original tower all that remains in one piece.">
  </figure>
</figure>
앞선 예는 다음과 같이 좀 더 간결하게 작성될 수 있습니다 (중첩된 figure/figcaption 쌍들의 위치에 title 속성(attribute)들을 사용하여):
<figure>
  <img src="castle1423.jpeg" title="Etching. Anonymous, ca. 1423."
      alt="The castle has one tower, and a tall wall around it.">
  <img src="castle1858.jpeg" title="Oil-based paint on canvas. Maria Towle, 1858."
      alt="The castle now has two towers and two walls.">
  <img src="castle1999.jpeg" title="Film photograph. Peter Jankle, 1999."
      alt="The castle lies in ruins, the original tower all that remains in one piece.">
  <figcaption>The castle through the ages: 1423, 1858, and 1999 respectively.</figcaption>
</figure>
삽화는 종종 콘텐트로부터 암묵적으로만 참조됩니다:
<article>
  <h1>Fiscal negotiations stumble in Congress as deadline nears</h1>
  <figure>
    <img src="obama-reid.jpeg" alt="Obama and Reid sit together smiling in the Oval Office.">
    <figcaption>Barack Obama and Harry Reid. White House press photograph.</figcaption>
  </figure>
  <p>Negotiations in Congress to end the fiscal impasse sputtered on Tuesday, leaving both chambers
  grasping for a way to reopen the government and raise the country’s borrowing authority with a
  Thursday deadline drawing near.</p>
  ...
</article>

4.4.12. figcaption 요소(element)

카테고리:
없음.
이 요소(element)가 사용될 수 있는 컨텍스트:
figure 요소(element)의 후손으로.
콘텐트 모델:
흐름(flow) 콘텐트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
Any role value.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLElement를 사용.

figcaption 요소(element)는 figcaption 요소(element)의 부모 figure 요소(element)의 나머지 콘텐츠가 있다면 그에 대한 캡션이나 범례를 나타냅니다.

4.4.13. main 요소(element)

카테고리:
흐름(flow) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
article, aside, footer, header, nav 후손 요소(element)가 없는 흐름(flow) 콘텐트가 기대되는 곳.
콘텐트 모델:
흐름(flow) 콘텐트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
main 역할(role) (기본 값 - 설정하지 마세요) 또는 presentation.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLElement를 사용.

main 요소(element)는 문서나 어플리케이션의 <{body]>의 주요 콘텐트를 나타냅니다.

main 요소(element)는 섹션화(sectioning) 콘텐트가 아니며 문서 개요(outline)에 영향을 가지지 않습니다.

문서의 주요 콘텐트 영역은 그 문서에 유일하고, 사이트 탐색 링크들, 저작권 정보, 사이트 로고와 배너 및 검색 양식들 (문서나 어플리케이션의 주요 기능이 검색 양식의 것이 아닌 한) 같은 문서들의 세트에 걸쳐 반복되는 콘텐트를 제외한 콘텐트를 포함합니다.

작성자들은 article, aside, footer, header, nav 요소(element)의 후손으로 main 요소(element)를 포함하지 않아야(must) 합니다.

main 요소(element)는 문서나 어플리케이션의 하위 섹션들의 주요 콘텐트 영역을 식별하기 위한 사용에 적절하지 않습니다. 가장 간단한 해결책은 하위 섹션의 주요 콘텐트를 전혀 마크업 하지 않고 단지 암묵적으로 남겨두되 작성자가 적절한 §4.4 섹션화(sectioning) 콘텐트섹션화(sectioning) 콘텐트를 사용할 수 있도록 하는 것입니다.

다음 예에서, 주요 콘텐트가 main 요소(element)의 사용에 의해 식별되는 스케이트보드들에 대한 (웹 페이지의 주요 주제) 2개의 아티클을 볼 수 있습니다.

<!-- other content -->

<main>

  <h1>Skateboards</h1>
  <p>The skateboard is the way cool kids get around</p>

  <article>
    <h2>Longboards</h2>
    <p>Longboards are a type of skateboard with a longer
    wheelbase and larger, softer wheels.</p>
    <p>... </p>
    <p>... </p>
  </article>

  <article>
    <h2>Electric Skateboards</h2>
    <p>These no longer require the propelling of the skateboard
    by means of the feet; rather an electric motor propels the board,
    fed by an electric battery.</p>
    <p>... </p>
    <p>... </p>
  </article>

</main>

<!-- other content -->

여기 졸업식 프로그램 메인 콘텐트 섹션은 main 요소(element)의 사용에 의해 정의됩니다. 이 예에서 main 요소(element)가 메인 콘텐트의 하위 섹션들로의 링크들로 구성되는 nav 요소(element)를 포함하는 것에 주목하세요.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Graduation Ceremony Summer 2022</title>
  </head>
  <body>

    <header>The Lawson Academy:
    <nav>
      <ul>
        <li><a href="courses.html">Courses</a></li>
        <li><a href="fees.html">Fees</a></li>
        <li><a>Graduation</a></li>
      </ul>
    </nav>
    </header>

    <main>

      <h1>Graduation</h1>

      <nav>
        <ul>
          <li><a href="#ceremony">Ceremony</a></li>
          <li><a href="#graduates">Graduates</a></li>
          <li><a href="#awards">Awards</a></li>
        </ul>
      </nav>

      <h2 id="ceremony">Ceremony</h2>
      <p>Opening Procession</p>
      <p>Speech by Valedictorian</p>
      <p>Speech by Class President</p>
      <p>Presentation of Diplomas</p>
      <p>Closing Speech by Headmaster</p>

      <h2 id="graduates">Graduates</h2>
      <ul>
        <li>Eileen Williams</li>
        <li>Andy Maseyk</li>
        <li>Blanca Sainz Garcia</li>
        <li>Clara Faulkner</li>
        <li>Gez Lemon</li>
        <li>Eloisa Faulkner</li>
      </ul>

      <h2 id="awards">Awards</h2>
      <ul>
        <li>Clara Faulkner</li>
        <li>Eloisa Faulkner</li>
        <li>Blanca Sainz Garcia</li>
      </ul>

    </main>

    <footer> Copyright 2012 B.lawson</footer>

  </body>
</html>

다음 예에서, headerfooter는 웹사이트에 일반적이고 main의 콘텐트에 따라 다르지 않기 때문에 둘 모두 main 요소(element) 밖에 있습니다.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Great Dogs for Families</title>
  </head>
  <body>

    <header>
      <h1>The Border Terrier</h1>
      <nav>
        <ul>
          <li><a href="index.html">Home</a></li>
          <li><a href="about.html">About</a></li>
          <li><a href="health.html">Health</a></li>
        </ul>
      </nav>
    </header>
    <main>
      <h2>Welcome!</h2>
      <p>This site is all about the Border Terrier, the best breed of dog
      that there is!</p>
    </main>
    <footer>
      <small>Copyright © <time datetime="2013">2013</time> by I. Devlin</small>
    </footer>

  </body>
</html>

여기, 동일한 일반적인 headerfooter 요소(element)들이 main 밖에 남아있고, 추가적인 header 요소(element)가 관련된 제목(heading)과 페이지 내의 내비게이션을 포함함에 따라 그 콘텐트가 main 내의 콘텐트에 관련되기 때문에 main 요소(element) 안에 있습니다. 페이지 내의 내비게이션은 main 요소(element) 내에 또 존재하는 footer 안에 반복됩니다.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Great Dogs for Families</title>
  </head>
  <body>

    <header>
      <h1>The Border Terrier</h1>
      <nav>
        <ul>
          <li><a href="index.html">Home</a></li>
          <li><a href="about.html">About</a></li>
          <li><a href="health.html">Health</a></li>
        </ul>
      </nav>
    </header>
    <main>
      <section>
        <header>
          <h2>About</h2>
          <nav>
            <ul>
              <li><a href="#basic">Basic</a></li>
              <li><a href="#app">Appearance</a></li>
              <li><a href="#temp">Temperament</a></li>
            </ul>
          </nav>
        </header>
        <section id="basic">
          <h3>Basic Information</h3>
          <p>The Border Terrier is a small, rough-coated breed of
          dog of the terrier group, originally bred as fox and vermin
          hunters. [...]</p>
        </section>
        <section id="app">
          <h3>Appearance</h3>
          <p>Identifiable by their otter-shaped heads, Border Terriers
          have a broad skull and short (although many be fairly long),
          strong muzzle with a scissors bite. [...]</p>
        </section>
        <section id="temp">
          <h3>Temperament</h3>
          <p>Though sometimes stubborn and strong willed, border terriers
          are, on the whole very even tempered, and are friendly and rarely
          aggressive. [...] </p>
        </section>
        <footer>
          <a href="#basic">Basic</a> -
          <a href="#app">Appearance</a> -
          <a href="#temp">Temperament</a>
        </footer>
      </section>
    </main>
    <footer>
      <small>Copyright © <time datetime="2013">2013</time> by I. Devlin</small>
    </footer>

  </body>
</html>

이 예는 aside를 포함한다는 것을 제외하고 이전 것과 대체로 동일합니다. aside의 콘텐트는 모든 콘텐트가 보더 테리어에 대한 main 요소(element) 내의 콘텐트에 관련된 것으로 간주되므로, asidemain 요소(element) 안에 배치됩니다.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Great Dogs for Families</title>
  </head>
  <body>

    <header>
      <h1>The Border Terrier</h1>
      <nav>
        <ul>
          <li><a href="index.html">Home</a></li>
          <li><a href="about.html">About</a></li>
          <li><a href="health.html">Health</a></li>
        </ul>
      </nav>
    </header>
    <main>
      <section>
        <header>
          <h2>About</h2>
          <nav>
            <ul>
              <li><a href="#basic">Basic</a></li>
              <li><a href="#app">Appearance</a></li>
              <li><a href="#temp">Temperament</a></li>
            </ul>
          </nav>
        </header>
        <section id="basic">
          <h3>Basic Information</h3>
          <p>The Border Terrier is a small, rough-coated breed of
          dog of the terrier group, originally bred as fox and vermin
          hunters. [...]</p>
        </section>
        <section id="app">
          <h3>Appearance</h3>
          <p>Identifiable by their otter-shaped heads, Border Terriers
          have a broad skull and short (although many be fairly long),
          strong muzzle with a scissors bite. [...]</p>
        </section>
        <section id="temp">
          <h3>Temperament</h3>
          <p>Though sometimes stubborn and strong willed, border terriers
          are, on the whole very even tempered, and are friendly and rarely
          aggressive. [...] </p>
        </section>
        <aside>
          <h3>History</h3>
          <p>The Border Terrier originates in, and takes its name from the
          Scottish borders. [...] </p>
        </aside>
        <footer>
          <a href="#basic">Basic</a> -
          <a href="#app">Appearance</a> -
          <a href="#temp">Temperament</a>
        </footer>
      </section>
    </main>
    <footer>
      <small>Copyright © <time datetime="2013">2013</time> by I. Devlin</small>
    </footer>

  </body>
</html>

다음 예에서, 광고를 포함하는 두 aside 요소(element)들은 그들의 콘텐트가 main 내의 콘텐트에 따라 다르지 않기 때문에 main 요소(element) 밖에 배치되었습니다. 이 aside들은 headerfooter에서 보여진 것과 같이 일반적인 것들이기 때문에, 모든 페이지에 존재할 수 있습니다.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Great Dogs for Families</title>
  </head>
  <body>

    <header>
      <h1>The Border Terrier</h1>
      <nav>
        <ul>
          <li><a href="index.html">Home</a></li>
          <li><a href="about.html">About</a></li>
          <li><a href="health.html">Health</a></li>
        </ul>
      </nav>
    </header>
    <main>
      <h2>Welcome!</h2>
      <p>This site is all about the Border Terrier, the best breed of dog
      that there is!</p>
    </main>
    <aside class="advert">
      <h2>Border Farm Breeders</h2>
      <p>We are a certified breeder of Border Terriers, contact us at...</p>
    </aside>
    <aside class="advert">
      <h2>Grumpy’s Pet Shop</h2>
      <p>Get all your pet’s needs at our shop!</p>
    </aside>

    <footer>
      <small>Copyright © <time datetime="2013">2013</time> by I. Devlin</small>
    </footer>

  </body>
</html>

4.4.14. div 요소(element)

카테고리:
흐름(flow) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
흐름(flow) 콘텐트가 예상 되는 곳.
콘텐트 모델:
흐름(flow) 콘텐트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
Any role value.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
interface HTMLDivElement : HTMLElement {};

div 요소(element)는 전혀 특별한 의미(meaning)를 가지지 않습니다. 그것은 자신의 자식을 나타냅니다. 그것은 연속적인 요소(element)들의 그룹에 공통된 의미론(semantics)을 마크업 하기 위해 class, lang, title 속성(attribute)들을 가지고 사용될 수 있습니다.

작성자들은 다른 요소(element)가 적절하지 않은 경우에 대해, 최후의 수단의 요소(element)로 div 요소(element)를 간주하도록 강력하게 권장됩니다. div 요소(element) 대신 좀 더 적절한 요소(element)들의 사용은 독자들에 대한 더 나은 접근성과 작성자들에 대한 쉬운 유지보수로 이어집니다.

예를 들어, article를 사용하여 마크업되는 블로그 게시물, section을 사용하는 챕터, nav를 사용하여 지원된 페이지의 내비게이션, fieldset을 사용하는 양식 장치들(form contorls)의 그룹입니다.

반면에, div 요소(element)들은 스타일 목적들이나 비슷한 방법으로 모두 주석(annotate)이 달리는 섹션 내의 여러 문단들을 감싸는데 유용할 수 있습니다. 다음 예에서, 별도의 두 문단 요소(element)들에 언어를 설정하는 대신, 한 번에 두 개의 문단의 언어를 설정하기 위한 방법으로 사용된 div 요소(element)들이 보여집니다:

<article lang="en-US">
  <h2>My use of language and my cats</h2>
  <p>My cat’s behavior hasn’t changed much since her absence, except
  that she plays her new physique to the neighbors regularly, in an
  attempt to get pets.</p>
  <div lang="en-GB">
  <p>My other cat, colored 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 recognizes that
  their flat is a mirror image of ours.</p>
  <p>Hm, I just noticed that in the last paragraph I used British
  English. But I’m supposed to write in American English. So I
  shouldn’t say "pavement" or "flat" or "color"...</p>
  </div>
  <p>I should say "sidewalk" and "apartment" and "color"!</p>
</article>

4.5. 텍스트 수준 의미론

4.5.1. a 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
요소(element)가 href 속성(attribute)을 가진다면: 대화형(interactive) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
어구(phrasing) 콘텐트가 기대되는 곳.
콘텐트 모델:
투명, 하지만 후손 대화형(interactive) 콘텐트a 요소(element)가 존재하지 않아야(must) 합니다.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
href - 하이퍼링크의 주소
target - 하이퍼링크 탐색§4.10.22 Form submission에 대한 기본 브라우징 컨텍스트
download - 리소스로 탐색하는 대신 다운로드 할지 여부, 그리고 다운로드 한다면 그것의 파일 이름.
rel — 이 문서 (혹은 하위 섹션/주제)에서 목적지 리소스로의 관계
rev — 목적지 리소스로부터 이 문서 (혹은 하위 섹션/주제)로의 역방향 연결 관계
hreflang - 연결된 리소스의 언어
type - 참조된 리소스의 유형에 대한 힌트
허용된 ARIA 역할(role) 속성(attribute) 값들:
link (기본 값 - 설정하지 마세요), button, checkbox, menuitem, menuitemcheckbox, menuitemradio, radio, switch [WAI-ARIA-1.1], tab, treeitem
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
interface HTMLAnchorElement : HTMLElement {
  attribute DOMString target;
  attribute DOMString download;
  attribute DOMString rel;
  attribute DOMString rev;
  [SameObject, PutForwards=value] readonly attribute DOMTokenList relList;
  attribute DOMString hreflang;
  attribute DOMString type;
  attribute DOMString text;
};
HTMLAnchorElement implements HTMLHyperlinkElementUtils;

a 요소(element)가 href 속성(attribute)를 가진다면, 그것은 그것의 콘텐츠에 의해 라벨링 된 하이퍼링크를 (하이퍼텍스트 앵커) 나타냅니다.

a 요소(element)가 href 속성(attribute)을 가지지 않는다면, 요소(element)는 관련되어있다면 요소(element)의 콘텐츠로만 구성되는 링크가 있을 수 있는 위치에 대한 자리 표시자(placeholder)를 나타냅니다.

target, download, rel, rev, hreflang, type 속성(attribute)들은 href 속성(attribute)이 존재하지 않는다면 생략되어야(must) 합니다.

사이트가 모든 페이지에 일관된 탐색 도구 모음을 사용한다면, 정상적으로 페이지 자체로 연결하는 링크는 a 요소(element)를 사용하여 마크업 될 수 있습니다:

<nav>
  <ul>
    <li> <a href="/">Home</a> </li>
    <li> <a href="/news">News</a> </li>
    <li> <a>Examples</a> </li>
    <li> <a href="/legal">Legal</a> </li>
  </ul>
</nav>
href, target, download 및 속성(attribute)들은 사용자가 a 요소(element)를 사용하여 생성된 하이퍼링크들을 따라가거나 하이퍼링크들을 다운로드 할 때 발생하는 것에 영향을 줍니다. rel, rev, hreflang, type 속성(attribute)들은 사용자가 링크를 따라가기 전에 대상 리소스의 특징 같은 것을 사용자에게 나타내는데 사용될 수 있습니다.

하이퍼링크들을 생성하는 a 요소(element)들의 활성화 동작은 다음 단계들을 수행하는 것입니다:

  1. a 요소(element)의 Document완전히 활성화되어 있지 않다면, 이 단계들을 중단합니다.

  2. a 요소(element)가 download 속성(attribute)를 가지고 알고리즘이 팝업을 보여주도록 허용되지 않았거나, 요소(element)의 target 속성(attribute)이 존재하고 브라우징 컨텍스트 이름으로 target 속성(attribute)의 값을 사용하여 브라우징 컨텍스트 이름이 주어진 브라우징 컨텍스트을 선택하기 위한 규칙을 적용하는 것이 선택된 브라우징 컨텍스트가 존재하지 않게 되는 것을 초래한다면, 이 하위 단계들을 수행합니다:

    1. 엔트리 설정 객체가 존재한다면, InvalidAccessError 예외를 던집니다.

    2. 하이퍼링크를 따라가지 않고 이 단계들을 중단합니다.

  3. click 이벤트의 대상이 명시된 ismap 속성(attribtue)를 가진 img 요소(element)라면, 다음과 같이 서버 사이드 이미지맵 처리가 수행되어야(must)합니다:

    1. click 이벤트가 img 요소에 실제 포인팅 디바이스에서 작동된 click 이벤트 였다면, x를 이미지의 왼쪽 테두리가 있다면 왼쪽 테두리의 왼쪽 모서리로부터, 혹은 그렇지 않으면 이미지의 왼쪽 모서리로부터 클릭 위치까지의 거리를 CSS 픽셀로 두고, y를 이미지의 상단 테두리가 있다면 상단 테두리의 상단 모서리로부터, 혹은 그렇지 않으면 이미지의 상단 모서리로부터의 클릭 위치까지의 거리를 CSS 픽셀로 둡니다. 그렇지 않으면 xy를 0으로 둡니다.

    2. hyperlink suffix를 U+003F 물음표 문자, ASCII 숫자들을 사용하여 십진 정수로 표현된 x의 값, U+002C 콤마 문자 (,), ASCII 숫자들을 사용하여 십진 정수로 표현된 y의 값으로 둡니다.

  4. 마지막으로, 유저 에이전트는 위 단계들이 정의되었다면, hyperlink suffix를 전달하여, download 속성(attribtue)과 모든 표현된 사용자 환경 설정에 의해 결졍된 대로, a 요소(element)에 의해 생성된 하이퍼링크를 따라가거나 하이퍼링크를 다운로드해야(must) 합니다.

a . text
textContent과 동일.
IDL 속성(attribute)들 download, target, rel, rev, hreflang, type는 동일한 이름의 각 콘텐트 속성(attribute)들을 반영해야(must) 합니다.

IDL 속성(attribute) relListrel 콘텐트 속성(attribute)을 반영해야(must) 합니다.

text IDL 속성(attribute)는 가져올 때 요소(element)의 textContent IDL 속성(attribute)와 동일한 값을 반환해야(must) 하고, 설정 할 때, 요소(element)의 textContent IDL 속성(attribute)에 새로운 값이 설정된 것 같이 동작해야(must) 합니다.


a 요소(element)는 또한 HTMLHyperlinkElementUtils 인터페이스를 지원합니다. [URL]

요소(element)가 생성될 때, 그리고 요소(element)의 href 콘텐트 속성(attribute)이 설정, 변경, 제거 될 때마다, 유저 에이전트는 요소(element)의 HTMLHyperlinkElementUtils 인터페이스의 입력 설정 알고리즘을 href 콘텐트 속성(attribute)이 있다면 그 속성의 값을 가지고, 그렇지 않으면 주어진 값으로 빈 문자열을 가지고 호출해야(must) 합니다.

요소(element)의 HTMLHyperlinkElementUtils 인터페이스의 기본 URL 획득(get the base) 알고리즘은 단순하게 문서 기본 URL을 반환해야(must) 합니다.

요소(element)의 HTMLHyperlinkElementUtils 인터페이스의 질의 인코딩은 문서의 문자 인코딩입니다.

요소(element)의 HTMLHyperlinkElementUtils 인터페이스가 문자열 value를 가지고 그것의 갱신 단계들을 작동시킬 경우, 유저 에이전트는 요소(element)의 href 콘텐트 속성(attribute)를 문자열 value로 설정해야(must) 합니다.

a 요소(element)는 전체 문단들, 목록들, 표들, 등등 심지어 전체 섹션까지도 내부에 상호작용 콘텐트가 (예를 들어, 버튼이나 다른 링크들) 존재하지만 않으면 감쌀 수 있습니다. 이 예는 이것이 전체 광고 블럭이 링크 안으로 들어가게 하는데 사용될 수 있는 방식을 보여줍니다:
<aside class="advertising">
  <h1>Advertising</h1>
  <a href="https://ad.example.com/?adid=1929&amp;pubid=1422">
  <section>
    <h1>Mellblomatic 9000!</h1>
    <p>Turn all your widgets into mellbloms!</p>
    <p>Only $9.99 plus shipping and handling.</p>
  </section>
  </a>
  <a href="https://ad.example.com/?adid=375&amp;pubid=1422">
  <section>
    <h1>The Mellblom Browser</h1>
    <p>Web browsing at the speed of light.</p>
    <p>No other browser goes faster!</p>
  </section>
  </a>
</aside>

4.5.2. em 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
어구(phrasing) 콘텐트가 기대되는 곳.
콘텐트 모델:
어구(phrasing) 콘텐트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLElement를 사용.

em 요소(element)는 그것의 콘텐츠의 역설 강조(stress emphasis)를 나타냅니다.

콘텐트의 특정 부분의 강조 수준은 조상 em 요소(elemenet)들의 수에 의해 주어집니다.

역설 강조(stress emphasis)의 위치는 문장의 의미(meaning)를 변경합니다. 따라서 요소(element)는 콘텐트의 필수적인 부분을 구성합니다. 이 방법으로 사용되는 강조의 정확한 방법은 언어에 따라 다릅니다.

이 예제들은 역설 강조(stress emphasis)가 의미(meaning)을 변경하는 방식을 보여줍니다. 먼저, 강조 없는, 사실에 대한 일반적인 문장입니다:
<p>Cats are cute animals.</p>

첫 번째 단어를 강조하여, 문장이 논의 중인 동물의 종류가 문제의 것임을 나타냅니다 (어쩌면 누군가가 개들이 귀엽다고 주장하고 있을 것입니다):

<p><em>Cats</em> are cute animals.</p>

강조를 동사로 옮기는 것은, 전체 문장의 진실성이 논의되고 있는 것임을 강조하는 것이 됩니다 (어쩌면 누군가가 고양이는 귀엽지 않다라고 말하고 있을 것입니다):

<p>Cats <em>are</em> cute animals.</p>

그것을 형용사로 옮김에 의해, 고양이의 정확한 특성이 다시 주장됩니다 (어쩌면 누군가가 고양이는 사나운 동물이라고 주장했을 것입니다):

<p>Cats are <em>cute</em> animals.</p>

비슷하게, 누군가 고양이는 채소라고 주장한다면, 이를 정정하는 누군가는 마지막 단어를 강조할 수 있습니다:

<p>Cats are cute <em>animals</em>.</p>

전체 문장을 강조하여, 발표자가 요점을 이해시키기 위해 열심히 싸우고 있음이 명확해 집니다. 역설 강조(stress emphasis)의 종류는 또한 일반적으로 구두점에 영향을 주고, 이런 이유로 여기 느낌표가 있습니다.

<p><em>Cats are cute animals!</em></p>

귀여움을 강조하는 것이 섞인 분노는 다음과 같은 마크업을 이끌어 낼 수 있습니다:

<p><em>Cats are <em>cute</em> animals!</em></p>
em 요소(element)는 일반적인 "이탤릭체" 요소(element)가 아닙니다. 때때로, 다른 분위기나 음성으로 있는 것 처럼, 텍스트는 문단의 나머지로부터 눈에 띄기 위한 것입니다. 이를 위해, i 요소(element)가 좀 더 적절합니다.

em 요소(element)는 또한 중요성을 전달하기 위한 것이 아닙니다; 그 목적을 위해, strong 요소(element)가 좀 더 적절합니다.

4.5.3. strong 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
어구(phrasing) 콘텐트가 기대되는 곳.
콘텐트 모델:
어구(phrasing) 콘텐트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLElement를 사용.

strong 요소(element)는 그것의 콘텐츠에 대한 강한 중요성, 심각성, 긴급성을 나타냅니다.

중요성: strong 요소(element)는 더 상세하거나, 더 유쾌하거나, 한낱 상투어일 수 있는 다른 부분들로부터 정말 중요한 부분을 구별하기 위해 제목(heading), 캡션, 문단에 사용될 수 있습니다.

예를 들어, 이전 문단의 첫 번째 단어가 문단의 나머지의 좀 더 자세한 텍스트로부터 그것을 구별하기 위해 strong으로 마크업 됩니다.

심각성: strong 요소(element)는 주의나 경고 안내를 마크업하는데 사용될 수 있습니다.

긴급성: strong 요소(element)는 사용자가 문서의 다른 부분들보다 빨리 볼 필요가 있는 콘텐츠를 표시하는데 사용될 수 있습니다.

콘텐츠의 부분의 중요성의 상대적 수준은 그것의 조상 strong 요소(element)들의 객수에 의해 주어집니다; 각 strong 요소(element)는 그것의 콘텐츠의 중요성을 증가시킵니다.

strong 요소(element)로 텍스트의 부분의 중요성을 변경하는 것은 문장의 의미(meaning)를 변경하지 않습니다.

여기, 단어 "chapter"와 실제 챕터 번호는 단순한 상투어에 불과하고, 챕터의 실제 이름이 strong으로 마크업 됩니다:
<h1>Chapter 1: <strong>The Praxis</strong></h1>

다음 예에서, 캡션 내의 도표의 이름이 상투적인 텍스트와 (앞) 설명을 (뒤) 구별하기 위해 strong으로 마크업됩니다:

<figcaption>Figure 1. <strong>Ant colony dynamics</strong>. The ants in this colony areaffected by the heat source (upper left) and the food source (lower right).</figcaption>

이 예에서, 제목(heading)은 실제로 "Flowers, Bees, and Honey"이지만, 작성자는 제목(heading)에 가벼운 마음으로 추가 사항을 추가했습니다. 따라서 strong 요소(element)는 나중 부분으로부터 그것을 구별하기 위해 첫 번째 부분을 마크업하는데 사용됩니다.

<h1><strong>Flowers, Bees, and Honey</strong> and other things I don’t understand</h1>
여기 얼마나 중요한지에 따라 마크업 된 다양한 부분을 가진 게임의 주의 안내의 예가 있습니다:
<p><strong>Warning.</strong> This dungeon is dangerous.
<strong>Avoid the ducks.</strong> Take any gold you find.
<strong><strong>Do not take any of the diamonds</strong>,
they are explosive and <strong>will destroy anything within
ten meters.</strong></strong> You have been warned.</p>
이 예에서, strong 요소(element)가 사용자가 먼저 읽도록 의도 된 텍스트의 일부를 나타내는데 사용됩니다.
<p>Welcome to Remy, the reminder system.</p>
<p>Your tasks for today:</p>
<ul>
  <li><p><strong>Turn off the oven.</strong></p></li>
  <li><p>Put out the trash.</p></li>
  <li><p>Do the laundry.</p></li>
</ul>

4.5.4. small 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
어구(phrasing) 콘텐트가 기대되는 곳.
콘텐트 모델:
어구(phrasing) 콘텐트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLElement를 사용.

small 요소(element)는 작은 글자 부분 같은 보조 코멘트들을 나타냅니다.

작은 글자 부분은 일반적으로 고지 사항들, 경고 사항들, 법적 제한 사항들, 저작권들의 특징을 가집니다. 작은 글자 부분은 또한 때때로 속성(attribution)에 대해 혹은 저작권 요구사항들을 만족시키는 것에 대해 사용됩니다.

small 요소(element)는 "덜 강조"하거나, em 요소(element)에 의해 강조되거나 strong 요소(element)로 중요한 것으로 표기 된 텍스트의 중요도를 감소시키지 않습니다. 강조 혹은 중요하지 않은 것으로 텍스트를 표기하려면, 단순히 각각 em이나 strong 요소(element)들로 그것을 마크업 하지 않으면 됩니다.

small 요소(element)는 여러 문단들, 목록들, 텍스트의 섹션들 같은 텍스트의 확장된 범위에 사용되지 않아야(must) 합니다. 이것은 일련의 짧은 텍스트에만 의도된 것입니다. 예를 들어, 사용 약관들을 나열하는 페이지의 텍스트는 small 요소(element)들에 적합한 후보가 아닐 것입니다: 그러한 경우, 텍스트는 보조 코멘트가 아니며, 페이지의 주요 콘텐트입니다.

이 예에서, small 요소(element)는 부가 가치세가 호텔 방의 가격에 포함되어 있지 않음을 나타내기 위해 사용됩니다:
<dl>
  <dt>Single room
  <dd>199 € <small>breakfast included, VAT not included</small>
  <dt>Double room
  <dd>239 € <small>breakfast included, VAT not included</small>
</dl>
이 두 번째 예에서, small 요소(elmeent)는 아티클의 보조 코멘트로 사용됩니다.
<p>Example Corp today announced record profits for the
second quarter <small>(Full Disclosure: Foo News is a subsidiary of
Example Corp)</small>, leading to speculation about a third quarter
merger with Demo Group.</p>

이것은 여러 문단들이 될 수 있고 테스트의 주요 흐름으로부터 제거되는 사이드바와 구별됩니다. 다음 예에서, 동일한 아티클의 사이드바를 볼 수 있습니다. 이 사이드바는 또한 사이드바 내의 정보의 소스를 나타내는 작은 글자 부분을 가집니다.

<aside>
  <h1>Example Corp</h1>
  <p>This company mostly creates small software and Web
  sites.</p>
  <p>The Example Corp company mission is "To provide entertainment
  and news on a sample basis".</p>
  <p><small>Information obtained from <a
  href="https://example.com/about.html">example.com</a> home
  page.</small></p>
</aside>

이 마지막 예에서, small 요소(element)는 중요한 작은 글자 부분이 되는 것으로 표기됩니다.

<p><strong><small>Continued use of this service will result in a kiss.</small></strong></p>

4.5.5. s 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
어구(phrasing) 콘텐트가 기대되는 곳.
콘텐트 모델:
어구(phrasing) 콘텐트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
Any aria-* attributes applicable to the allowed roles.
DOM 인터페이스:
HTMLElement를 사용.

s 요소(element)는 더 이상 정확하지 않거나 더 이상 관련이 없는 콘텐츠를 나타냅니다.

s 요소(element) 문서 편집을 나타내는 경우 적절하지 않습니다; 문서로부터 제거된 테스트의 범위를 표현하기 위해서는 del 요소(element)를 사용하세요.

이 예에서 궈장 소매가는 새로운 할인 가를 가지는 문제의 상품에 더 이상 관련이 없는 것으로 표기됩니다.
<p>Buy our Iced Tea and Lemonade!</p>
<p><s>Recommended retail price: $3.99 per bottle</s></p>
<p><strong>Now selling for just $2.99 a bottle!</strong></p>

4.5.6. cite 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
어구(phrasing) 콘텐트가 기대되는 곳.
콘텐트 모델:
어구(phrasing) 콘텐트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLElement를 사용.

cite 요소(element)는 창작물에 대한 참조를 나타냅니다. 그것은 작업물이나 작성자나 (개인, 사람들 혹은 단체) URL 참조의 제목이나 출처(citation) 메타데이터의 추가에 사용된 규칙에 따라 축약된 구성의 참조를 포함해야(must) 합니다.

창작물은 책, 신문, 에세이, 시, 악보, 노래, 대본, 영화, TV 쇼, 게임, 조각품, 그림, 공연 작품, 연극, 오페라, 뮤지컬, 전시회, 법률 사건 보고서, 컴퓨터 프로그램, 웹 사이트, 웹 페이지, 블로그 게시물이나 댓글, 포럼 게시물이나 댓글, 트윗, 기록물이나 구술서 등등을 포함합니다.

여기 cite 요소(element)를 사용하여 참조된 인용구(quote)의 작성자의 예입니다:
<p>In the words of <cite>Charles Bukowski</cite> -
<q>An intellectual says a simple thing in a hard way. An artist says a hard thing in a simple way.</q></p>
이 두 번째 예제는 cite 요소(element)를 사용하여 작성자 이름을 참조하는 것에 의해 트윗의 작성자를 식별합니다:
<blockquote class="twitter-tweet">
<p>♥ Bukowski in <a href="https://twitter.com/search?q=%23HTML5&src=hash">#HTML5</a> spec examples
<a href="https://t.co/0FIEiYN1pC">https://t.co/0FIEiYN1pC</a></p><cite>— karl dubost (@karlpro)
<a href="https://twitter.com/karlpro/statuses/370905307293442048">August 23, 2013</a></cite>
</blockquote>
이 예에서 cite 요소(element)는 참고문헌에서 작품의 제목을 참조하는데 사용됩니다:
<p><cite>Universal Declaration of Human Rights</cite>, United Nations,
December 1948. Adopted by General Assembly resolution 217 A (III).</p>
이 예에서 cite 요소(element)는 텔레비젼 쇼의 제목을 참조하는데 사용됩니다:
<p>Who is your favorite doctor (in <cite>Doctor Who</cite>)?</p>
cite 요소(element)에 대한 매우 일반적인 사용은 이 예에서와 같이 블로그 게시물이나 포럼에 댓글의 작성자를 식별하는 것입니다:
<article id="comment-1">
  Comment by <cite><a href="https://oli.jp">Oli Studholme</a></cite>
  <time datetime="2013-08-19T16:01">August 19th, 2013 at 4:01 pm</time>
  <p>Unfortunately I don’t think adding names back into the definition of <code>cite</code>
  solves the problem: of the 12 blockquote examples in
  <a href="https://oli.jp/example/blockquote-metadata/">Examples of block quote metadata</a>,
  there’s not even one that’s <em>just</em> a person’s name.</p>
  <p>A subset of the problem, maybe…</p>
</article>
cite 요소(element)의 다른 일반적인 사용은 이 예에서와 같이, 검색 결과의 URL을 참조하는 것입니다:
<div id="resultStats">About 416,000,000 results 0.33 seconds) </div>
...
<p><a href="https://www.w3.org/html/wg/">W3C <i>HTML Working Group</i></a></p>
<p><cite>www.w3.org/<b>html</b>/wg/</cite></p>
<p>15 Apr 2013 - The <i>HTML Working Group</i> is currently chartered to continue its
work through 31 December 2014. A Plan 2014 document published by the...</p>
...
cite 요소(element)는 Ibid와 같은 축약된 참조를 식별하는 데 사용됩니다. 이것은 이 참조가 기본 참조에 연결되는 것이 좋습니다:
<article>
  <h2>Book notes</h2>
  ...
  ...
  <blockquote>"Money is the real cause of poverty,"
  <footer>
  <cite id="baseref">The Ragged-Trousered Philanthropists, page 89.</cite>
  </footer>
  </blockquote>
  ...
  ...
  <blockquote>"Money is the cause of poverty because it is the device by which those who
  are too lazy to work are enabled to rob the workers of the fruits of their labour."
  <a href="#baseref"><cite>Ibid.</cite></a>
  </blockquote>
  ...
</article>

출처(citation)인용(quote)이 (q 요소(element)가 적절한) 아닙니다.

cite는 인용(quote)들이 아니기 때문에, 잘못된 사용법입니다:
<p><cite>This is wrong!, said Hillary.</cite> is a quote from the
popular daytime TV drama When Ian became Hillary.</p>

이것이 올바른 사용법의 예입니다:

<p><q>This is correct, said Hillary.</q> is a quote from the
popular daytime TV drama <cite>When Ian became Hillary</cite>.</p>

4.5.7. q 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
어구(phrasing) 콘텐트가 기대되는 곳.
콘텐트 모델:
어구(phrasing) 콘텐트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
cite - 인용구의 소스나 편집에 대한 추가 정보로의 링크
허용된 ARIA 역할(role) 속성(attribute) 값들:
모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLQuoteElement를 사용.

q 요소(element)는 다른 소스로부터 인용된 일부 어구(phrasing) 콘텐트나타냅니다.

요소(element)의 콘텐츠를 인용하는 인용 구두점(인용 부호 같은)은 q 요소(element)들의 즉시 앞, 뒤, 안에 나타나지 않아야(must) 합니다; 그것들은 유저 에이전트에 의한 렌더링에 삽입될 것입니다.

q 요소(element) 내의 콘텐트는 다른 소스로부터 인용되어야(must)하고, 주소를 가진다면 주소는 cite 속성(attribute)에 인용될 수 있습니다. 소스는 소설이나 시나리오의 등장 인물들을 인용할 때 처럼, 허구적일 수 있습니다.

cite 속성(attribute)이 존재한다면, 그것은 유효한 잠정적으로 공백으로 둘러 싸일 수 있는 URL이어야(must) 합니다. 해당하는 출처 링크를 얻기 위해, 속성(attribute)의 값은 요소(element)의 노드 문서에 관련하여 해석되어야(must) 합니다. 유저 에이전트는 사용자가 그 출처 링크들을 따라가는 것을 허용할 수 있지만, 그것들은 주로 특정한 사용을 위해 (예를 들어, 사이트의 인용들 사용에 대한 통계를 수집하는 서버 사이드 스크립트에 의해) 의도된 것이지, 독자들을 위한 것이 아닙니다.

q 요소(element)는 인용(quote)들을 나타내지 않는 인용 부호 위치에 사용되지 않아야(must) 합니다; 예를 들어, 비꼬는 문장들을 마크업하기 위해 q 요소(element)를 사용하는 것은 부적절합니다.

인용구(quotation)들을 마크업하기 위한 q 요소(element)들의 사용은 전적으로 선택적입니다; q 요소(element) 없이 명시적 인용 구두점을 사용하는 것은 적절합니다.

여기 q 요소(element)의 사용의 간단한 예가 있습니다:
<p>The man said <q>Things that are impossible just take
longer</q>. I disagreed with him.</p>
여기 q 요소(element) 안에 명시적인 출처(citation) 링크와, 밖에 명시적인 출처(citation)를 모두 가진 예가 있습니다:
<p>The W3C page <cite>About W3C</cite> says the W3C’s
mission is <q cite="https://www.w3.org/Consortium/">To lead the
World Wide Web to its full potential by developing protocols and
guidelines that ensure long-term growth for the Web</q>. I
disagree with this mission.</p>
다음 예에서, 인용구(quotation) 자체가 인용구(quotation)를 포함합니다:
<p>In <cite>Example One</cite>, he writes <q>The man
said <q>Things that are impossible just take longer</q>. I
disagreed with him</q>. Well, I disagree even more!</p>
다음 예에서, 인용 부호들이 q 요소(element) 대신 사용됩니다:
<p>His best argument was ❝I disagree❞, which
I thought was laughable.</p>
다음 예에는, 인용(quote)이 없습니다 — 인용 부호들은 단어를 이름을 지정하는데 사용됩니다. 이 경우에 q 요소(element)의 사용은 적절하지 않을 것입니다.
<p>The word "ineffable" could have been used to describe the disaster
resulting from the campaign’s mismanagement.</p>

4.5.8. dfn 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
어구(phrasing) 콘텐트가 기대되는 곳.
콘텐트 모델:
어구(phrasing) 콘텐트, dfn 후손 요소(element)들이 없어야(must) 합니다.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
또한, title 속성(attribute)은 이 요소(element)에서 특별한 의미(semantics)를 가집니다.
허용된 ARIA 역할(role) 속성(attribute) 값들:
모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLElement를 사용.

dfn 요소(element)는 용어의 정의 사례를 나타냅니다. dfn 요소(element)의 가장 가까운 조상 문단, 설명 목록 그룹, 섹션은 또한 dfn 요소(element)에 의해 주어진 용어에 대한 정의(들)를 포함해야(must) 합니다.

정의 용어: dfn 용어(element)가 title 속성(attribute)을 가진다면, 그 속성(attribute)의 정확한 값은 정의되는 용어입니다. 그렇지 않고, 그것이 정확히 한 개 자식 요소(element) 노드를 가지고 자식 Text 노드들을 가지지 않으며, 그 자식 요소(element)가 title 속성(attribute)을 가진 abbr 요소(element)라면, 속성(attribute)의 정확한 값은 정의되는 용어입니다. 그렇지 않으면, 그것은 정의되는 용어를 제공하는 dfn 요소(element)의 정확한 textContent입니다.

dfn 요소(element)의 title 속성(attribute)이 존재한다면, 그것은 정의되는 용어만을 포함해야(must) 합니다.

조상 요소(element)들의 title 속성(attribute)은 dfn 요소(element)들에 영향을 주지 않습니다.

dfn 요소(element)로 연결하는 a 요소(element)는 dfn 요소(element)에 의해 정의된 용어의 사례를 나타냅니다.

다음 코드 조각에서, 용어 "Garage Door Opener"는 첫 번째 문단에서 처음 정의되고, 이후 두 번째 문단에서 사용됩니다. 두 모든 경우에, 그것의 축약어는 실제로 보여지는 것입니다.
<p>The <dfn><abbr title="Garage Door Opener">GDO</abbr></dfn>
is a device that allows off-world teams to open the iris.</p>
<!-- ... later in the document: -->
<p>Teal’c activated his <abbr title="Garage Door Opener">GDO</abbr>
and so Hammond ordered the iris to be opened.</p>

a 요소(element)의 추가 사항을 가지고, 참조가 명시적으로 될 수 있습니다:

<p>The <dfn id=gdo><abbr title="Garage Door Opener">GDO</abbr></dfn>
is a device that allows off-world teams to open the iris.</p>
<!-- ... later in the document: -->
<p>Teal’c activated his <a href=#gdo><abbr title="Garage Door Opener">GDO</abbr></a>
and so Hammond ordered the iris to be opened.</p>

4.5.9. abbr 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
어구(phrasing) 콘텐트가 기대되는 곳.
콘텐트 모델:
어구(phrasing) 콘텐트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
Also, the title attribute has special semantics on this element.
허용된 ARIA 역할(role) 속성(attribute) 값들:
모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLElement를 사용.

abbr 요소(element)는 선택적으로 그것의 본디말을 가지고, 축약어나 두문자어를 나타냅니다. title 속성(attribute)은 축약어의 본디말을 제공하는데 사용될 수 있습니다. 속성(attribute)이 명시되었다면, 속성(attribute)은 축약어의 본디말을 포함해야(must)하고, 그렇지 않으면 아무 것도 포함하지 않아야(must) 합니다.

아래 문단은 abbr 요소(element)로 마크업 된 축약어를 포함합니다. 이 문단은 "Web Hypertext Application Technology Working Group" 용어를 정의합니다.
<p>The <dfn id=whatwg><abbr
title="Web Hypertext Application Technology Working Group">WHATWG</abbr></dfn>
is a loose unofficial collaboration of Web browser manufacturers and
interested parties who wish to develop new technologies designed to
allow authors to write and deploy Applications over the World Wide
Web.</p>

이를 작성하기 위한 또 다른 동등한 방법은 다음과 같을 것입니다:

<p>The <dfn id=whatwg>Web Hypertext Application Technology
Working Group</dfn> (<abbr
title="Web Hypertext Application Technology Working Group">WHATWG</abbr>)
is a loose unofficial collaboration of Web browser manufacturers and
interested parties who wish to develop new technologies designed to
allow authors to write and deploy Applications over the World Wide
Web.</p>
이 문단은 두 축약어들을 가집니다. 오직 하나만 정의되는 방식에 주목하세요; 그것과 연관된 본디말이 없는 다른 하나는 abbr 요소(element)를 사용하지 않습니다.
<p>The
<abbr title="Web Hypertext Application Technology Working Group">WHATWG</abbr>
started working on HTML in 2004.</p>
이 문단은 축약어를 그것의 정의로 연결합니다.
<p>The <a href="#whatwg"><abbr
title="Web Hypertext Application Technology Working Group">WHATWG</abbr></a>
community does not have much representation from Asia.</p>
이 문단은 아마도 축약어들에 대해 스타일을 적용하기 위한 (예를 들어, 작은 대문자) 훅(hook)이기 때문에, 본디말을 제공하는 것 없이 축약어를 마크업합니다.
<p>Philip and Dashiva both denied that they were going to
get the issue counts from past revisions of the specification to
backfill the <abbr>WHATWG</abbr> issue graph.</p>

축약어가 복수형이라면, 본디말의 문법에 맞는 수는 (복수 vs 단수) 요소(element)의 콘텐츠의 문법에 맞는 수와 일치해야(must) 합니다.

여기 복수는 요소(element) 밖이고, 본디말은 단수입니다:
<p>Two <abbr title="Working Group">WG</abbr>s worked on
this specification: the <abbr>WHATWG</abbr> and the
<abbr>HTMLWG</abbr>.</p>

여기 복수는 내부 요소(element)이고 본디말은 복수입니다:

<p>Two <abbr title="Working Groups">WGs</abbr> worked on
this specification: the <abbr>WHATWG</abbr> and the
<abbr>HTMLWG</abbr>.</p>

축약어는 이 요소(element)를 사용하여 마크업 될 필요는 없습니다. 이것은 다음 경우들에서 유용할 것으로 기대됩니다:

  • 본디말을 인라인으로 (예를 들어, 괄호 안에) 포함하기 위한 대안 인 title 속성(attribute)을 가진 abbr 요소(element)를 사용하는 경우, 작성자가 본디말들을 제공하기 원하는 축약어들.

  • 작성자들이 title 속성(attribute)을 가진 abbr 요소(element)를 사용하는 축약어를 마크업 하도록 권장되거나 확장이 사용되는 첫 번째 텍스트 내에 본디말이 인라인으로 포함시키도록 권장되는 문서의 독자들에게 익숙하지 않을 것 같은 축약어들.

  • 의미론적으로 주석이 달릴 필요가 있는 축약어들, 예를 들어, 때문에 스타일시트와 주어진 특정 스타일로부터 식별될 수 있는, title 속성(attribute)이 없이 사용 될 수 있는 abbr 요소(element).

한 번 title 속성(attribute)에 본디말을 제공하는 것은 동일한 콘텐츠를 가지지만 title 속성(attribute)이 없는 동일 문서의 다른 abbr 요소(element)들이 필연적으로 동일한 본디말을 가지는 것 처럼 동작하는 것을 야기시키지 않을 것입니다. 매 abbr 요소(element)는 독립적입니다.

4.5.10. ruby 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
어구(phrasing) 콘텐트가 기대되는 곳.
콘텐트 모델:
본문 참고.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLElement를 사용.

ruby 요소(element)는 루비 주석으로 마크업 되는 하나 이상의 어구 콘텐트의 범위를 허용합니다. 루비 주석들은 주로 발음에 대한 혹은 다른 주석들에 포함시키기 위한 지침으로서 동아시아 글자에 사용 된 기본 텍스트와 나란히 표현된 짧은 일련의 텍스트입니다. 일본어에서, 이 글자의 형식은 또한 후리가나로 알려져 있습니다. 루비 텍스트는 기본 텍스트의 사이드, 양쪽 사이드 모두에 나타날 수 있고, CSS를 사용하여 그것의 위치를 제어할 수 있습니다. 루비에 대한 더 완벽한 소개는 루비 마크업에 대한 사용법들 & 탐색적 접근법들 문서뿐 아니라 CSS Ruby에서 찾을 수 있습니다. [RUBY-UC] [CSS3-RUBY]

ruby 요소(element)들의 콘텐트 모델은 하나 이상의 다음 시퀀스들로 구성됩니다:

  1. 하나 이상의 어구(phrasing) 콘텐트 노드들이나 rb 요소(element)들.

  2. rp 요소(element)가 즉시 앞서거나 즉시 뒤따르는, 하나 이상의 rtrtc 요소(element)들.

아래 설명된 특정한 (결코 이에 국한되지 않지만) 것들을 포함하여, ruby, rb, rtc, rt 요소(element)들은 다양한 주석들에 사용될 수 있습니다. 특히, 일본어 루비에 자세한 사항들과 일본어에 대한 루비를 표현하는 방법에 대해, 일본어 텍스트 레이아웃에 대한 요구사항들을 참조하세요. [JLREQ] rp 요소(element)는 루비 렌더링이 지원되지 않는 경우 폴백으로 사용될 수 있습니다.

각 기본 문자들에 대한 모노 루비

주석들은 (루비 텍스트) 각 표의 문자 (기본 텍스트)와 개별적으로 연관됩니다. 일본어에서 이것은 일반적으로 칸지 문자들의 독음을 제공하는데 사용되는 히라가나나 카타카나 문자들입니다.

<ruby>base<rt>annotation</ruby>

rb 요소(element)가 사용되지 않는 경우, 기본 텍스트는 위와 같이 암묵적입니다. 하지만 그것을 명시적으로 만들 수도 있습니다. 이것은 특히 스타일링 하거나, 더 아래의 쥬쿠고(じゅくご, 숙어)에서와 같이, 연이은 기본 텍스트들이 그룹으로 취급되는 경우에 유용할 수 있습니다.

<ruby><rb>base<rt>annotation</ruby>

다음 예에서, 각 주석이 단일 기본 문자에 일치하는 방식에 주목하세요.

<ruby><rt></rt></ruby><ruby><rt>ほん</rt></ruby>
<ruby><rt></rt></ruby><ruby><rt></rt></ruby>
いた<ruby><rt>さく</rt></ruby><ruby><rt>ぶん</rt></ruby>です。

일반 텍스트에 배치된 루비 텍스트는 다음 이미지와 유사한 구조를 제공합니다:

일반 텍스트와 혼합된 루비의 예.

이 예는 각각 한 개의 기본 텍스트 세그먼트와 주석을 가진 (위 마크업에서 처럼) 두 개의 다닥다닥 붙은 ruby 요소(element)들 대신, 다음과 같이 기본 텍스트의 두 세그먼트들과 두 주석을 (각각에 대해 하나씩) 가진 한 개 ruby 요소(element)를 사용하여 작성될 수도 있습니다:

<ruby><rt></rt><rt>ほん</rt><rt></rt></ruby><ruby><rt></rt></ruby>
いた<ruby><rt>さく</rt><rt>ぶん</rt></ruby>です。

그룹 루비

그룹 루비는 종종 표음 주석들이 적당한 기본 문자들에 일치되지 않는 경우에, 혹은 전체 기본 텍스트에 걸친 시맨틱 어휘들에 대해 사용됩니다. 예를 들어, 단어 "today"는 문자 그대로 "this day"인 문자 今日로 작성됩니다. 하지만, 그것은 "this" 부분과 "day" 부분으로 분해될 수 없는 きょう (kyou)라고 발음됩니다. 일반적인 표현에서, 그룹 루비로 주석이 달린 텍스트를 분리할 수 없습니다; 그것은 다음 행 위에 단일 개체로 감싸져야(has to) 합니다. 루비 텍스트 주석은 하나 이상의 문자로 구성 된 기본 텍스트에 일치하는 경우, 그 기본 텍스트는 그룹화 된 것입니다.

다음 그룹 루비는:

きょう로 주석을 다는 今日 그룹 루비 예

다음 과 같이 마크업 될 수 있습니다:

<ruby>今日<rt>きょう</ruby>

쥬쿠고 루비

쥬쿠고는 일본어 복합 명사를, 즉, 하나 이상의 칸지 문자로 구성된 단어를, 나타냅니다. 쥬쿠고 루비는 쥬쿠고 텍스트를 통해 루비 주석들을 설명하는데 사용되는 것이 아니라, 모노 혹은 그룹 루비와 약간 다른 행동을 가진 루비를 설명하는데 사용되는 용어입니다. 쥬쿠고 루비는 루비 텍스트와 각각의 기본 문자들 사이에 강한 연관이 있다는 점에서 모노 루비와 유사하지만, 루비 텍스트는 일반적으로 여러 표의 문자들이 같은 행에 있는 경우 표의 문자들 위에 함께 그룹화되어 표현됩니다.

이 예에서 차이가 포착됩니다:

Example of jukugo ruby

다음과 같이 마크업 될 수 있습니다:

<ruby><rb><rb><rt><rt><rt>きょう</ruby>

이 예에서, 각 rt 요소(element)는 그것의 각 rb 요소(element)와 쌍을 이루고, 두 기본 텍스트의 시퀀스와 루비 주석들이 되는 교차된 rb/rt 접근 방식의 차이점은 일반적인 컨테이너에 암묵적으로 위치되기 때문에 그룹화 정보가 포착된다는 것입니다.

쥬쿠고 루비 표현에 대한 더 자세한 사항들에 대해서는, 일본 텍스트 레이아웃에 대한 요구사항들의 부록 F와 루비 마크업에 대한 사용법들 & 탐색적 접근법들의 사용법 C: 쥬쿠고 루비를 참고하세요. [JLREQ] [RUBY-UC]

인라인 루비

일부 컨텍스트들에서, 예를 들어, 글자 크기나 행 높이가 루비를 읽기에 너무 작은 경우, 루비가 텍스트 뒤의 괄호에 주석이 나타나는 인라인 루비 주석이 바람직합니다. 이것은 또한 루비 주석들의 렌더링을 지원하지 않는 유저 에이전트에 대한 간편한 폴백 방법을 제공합니다.

인라인 하는 것은 그룹화를 고려합니다. 예를 들어 도쿄는 とう로 발음되는 東, きょう로 발음되는 京 두 칸지 문자로 작성됩니다. 각 기본 문자는 개별적으로 주석이 달려야(should) 하지만 폴백은 東(とう)京(きょう)가 아니라 東京(とうきょう)가 되어야(should) 합니다. 이것은 다음과 같이 마크업 될 수 있습니다:

<ruby><rb><rt>とう<rt>きょう</ruby>

위 마크업은 루비 레이아웃을 지원하는 브라우저들에 대해 인라인 하는 경우 괄호들의 사용을 가능하게 하지만, 이를 지원하지 않는 브라우저에 대해서는 괄호 폴백을 제공하는데 실패하게 될 것에 주목하세요. 이것은 rp 요소(element)가 유용한 경우입니다. 루비 레이아웃이 제공되지 않는 경우 적절한 폴백을 제공하기 위해 위 예에 그것이 삽입 될 수 있습니다:

<ruby><rb><rp>(<rt>とう<rt>きょう<rp>)</ruby>

독음과 의미 주석을 모두 가지는 텍스트 (양쪽 사용이 가능한 루비)

때때로, 루비는 기본 텍스트에 두 번 주석을 다는데 사용 될 수 있습니다.

다음 예에서, San Francisco에 대한 중국어는 (旧金山, 즉, "old gold mountain") 발음을 제공하는 핀인(중국어의 로마자 표기법)과 본래의 영어를 사용하여 주석이 달립니다.

주석으로 핀인과 원래 영어를 모두 가진, 중국어로 San Francisco

다음과 같이 마크업 됩니다:

<ruby><rb><rb><rb><rt>jiù<rt>jīn<rt>shān<rtc>San Francisco</ruby>

이 예에서, 일련의 세 개의 기본 문자들의 기본 텍스트는 첫 번째 (암묵적) 컨테이너의 세 핀인 루비 텍스트 세그먼트로 주석이 달리고, rtc 요소(element)는 도시의 영어 이름이 되는 두 번째 단일 루비 텍스트 주석을 제공하기 위해 도입됩니다.

또한 동시에 기본 문자들과 그룹화 정보 주석의 쌍을 유지하는 반면 카나와 로마지 발음 모두에 주석이 사용될 수 있는 방법을 보여주기 위해 위 쥬쿠고 예를 上手 ("skill")를 가지고 다시 논의 할 수 있습니다.

上手 ("skill") annotated in both kana and romaji, shown in both jukugo and mono styles.

다음과 같이 마크업 됩니다:

<ruby><rb><rb><rt>じよう<rt><rtc><rt>jou<rt>zu</ruby>

rtc 요소(element)의 직속 자식인 텍스트는 그것이 rt 요소(element)에 포함되어 있던 것 처럼, 암묵적으로 루비 텍스트 세그먼트를 생성합니다. 이 인워적인 예에서, 이것은 기본 심볼의 양쪽에 나타나도록 의도된 주석들을 가지고 영어와 프랑스어로 이름이 주어진 일부 기호들로 보여집니다.

<ruby><rt>Heart<rtc lang=fr>Cœur</rtc><rt>Shamrock<rtc lang=fr>Trèfle</rtc><rt>Star<rtc lang=fr>Étoile
</ruby>

유사하게, ruby 요소(element) 바로 내부의 텍스트는 rb 요소(element)에 포함되어 있던 것 처럼 암묵적으로 루비 기본 문자를 생성하고, ruby의 자식 rt는 암묵적으로 rtc 컨테이너에 포함됩니다. 사실 상, 위 예는 다음과 동등합니다 (의미적으로, DOM에서 생성되는 것은 아니기는 하지만):

<ruby>
  <rb></rb><rtc><rt>Heart</rt></rtc><rtc lang=fr><rt>Cœur</rt></rtc>
  <rb></rb><rtc><rt>Shamrock</rt></rtc><rtc lang=fr><rt>Trèfle</rt></rtc>
  <rb></rb><rtc><rt>Star</rt></rtc><rtc lang=fr><rt>Étoile</rt></rtc>
</ruby>

루비 요소(element) 내에서, 콘텐트는 일련의 루비 세그먼트들로 나누어 집니다. 각 루비 세그먼트는 다음에 의해 기술됩니다:
  • 각각이 어구(phrasing) 콘텐트나 rb 요소(element)를 포함할 수 있는 DOM 범위인, 0개 이상의 루비 기본 문자들

  • 기본 문자 범위는 모든 기본 문자들을 포함하는 DOM 범위 입니다. 이것은 루비 기본 컨테이너입니다.

  • 명시적인 rtc 요소(element)에 해당하거나, 루비 텍스트 컨테이너에 포함될 때 암묵적으로 인식된 rt 요소(element)의 시퀀스들일 수 있는 0개 이상의 루비 텍스트 컨테이너들.

루비 텍스트 컨테이너는 각각이 어구(phrasing) 콘텐트나 rt 요소(element)를 포함할 수 있는 DOM 범위인 0개 이상의 루비 텍스트 주석들과 그 컨테이너에 대한 모든 주석들을 포함하는 범위인 주석 범위에 의해 기술됩니다. 루비 텍스트 컨테이너는 또한 루비 주석 컨테이너로 (주로 CSS 컨텍스트에서) 알려져 있습니다.

뿐만 아니라, 루비 요소(element)는 무시된 루비 콘텐트를 포함합니다. 무시된 루비 콘텐트는 문서의 의미론의 일부를 구성하지 않습니다. 이는 뒤 쪽의 것이 루비를 전혀 지원하지 않는 유저 에이전트에 사용되는 몇몇의 요소(element) 간 여백rp 요소(element)들로 구성됩니다.

주석 쌍의 처리는 루비 주석들루비 기본 문자를 연관짓흡니다. 각 루비 세그먼트 내에서, 루비 기본 문자 컨테이너 내의 각 루비 베이스는 순서에 따라 루비 텍스트 컨테이너의 한 개 루비 텍스트 주석과 짝지어 집니다. 루비 주석 컨텐이너루비 텍스트 주석들이 충분하지 않다면, 마지막 것은 초과분의 루비 기본 문자들과 연관되어집니다. (루비 주석 컨텐이너에 어떠한 것도 없다면, 익명의 빈 것이 존재한다고 가정됩니다.) 루비 기본 문자들이 충분하지 않다면, 모든 나머지 루비 텍스트 주석들루비 기본 문자 컨테이너의 끝에 삽입된 익명의 기본 문자인 빈 것과 연관되는 것으로 간주됩니다.

용어 루비 세그먼트, 루비 기본 문자, 루비 텍스트 주석, 루비 텍스트 컨테이너, 루비 기본 컨테이너, 루비 주석 컨테이너CSS 루비 모듈 레벨 3에서 그것들과 동등한 것들을 가지는 것에 주목하세요. [CSS3-RUBY]

비공식적으로, 분할과 분류 알고리즘은 아래 작업들의 간단한 설정을 수행합니다. 먼저 기본 문자들의 목록 내의 인접한 rb 요소(element)들, 텍스트 노드들, 비 루비 요소(element)들을 처리합니다. 이후, 자동으로 익명 루비 텍스트 컨테이너에 매핑되는 것으로 간주된 많은 rtc 요소(element)들이나 rt 요소(element)들의 시퀀스들을 처리합니다. 위 데이터 모델에서 설명된 대로 루비 세그먼트를 형성하는 이 데이터 항목들을 묶습니다. 주어진 ruby 요소(element)의 콘텐트의 끝에 도달할 때까지 그러한 세크먼트들을 계속 생성할 것입니다. 이 비공식적인 설명과 비교되는 아래 알고리즘의 복잡성은 작성자에게 친숙한 문접의 지원과 요소(element) 간 여백을 염두하는 필요에서 기인합니다.

임의의 특정 시간에, ruby 요소(element)의 콘텐트의 분할과 분류는 다음 알고리즘을 수행한 것으로부터 얻어지는 결과입니다:

  1. root를 알고리즘이 실행되는 ruby 요소(element)로 둡니다.
  2. index를 0으로 둡니다.
  3. ruby segments를 빈 목록으로 둡니다.
  4. current bases를 DOM 범위들의 빈 목록으로 둡니다.
  5. current bases range를 null로 둡니다.
  6. current bases range start를 null로 둡니다.
  7. current annotations를 DOM 범위들의 빈 목록으로 둡니다.
  8. current annotations range를 null로 둡니다.
  9. current annotations range start를 null로 둡니다.
  10. current annotation containers를 빈 목록으로 둡니다.
  11. current automatic base nodes를 DOM 범위들의 빈 목록으로 둡니다.
  12. current automatic base range start를 null로 둡니다.
  13. 자식 루비 처리: indexroot 내 자식 노드들의 수보다 크거나 같다면, 루비 세그먼트를 커밋하기 위한 단계를 수행하고, ruby segments를 반환하고, 이 단계들을 중단합니다.
  14. current childrootindex번째 노드로 둡니다.
  15. current childText 노드가 아니고 Element 노드가 아니라면, index를 1 증가시키고 자식 루비 처리로 라벨링 된 단계로 건너뜁니다.
  16. current childrp 요소(element)라면, index를 1 증가시키고 자식 루비 처리로 라벨링 된 단계로 건너뜁니다. (이것은 현재 처리중인 범위에서 이 요소(element)를 포함하는 것의 효과를 가짐에 주목하세요. 이것은 잘못 위치된 rp가 올바르게 처리될 수 있도록 의도적으로 이루어집니다; 의미론적으로 그것들은 매 한가지로 무시됩니다.
  17. current childrt 요소(element)라면, 이 하위 단계들을 수행합니다:
    1. 자동 기본 문자 커밋을 위한 단계들을 수행합니다.
    2. 기본 범위 커밋을 위한 단계들을 수행합니다.
    3. current annotations가 비어있다면, current annotations range startindex의 값으로 설정합니다.
    4. 시작점경계점 (root, index)이고, 종료점경계점 (root, index + 1)인 새로운 DOM 범위를 생성하고, 그것을 current annotations의 끝에 추가(append)합니다.
    5. index을 1 증가시키고 자식 루비 처리로 라벨링 된 단계로 건너뜁니다.
  18. current childrtc 요소(element)라면, 이 하위 단계들을 수행합니다:
    1. 자동 기본 문자 커밋을 위한 단계들을 수행합니다.
    2. 기본 범위 커밋을 위한 단계들을 수행합니다.
    3. 현재 주석들 커밋을 위한 단계들을 수행합니다.
    4. 새로운 루비 주석 컨테이너를 생성합니다. 그것은 시작점경계점 (root, index)이고 종료점경계점 (root, index + 1)인 DOM 범위와 rtc 요소(element)를 처리하기 위한 단계들을 수행하여 반환된 주석들의 목록에 의해 형성됩니다. 이 새로운 루비 주석 컨테이너current annotation containers의 끝에 추가(append)합니다.
    5. index를 1 증가시키고 자식 루비 처리로 라벨링 된 단계로 건너뜁니다.
  19. current childText 노드이고, 요소(element) 간 여백이라면, 이 하위 단계들을 수행합니다:
    1. current annotations가 비어있지 않다면, index를 1 증가시키고 자식 루비 처리로 라벨링 된 단계로 건너뜁니다.
    2. 다음 하위 단계들을 수행합니다:
      1. lookahead indexindex의 값으로 설정합니다.
      2. 미리 보기: lookahead index를 1 증가시킵니다.
      3. lookahead indexroot 내의 자식 노드들의 수보다 크거나 같다면 이 하위 단계들을 중단합니다.
      4. peek childrootlookahead index번째 노드로 둡니다.
      5. peek childText 노드이고 요소(element) 간 여백이라면, 미리 보기로 라벨링 된 단계로 건너뜁니다.
      6. peek childrt 요소(element), 또는 rtc 요소(element), 또는 rp 요소(element)라면, indexlookahead index의 값으로 설정하고 자식 루비 처리로 라벨링 된 단계로 건너뜁니다.
  20. current annotations가 비어있지 않거나 current annotation containers가 비어있지 않다면, 루비 세그먼트 커밋을 위한 단계들을 수행합니다.
  21. current childrb 요소(element)라면, 이 하위 단계들을 수행합니다:
    1. 자동 기본 문자 커밋을 위한 단계를 수행합니다.
    2. current bases가 비어있다면, current bases range startindex의 값으로 설정합니다.
    3. 시작점경계점 (root, index)이고, 종료점경계점 (root, index + 1)인 새로운 DOM 범위를 생성하고, current bases의 끝에 추가(append)합니다.
    4. index를 1 증가시키고 자식 루비 처리로 라벨링 된 단계로 건너뜁니다.
  22. current automatic base nodes가 비어있다면, current automatic base range startindex의 값으로 설정합니다.
  23. current childcurrent automatic base nodes의 끝에 추가(append) 합니다.
  24. index를 1 증가시키고 자식 루비 처리로 라벨링 된 단계로 건너뜁니다.

위 단계가 루비 세그먼크 커밋에 응하는 경우, 알고리즘 내의 그 지점에서 다음 단계들을 수행함을 의미합니다:

  1. 자동 기본 문자 커밋을 위한 단계를 수행합니다.
  2. current bases, current annotations, current annotation containers가 모두 비어있다면, 이 단계들을 중단합니다.
  3. 기본 범위 커밋을 위한 단계들을 수행합니다.
  4. 현재 주석들 커밋을 위한 단계들을 수행합니다.
  5. 새로운 루비 세그먼트를 생성합니다. 이것은 current bases으로 설정된 기본 문자들의 목록과, current bases range로 설정된 DOM 범위와, current annotation containers 목록인 루비 주석 컨테이너들의 목록에 의해 기술됩니다. 이 새로운 루비 세그먼트ruby segments의 끝에 추가(append) 합니다.
  6. current bases를 빈 목록으로 둡니다.
  7. current bases range를 null로 둡니다.
  8. current bases range start를 null로 둡니다.
  9. current annotation containers를 빈 목록으로 둡니다.

위 단계들이 기본 범위 커밋에 응하는 경우, 이는 알고리즘 내의 그 지점에서 다음 단계들을 수행함을 의미합니다:

  1. current bases가 비어있다면, 이 단계들을 중단합니다.
  2. current bases range가 null이 아니라면, 이 단계들을 중단합니다.
  3. current bases range시작점경계점 (root, current bases range start)이고 종료점경계점 (root, index)인 DOM 범위로 둡니다.

위 단계들이 현재 주석들 커밋에 응하는 경우, 이는 알고리즘내의 그 지점에서 다음 단계들을 수행함을 의미합니다:

  1. current annotations이 비어있지 않고 current annotations range가 null 이라면 current annotations range시작점경계점 (root, current annotations range start)이고 종료점경계점 (root, index)인 DOM 범위로 둡니다.
  2. current annotations가 비어 있지 않다면, 새로운 루비 주석 컨테이너를 생성합니다. 이것은 current annotations로 설정된 주석 목록과 current annotations range로 설정 된 범위에 의해 기술됩니다. 이 새로운 루비 주석 컨테이너current annotation containers의 끝에 추가(append) 합니다.
  3. current annotations를 DOM 범위의 빈 목록으로 둡니다.
  4. current annotations range를 null로 둡니다.
  5. current annotations range start를 null로 둡니다.

위 단계들이 자동 기본 문자 커밋에 응하는 경우, 이는 알고리즘내의 그 지점에서 다음 단계들을 수행함을 의미합니다:

  1. current automatic base nodes가 비어있다면, 이 단계들을 중단합니다.
  2. current automatic base nodesText 노드들이 아닌 노드들이나 요소(element) 간 여백이 아닌 Text 노드들을 포함한다면, 이 하위 단계들을 수행합니다:
    1. current bases가 비어있다면, current bases range startcurrent automatic base range start의 값으로 설정합니다.
    2. 시작점경계점 (root, current automatic base range start)이고 종료점경계점 (root, index)인 새로운 DOM 범위를 생성하고, 그것을 current bases의 끝에 추가(append) 합니다.
  3. current automatic base nodes를 DOM 노드들의 빈 목록으로 둡니다.
  4. current automatic base range start를 null로 둡니다.

4.5.11. rb 요소(element)

카테고리:
없음.
이 요소(element)가 사용될 수 있는 컨텍스트:
ruby 요소(element)의 자식으로.
콘텐트 모델:
어구(phrasing) 콘텐트.
text/html에서 태그 생략:
rb 요소(element)의 종료 태그rb 요소(element)에 즉시rb, rt, rtc, 또는 rp 요소(element)가 뒤따르거나, 부모 요소(element)에 더 이상의 콘텐트가 존재하지 않는다면 생략될 수 있습니다.
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLElement를 사용.

rb 요소(element)는 루비 주석의 기본 텍스트 컴포넌트를 표기합니다. 이것이 ruby 요소(element)의 자식인 경우, 스스로는 아무 것도 나타내지 않지만, 부모 ruby 요소(element)가 그것나타내는 것을 결정하는 것의 일환으로 사용합니다.

ruby 요소(element)의 자식이 아닌 rb 요소(element)는 그것의 자식과 동일한 것을 나타냅니다.

4.5.12. rt 요소(element)

카테고리:
없음.
이 요소(element)가 사용될 수 있는 컨텍스트:
rubyrtc 요소(element)의 자식으로.
콘텐트 모델:
어구(phrasing) 콘텐트.
text/html에서 태그 생략:
rt 요소(element)의 종료 태그rt 요소(element)에 즉시 rb, rt, rtc 또는 rp 요소(element)가 뒤따르거나, 부모 요소(element)에 더 이상의 콘텐트가 존재하지 않는다면 생략 될 수 있습니다.
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLElement를 사용.

rt 요소(element)는 루비 주석의 루비 텍스트 컴포넌트를 표기합니다. 이것이 ruby 요소(element)의 자식이거나 ruby 요소(element)의 자식인 rtc 요소(element)의 자식인 경우, 그것은 스스로는 아무 것도 나타내지 않지만, 조상 ruby 요소(element)가 그것나타내는 것을 결정하는 것의 일환으로 사용합니다.

ruby 요소(element)의 자식이 아닌 rt 요소(element)나 ruby 요소(element)의 자식 rtc 요소(element)의 자식이 아닌 rt 요소(element)는 그것의 자식과 동일한 것을 나타냅니다.

4.5.13. rtc 요소(element)

카테고리:
없음.
이 요소(element)가 사용될 수 있는 컨텍스트:
ruby 요소(element)의 자식으로.
콘텐트 모델:
어구(phrasing) 콘텐트, rt, rp 요소(element)들.
text/html에서 태그 생략:
rtc 요소(element)의 종료 태그rtc 요소(element)에 rbrtc 요소(element)가 즉시 뒤따르거나 부모 요소(element)에 더 이상의 콘텐트가 없다면 생략 할 수 있습니다.
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLElement를 사용.

rtc 요소(element)는 루비 주석 내 루비 텍스트 컴포넌트들에 대한 루비 텍스트 컨테이너를 표기합니다. 이것이 ruby 요소(element)의 자식인 경우, 그것은 스스로는 아무 것도 나타내지 않지만, 조상 ruby 요소(element)가 그것나타내는 것을 결정하는 것의 일환으로 사용합니다.

ruby 요소(element)의 자식이 아닌 rtc 요소(element)는 그것의 자식과 동일한 것을 나타냅니다.

rtc 요소(element)가 ruby 요소(element)에 대한 콘텐트의 분할과 분류의 일부로 처리되는 경우, 다음 알고리즘은 rtc 요소(element)를 처리하는 방법을 정의합니다:

  1. root를 알고리즘이 수행되는 rtc 요소(element)로 둡니다.
  2. index를 0으로 둡니다.
  3. annotations를 DOM 범위들의 빈 목록으로 둡니다.
  4. current automatic annotation nodes를 DOM 범위들의 빈 목록으로 둡니다.
  5. current automatic annotation range start를 null로 둡니다.
  6. rtc 자식 처리: indexroot 내 자식 노드들의 수보다 크거나 같다면, 자동 주석 커밋을 위한 단계들을 수행하고, annotations를 반환하고, 이 단계들을 중단합니다.
  7. current childrootindex번째 노드로 둡니다.
  8. current childrt 요소(element)라면, 이 하위 단계들을 수행합니다:
    1. 자동 주석 커밋을 위한 단계들을 수행합니다.
    2. 시작점경계점 (root, index)이고, 종료점경계점 (root, index + 1)인 새로운 DOM 범위를 생성하고, 그것을 annotations에 추가(append) 합니다.
    3. index를 하나 증가시키고 rtc 자식 처리로 라벨링 된 단계로 건너뜁니다.
  9. current automatic annotation nodes가 비어있다면, current automatic annotation range startindex의 값으로 설정합니다.
  10. current childcurrent automatic annotation nodes의 끝에 추가(append) 합니다.
  11. index를 하나 증기시키고 rtc 자식 처리로 라벨링 된 단계로 건너뜁니다.

위 단계들이 자동 주석 커밋에 응하는 경우, 이는 알고리즘 내의 그 지점에서 다음 단계들을 수행함을 의미합니다:

  1. current automatic annotation nodes가 비어있다면, 이 단계들을 중단합니다.
  2. current automatic annotation nodesText 노드들이 아닌 노드들이나 요소(element) 간 여백이 아닌 Text 노드들을 포함한다면, 시작점경계점 (root, current automatic annotation range start)이고 종료점경계점 (root, index)인 새로운 DOM 범위를 생성하고, 그것을 annotations의 끝에 추가(append) 합니다.
  3. current automatic annotation nodes를 DOM 노드들의 빈 목록으로 둡니다.
  4. current automatic annotation range start를 null로 둡니다.

4.5.14. rp 요소(element)

카테고리:
없음.
이 요소(element)가 사용될 수 있는 컨텍스트:
rubyrtc 요소(element)의 자식으로, rt 요소(element)들 사이가 아닌, rtrtc 요소(element)의 바로 앞 또는 바로 뒤.
콘텐트 모델:
어구(phrasing) 콘텐트.
text/html에서 태그 생략:
rp 요소(element)의 종료 태그rp 요소(element)에 rb, rt, rtc, 또는 rp 요소(element)가 즉시 뒤따르거나, 부모 요소(element)에 더 이상의 콘텐트가 없다면 생략 가능합니다.
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLElement를 사용.

rp 요소(element)는 루비 주석을 지원하지 않는 유저 에이전트들에 의해 보여지는 폴백 텍스트를 제공하는데 사용됩니다. 광범위한 한 가지 규칙은 루비 주석의 루비 텍스트 컴포넌트 주위에 괄호들을 제공하는 것입니다.

rp 요소(element)들의 콘텐츠는 일반적으로 루비 주석을 지원하는 유저 에이전트들에 의해 표시되지 않습니다.

ruby 요소(element)의 자식인 rp 요소(element)는 아무 것도 나타내지 않습니다. 부모 요소(element)가 ruby 요소(element)가 아닌 rp 요소(element)는 그것의 자식을 나타냅니다.

텍스트 漢字 내의 각 표음 문자에 음독으로 주석이 달린 앞서 보여진 예제는 레거시 유저 에이전트들에서 음독이 괄호 안에 있도록 rp를 사용하도록 확장 될 수 있습니다 (더 나은 가독성을 만들기 위해 여백이 이 예제에 도입되는 것에 주목하세요):

...
<ruby>
  漢
  <rb>字</rb>
  <rp> (</rp>
  <rt>かん</rt>
  <rt>じ</rt>
  <rp>) </rp>
</ruby>
...
  

규범을 준수하는 유저 에이전트들에서 렌더링은 위와 같을 것이지만, 루비를 지원하지 않는 유저 에이전트들에서는 렌더링이 다음과 같을 것입니다:

... 漢字 (かんじ) ...

하나의 세그먼트에 대해 여러 주석들이 존재하는 경우, rp 요소(element)들은 또한 주석들 사이에 배치될 수 있습니다. 여기 양쪽 주석들을 사용하는 영어와 프랑스어로 주어진 이름들을 가지고 일부 기호들을 보여주지만 이번에는 rp 요소(element)도 가지는, 앞선 부자연스러운 사례의 다른 사본이 있습니다:

<ruby><rp>: </rp><rt>Heart</rt><rp>, </rp><rtc><rt lang=fr>Cœur</rt></rtc><rp>.</rp><rp>: </rp><rt>Shamrock</rt><rp>, </rp><rtc><rt lang=fr>Trèfle</rt></rtc><rp>.</rp><rp>: </rp><rt>Star</rt><rp>, </rp><rtc><rt lang=fr>Étoile</rt></rtc><rp>.</rp>
</ruby>

이것은 루비가 호환되지 않는 유저 에이전드들에서 다음과 같은 예제 표현을 만들것입니다:

♥: Heart, Cœur.
☘: Shamrock, Trèfle.
✶: Star, Étoile.

4.5.15. data 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
어구(phrasing) 콘텐트가 기대되는 곳.
콘텐트 모델:
어구(phrasing) 콘텐트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
value - 기계가 해석할 수 있는 값
허용된 ARIA 역할(role) 속성(attribute) 값들:
모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
interface HTMLDataElement : HTMLElement {
  attribute DOMString value;
};

data 요소(element)는 value 속성(attribute)에 있는 기계가 해석할 수 있는 콘텐츠의 형식과 함께, 그것의 콘텐츠를 나타냅니다.

value 속성(attribute)은 반드시 존재해야(must) 합니다. 그것의 값은 기계가 해석 할 수 있는 형식으로 요소(element)의 콘텐츠의 표현이어야(must) 합니다.

값이 날짜 혹은 시간 관련인 경우, 더 명시적인 time 요소(element)가 대신 사용될 수 있습니다.

요소(element)는 몇 가지 목적들에 사용 될 수 있습니다.

마이크로포맷들이나 마이크로데이터와 결합된 경우, 요소(element)는 데이터 처리기의 목적들을 위한 기계가 해석 할 수 있는 값과, 웹 브라우저에서의 표현 목적을 위한 사람이 읽을 수 있는 값 모두를 제공하는데 도움을 줍니다. 이 경우, value 속성(attribute) 내에 사용되는 형식은 사용되고 있는 마이크로포맷들이나 마이크로데이터에 의해 결정됩니다.

하지만, 요소(element)는 또한 스크립트가 사람이 읽을 수 있는 값과 함께 저장하기 위한 리터럴 값을 가지는 경우에 대해, 페이지에서 스크립트와 함께 사용 될 수 있습니다. 그러한 경우에, 사용되는 형식은 오직 스크립트의 요구에 의존됩니다. (data-* 속성(attribute)들은 또한 그러한 상황에서 유용할 수 있습니다.)

value IDL 속성(attribute)은 동일한 이름의 콘텐트 속성(attribute)을 반영해야(must) 합니다.

4.5.16. time 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
어구(phrasing) 콘텐트가 기대되는 곳.
콘텐트 모델:
요소(element)가 datetime 속성(attribute:)를 가진다면: 어구(phrasing) 콘텐트
그렇지 않으면: 아래 본문에 기술된 요구사항들에 일치해야(must) 하는 텍스트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
datetime - 기계가 해석 할 수 있는 값
허용된 ARIA 역할(role) 속성(attribute) 값들:
모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
interface HTMLTimeElement : HTMLElement {
  attribute DOMString dateTime;
};

time 요소(element)는 datetime 속성(attribute)의 기계가 해석 할 수 있는 그 콘텐츠의 형식과 함께, 그것의 콘텐츠를 나타냅니다. 콘텐츠의 종류는 다양한 날짜들, 시간들, 표준 시간대들, 기간들, 아래 설명된 것들에 한정됩니다.

datetime 속성(attribute)이 존재할 수 있습니다. 존재한다면, 그것의 값은 기계가 해석 할 수 있는 형식으로 요소(element)의 콘텐츠의 표현이어야(must) 합니다.

datetime 콘텐트 속성(attribute)을 가지지 않은 time 요소(element)는 어떤 후손 요소(element)들도 가지지 않아야(must) 합니다.

time 요소(element)의 일시(datetime) 값은 요소(element)의 datetime 콘텐트 속성(attribute)의 값을 가진다면 그 값이고, 그렇지 않으면 트리 순서에 따라 time 요소(element)의 자식인 모든 Text 노드들의 (주석들이나 요소(element)들 같은 다른 노드들을 제외하고) 콘텐츠의 결합입니다.

time 요소(element)의 일시(datetime) 값은 다음 문법들 중 하나에 일치해야(must) 합니다.

유효한 월 문자열
<time>2011-11</time>
유효한 날짜 문자열
<time>2011-11-18</time>
유효한 연도 없는 날짜 문자열
<time>11-18</time>
유효한 시간 문자열
<time>14:54</time>
<time>14:54:39</time>
<time>14:54:39.929</time>
유효한 변동 날짜와 시간 문자열
<time>2011-11-18T14:54</time>
<time>2011-11-18T14:54:39</time>
<time>2011-11-18T14:54:39.929</time>
<time>2011-11-18 14:54</time>
<time>2011-11-18 14:54:39</time>
<time>2011-11-18 14:54:39.929</time>

날짜는 있지만 표준 시간대가 없는 시간들은 하루 동안 각 표준 시간대 내 특정 시간에 보여지는 이벤트들을 명시하는데 유용합니다. 예를 들어, 2020 새해는 모든 표준 시간대에 걸쳐 정확히 동일한 순간이 아니라 각각의 표준 시간대에서 2020-01-01 00:00에 기념됩니다. 모든 표준 시간대에 걸쳐 동일한 시간에 발생하는 이벤트들에 대해, 예를 들어 화상 회의, 유효한 세계 날짜와 시간 문자열이 더 유용할 것입니다.

유효한 표준 시간대 편차 문자열
<time>Z</time>
<time>+0000</time>
<time>+00:00</time>
<time>-0800</time>
<time>-08:00</time>

날짜가 없는 시간들에 (또는 여러 날짜들에 되풀이 하는 이벤트들을 참조하는 시간들) 대해, 지리적 위치는 섬머타임제를 가지고 표준 시간대 편차들을 변경하기 때문에, 시간을 제어하는 지리적 위치를 명시하는 것은 보통 표준 시간대 편차를 명시하는 것보다 더 유용합니다. 일부 경우들에, 지리적 위치는 표준 시간대도 변경시킵니다, 예를 들어, 2011년의 끝에 사모아에서 발생한 것 같은, 그 표준 시간대의 경계들이 변경되는 경우. 표준 시간대 데이터베이스로 알려진, 표준 시간대의 경계들과 그 각각의 지역에서 적용되는 규칙들을 기술하는 표준 시간대 데이터베이스가 존재합니다. [TZDATABASE]

유효한 세계 날짜와 시간 문자열
<time>2011-11-18T14:54Z</time>
<time>2011-11-18T14:54:39Z</time>
<time>2011-11-18T14:54:39.929Z</time>
<time>2011-11-18T14:54+0000</time>
<time>2011-11-18T14:54:39+0000</time>
<time>2011-11-18T14:54:39.929+0000</time>
<time>2011-11-18T14:54+00:00</time>
<time>2011-11-18T14:54:39+00:00</time>
<time>2011-11-18T14:54:39.929+00:00</time>
<time>2011-11-18T06:54-0800</time>
<time>2011-11-18T06:54:39-0800</time>
<time>2011-11-18T06:54:39.929-0800</time>
<time>2011-11-18T06:54-08:00</time>
<time>2011-11-18T06:54:39-08:00</time>
<time>2011-11-18T06:54:39.929-08:00</time>
<time>2011-11-18 14:54Z</time>
<time>2011-11-18 14:54:39Z</time>
<time>2011-11-18 14:54:39.929Z</time>
<time>2011-11-18 14:54+0000</time>
<time>2011-11-18 14:54:39+0000</time>
<time>2011-11-18 14:54:39.929+0000</time>
<time>2011-11-18 14:54+00:00</time>
<time>2011-11-18 14:54:39+00:00</time>
<time>2011-11-18 14:54:39.929+00:00</time>
<time>2011-11-18 06:54-0800</time>
<time>2011-11-18 06:54:39-0800</time>
<time>2011-11-18 06:54:39.929-0800</time>
<time>2011-11-18 06:54-08:00</time>
<time>2011-11-18 06:54:39-08:00</time>
<time>2011-11-18 06:54:39.929-08:00</time>

날짜들과 표준 시간대 편차를 가진 시간들은 특정 이벤트를 명시하거나 시간이 특정 지리적 위치에 고정되지 않는 반복되는 가상의 이벤트들을 명시하는데 유용합니다. 예를 들어, 소행성 충돌의 정확한 시간이나 세계의 특정 부분이 섬머타임을 관찰하든 하지 않든 상관 없이 매일 세계시 1400에 열리는 일련의 회의 중 특정 회의의 정확한 시간. 특정 지리적 위치의 현지 표준 시간대 편차에 따라 정확한 시간이 다른 이벤트들에 대해, 지리적 위치가 결합된 유효한 변동 날짜와 시간 문자열이 더 유용할 것입니다.

유효한 주 문자열
<time>2011-W47</time>
적어도 하나가 U+0030 숫자 0이 아닌, 4개 이상의 ASCII 숫자들.
<time>2011</time>
<time>0001</time>
유효한 기간 문자열
<time>PT4H18M3S</time>
<time>4h 18m 3s</time>

앞선 많은 유효한 문법들은 "변동" 날짜와/또는 시간 값들을 (그것들은 표준 시간대 편차를 포함하지 않습니다) 기술합니다. 변동 시간 값들을 세계 ("증분") 시간 값들로 혹은 이로부터 (예를 들어, 자바스크립트의 Date 객체) 변경하는 경우 주의가 필요합니다. 많은 경우에, 암묵적 시각과 표준 시간대는 변환에 사용되고 날짜 자체의 값으로 변환에 예기치 않은 결과를 가져올 것입니다. [TIMEZONE]

요소(element)의 콘텐츠의 기계가 해석할 수 있는 동등한 것은 다음 알고리즘을 사용하여 요소(element)의 일시(datetime) 값으로부터 얻어져야(must) 합니다:

  1. 요소(element)의 일시(datetime) 값으로부터 월 문자열 해석을 반환한다면, 그것은 기계가 해석 할 수 있는 동등한 것입니다; 이 단계들을 중단합니다.
  2. 요소(element)의 일시(datetime) 값으로부터 월 문자열 해석날짜를 반환한다면, 그것은 기계가 해석 할 수 있는 동등한 것입니다; 이 단계들을 중단합니다.
  3. 요소(element)의 일시(datetime) 값으로부터 연도 없는 날짜 문자열 해석연도 없는 날짜를 반환한다면, 그것은 기계가 해석할 수 있는 동등한 것입니다; 이 단계들을 중단합니다.
  4. 요소(element)의 일시(datetime) 값으로부터 시간 문자열 해석시간을 반환한다면, 그것은 기계가 해석할 수 있는 동등한 것입니다; 이 단계들을 중단합니다.
  5. 요소(element)의 일시(datetime) 값으로부터 변동 날짜와 시간 문자열을 해석변동 날짜와 시간을 반환한다면, 그것은 기계가 해석할 수 있는 동등한 것입니다; 이 단계들을 중단합니다.
  6. 요소(element)의 일시(datetime) 값으로부터 표준 시간대 편차 문자열 해석표준 시간대 편차를 반환한다면, 그것은 기계가 해석할 수 있는 동등한 것입니다; 이 단계들을 중단합니다.
  7. 요소(element)의 일시(datetime) 값으로부터 변동 날짜와 시간 문자열 해석세계 날짜와 시간을 반환한다면, 그것은 기계가 해석할 수 있는 동등한 것입니다; 이 단계들을 중단합니다.
  8. 요소(element)의 일시(datetime) 값으로부터 주 문자열 해석를 반환한다면, 그것은 기계가 해석할 수 있는 동등한 것입니다; 이 단계들을 중단합니다.
  9. 요소(element)의 일시(datetime) 값이 적어도 하나가 U+0030 숫자 0이 아닌 ASCII 숫자들로 구성된다면, 기계가 해석 할 수 있는 동등한 것은 연도를 나타내는, 그 숫자들의 십진법 해석입니다. 이 단계들을 중단합니다.
  10. 요소(element)의 일시(datetime) 값으로부터 기간 문자열 해석기간을 반환한다면, 그것은 기계가 해석할 수 있는 동등한 것입니다; 이 단계들을 중단합니다.
  11. 기계가 해석 가능한 동등한 것이 없습니다.

위 참조된 알고리즘들은 임의의 문자열에 대해 알고리즘들 중 하나만 값을 반환하게 설계되도록 의도된 것입니다. 더 효율적인 처리 방법은 한 번에 이 모든 데이터 유형들을 해석하는 단일 알고리즘을 생성하는 것입니다; 그러한 알고리즘을 개발하는 것은 독자들에게 과제로 남겨집니다.

dateTime IDL 속성(attribute)은 요소(element)의 datetime 콘텐트 속성(attribute)을 반영해야(must) 합니다.

time 요소(element)는 데이터들을 인코드 하는데, 예를 들어 마이크로포맷들로, 사용될 수 있습니다. 다음은 time 요소(element)를 사용하는 hCalendar에서 변형을 사용하는 이벤트를 인코딩하는 가상의 방법을 보여줍니다:
<div class="vevent">
  <a class="url" href="https://www.web2con.com/">https://www.web2con.com/</a>
  <span class="summary">Web 2.0 Conference</span>:
  <time class="dtstart" datetime="2005-10-05">October 5</time> -
  <time class="dtend" datetime="2005-10-07">7</time>,
  at the <span class="location">Argent Hotel, San Francisco, CA</span>
  </div>
여기, 아톰 표현 형식을 기반으로한 가상의 마이크로데이터 표현 형식이 블로그 게시물의 게시 날짜를 마크업하기 위해 time 요소(element)를 가지고 사용됩니다.
<article vocab="https://n.example.org/" typeof="rfc4287">
  <h1 property="title">Big tasks</h1>
  <footer>Published <time property="published" datetime="2009-08-29">two days ago</time>.</footer>
  <p property="content">Today, I went out and bought a bike for my kid.</p>
</article>
이 예에서, 이번에는 schema.org 마이크로데이터 표현 형식을 사용하여, 다른 아티클의 게시 날짜는 time을 사용하여 마크업됩니다:
<article typeof="schema:BlogPosting">
  <h1 property="schema:headline">Small tasks</h1>
  <footer>Published <time property="schema:datePublished" datetime="2009-08-30">yesterday</time>.</footer>
  <p property="schema:articleBody">I put a bike bell on his bike.</p>
</article>
다음 코드 조각에서, time 요소(element)는 나중에 스크립트에 의한 처리를 위해 날짜를 ISO8601 형식으로 인코드 하는데 사용됩니다:
<p>Our first date was <time datetime="2006-09-23">a Saturday</time>.</p>

이 두 번째 코드 조각에서, 값은 시간을 포함합니다:

<p>We stopped talking at <time datetime="2006-09-24T05:00-07:00">5am the next morning</time>.</p>

페이지에 의해 로드 된 스크립트는 (그리고 따라서 time 요소(element)를 사용하여 날짜들과 시간들을 마크업하는 페이지의 내부 규칙을 공유하는 것이 된) 페이지를 살펴보고 날짜와 시간들의 색인을 생성하기 위해 그 안에 있는 모든 time 요소(element)들을 검토할 수 있습니다.

예를 들어, 이 요소(element)는 2011년 11월 18일은 "금요일"에 해당한다는 추가적인 의미(semantic)를 가진 문자열 "Friday"를 전달합니다:
Today is <time datetime="2011-11-18">Friday</time>.
이 예에서, 태평양 표준 시간대로 특정 시간이 명시됩니다:
Your next meeting is at <time datetime="2011-11-18T15:00-08:00">3pm</time>.

4.5.17. code 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
어구(phrasing) 콘텐트가 기대되는 곳.
콘텐트 모델:
어구(phrasing) 콘텐트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLElement를 사용.

code 요소(element)는 컴퓨터 코드의 코드 조각을 나타냅니다. 이것은 XML 요소(element) 이름, 파일 이름, 컴퓨터 프로그램, 컴퓨터가 인식하는 다른 문자열이 될 수 있습니다.

마크업 되는 컴퓨터 코드의 언어를 나타내는 공식적인 방법은 없습니다. 사용된 언어와 함께 code 요소(element)들을 표기하기를 원하는, 예를 들어, 문법 강조 스크립트가 올바른 규칙들을 사용할 수 있도록, 작성자들은 class 속성(attribute)을, 예를 들어, 요소(element)에 "language-"가 앞에 붙은 클래스를 추가하여, 사용할 수 있습니다.

다음 예는 구두점을 포함하여, 요소(element)가 요소(element)이름과 컴퓨터 코드를 마크업하기 위해 문단에 사용되는 방식을 보여줍니다.
<p>The <code>code</code> element represents a fragment of computer
code.</p>

<p>When you call the <code>activate()</code> method on the
<code>robotSnowman</code> object, the eyes glow.</p>

<p>The example below uses the <code>begin</code> keyword to indicate
the start of a statement block. It is paired with an <code>end</code>
keyword, which is followed by the <code>.</code> punctuation character
(full stop) to indicate the end of the program.</p>
다음 예는 코드 블럭이 precode 요소(element)들을 사용하여 마크업 될 수 있는 방법을 보여줍니다.
<pre><code class="language-pascal">var i: Integer;
begin
    i := 1;
end.</code></pre>

클래스가 그 예에서 사용된 언어를 나타내기 위해 사용됩니다.

더 자세한 사항들을 위해 pre 요소(element)를 참고하세요.

4.5.18. var 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
어구(phrasing) 콘텐트가 기대되는 곳.
콘텐트 모델:
어구(phrasing) 콘텐트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLElement를 사용.

var 요소(element)는 변수를 나타냅니다. 이것은 수학적 표현이나 프로그래밍 컨텍스트에서의 실제 변수, 상수를 나타내는 식별자, 물리적 수량을 식별하는 부호, 함수 매개변수, 본문 내 플레이스홀더로 사용되는 용어 일 수 있습니다.

아래 문단에서, 글자 "n"은 본문에서 변수로 사용되고 있습니다:
<p>If there are <var>n</var> pipes leading to the ice
cream factory then I expect at <em>least</em> <var>n</var>
flavors of ice cream to be available for purchase!</p>

수학의 경우, 매우 간단한 표현식이 아닌 한, MathML이 더 적절합니다. 하지만, var 요소(element)는 여전히 MathML 표현식들에서 언급되는 특정 변수들을 가리키는데 사용될 수 있습니다.

이 예에서, 방정식 내에서 변수들을 참조하는 범례를 가지고 방정식이 보여집니다. 표현식 자체는 MathML로 마크업 되지만, 변수들은 var를 사용하여 삽화의 범례 내에서 언급됩니다.
<figure>
  <math>
  <mi>a</mi>
  <mo>=</mo>
  <msqrt>
    <msup><mi>b</mi><mn>2</mn></msup>
    <mi>+</mi>
    <msup><mi>c</mi><mn>2</mn></msup>
  </msqrt>
  </math>
  <figcaption>
  Using Pythagoras' theorem to solve for the hypotenuse <var>a</var> of
  a triangle with sides <var>b</var> and <var>c</var>
  </figcaption>
</figure>
여기, 질량 에너지 등가성을 설명하는 방정식이 문장에 사용되고, var 요소(element)가 그 방정식에서 변수들과 상수들을 표기하는데 사용됩니다:
<p>Then he turned to the blackboard and picked up the chalk. After a few moment’s
thought, he wrote <var>E</var> = <var>m</var> <var>c</var><sup>2</sup>. The teacher
looked pleased.</p>

4.5.19. samp 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
어구(phrasing) 콘텐트가 기대되는 곳.
콘텐트 모델:
어구(phrasing) 콘텐트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLElement를 사용.

samp 요소(element)는 견본 혹은 다른 프로그램이나 컴퓨팅 시스템으로부터의 인용된 출력을 나타냅니다.

더 자세한 사항들을 위해 prekbd 요소(element)들을 참고하세요.

이 요소(element)는 웹 어플리케이션에서의 직접적인 출력을 제공하는데 사용될 수 있는 output 요소(element)와 뚜렷한 차이를 보입니다.

이 예는 인라인으로 사용되는 samp 요소(element)를 보여줍니다:
<p>The computer said <samp>Too much cheese in tray
two</samp> but I didn’t know what that meant.</p>
이 두 번째 예는 견본 출력 블럭을 보여줍니다. 중첩된 sampkbd 요소(element)들은 스타일 시트를 사용하여 견본 출력의 특정 요소(element)들의 스타일링을 허용합니다. 매우 정밀한 스타일링을 가능하게 하기 위해, 한층 더 자세한 마크업으로 주석이 달린 samp의 몇 부분도 있습니다. 이를 이루기 위해, span 요소(element)들이 사용됩니다.
<pre><samp><span class="prompt">jdoe@mowmow:~$</span> <kbd>ssh demo.example.com</kbd>
Last login: Tue Apr 12 09:10:17 2005 from mowmow.example.com on pts/1
Linux demo 2.6.10-grsec+gg3+e+fhs6b+nfs+gr0501+++p3+c4a+gr2b-reslog-v6.189 #1 SMP Tue Feb 1 11:22:36 PST 2005 i686 unknown

<span class="prompt">jdoe@demo:~$</span> <span class="cursor">_</span></samp></pre>

4.5.20. kbd 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
어구(phrasing) 콘텐트가 기대되는 곳.
콘텐트 모델:
어구(phrasing) 콘텐트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLElement를 사용.

kbd 요소(element)는 사용자 입력을 (음성 명령들 같은 다른 입력을 나타내는데 사용될 수도 있지만, 일반적으로 키보드 입력) 나타냅니다.

kbd 요소(element)가 samp 요소(element) 안에 중첩되는 경우, 그것은 시스템에 의해 반영된 입력을 나타냅니다.

kbd 요소(element)가 samp 요소(element)를 포함하는 경우, 그것은 시스템 출력에 기반한 입력을, 예를 들어 메뉴 항목 호출, 나타냅니다.

kbd 요소(element)가 다른 kbd 요소(element) 내에 중첩되는 경우, 그것은 입력 메커니즘에 대한 적절한 실제 키나 다른 입력 단일 장치를 나타냅니다.

여기 kbd 요소(element)가 누를 키들을 나타내는데 사용됩니다:
<p>To make George eat an apple, press <kbd><kbd>Shift</kbd>+<kbd>F3</kbd></kbd></p>

이 두 번째 예에서, 사용자는 특정 메뉴 항목을 고르도록 지시 받습니다. 바깥 kbd 요소(element)는 입력의 각 개별 단계를 나타내는 내부 kbd 요소(element)들과 그 kbd 요소(element)들 내부에 단계들이 시스템에 의해 표시되고 있는 어떤 것에 기반한 입력 임을, 이 예에서는 메뉴 레이블들을, 나타내는 samp요소(element)를 가지고 마크업 합니다:

<p>To make George eat an apple, select
    <kbd><kbd><samp>File</samp></kbd>|<kbd><samp>Eat Apple...</samp></kbd></kbd>
</p>

이러한 정확성은 필요하지 않습니다; 다음은 동일하게 괜찮습니다:

<p>To make George eat an apple, select <kbd>File | Eat Apple...</kbd></p>

4.5.21. subsup 요소(element)들

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
어구(phrasing) 콘텐트가 기대되는 곳.
콘텐트 모델:
어구(phrasing) 콘텐트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLElement를 사용.

sup 요소(element)는 어깨 글자를 나타내고, sub 요소(element)는 다리 글자를 나타냅니다.

이 요소(element)들은 표현(presentation)의 목적을 위한 글씨체 표현(presentation)이 아니라, 특정한 의미를 가지는 표기법을 마크업 하기 위헤서만 사용되어야(must)합니다. 예를 들어, subsup 요소(element)가 LaTeX 문서 준비 시스템의 이름에 사용되는 것은 부적절할 것입니다. 일반적으로, 작성자는 그 요소(element)들의 부재가 콘텐트의 의미를 변경하는 경우에만 이 요소(element)들을 사용해야(should) 합니다.

특정 언어에서, 어깨 글자들은 어떤 축약어들을 위한 표기법의 일부입니다.

<p>The most beautiful women are
<span lang="fr"><abbr>M<sup>lle</sup></abbr> Gwendoline</span> and
<span lang="fr"><abbr>M<sup>me</sup></abbr> Denise</span>.</p>

sub 요소(element)는 다리 문자들을 가지는 변수들에 대해, var 요소(element) 내에 사용될 수 있습니다.

여기, sub 요소(element)가 변수들의 모음에서 변수를 식별하는 다리 문자를 나타내는데 사용됩니다:
<p>The coordinate of the <var>i</var>th point is
(<var>x<sub><var>i</var></sub></var>, <var>y<sub><var>i</var></sub></var>).
For example, the 10th point has coordinate
(<var>x<sub>10</sub></var>, <var>y<sub>10</sub></var>).</p>

수학적 표현식은 종종 어깨 문자들과 다리 문자들을 사용합니다. 작성자들은 수학을 마크업하는데 MathML을 사용하도록 권장되지만, 상세한 수학적 마크업이 요구되지 않는다면 subsup를 사용하는 것을 선택할 수 있습니다. [MATHML]

<var>E</var>=<var>m</var><var>c</var><sup>2</sup>
f(<var>x</var>, <var>n</var>) = log<sub>4</sub><var>x</var><sup><var>n</var></sup>

4.5.22. i 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
어구(phrasing) 콘텐트가 기대되는 곳.
콘텐트 모델:
어구(phrasing) 콘텐트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLElement를 사용.

i 요소(element)는 다른 어조나 분위기의 텍스트 범위, 분류학상의 명칭, 기술 용어, 다른 언어의 관용구, 음역, 생각, 서양 문학의 배 이름 같은 텍스트의 다른 특징을 나타내는 방식으로 일반 본문으로부터의 보충을 나타냅니다.

주요 텍스트와 다른 언어의 용어는 lang 속성(attribute)들을 (혹은 XML 에서는 XML 네임스페이스에 있는 lang 속성(attribute)들) 가지고 주석(annotate)을 달아야(should) 합니다.

아래 예들은 i 요소(element)의 사용을 보여줍니다:
<p>The <i class="taxonomy">Felis silvestris catus</i> is cute.</p>
<p>The term <i>prose content</i> is defined above.</p>
<p>There is a certain <i lang="fr">je ne sais quoi</i> in the air.</p>

다음 예에서, 꿈 장면이 i 요소(element)들을 사용하여 마크업 됩니다.

<p>Raymond tried to sleep.</p>
<p><i>The ship sailed away on Thursday</i>, he
dreamt. <i>The ship had many people aboard, including a beautiful
princess called Carey. He watched her, day-in, day-out, hoping she
would notice him, but she never did.</i></p>
<p><i>Finally one night he picked up the courage to speak with
her—</i></p>
<p>Raymond woke with a start as the fire alarm rang out.</p>

작성자들은 요소(element)가 사용되는 이유를 식별하기 위해 i 요소(element)에 class 속성(attribute)을 사용할 수 있기 때문에, 특정한 용도의 (예를 들어, 분류학상의 용어들과 다르게 꿈 장면) 스타일이 나중에 변경되는 경우, 작성자는 각 용도를 주석을 다는 전체 문서를 (혹은 일련의 관련된 문서) 살펴볼 필요가 없습니다.

작성자들은 i 요소(element)보다 더 적절한 다른 요소(element)들이 있을 수 있는지, 예를 들어, 역설 강조(stress emphasis)를 마크업하기 위한 em 요소(element)나 용어의 정의 예를 마크업하기 위한 dfn 요소(element), 고려하도록 권장됩니다.

스타일 시트들은 다른 요소(element)가 재 스타일링 될 수 있는 것처럼, i 요소(element)들에 형식을 지정하는데 사용될 수 있습니다. 따라서, i 요소(element)들 내의 콘텐트가 필연적으로 이탤릭체가 되는 경우가 아닙니다.

4.5.23. b 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
어구(phrasing) 콘텐트가 기대되는 곳.
콘텐트 모델:
어구(phrasing) 콘텐트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLElement를 사용.

b 요소(element)는 문서 개념에서 핵심 단어들, 리뷰의 상품 이름, 상호작용 텍스트 중심 소프트웨어의 실행 가능한 단어들, 기사 헤드라인 같은, 추가적인 중요성을 전달하지 않고 다른 어조나 분위기의 영향 없이 실용적인 목적으로 주의가 끌어지는 텍스트의 범위를 나타냅니다.

다음 예는 중요한 것으로 그것들을 표기하지 않고 핵심 단어들을 강조(highlight)하기 위한 b 요소(element)의 사용을 보여줍니다:
<p>The <b>frobonitor</b> and <b>barbinator</b> components are fried.</p>
다음 예에서, b 요소(element)의 사용에 의해 텍스트 어드벤쳐의 객체들이 특별한 것으로 강조(highlight)됩니다..
<p>You enter a small room. Your <b>sword</b> glows
brighter. A <b>rat</b> scurries past the corner wall.</p>
b 요소(element)가 적절한 다른 경우는 헤드라인(혹은 톱뉴스) 문장이나 문단에 표기하는 것입니다. 다음 예는 토끼를 자신들의 가족으로 입양한 새끼 고양이들에 대한 BBC 기사가 마크업 될 수 있는 방식을 보여줍니다:
<article>
  <h2>Kittens 'adopted' by pet rabbit</h2>
  <p><b class="lede">Six abandoned kittens have found an
  unexpected new mother figure — a pet rabbit.</b></p>
  <p>Veterinary nurse Melanie Humble took the three-week-old
  kittens to her Aberdeen home.</p>
[...]

i 요소(element)와 마찬가지로, 작성자들은 요소(element)가 사용되는 이유를 식별하기 위해 b 요소(element)에 class 속성(attribute)을 사용할 수 있기 때문에, 특정한 용도의 스타일이 나중에 변경되는 경우, 작성자는 각 용도를 주석을 달 필요가 없습니다.

b 요소(element)는 더 적절한 다른 요소가 없는 경우에 마지막 수단으로 사용되어야(should) 합니다. 특히, 제목(heading)들은 h1부터 h6 요소(element)들을 사용해야(should) 하고, 역설 강조(stress emphasis)는 em 요소(element)를 사용해야(should) 하고, 중요성은 strong 요소(element)를 가지고 나타내져야 하며, 텍스트 표기나 강조는 mark 요소(element)를 사용해야(should) 합니다.

다음은 맞지 않는 사용법일 것 입니다:
<p><b>WARNING!</b> Do not frob the barbinator!</p>

이전 예에서, 사용할 올바른 요소(element)는 b가 아니라 strong 였을 것입니다.

스타일 시트들은 다른 요소(element)가 재 스타일링 될 수 있는 것처럼, b 요소(element)들에 형식을 지정하는데 사용될 수 있습니다. 따라서, b 요소(element)들 내의 콘텐트가 필연적으로 굵은 글꼴이 되는 경우가 아닙니다.

4.5.24. u 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
어구(phrasing) 콘텐트가 기대되는 곳.
콘텐트 모델:
어구(phrasing) 콘텐트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLElement를 사용.

u 요소(element)는 불분명한 텍스트의 범위나, 명시적으로 렌더링 되어있기는 하지만, 중국어 텍스트의 고유 명사가 되는 것으로 라벨링 하는 것 같은 (중국어 고유 명사 기호) 비 텍스트 주석이나, 철자가 틀린 것으로서의 텍스트 라벨링을 나타냅니다.

대다수의 경우에, 다른 요소(element)가 더 적절할 것 같습니다: 역설 강조(stress emphasis)를 표기하기 위해서는 em 요소(element)가 사용되어야(should); 핵심 단어들이나 핵심 어구들을 표기하기 위해서는 문맥에 따라 b 요소(element)나 mark 요소(element)가 사용되어야(should); 책 제목들을 표기하기 위해, cite 요소(element)가 사용되어야(should); 명시적인 텍스트 주석들을 가진 텍스트 라벨링을 위해, ruby 요소가 사용되어야(should); 기술 용어, 분류학상 명칭, 음역, 생각, 서양 문학의 배 이름을 라벨링 하기 위해, i 요소(element)가 사용되어야(should) 합니다.

시각적 표현에서 u 요소(element)의 기본 렌더링은 전통적인 하이퍼링크들의 렌더링 (밑줄긋기)와 충돌합니다. 작성자들은 하이퍼링크에 대한 혼란이 야기되는 경우 u 요소(element)를 사용하는 것을 피하도록 권장됩니다.

4.5.25. mark 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
어구(phrasing) 콘텐트가 기대되는 곳.
콘텐트 모델:
어구(phrasing) 콘텐트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLElement를 사용.

mark 요소(element)는 다른 컨텍스트에서 그것의 관련성을 위해, 참조 목적으로 표기 혹은 강조된 문서 내의 일련의 텍스트를 나타냅니다. 인용구(quotation)나 본문으로부터 참조된 텍스트의 다른 블럭에 사용되는 경우, 그것은 본래는 존재하지 않았으나 독자들의 주의를 블럭이 본래 작성되었을 때 원작자에 의해 중요하다고 고려되지 않았지만 현재는 전에 예상하지 못한 검토 하에 있는 텍스트의 일부로 가져오기 위해 추가된 강조를 나타냅니다. 문서의 주요 본문에 사용되는 경우, 사용자의 현재 행동에 관련되는 것 같기 때문에 강조된 문서의 일부를 나타냅니다.

이 예는 인용구(quotation)의 특정 부분으로 주의를 가져오는데 mark 요소(element)가 사용될 수 있는 방법을 보여줍니다:
<p lang="en-US">Consider the following quote:</p>
<blockquote lang="en-GB">
  <p>Look around and you will find, no-one’s really
  <mark>colour</mark> blind.</p>
</blockquote>
<p lang="en-US">As we can tell from the <em>spelling</em> of the word,
the person writing this quote is clearly not American.</p>

(그러나, 오타로 요소(element)를 표기하기 위한 목적이라면, u 요소(element)가, 아마도 클래스를 가진, 더 적절할 것입니다.)

mark 요소(element)의 다른 예는 어떤 검색 문자열과 일치하는 문서의 일부를 강조하는 것입니다. 누군가 문서를 보고 서버가 사용자가 단어 "kitten"에 대해 검색했다는 것을 알았다면, 서버는 다음과 같은 수정된 문단을 가진 문서를 반환 할 수 있습니다:
<p>I also have some <mark>kitten</mark>s who are visiting me
these days. They’re really cute. I think they like my garden! Maybe I
should adopt a <mark>kitten</mark>.</p>
다음 코드 조각에서, 텍스트의 문단은 코드 조각의 특정한 부분을 가리킵니다.
<p>The highlighted part below is where the error lies:</p>
<pre><code>var i: Integer;
begin
    i := <mark>1.1</mark>;
end.</code></pre>

이것은 span이 더 적절한 문법 강조와는 별개입니다. 둘을 결합하면 다음이 얻어집니다:

<p>The highlighted part below is where the error lies:</p>
<pre><code><span class=keyword>var</span> <span class=ident>i</span>: <span class=type>Integer</span>;
<span class=keyword>begin</span>
    <span class=ident>i</span> := <span class=literal><mark>1.1</mark></span>;
<span class=keyword>end</span>.</code></pre>
이것은 본래는 강조(emphasis) 되지 않은 인용된 부분을 강조(highlight)하기 위한 mark의 사용을 보여주는 다른 예입니다. 이 예에서, 일반적인 표기법은 작성자가 이탤릭체로 렌더링 되게 하기 위해 명시적으로 인용구 내의 mark 요소(element)들을 스타일하도록 이끕니다.
<head>
  <style>
  blockquote mark, q mark {
    font: inherit; font-style: italic;
    text-decoration: none;
    background: transparent; color: inherit;
  }
  .bubble em {
    font: inherit; font-size: larger;
    text-decoration: underline;
  }
  </style>
</head>
<article>
  <h1>She knew</h1>
  <p>Did you notice the subtle joke in the joke on panel 4?</p>
  <blockquote>
  <p class="bubble">I didn’t <em>want</em> to believe. <mark>Of course
  on some level I realized it was a known-plaintext attack.</mark> But I
  couldn’t admit it until I saw for myself.</p>
  </blockquote>
  <p>(Emphasis mine.) I thought that was great. It’s so pedantic, yet it
  explains everything neatly.</p>
</article>

부수적으로, 이 예에서 인용되는 원본 텍스트의 일부인 em 요소(element)와 mark 요소(element) 사이의 차이에 주목하세요.

다음 예는 텍스트의 범위의 관련성(relevance)을 나타내는 것과 (mark) 달리 텍스트의 범위의 중요성(importance)을 나타내는 것 (strong) 사이의 차이를 보여줍니다. 이 예는 발췌가 시험과 연관된 부분이 강조된 교과서에서 발췌한 것입니다. 안전 경고문들은 비록 중요할 지라도 시험과는 분명히 관련이 없습니다.
<h3>Wormhole Physics Introduction</h3>

<p><mark>A wormhole in normal conditions can be held open for a
maximum of just under 39 minutes.</mark> Conditions that can increase
the time include a powerful energy source coupled to one or both of
the gates connecting the wormhole, and a large gravity well (such as a
black hole).</p>

<p><mark>Momentum is preserved across the wormhole. Electromagnetic
radiation can travel in both directions through a wormhole,
but matter cannot.</mark></p>

<p>When a wormhole is created, a vortex normally forms.
<strong>Warning: The vortex caused by the wormhole opening will
annihilate anything in its path.</strong> Vortexes can be avoided when
using sufficiently advanced dialing technology.</p>

<p><mark>An obstruction in a gate will prevent it from accepting a
wormhole connection.</mark></p>

4.5.26. bdi 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
어구(phrasing) 콘텐트가 기대되는 곳.
콘텐트 모델:
어구(phrasing) 콘텐트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
또한, dir 범용 속성(attribute)은 이 요소(element)에서 특정한 의미(semantics)를 가집니다.
허용된 ARIA 역할(role) 속성(attribute) 값들:
모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLElement를 사용.

bdi 요소(element)는 양방향성 텍스트 서식의 목적으로 주변으로부터 구분되는 텍스트의 범위를 나타냅니다. [BIDI]

dir 범용 속성(attribute)은 이 요소(element)에서 기본으로 auto가 입니다(다른 요소(element)들과 마찬가지로 부모 요소(element)로부터 상속하지 않습니다).

이 요소(element)는 특히 알 수 없는 방향성을 가진 사용자 생성 콘텐트를 포함할 경우 유용합니다.

이 예에서, 사용자 이름들은 사용자가 제출한 게시물의 숫자와 함께 보여집니다. bdi 요소(element)가 사용되지 않았다면, 아랍 사용자의 사용자 이름은 텍스트를 혼란스럽게 만들 것입니다 (양방향 알고리즘은 단어 "posts" 다음보다 단어 "User" 다음에 콜론과 숫자 "3"을 둘 것입니다).

<ul>
  <li>User <bdi>jcranmer</bdi>: 12 posts.
  <li>User <bdi>hober</bdi>: 5 posts.
  <li>User <bdi>إيان</bdi>: 3 posts.
</ul>
bdi 요소(element)를 사용하는 경우, 사용자 이름이 예상대로 작동합니다.
bdi 요소(element)가 b 요소(element)로 교체되었다면, 사용자 이름은 양방향 알고리즘을 혼란스럽게 만들고 세 번째 글머리 기호는 "User 3:", 그 뒤로 아랍 이름 (오른쪽에서 왼쪽), 그 뒤로 "posts" 그리고 마침표라고 나타내게 될 것입니다.

4.5.27. bdo 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
어구(phrasing) 콘텐트가 기대되는 곳.
콘텐트 모델:
어구(phrasing) 콘텐트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
또한, dir 범용 속성(attribute)은 이 요소(element)에서 특별한 의미(semantics)를 가집니다.
허용된 ARIA 역할(role) 속성(attribute) 값들:
모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLElement를 사용.

bdo 요소(element)는 그것의 자식에 대한 명시적인 텍스트 방향성 서식 제어를 나타냅니다. 이 요소(element)는 작성자가 명시적으로 방향 재정의를 명시하는 것에 의해 유니코드 방향성 알고리즘을 재정의 하는 것을 허용합니다. [BIDI]

작성자들은 이 요소(element)에 왼쪽에서 오른쪽 재정의를 명시하기 위한 값 ltr과 오른쪽에서 왼쪽 재정의를 명시하기 위한 값 rtl을 가지고 dir 속성(attribute)을 명시해야(must) 합니다. auto 값은 명시되지 않아야(must) 합니다.

4.5.28. span 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
어구(phrasing) 콘텐트가 기대되는 곳.
콘텐트 모델:
어구(phrasing) 콘텐트.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
interface HTMLSpanElement : HTMLElement {};

span 요소(element)는 그 자체로는 아무 것도 의미(mean)하지 않지만, 범용 속성(attribute)들과 예를 들어, 예를 들어, class, lang, 또는 dir과 함께 사용되는 경우에 유용할 수 있습니다. 그것은 그것의 자식을 나타냅니다.

이 예에서, 코드 조각은 그것의 키워드들과 식별자들이 CSS로부터 색상이 입혀질 수 있도록 span 요소(element)들과 class 속성(attribute)들을 사용하여 마크업됩니다:
<pre><code class="lang-c"><span class="keyword">for</span> (<span class="ident">j</span> = 0; <span class="ident">j</span> &lt; 256; <span class="ident">j</span>++) {
  <span class="ident">i_t3</span> = (<span class="ident">i_t3</span> & 0x1ffff) | (<span class="ident">j</span> &lt;&lt; 17);
  <span class="ident">i_t6</span> = (((((((<span class="ident">i_t3</span> >> 3) ^ <span class="ident">i_t3</span>) >> 1) ^ <span class="ident">i_t3</span>) >> 8) ^ <span class="ident">i_t3</span>) >> 5) & 0xff;
  <span class="keyword">if</span> (<span class="ident">i_t6</span> == <span class="ident">i_t1</span>)
    <span class="keyword">break</span>;
}</code></pre>

4.5.29. br 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
어구(phrasing) 콘텐트가 기대되는 곳.
콘텐트 모델:
없음.
text/html에서 태그 생략:
종료 태그 없음.
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
interface HTMLBRElement : HTMLElement {};

br 요소(element)는 줄 바꿈을 나타냅니다.

줄 바꿈들이 보통 시각 매체에서 물리적으로 다음 텍스트를 새로운 줄로 옮기는 것으로 표현되는 반면, 스타일 시트나 유저에이전트는 줄 바꿈이 다른 방법으로, 예를 들어 녹색 점이나 추가적인 공백, 렌더링 되도록 하는 것은 동일하게 정당할 것입니다.

br 요소(element)들은 시들이나 주소들에서와 같이, 실제로 콘텐트의 일부인 줄 바꿈을 위해서만 사용되어야 합니다.

다음 예는 br 요소(element)의 올바른 사용예입니다:
<p>P. Sherman<br>
42 Wallaby Way<br>
Sydney</p>

br 요소(element)들은 문단 내 주제 그룹을 분별하기 위해 사용되지 않아야(must) 합니다.

다음 예들은 br 요소(element)를 오용한 것으로, 부적합 합니다:
<p><a ...>34 comments.</a><br>
<a ...>Add a comment.</a></p>
<p><label>Name: <input name="name"></label><br>
<label>Address: <input name="address"></label></p>

여기 위에 대한 옳바른 대안이 있습니다:

<p><a ...>34 comments.</a></p>
<p><a ...>Add a comment.</a></p>
<p><label>Name: <input name="name"></label></p>
<p><label>Address: <input name="address"></label></p>

문단이 어떤 것으로도 구성되지 않고 단일 br 요소(element)로 구성된다면, 그것은 플레이스홀더 빈 줄을 (예를 들어, 템플릿에서) 나타냅니다. 그러한 빈 줄들은 표현(presentaion) 목적들을 위해 사용되지 않아야(must) 합니다.

br 요소(element)들 내부의 어떤 콘텐트도 주변 텍스트의 일부로 간주되지 않아야(must) 합니다.

이 요소(element)는 양방향성 알고리즘을 수반하는 렌더링 요구사항들을 가집니다.

4.5.30. wbr 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
어구(phrasing) 콘텐트가 기대되는 곳.
콘텐트 모델:
없음.
text/html에서 태그 생략:
종료 태그 없음.
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLElement를 사용.

wbr 요소(element)는 줄 바꿈 기회를 나타냅니다.

다음 예에서, 효과를 위해, 누군가 하나의 긴 단어로 쓰여진 무언가를 말한 것으로 인용됩니다. 하지만, 텍스트가 읽을 수 있는 방식으로 감싸질 수 있는 것을 보장하기 위해, 인용구 내 각각의 단어들이 wbr 요소(element)들을 사용하여 나뉩니다.
<p>So then he pointed at the tiger and screamed
"there<wbr>is<wbr>no<wbr>way<wbr>you<wbr>are<wbr>ever<wbr>going<wbr>to<wbr>catch<wbr>me"!</p>
여기 특히 프로그램 목록에서 코드의 긴 줄들이 wbr 요소(element)들을 사용하여 주어진 지점들을 감싸는 것을 제안했습니다.
<pre>...
Heading heading = Helm.HeadingFactory(HeadingCoordinates[1], <wbr>HeadingCoordinates[2], <wbr>HeadingCoordinates[3], <wbr>HeadingCoordinates[4]);
Course course = Helm.CourseFactory(Heading, <wbr>Maps.MapFactoryFromHeading(heading), <wbr>Speeds.GetMaximumSpeed().ConvertToWarp());
...</pre>

wbr 요소(element)들 내 어떤 콘텐트도 주변 텍스트의 일부로 간주되지 않아야(must) 합니다.

var wbr = document.createElement("wbr");wbr.textContent = "This is wrong";
document.body.appendChild(wbr);

이 요소(element)는 양방향성 알고리즘을 수반하는 렌더링 요구사항들을 가집니다.

4.5.31. 사용법 요약

이 섹션은 비규범적입니다.

요소(element) 목적
a 하이퍼링크들
Visit my <a href="drinks.html">drinks</a> page.
em 역설 강조(stress emphasis)
I must say I <em>adore</em> lemonade.
strong 중요성
This tea is <strong>very hot</strong>.
small 보조 코멘트들
These grapes are made into wine. <small>Alcohol is addictive.</small>
s 정확하지 않은 텍스트
Price: <s>£4.50</s> £2.00!
cite 작품들의 제목들
The case <cite>Hugo v. Danielle</cite> is relevant here.
q 인용구(quotation)들
The judge said <q>You can drink water from the fish tank</q> but advised against it.
dfn 장의 사례
The term <dfn>organic food</dfn> refers to food produced without synthetic chemicals.
abbr 축약어들
Organic food in Ireland is certified by the <abbr title="Irish Organic Farmers and Growers Association">IOFGA</abbr>.
ruby, rb, rp, rt, rtc 루비 주석(annotation)들
<ruby> <rb>OJ <rp>(<rtc><rt>Orange Juice</rtc><rp>)</ruby>
data 기계가 해석할 수 있는 동등한 것
Available starting today! <data value="UPC:022014640201">North Coast Organic Apple Cider</data>
time 날짜 혹은 시간 관련 데이터의 기계가 해석 할 수 있는 동등한 것
Available starting on <time datetime="2011-11-18">November 18th</time>!
code 컴퓨터 코드
The <code>fruitdb</code> program can be used for tracking fruit production.
var 변수들
If there are <var>n</var> fruit in the bowl, at least <var>n</var>÷2 will be ripe.
samp 컴퓨터 출력
The computer said <samp>Unknown error -3</samp>.
kbd 사용자 입력
Hit <kbd>F1</kbd> to continue.
sub 다리 글자들
Water is H<sub>2</sub>O.
sup 어깨 글자들
The Hydrogen in heavy water is usually <sup>2</sup>H.
i 다른 어조
Lemonade consists primarily of <i>Citrus limon</i>.
b 키워드들
Take a <b>lemon</b> and squeeze it with a <b>juicer</b>.
u 주석(annotation)들
The mixture of apple juice and <u class="spelling">eldeflower</u> juice is very pleasant.
mark 강조(highlight)
Elderflower cordial, with one <mark>part</mark> cordial to ten <mark>part</mark>s water, stands a<mark>part</mark> from the rest.
bdi 텍스트 방향 구분
The recommended restaurant is <bdi lang="">My Juice Café (At The Beach)</bdi>.
bdo 텍스트 방향 서식
The proposal is to write English, but in reverse order. "Juice" would become "<bdo dir=rtl>Juice</bdo>"
span 기타
In French we call it <span lang="fr">sirop de sureau</span>.
br 줄 바꿈
Simply Orange Juice Company<br>Apopka, FL 32703<br>U.S.A.
wbr 줄 바꿈 기회
www.simply<wbr>orange<wbr>juice.com

4.6. 편집

insdel 요소(element)들은 문서에 대한 편집을 나타냅니다.

4.6.1. ins 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
어구(phrasing) 콘텐트가 기대되는 곳.
콘텐트 모델:
투명.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
cite - Link to the source of the quotation or more information about the edit
datetime - Date and (optionally) time of the change
허용된 ARIA 역할(role) 속성(attribute) 값들:
모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLModElement 인터페이스를 사용.

ins 요소(element)는 문서에 대한 삽입을 나타냅니다.

다음은 단일 문단의 삽입을 나타냅니다:
<aside>
  <ins>
  <p> I like fruit. </p>
  </ins>
</aside>

다음과 같이 할 경우, because aside 요소(element) 내 모든 것이 여기서 어구(phrasing) 콘텐트로 세기 때문에 단 하나의 문단만 존재합니다:

<aside>
  <ins>
  Apples are <em>tasty</em>.
  </ins>
  <ins>
  So are pears.
  </ins>
</aside>

ins 요소(element)들은 암묵적 문단 경계들을 가로지르지 않아야(should) 합니다.

다음 예는 두 문단들의 추가를 보여주며, 두 번째 것이 두 개 부분들에 삽입되었습니다. 이 예에서 첫 번째 ins 요소(element)는 따라서 문단 경계를 가로지르며, 이는 잘못된 형식으로 간주됩니다.
<aside>  <!-- don’t do this -->
  <ins datetime="2005-03-16 00:00Z">
  <p> I like fruit. </p>
  Apples are <em>tasty</em>.
  </ins>
  <ins datetime="2007-12-19 00:00Z">
  So are pears.
  </ins>
</aside>

여기 이것을 마크업하는 더 나은 방법이 있습니다. 더 많은 요소(element)들을 사용하지만, 암묵적인 문단 경계들을 가로지르는 요소(element)들은 없습니다.

<aside>
  <ins datetime="2005-03-16 00:00Z">
  <p> I like fruit. </p>
  </ins>
  <ins datetime="2005-03-16 00:00Z">
  Apples are <em>tasty</em>.
  </ins>
  <ins datetime="2007-12-19 00:00Z">
  So are pears.
  </ins>
</aside>

4.6.2. del 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
어구(phrasing) 콘텐트가 기대되는 곳.
콘텐트 모델:
투명.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
cite - 인용구(quotation) 혹은 편집에 대한 더 많은 정보의 소스로의 링크
datetime - 변경의 날짜와 (선택적으로) 시간
허용된 ARIA 역할(role) 속성(attribute) 값들:
모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
HTMLModElement 인터페이스를 사용.

del 요소(element)는 문서로부터의 제거를 나타냅니다.

del 요소(element)는 암묵적 문단 경계를 가로지르지 않아야(should) 합니다.

다음은 완료된 것의 날짜와 시간을 줄을 그어 지워진 항목들이 있는 "할 일" 목록을 보여줍니다.
<h1>To Do</h1>
<ul>
  <li>Empty the dishwasher</li>
  <li><del datetime="2009-10-11T01:25-07:00">Watch Walter Lewin’s lectures</del></li>
  <li><del datetime="2009-10-10T23:38-07:00">Download more tracks</del></li>
  <li>Buy a printer</li>
</ul>

4.6.3. insdel 요소(element)들에 공통된 속성(attribute)들

cite 속성(attribute)은 변경을 설명하는 문서의 주소를 명시하는데 사용될 수 있습니다. 그 문서가 긴 경우, 예를 들어 회의록의 경우, 작성자들은 변경을 논하는 그 문서의 특정 부분을 가리키는 문서 조각 식별자를 포함하도록 권장됩니다.

cite 속성(attribute)이 존재한다면, 그것은 변경을 설명하는 유효한 잠정적으로 공백으로 둘러 싸일 수 있는 URL이어야(must) 합니다. 해당하는 출처(citation) 링크를 얻기 위해, 속성(attribute)의 값은 요소(element)에 관련하여 반영되어야(must) 합니다. 유저 에이전트들은 그러한 출처(citation) 링크드를 따라가는 것을 허용할 수 있지만, 그것들은 독자들을 위한 것이 아닌, 주로 특정한 사용을 (예를 들어, 사이트의 편집들에 대한 통계를 수집하는 서버 사이드 스크립트들) 위해 의도된 것입니다.

datetime 속성(attribute)은 변경의 시간과 날짜를 명시하는데 사용 될 수 있습니다.

존재한다면, datetime 속성(attribute)이 값은 선택적인 시간을 가진 유효한 날짜 문자열이어야(must) 합니다.

유저 에이전트들은 날짜나 시간 문자열 해석 알고리즘에 따라 datetime 속성(attribute)을 해석해야(must) 합니다. 그것이 날짜세계 날짜와 시간을 반환하지 않는다면, 수정 사항은 연관된 타임스탬프를 (값은 비 규범적입니다; 이것은 선택적인 시간을 가진 유효한 날짜 문자열이 아닙니다) 가지지 않습니다. 그렇지 않으면, 수정 사항은 주어진 날짜세계 날짜와 시간에 만들어진 것으로 표기됩니다. 주어진 값이 세계 날짜와 시간이라면 유저 에이전트들은 주어진 일시(datetime)이 존재하는 표준 시간대를 결정하기 위해 연관된 표준시간대 편차 정보를 사용해야(should) 합니다.

이 값은 사용자에게 보여질 수 있지만, 주로 특정한 사용에 대해 의도된 것입니다.

insdel 요소(element)들은 HTMLModElement 인터페이스를 구현해야(must) 합니다:

interface HTMLModElement : HTMLElement {
  attribute DOMString cite;
  attribute DOMString dateTime;
};

cite IDL 속성(attribute)은 요소(element)의 cite 콘텐트 속성(attribute)을 반영해야(must) 합니다. dateTime IDL 속성(attribute)은 요소(element)의 datetime 콘텐트 속성(attribute)을 반영해야(must) 합니다.

4.6.4. 편집과 문단

이 섹션은 비규범적입니다.

insdel 요소(element)들은 문단화에 영향을 가지지 않기 때문에, 문단들이 암묵적 인 경우 (명시적인 p 요소(element)들 없이), insdel 요소(element)가 전체 문단이나 다른 비 어구(phrasing) 콘텐트들과 다른 문단의 일부 모두에 걸치는 것이 가능합니다. 예를 들어:

<section>
  <ins>
  <p>
    This is a paragraph that was inserted.
  </p>
  This is another paragraph whose first sentence was inserted
  at the same time as the paragraph above.
  </ins>
  This is a second sentence, which was there all along.
</section>

p 요소(element)들 내 일부 문단들을 감싸는 것만으로, 동일한 insdel 요소(element)에 의해 씌워지는 한 개 문단의 말미, 두 번째 문단 전체, 세 번째 문단의 서두를 얻게 될 수 있습니다 (하지만 이것은 매우 혼란스럽고, 좋은 사례로 간주되지 않습니다):

<section>  This is the first paragraph. <ins>This sentence was
  inserted.
  <p>This second paragraph was inserted.</p>
  This sentence was inserted too.</ins> This is the
  third paragraph in this example.
  <!-- (don’t do this) -->
</section>

하지만, 암묵적인 문단들이 정의되는 방법 때문에, 동일한 insdel 요소(element)를 사용하여 한 개 문단의 말미와 다음 문단의 서두를 마크업하는 것을 가능하지 않습니다. 대신 예를 들어 다음과 같이, 하나의 (혹은 두 개의) p 요소(element)들과 두 개의 insdel 요소(element)들을 사용해야(have to) 합니다:

<section>
  <p>This is the first paragraph. <del>This sentence was
  deleted.</del></p>
  <p><del>This sentence was deleted too.</del> That
  sentence needed a separate &lt;del&gt; element.</p>
</section>

부분적으로 위에 설명된 혼란의 이유로, 작성자들은 암묵적 문단들 경계들을 가로지르는 insdel 요소(element)들을 가지는 대신, 항상 모든 문단을 p 요소(element)를 가지고 마크업 하도록 강하게 권장됩니다.

4.6.5. 편집과 목록

이 섹션은 비규범적입니다.

olul 요소(element)들의 콘텐트 모델들은 자식으로 insdel 요소(element)들을 허용하지 않습니다. 목록들은 삭제된 것으로 표기된 항목들을 포함하여, 항상 모든 그들의 항목들을 나타냅니다.

항목이 삽입되었거나 삭제되었음을 나타내기 위해, insdel 요소(element)는 li 요소(element)의 콘텐츠를 둘러 감쌀 수 있습니다. 항목이 다른 것으로 교체되었다는 것을 나타내기 위해, 단일 li 요소(element)가 하나 이상의 ins 요소(element)들이 뒤따르는 하나 이상의 del 요소(element)들을 가질 수 있습니다.

다음 예에서, 빈 것으로 시작된 항목은 시간이 지남에 따라 추가되고 제거된 항목들을 가집니다. 예에서 강조되어진 부분은 목록의 "현재" 상태인 부분들을 보여줍니다. 하지만, 목록 항목 번호들은 편집들을 고려하지 않습니다.
<h1>Stop-ship bugs</h1>
<ol>
  <li><ins datetime="2008-02-12T15:20Z">Bug 225:
  Rain detector doesn’t work in snow</ins></li>
  <li><del datetime="2008-03-01T20:22Z"><ins datetime="2008-02-14T12:02Z">Bug 228:
  Water buffer overflows in April</ins></del></li>
  <li><ins datetime="2008-02-16T13:50Z">Bug 230:
  Water heater doesn’t use renewable fuels</ins></li>
  <li><del datetime="2008-02-20T21:15Z"><ins datetime="2008-02-16T14:25Z">Bug 232:
  Carbon dioxide emissions detected after startup</ins></del></li>
</ol>
다음 예에서, 과일로 시작된 목록은 색상들을 가진 목록으로 교체되었습니다.
<h1>List of <del>fruits</del><ins>colors</ins></h1>
<ul>
  <li><del>Lime</del><ins>Green</ins></li>
  <li><del>Apple</del></li>
  <li>Orange</li>
  <li><del>Pear</del></li>
  <li><ins>Teal</ins></li>
  <li><del>Lemon</del><ins>Yellow</ins></li>
  <li>Olive</li>
  <li><ins>Purple</ins></li>
</ul>

4.6.6. 편집과 표

이 섹션은 비규범적입니다.

표 모델의 일부를 형성하는 요소(element)들은 insdel 요소(element)들을 허용하지 않는 복잡한 콘텐트 모델을 가지므로, 표에 대한 편집을 나타내는 것은 어려울 수 있습니다.

전체 행 또는 전체 열이 추가 혹은 제거되었음을 나타내기 위해, 그 행이나 열 내의 각 칸의 전체 콘텐츠가 insdel 요소(element)들로 (각각) 감싸질 수 있습니다.

여기, 표의 행이 추가되었습니다:
<table>
  <thead>
  <tr> <th> Game name           <th> Game publisher   <th> Verdict
  <tbody>
  <tr> <td> Diablo 2            <td> Blizzard         <td> 8/10
  <tr> <td> Portal              <td> Valve            <td> 10/10
  <tr> <td> <ins>Portal 2</ins> <td> <ins>Valve</ins> <td> <ins>10/10</ins>
</table>

여기, 열이 제거되었습니다 (이유를 설명하는 페이지로의 링크와 마찬가지로, 제거된 시간도 주어집니다):

<table>
  <thead>
  <tr> <th> Game name           <th> Game publisher   <th> <del cite="/edits/r192" datetime="2011-05-02 14:23Z">Verdict</del>
  <tbody>
  <tr> <td> Diablo 2            <td> Blizzard         <td> <del cite="/edits/r192" datetime="2011-05-02 14:23Z">8/10</del>
  <tr> <td> Portal              <td> Valve            <td> <del cite="/edits/r192" datetime="2011-05-02 14:23Z">10/10</del>
  <tr> <td> Portal 2            <td> Valve            <td> <del cite="/edits/r192" datetime="2011-05-02 14:23Z">10/10</del>
</table>

일반적으로 말해서, 더 복잡한 편집들을 (예를 들어, 모든 이후 칸테들이 위나 왼쪽으로 이동시켜 칸이 삭제되는) 나타내는 좋은 방법은 없습니다.

4.7. 삽입(embedded) 콘텐트

4.7.1. 소개

이 섹션은 비규범적입니다.

단일 이미지 리소스가 존재하는 경우, HTML에 이미지를 삽입하기 위해 img 요소(element)와 그것의 srcalt 속성(attribute)들을 사용합니다.

<h2>From today’s featured article</h2>
<img src="/uploads/100-marie-lloyd.jpg" alt="" width="100" height="150">
<p><b><a href="/wiki/Marie_Lloyd">Marie Lloyd</a></b> (1870–1922)
was an English <a href="/wiki/Music_hall">music hall</a> singer, ...

하지만, 작성자들이 유저 에이전트가 선택할 수 있는 여러 이미지 리소스들을 사용하기를 원할 수 있는 여러 상황들이 있습니다:

  • 다른 사용자들은 다른 환경적 특성들을 가질 수 있습니다:

    • 사용자의 물리적 화면 크기는 다른 사용자와 서로 다를 수 있습니다.

      휴대 전화의 화면은 대각선으로 4인치일 수 있는 반면, 노트북의 화면은 대각선으로 14인치일 수 있습니다.

      전화의 화면은 노트북의 화면과 비교하여 매우 작습니다.

      이것은 이미지의 렌더링 된 크기가 뷰포트 크기에 따라 달라지는 경우에만 관련이 있습니다.

    • 사용자들의 화면 픽셀 밀도는 다른 사용자와 서로 다를 수 있습니다.

      휴재 전화의 화면은 그것들의 물리적 화면 크기와 상관없이, 다른 휴대 전화의 크기와 비교하여 인치 당 3배의 물리적 픽셀을 가질 수 있습니다.

      전화 하나는 큰 픽셀들을 가지고, 다른 것은 작은 픽셀들을 가집니다.

    • 사용자의 확대 수준은 다른 사용자와 다를 수 있거나, 단일 사용자에 대해서 시간이 지남에 따라 변경될 수 있습니다.

      사용자는 좀 더 자세한 모습을 얻을 수 있도록 특정 이미지를 확대할 수 있습니다.

      확대 수준과 화면 픽셀 밀도는 (이전 지점) CSS 픽셀 당 물리적 화면 픽셀 수 모두에 영향을 줄 수 있습니다. 이 비율은 일반적으로 기기 픽셀 비율을 나타냅니다.

    • 사용자의 화면 방향은 다른 사용자와 다를 수 있거나, 단일 사용자에 대해 시간이 지남에 따라 변할 수 있습니다.

      태블릿은 똑바로 세우거나 90도 회전시킬 수 있기 때문에, 화면은 "세로" 또는 "가로"입니다.

      태블릿은 두 개 방향을 가집니다.

    • 사용자의 네트워크 속도, 네트워크 지연, 대역폭 비용은 다른 사용자와 다를 수 있거나, 단일 사용자에 대해 시간이 지남에 따라 변할 수 있습니다.

      사용자는 직장에서 낮은 지연과 고정 비용 연결로 빠를 수, 집에서 낮은 지연과 고정 비용 연결로 느릴 수, 다른 곳에서 높은 지연과 다양한 비용 연결이 될 수 있습니다.

  • 작성자들은 일반적으로 뷰포트의 너비에 따라 다르게 렌더링되는 크기를 가진 동일한 이미지를 보기 원할 수 있습니다. 이것은 보통 뷰포트기반 선택을 나타냅니다.

    웹 페이지는 항상 전체 뷰포트 너비에 걸치는 상단에 배너를 가질 수 있습니다. 이 경우에, 이미지의 렌더링 된 크기는 화면의 물리적 크기에 따라 다릅니다 (최대화 된 브라우저 창이라고 가정하여).

    똑바로 들고 있는 휴대 전화는 상단에 작은 늑대를 보여주고, 태블릿은 동일한 이미지를 보여주지만 더 큽니다.

    다른 웹 페이지는, 작은 물리적 크기를 가진 화면들에 대해서는 단일 열을, 중간 물리적 크기를 가진 화면들에 대해서는 두 개 열들을, 큰 물리적 크기를 가진 화면들에 대해서는 세 개 열들을, 뷰포트를 채우도록 각 경우에 렌더링 된 크기내에 다양한 이미지들을 가진, 열(column)들에 이미지를 가질 수 있습니다. 이 경우, 이미지의 렌더링 된 크기는 화면이 작아짐에도 불구하고, 두 개 열 레이아웃에 비해 한 개 열 레이아웃에서 수 있습니다.

    회전 된 휴대 전화는 케틀벨 스윙 이미지의 상단 부분을 보여줍니다; 똑바로 들고 있는 태블릿은 두 개 열들에 약간 작은 이미지들을 보여줍니다; 노트북은 세 개 열들에 이미지들을 보여줍니다.

  • 작성자들은 렌더링 된 이미지의 크기에 따라 다른 이미지 콘텐트를 보여주기를 원합니다. 이것은 보통 art direction을 나타냅니다.

    웹 페이지가 큰 물리적 크기를 가진 화면에 보여지는 경우 (최대화 된 브라우저 창이라고 가정하여), 작성자는 이미지의 중요한 부분을 둘러싸는 덜 관련된 부분들을 포함하기를 원할 수 있습니다. 동일한 웹 페이지가 작은 물리적 크기를 가진 화면에 보여지는 경우, 작성자는 이미지의 중요한 부분만을 보여주기를 원할 수 있습니다.

    똑바로 들고 있는 휴대 전화는 늑대의 잘려진 이미지를 보여줍니다; 회전 된 태블릿은 잘려지지 않은 이미지를 보여줍니다.

  • 작성자들은 유저 에이전트가 지원하는 이미지 형식에 따라, 동일한 이미지 콘텐트이지만 다른 이미지 형식을 사용하는 이미지를 보여주기 원할 수 있습니다. 이것은 보통 이미지 형식 기반 선택을 나타냅니다.

    웹 페이지는 JPEG, WebP, JEGP XR 이미지 형식으로 몇 가지 이미지들을 가질 수 있으며, 후자의 두 개는 JPEG와 비교하여 더 우수한 압축을 가집니다. 다른 유저 에이전트들은 더 나은 압축률을 제공하는 몇 형식들을 가진 다른 이미지 형식들을 지원하기 때문에, 작성자들은 그것들을 지원하지 않는 유저 에이전트들에 대해 JPEG 폴백을 제공하면서 지원하는 유저 에이전트들에 더 나은 형식들을 제공하려고 합니다.

위 상황들은 상호 배타적이지 않습니다. 예를 들어, 다른 기기 픽셀 비율에 대한 다른 리소스들을 art direction에 대한 다른 리소스들과 결합하는 것은 합리적입니다.

스크립팅을 사용하여 이 문제들을 해결하는 것이 가능한 반면, 그렇게 하는 것은 다른 문제들을 도입시킵니다:

  • 일부 유저 에이전트들은 스크립트가 수행 될 기회를 가지기 전에 HTML 마크업에 명시된 이미지들을 공격적으로 다운로드하기 때문에, 웹 페이지들은 더 빨리 로딩이 완료됩니다. 스크립트가 다운로드 할 이미지를 변경한다면, 유저 에이전트는 대신 더 나쁜 페이지 로딩 성능을 야기할 수 있는 잠재적으로 두 개의 분리된 다운로드들을 시작할 것입니다.
  • 작성자가 HTML 마크업에 이미지를 명시하는 것을 방지하고 대신 스크립트로부터 단일 다운로드를 인스턴스화 한다면, 그것은 위 이중 다운로드 문제를 방지하지만 대신 스크립팅이 비활성화 된 사용자들에 대해 이미지를 전혀 다운로드하지 않게 하고 적극적인 이미지 다운로드 최적화를 비활성화 합니다.

이를 염두해 두고, 이 명세는 선언적 방법으로 위 문제를 해결하는 많은 기능들을 소개합니다.

이미지의 렌더링 된 크기가 고정 된 경우 기기 픽셀 비율기반 선택

img 요소(element)의 srcsrcset 속성(attribute)들이 크기가 다양한 여러 이미지들을 제공하기 위해 x 설명자를 사용하여 사용될 수 있습니다 (작은 이미지는 큰 이미지의 축소 버전입니다).

이미지의 렌더링된 크기가 뷰포트 너비에 따라 다르지만 (뷰포트 기반 선택) art direction과 함께 사용될 수 있는 경우 x 설명자는 적절하지 않습니다.

<h2>From today’s featured article</h2>
<img src="/uploads/100-marie-lloyd.jpg"
      srcset="/uploads/150-marie-lloyd.jpg 1.5x, /uploads/200-marie-lloyd.jpg 2x"
      alt="" width="100" height="150">
<p><b><a href="/wiki/Marie_Lloyd">Marie Lloyd</a></b> (1870–1922)
was an English <a href="/wiki/Music_hall">music hall</a> singer, ...

유저 에이전트는 사용자의 화면의 픽셀 밀도, 확대 수준, 사용자의 네트워크 상태들 같은 다른 요소들에 따라 주어진 리소스들 중 어떤 것을 선택할 수 있습니다.

srcset 속성(attribute)을 아직 이해하지 못하는 이전의 유저 에이전트들과의 하위 호환성을 위해, URL 중 하나는 img 요소(element)의 src 속성(attribute)에 명시됩니다. 이것은 이전 유저 에이전트들에서조차도 유용하게 (아마도 사용자가 원하는 것보다 낮은 해상도 일지라도) 표시되는 것을 야기할 것입니다. 새로운 유저 에이전트들에 대해, src 속성(attribute)은 마치 srcset1x 설명자로 명시된 것 처럼 리소스 선택에 참여합니다.

이미지의 렌더링 되는 크기는 유저 에이전트가 이미지가 다운로드 되기 전에 이미지에 대한 공간을 할당하는 것을 허용하는 widthheight 속성(attribute)들에 주어집니다.

뷰포트 기반 선택

srcsetsizes 속성(attribute)들은 w 설명자를 사용하여, 크기가 다른 여러 이미지를 제공하는데 사용될 수 있습니다 (작은 이미지는 큰 이미지의 축소 버전입니다).

이 예에서, 배너 이미지는 (적절한 CSS를 사용하여) 전체 뷰포트 너비를 차지합니다.
<h1><img sizes="100vw" srcset="wolf-400.jpg 400w, wolf-800.jpg 800w, wolf-1600.jpg 1600w"
    src="wolf-400.jpg" alt="The rad wolf"></h1>

유저 에이전트는 명시된 w 설명자와 sizes 속성(attribute)에 명시된 렌더링 되는 크기로부터 각 이미지의 실질적인 픽셀 밀도를 계산할 것입니다. 그 후 사용자의 화면의 픽셀 밀도, 확대 수준, 사용자의 네트워크 조건들과 같은 가능한 다른 요인들에 따라 주어진 리소스 중 어느 것을 선택할 수 있습니다.

사용자의 화면이 320 CSS 픽셀 너비라면, 이것은 wolf-400.jpg 1.25x, wolf-800.jpg 2.5x, wolf-1600.jpg 5x를 명시하는 것과 동등합니다. 반면에, 사용자의 화면이 1200 CSS 픽셀 너비라면, 이것은 wolf-400.jpg 0.33x, wolf-800.jpg 0.67x, wolf-1600.jpg 1.33x을 명시하는 것과 동등합니다. w 설명자와 sizes 속성(attribute)을 사용하는 것에 의해, 유저 에이전트는 사용자의 디바이스의 크기에 상관없이 다운로드할 적절한 이미지 소스를 선택할 수 있습니다.

하위 호환성을 위해, URL들 중 하나는 img 요소(element)의 src 속성(attribute)에 명시됩니다. 새로운 유저 에이전트들에서, src 속성(attribute)은 srcset 속성(attribute)이 w 설명자들을 사용하는 경우 무시됩니다.

이 예에서, sizes 속성(attribute)은 기본 값이 100vw이기 때문에 생략될 수 있습니다.

이 예에서, 웹 페이지는 뷰포트의 너비에 따른 세 가지 레이아웃들을 가집니다. 좁은 레이아웃은 이미지들의 한 개 열을 (각 이미지의 너비가 약 100%) 가지고, 중간 레이아웃은 이미지들의 두 개 열을 (각 이미지의 너비가 약 50%) 가지며, 가장 넓은 레이아웃은 이미지들의 세 개 열과 일부 페이지 여백을 (각 이미지의 너비는 약 33%) 가집니다. 이 레이아웃들은 뷰포트가 각각 폭 30em과 폭 50em 인 경우에 나뉩니다.
<img sizes="(max-width: 30em) 100vw, (max-width: 50em) 50vw, calc(33vw - 100px)"
srcset="swing-200.jpg 200w, swing-400.jpg 400w, swing-800.jpg 800w, swing-1600.jpg 1600w"
src="swing-400.jpg" alt="Kettlebell Swing">

sizes 속성(attribute)은 30em50em에 레이아웃 브레이크포인트들을 설정하고, 이 브레이크포인트들 사이의 이미지 크기들을 100vw, 50vw, calc(33vw - 100px)로 선언합니다. 이 크기들은 CSS에 명시된 실제 이미지 너비와 정확하게 일치해야(have to) 할 필요는 없습니다.

유저 에이전트는 true로 평가되는 <media-condition> (괄호 안의 부분)를 가진 첫 번째 항목을 사용하거나, 모든 것이 false로 평가되는 경우 마지막 항목 (calc(33vw - 100px))를 사용하여 sizes 속성(attribute)으로부터 너비를 선택할 것입니다.

예를 들어, 뷰포트 너비가 29em이라면, (max-width: 30em)는 true로 평가되고 100vw가 사용되고, 따라서 리소스 선택의 목적에 대한 이미지 크기는 29em입니다. 뷰포트 너비가 32em이라면, (max-width: 30em)는 false로 평가되고 (max-width: 50em)가 true로 평가되며 50vw가 사용되고, 따라서 리소스 선택의 목적에 대한 이미지 크기는 16em입니다(뷰포트 너비의 반). 약간 넓은 뷰포트는 레이아웃이 다르기 때문에 더 작은 이미지를 야기하는 것에 주목하세요.

유저 에이전트는 이후 실질적인 픽셀 밀도를 계산하고 이전 예와 마찬가지로 적절한 리소스를 선택할 수 있습니다.

Art direction 기반 선택

media 속성(attribute)을 가진 picture 요소(element)와 source 요소(element)는 이미지 콘텐트가 다른 여러 이미지들을 제공하는데 사용될 수 있습니다(예를 들어 작은 이미지는 큰 이미지의 잘려진 버전이 될 수 있습니다.).

<picture>
  <source media="(min-width: 45em)" srcset="large.jpg">
  <source media="(min-width: 32em)" srcset="med.jpg">
  <img src="small.jpg" alt="The wolf runs through the snow.">
</picture>

유저 에이전트는 media 속성(attribute) 내 미디어쿼리와 일치하는 첫 번째 source 요소(element)를 선택할 것이고, 이후 그것의 srcset 속성(attribute)으로부터 적절한 URL을 선택할 것입니다.

이미지의 렌더링 되는 크기는 선택되는 리소스에 따라 달라집니다. 유저 에이전트가 다운로드 된 이미지를 소유하기 전에 사용할 수 있는 치수를 명시하기 위해 CSS가 사용될 수 있습니다.

img { width: 300px; height: 300px }
@media (min-width: 32em) { img { width: 500px; height:300px } }
@media (min-width: 45em) { img { width: 700px; height:400px } }
이 예는 art direction기기 픽셀 비율 기반 선택을 결합합니다. 뷰포트의 반을 차지하는 배너는 넓은 화면들에 대한 하나와 좁은 화면들에 대한 하나 두 가지 버전들로 제공됩니다.
<h1>
  <picture>
  <source media="(max-width: 500px)" srcset="banner-phone.jpeg, banner-phone-HD.jpeg 2x">
  <img src="banner.jpeg" srcset="banner-HD.jpeg 2x" alt="The Breakfast Combo">
  </picture>
</h1>
이미지 형식 기반 선택

source 요소(element)에 type 속성(attribute)이 다른 형식들로 여러 이미지들을 제공하는데 사용될 수 있습니다.

<h2>From today’s featured article</h2>
<picture>
  <source srcset="/uploads/100-marie-lloyd.webp" type="image/webp">
  <source srcset="/uploads/100-marie-lloyd.jxr" type="image/vnd.ms-photo">
  <img src="/uploads/100-marie-lloyd.jpg" alt="" width="100" height="150">
</picture>
<p><b><a href="/wiki/Marie_Lloyd">Marie Lloyd</a></b> (1870–1922)
was an English <a href="/wiki/Music_hall">music hall</a> singer, ...

이 예에서, 유저 에이전트는 지원되는 MIME 타입을 가지는 type 속성(attribute)을 가진 첫 번째 source를 선택할 것입니다. 유저 에이전트가 WebP 이미지들을 지원한다면, 첫 번째 source 요소(element)가 선택됩니다. 그렇지 않고, 유저 에이전트가 JPEG XR 이미지들을 지원한다면, 두 번째 source 요소(element)가 선택 될 것입니다. 그 형식들 중 어떤 것도 지원되지 않는다면, img 요소(element)가 선택 될 것입니다.

4.7.2. 종속성

미디어 쿼리 [MEDIAQ]

<media-condition>

CSS 값과 단위 [CSS-VALUES]

<length>

CSS 구문 [CSS-SYNTAX-3]

콤마로 구분된 컴포넌트 값들의 목록 해석

컴포넌트 값

<whitespace-token>

4.7.3. picture 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
삽입(embedded) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
삽입(embedded) 콘텐트가 예상되는 곳.
콘텐트 모델:
선택적으로 스크립트 지원 요소(element)들과 섞어서, 한 개 img 요소(element)가 뒤따르는 0개 이상의 source 요소(element)들.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
없음
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
DOM 인터페이스:
interface HTMLPictureElement : HTMLElement {};

picture 요소(element)는 화면 픽셀 밀도, 뷰포트 크기, 이미지 형식, 다른 요인들에 기반하여, 작성자들이 사용할 이미지 리소스에 대해 유저 에이전트에게 선언적으로 제어하거나 힌트를 제공할 수 있도록 허용하기 위해 그것의 포함된 img 요소(element)에 여러 소스들을 제공하는 컨테이너 입니다. 이것은 그것의 자식을 나타냅니다.

picture 요소(element)는 유사하게 보이는 videoaudio 요소(element)들과는 다소 다릅니다. 그들 모두가 source 요소(element)들을 포함하는 반면, source 요소(element)의 src 속성(attribute)은 요소(element)가 picture 요소(element)에 중첩되어 있는 경우 의미(meaning)를 가지지 않고, 리소스 선택 알고리즘이 다릅니다. 뿐만 아니라, picture 요소(element) 자체는 어떤 것도 표시하지 않습니다; 단지 여러 URL들 중에서 선택할 수 있는 포함된 img 요소(element)에 대한 컨텍스트를 제공할 뿐입니다.

4.7.4. picture 요소(element)와 함께 사용되는 경우 source 요소(element)

카테고리:
source 요소(element)와 동일.
이 요소(element)가 사용될 수 있는 컨텍스트:
picture 요소(element)의 자식으로, img 요소(element) 이전에.
콘텐트 모델:
source 요소(element)와 동일.
text/html에서 태그 생략:
종료 태그 없음.
콘텐트 속성(attribute)들:
범용 속성(attribute)들
srcset - 다른 상황들에 (예를 들어, 고해상도 디스플레이들, 작은 모니터들 등) 사용될 이미지들
sizes - 브레이크포인트들 사이의 이미지 크기들
media - 적용 가능한 매체
type - 삽입된 리소스의 유형
허용된 ARIA 역할(role) 속성(attribute) 값들:
없음
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
DOM 인터페이스:
partial interface HTMLSourceElement {
  attribute DOMString srcset;
  attribute DOMString sizes;
  attribute DOMString media;
};

이 섹션에서 작성 요구 사항들은 source 요소(element)가 picture 요소(element)인 부모를 가지는 경우에만 적용됩니다.

source 요소(element)는 작성자들이 img 요소(element)들에 대한 여러 대체 소스 세트들을 명시하는 것을 허용합니다. 이것은 그 자체로 아무 것도 나타내지 않습니다.

srcset 콘텐트 속성(attribute)은 존재해야(must) 하고, 각각 다음 것이 U+002C 콤마 문자 (,)로 구분되는 하나 이상의 이미지 후보 문자열들로 구성되어야(must) 합니다. 이미지 후보 문자열들이 설명자를 포함하지 않고 URL 이후 공백 문자들을 포함하지 않는다면, 다음 이미지 후보 문자열이 있다면 이것은 하나 이상의 공백 문자들로 시작해야(must) 합니다.

srcset 속성(attribute)이 너비 설명자를 사용하는 이미지 후보 문자열들을 가진다면, sizes 콘텐트 속성(attribute) 역시 존재해야(must)하고, 값은 유효한 소스 크기 목록이어야(must) 합니다.

media 콘텐트 속성(attribute) 역시 존재 할 수 있습니다. 존재한다면, 값은 유효한 미디어쿼리 목록을 포함해야(must) 합니다.

type 콘텐트 속성(attribute) 역시 존재할 수 있습니다. 존재한다면, 값은 유효한 MIME 타입이어야(must) 합니다. 이것은 유저 에이전트가 주어진 유형을 지원하지 않을 경우 다음 source 요소(element)로 건너뛰는 것을 허용하기 위해 소스 세트에 이미지들의 유형을 제공합니다.

type 속성(attribute)가 명시되지 않은 경우, 유저 에이전트는 다른 source 요소(element)를 가져온 이후 이미지 형식을 지원하지 않는 다는 것을 발견한다면 그것을 선택하지 않을 것입니다.

source 요소(element)가 다음 형제 source 요소(element)나 srcset 속성(attribute)이 명시된 img 요소(element)를 가지는 경우, 그것은 다음 중 적어도 하나를 가져야(must) 합니다:

src 속성(attribute)은 존재하지 않아야(must) 합니다.

IDL 속성(attribute)들 srcset, sizes, media는 동일한 이름의 각 콘텐트 속성(attribute)들을 반영 해야(must) 합니다.

4.7.5. img 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
삽입(embedded) 콘텐트.
양식(form) 관련 요소(element).
요소(element)가 usemap 속성(attribute)을 가진다면: 대화형(interactive) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
삽입(embedded) 콘텐트가 예상되는 곳.
콘텐트 모델:
없음
text/html에서 태그 생략:
종료 태그 없음.
콘텐트 속성(attribute)들:
범용 속성(attribute)들
alt - 이미지들이 사용 가능하지 않은 경우 대체 텍스트
src - 리소스의 주소
srcset - 다른 상황들에서 (예를 들어, 고화질 디스플레이들, 작은 모니터들 등등) 사용할 이미지들
sizes - 브레이크포인트들 사이의 이미지 크기들
crossorigin - 요소(element)가 교차출처 요청들을 처리하는 방법
usemap - 사용할 이미지 맵의 이름
ismap - 이미지가 서버 사이드 이미지 맵인지의 여부
width - 가로 치수
height - 세로 치수
허용된 ARIA 역할(role) 속성(attribute) 값들:
alt 속성(attribute) 값이 비어있는 (alt="") img 요소(element)에 대해서는 presentation 역할(role)만, 그렇지 않으면 모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
[NamedConstructor=Image(선택적으로 부호 없는 너비 길이, 선택적으로 부호 없는 높이 길이)]
interface HTMLImageElement : HTMLElement {
  attribute DOMString alt;
  attribute DOMString src;
  attribute DOMString srcset;
  attribute DOMString sizes;
  attribute DOMString? crossOrigin;
  attribute DOMString useMap;
  attribute boolean isMap;
  attribute unsigned long width;
  attribute unsigned long height;
  readonly attribute unsigned long naturalWidth;
  readonly attribute unsigned long naturalHeight;
  readonly attribute boolean complete;
  readonly attribute DOMString currentSrc;
};

img 요소(element)는 이미지와 그것의 폴백 콘텐트를 나타냅니다.

srcsrcset, 그리고 부모가 picture 요소(element)인 경우 앞선 형제 source 요소(element)의 srcset 속성(attribute)들에 의해 주어진 이미지는 삽입(embedded) 콘텐트입니다; alt 속성(attribute)의 값은 img 요소(element)의 폴백 콘텐트이고, 이미지를 처리할 수 없거나 이미지 로딩이 비활성화 된 사용자나 유저 에이전트들에 대한 동등한 콘텐트를 제공합니다.

이미지의 대체 표현들에 대한 요구사항은 다음 섹센에 기술됩니다.

src 속성(attribute)은 존재해야(must)하고, 선택적으로 애니메이트 되고, 페이지화 되거나 스크립트화 되지 않는 비상호작용 이미지 리소스를 참조하는 유효한 잠정적으로 공백으로 둘러 싸일 수 있는 비어있지 않은 URL을 포함해야(must) 합니다.

srcset 속성(attribute)도 존재 할 수 있습니다. 존재한다면, 그것의 값은 하나 이상의, U+002C 콤마 문자 (,)로 다음이 각각 분리된, 이미지 후보 문자열들로 구성되어야(must) 합니다. 이미지 후보 문자열들이 설명자들을 포함하지 않고 URL 이후 공백 문자를 가지지 않는다면, 다음 이미지 후보 문자열이 있다면 하나 이상의 공백 문자들로 시작해야(must) 합니다.

이미지 후보 문자열은 이 목록 아래에 기술된 추가적인 제약 사항들을 가지고 순서에 따라 다음 컴포넌트들로 구성됩니다:

  1. 0개 이상의 공백 문자들.
  2. 선택적으로 애니메이트 되고, 페이지화 되거나 스크립트화 되지 않은 비상호작용 이미지 리소스를 참조하는, U+002C 콤마 문자 (,)로 시작하거나 끝나지 않는 유효한 비어있지 않은 URL.
  3. 0개 이상의 공백 문자들.
  4. 다음 중 0개 이상:

  5. 0개 이상의 공백 문자들.

동일한 요소(element)에 대한 다른 이미지 후보 문자열너비 설명자 값과 동일한 너비 설명자 값을 가진 요소(element)에 대한 이미지 후보 문자열은 존재하지 않아야(must) 합니다.

동일한 요소(element)에 대한 다른 이미지 후보 문자열픽셀 밀도 설명자 값과 동일한 픽셀 밀도 설명자 값을 가진 요소(element)에 대한 이미지 후보 문자열은 존재하지 않아야(must) 합니다. 이 요구사항의 목적을 위해, 설명자들이 없는 이미지 후보 문자열1x 설명자를 가진 이미지 후보 문자열과 동등합니다.

source 요소(element)가 sizes 속성(attribute)을 가지거나 img 요소(element)가 sizes 속성(attribute)을 가진다면, 그 요소(element)에 대한 모든 이미지 후보 문자열을은 명시된 너비 설명자를 가져야(must) 합니다.

sourceimg 요소(element)에 대한 이미지 후보 문자열이 명시된 너비 설명자를 가진다면, 그 요소(element)에 대한 모든 다른 이미지 후보 문자열는 명시된 너비 설명자 역시 가져야(must) 합니다.

이미지 후보 문자열너비 설명자에 명시된 너비는 이미지 후보 문자열의 URL에 의해 주어진 리소스가 고유 너비를 가진다면 리소스의 고유 너비와 일치해야(must)합니다.

위 요구사항들은 이미지가 정적 비트맵(예를 들어, PNG, GIF, JPEG), 단일 페이지 벡터 문서 (단일 페이지 PDF, SVG 루트 요소(element)를 가진 XML 파일), 애니메이트 된 비트맵(APNG, animated GIF), 애니메이트 된 벡터 그래픽(선언전 SMIL 애니메이션을 사용하는 SVG 루트 요소(element)를 가진 XML 파일들), 등등 일 수 있다는 것을 의미합니다. 하지만, 이 정의들은 스크린트가 있는 SVG 파일들, 여러 페이지 PDF 파일들, 상호작용 MNG 파일들, HTML 문서들, 평문 문서들, 등등을 불가능하게 합니다. [PNG] [GIF] [JPEG] [PDF] [XML] [APNG] [SVG11] [MNG]

srcset 속성(attribute)가 존재한다면, sizes 속성(attribute)도 존재할 수 있습니다. 이 속성(attribute)이 존재한다면, 그 값은 유효한 소스 크기 목록이어야(must) 합니다.

유효한 소스 크기 목록은 다음 뭄법과 일치하는 문자열입니다: [CSS-VALUES] [MEDIAQ]

<source-size-list> = <source-size># [ , <source-size-value> ]? | <source-size-value>
<source-size> = <media-condition> <source-size-value>
<source-size-value> = <length>

<source-size-value>는 음수가 아니어야(must) 합니다.

관련되는 것에 대한 혼란을 방지하기 위해, 백분율은 <source-size-value>에 허용되지 않습니다. vw 단위가 viewport 너비에 연관된 크기로 사용될 수 있습니다.

img 요소(element)는 레이아웃 도구로 사용되지 않아야 합니다. 특히, 투명 이미지는 거의 의미를 전달하지 않고 문서에 유용한 어떠한 것을 거의 추가하지 않기 때문에, img 요소(element)들은 투명 이미지들을 표시하는데 사용되지 않아야(should) 합니다.


crossorigin 속성(attribute)는 CORS 설정 속성(attribute) 입니다. 그것의 목적은 교차 출처 접근을 허용하는 서드 파티 사이트들로부터 이미지를 canvas를 가지고 사용하도록 허용하는 것입니다.


img 요소(element)는 현재 요청보류 중인 요청을 가집니다. 현재 요청은 초기에 새로운 이미지 요청으로 설정됩니다. 보류 중인 요청은 초기에 null로 설정됩니다. 현재 요청은 보통 img 요소(element) 자체로 언급됩니다.

이미지 요청상태, 현재 URL, 이미지 데이터를 가집니다.

이미지 요청상태는 다음 중 하나입니다:

사용 불가
유저 에이전트가 이미지 데이터를 얻지 못했거나 이미지의 일부 혹은 모든 데이터를 얻었지만 이미지 치수들을 얻기에 이미지를 충분히 디코드 하지 못한 경우.
일부 사용 가능
유저 에이전트가 이미지 데이터의 일부를 얻었고 적어도 이미지 치수들이 사용 가능 한 경우.
완전히 사용 가능
유저 에이전트가 모든 이미지 데이터를 얻었고 적어도 이미지 치수들이 사용 가능한 경우.
깨짐
유저 에이전트가 얻을 수 있는 모든 이미지 데이터를 얻었지만, 이미지 치수들을 얻기에 충분히 디코드 될 수 없는 경우 (예를 들어, 이미지가 손상되었거나, 지원되지 않는 형식이거나, 얻어질 수 있는 데이터가 없는 경우).

이미지 요청현재 URL은 초기에 빈 문자열입니다.

이미지 요청이미지 데이터는 디코드 된 이미지 데이터입니다.

이미지 요청일부 사용 가능한 상태에 있거나 완전히 사용 가능한 상태에 있는 경우, 그것은 사용 가능하다고 불립니다.

이미지 요청은 초기에 사용 불가입니다.

img 요소(element)가 사용 가능한 경우, 너비가 이미지의 밀도 보정 고유 너비이고, 높이가 이미지의 밀도 보정 고유 높이이며, 모양이 이미지의 고유 모양인 페인트 소스를 제공합니다.

스크립팅이 비활성화 된 브라우징 컨텍스트에서, 유저 에이전트들은 즉시 혹은 요청 시 마다 이미지들을 얻을 수 있습니다. 스크립팅이 활성화 된 브라우징 컨텍스트에서, 유저 에이전트들은 즉시 이미지들을 얻어야(must) 합니다.

이미지들을 즉시 얻는 유저 에이전트는 img 요소(element)가 생성되거나 관련 변경들을 경험할 때마다, 애니메이션 재시작 플래그 설정이 명시된 경우 이 플래그를 가지고 즉시 img 요소(element)의 이미지 데이터를 업데이트해야(must) 합니다.

이미지들을 요청 시마다 얻는 유저 에이전트는 img 요소(element)가 사용 불가 상태에 있을 경우에 한하여 이미지 데이터가 요구 될 때마다 (즉, 요청 시 마다) img 요소(element)의 이미지 데이터를 업데이트 해야(must) 합니다. img 요소(element)가 관련 변경들을 경험할 경우, 유저 에이전트가 요청 시에 이미지를 얻기만 한다면, img 요소(element)는 사용 불가 상태를 반환해야(must) 합니다.

img 요소(element)에 대한 관련 변경들은 다음과 같습니다:

  • 요소(element)의 src, srcset, width, sizes 속성(attribute)들이 설정, 변경, 제거 되는 것.
  • 요소(element)의 src 속성(attribute)이 이전 값과 동일한 값으로 설정 되는 것. 이것은 이미지 데이터 업데이트 알고리즘을 위한 애니메이션 재시작 플래그를 설정해야(must) 합니다.
  • 요소(element)의 crossorigin 속성(attribute)의 상태가 변경되는 것.
  • 요소(element)가 picture 부모 요소(element)로 삽입되거나 picture 부모 요소(element)로부터 제거되는 것.
  • 요소(element)의 부모가 picture 요소(element)이고 source 요소(element)가 이전 형제로 삽입 되는 것.
  • 요소(element)의 부모가 picture 요소(element)이고 이전 형제였던 source 요소(element)가 제거 되는 것.
  • 요소(element)의 부모가 picture 요소(element)이고 이전 형제인 source 요소(element)가 그것의 srcset, sizes, media, type 속성(attribute)들이 설정, 변경, 제거 되는 것.
  • 요소(element)의 채택 단계들이 수행되는 것.

img 요소(element)는 초기에 null 이어야(must) 하는 마지막 선택 된 소스를 가집니다.

이미지 요청은 초기에 uyndefined여야(must) 하는, 현재 픽셀 밀도를 가집니다.

img 요소(element)가 1.0이 아닌 현재 픽셀 밀도를 가지는 경우, 요소(element)의 이미지 데이터는 그것의 해상도가 CSS 픽셀 당 기기 픽셀로, 현재 픽셀 밀도 였던 것처럼 취급되어야(must) 합니다. 이미지의 밀도 보정 고유 너비와 높이현재 픽셀 밀도를 고려한 이후의 고유 너비와 높이입니다.

예를 들어, CSS 인치 당 96 CSS 픽셀로 주어진 스크린은, 현재 픽셀 밀도가 3.125라면, 그것은 CSS 인치 당 96 × 3.125 = 300 기기 픽셀이 있음을 의미하고, 따라서 이미지 데이터가 300x600이라면, 그것은 300 ÷ 3.125 = 96 CSS 픽셀 x 600 ÷ 3.125 = 192 CSS 픽셀의 고유 치수들 을 가집니다. 2.0의 현재 픽셀 밀도과 (CSS 인치 당 192 기기 픽셀) 동일한 이미지 데이터 (300x600)을 가진 경우, 고유 치수들은 150x300 이 될 것입니다.

Document 객체는 사용 가능한 이미지들의 목록을 가져야(must) 합니다. 이 목록 내의 각 이미지는 절대 URL, CORS 설정 속성(attribute) 모드, 그리고 모드가 No CORS라면 출처로 구성되는 튜플에 의해 식별됩니다. 각 이미지는 뿐만 아니라 상위 계층 캐싱 무시 플래그를 가집니다. 유저 에이전트들은 하나의 Document 객체의 사용 가능한 이미지들의 목록으로부터 항목들을 언제든지 다른 곳으로 복사할 수 있지만 (예를 들어, Document가 생성 될 때, 유저 에이전트들은 다른 Document들에 로드되는 모든 이미지들에 그것을 추가할 수 있습니다), 그렇게 수행될 때 이 방법으로 복사된 항목들의 키들을 변경하지 않아야(must)하고, 복사된 항목들에 대한 상위 계층 캐싱 무시 플래그를 해제해야(must) 합니다. 유저 에이전트들은 언제든지 (예를 들어, 메모리를 절약하기 위해) 그 목록들로부터 이미지들을 제거 할 수도 있습니다. 유저 에이전트들은 상위 계층 캐싱 무시 플래그가 해제 된 경우 리소스에 대해 주어진 상위 계층 캐싱 의미에 (예를 들어, HTTP Cache-Control 응답 헤더) 적절하게 사용 가능한 이미지들의 목록에서 항목들을 제거해야(must) 합니다.

사용 가능한 이미지들 목록src 속성(attribute)을 이전에 로드된 URL로 변경할 때 동기적 전환을 활성화하고, HTTP당 캐싱을 허용하지 않는 경우에도 동일한 문서에서 이미지들을 재 다운로드하는 것을 방지하기 위해 의도되었습니다. 이전 이미지가 여전히 로딩 중인 동안 동일한 이미지를 다시 다운로드 하는 것을 방지하는데에는 사용되지 않습니다.

예를 들어, 리소스가 HTTP 응답 헤더 Cache-Control: must-revalidate를 가진다면, 유저 에이전트는 사용 가능한 이미지들 목록으로부터 그것을 제거할 것이지만 별도로 이미지 데이터를 유지할 수 있고, 서버가 204 No Content 상태로 응답한다면 그것을 사용할 수 있습니다.

유저 에이전트가 선택적으로 애니메이션 재시작 플래그 설정을 가지고, img 요소(element)의 이미지 데이터를 업데이트하기 위한 경우, 다음 단계들을 수행해야(must) 합니다:

  1. 요소(element)의 노드 문서활성 문서가 아니라면, 이 하위 단계들을 수행합니다:

    1. 병렬로 이 알고리즘을 수행하는 것을 계속합니다.
    2. 요소(element)의 노드 문서활성 문서일 때가지 대기합니다.
    3. img 요소에 대한 이 알고리즘의 다른 인스턴스가 이 인스턴스 이후에 시작되었다면 (그것이 중단되었고 더 이상 수행중이 아니라 하더라도), 이 단계들을 중단합니다.
    4. 이 알고리즘을 계속하기 위한 마이크로작업을 대기열에 넣습니다.
  2. 유저 에이전트가 이미지들을 지원하지 못하거나, 그것의 이미지들에 대한 지원이 비활성화 되었다면, 현재 요청보류 중인 요청에 대한 이미지 요청을 중단시키고, 현재 요청사용 불가 상태로 설정하고, 보류 중인 요청을 null로 두고, 이 단계들을 중단합니다.
  3. 요소(element)가 srcsetpicture를 사용하지 않고 부모를 가지지 않거나 부모를 가지지만 picture 요소(element)가 아니고, 명시된 src 속성(attribute)을 가지며 그 값이 빈 문자열이 아니라면, selected source를 요소(element)의 src 속성(attribute)의 값으로 두고, selected pixel density를 1.0으로 둡니다. 그렇지 않으면 selected source를 null로 두고 selected pixel density를 undefined로 둡니다.

  4. img 요소(element)의 마지막 선택 된 소스selected source로 둡니다.
  5. selected source가 null이 아니라면, 이 하위 단계들을 수행합니다:

    1. 요소(element)에 관련하여, selected source해석하고, 결과를 absolute URL로 둡니다. 그것이 성공적이지 않다면, 이 단계들의 내부 설정을 중단합니다.
    2. key를 결과로 나온 절대 URL, img 요소(element)의 crossorigin 속성(attribute)의 모드, 그리고 그 모드가 No CORS가 아니라면 노드 문서출처로 구성되는 튜플로 둡니다.
    3. 사용 가능한 이미지들의 목록key에 대한 항목을 포함한다면, 이 하위 단계들을 수행합니다:

      1. 그 항목에 대한 상위 계층 캐싱 무시 플래그를 설정합니다.
      2. 현재 요청보류 중인 요청에 대한 이미지 요청을 중단 시킵니다.
      3. 보류 중인 요청을 null로 둡니다.
      4. 현재 요청이미지 데이터가 항목의 이미지 데이터이고 상태가 완전히 사용 가능 상태로 설정 된 새로운 이미지 요청으로 둡니다.
      5. 이미지의 표현을 적절하게 업데이트 합니다.
      6. 현재 요청현재 픽셀 밀도selected pixel density로 둡니다.
      7. 애니메이션 재시작이 설정되고, 현재 응답현재 URLabsolute URL로 변경하고, 이후 img 요소(element)에 load라는 단순 이벤트를 발생시킨다면, 애니메이션을 재시작하기 위한 작업을 대기열에 넣습니다.
      8. 이미지 데이터 업데이트 알고리즘을 중단합니다.
  6. 이 알고리즘이 호출되는 작업이 계속되는 것을 허용하여, 병렬로 안정 상태를 기다립니다. 동기 섹션은 알고리즘이 동기 섹션이 종료되었다고 알릴 때까지 이 알고리즘의 모든 나머지 단계들로 구성됩니다. (동기 섹션내 단계들은 ⌛로 표기됩니다.)
  7. ⌛ 이 img 요소(element)에 대한 이 알고리즘의 다른 인스턴스가 이 인스턴스 이후 시작되었다면 (그것이 중단되고 더 이상 수행 중이 아닐지라도), 이 단계들을 중단합니다.

    예를 들어, src, srcset, crossorigin 속성(attribute)가 연속적으로 모두 설정되어 있는 경우, 여러 요청들을 방지하기 위해, 오직 마지막 인스턴스만 적용됩니다.

  8. selected sourceselected pixel density를 각각 이미지 소스 선택으로부터 얻어진 결과 URL과 픽셀 밀도로 둡니다.

  9. selected source가 null이라면, 이 하위 단계들을 수행합니다:

    1. 현재 요청깨짐 상태로 설정하고, 현재 요청보류 중인 요청에 대한 이미지 요청을 중단하고, 보류 중인 요청을 null로 둡니다.
    2. 현재 요청현재 ULR을 빈 문자열로 변경하기 위한 작업을 대기열에 넣고, 이후 요소(element)가 src 속성(attribute)을 가지거나 그것이 srcset이나 picture를 사용한다면, img 요소(element)에 error라는 단순 이벤트를 발생시킵니다.
    3. ⌛ 이 알고리즘을 중단합니다.
  10. img 요소(element)에 loadstart라는 진행 이벤트를 발생시키기 위한 작업을 대기열에 넣습니다.

    ⌛ 요소(element)의 노드 문서에 관련하여, selected source해석하고, absolute URL결과 URL 문자열로 둡니다. 그것이 성공적이지 않다면, 이 하위 단계들을 수행합니다:

    1. 현재 요청보류 중인 요청에 대한 이미지 요청을 중단시킵니다.
    2. 현재 요청깨짐 상태로 설정합니다.
    3. 보류 중인 요청을 null로 둡니다.
    4. 현재 요청현재 URLselected source로 변경하기 위한 작업을 대기열에 넣고, img 요소(element)에 error라는 단순 이벤트를 발생시킨 후 img 요소(element)에 loadend라는 단순 이벤트를 발생시킵니다.
    5. 이미지 데이터 업데이트 알고리즘을 중단시킵니다.
  11. 보류 중인 요청이 null이 아니고, absolute URL보류 중인 요청현재 URL과 동일하다면, 이 단계들을 중단합니다.

    absolute URL현재 요청현재 URL과 동일하고, 현재 요청일부 사용 가능 상태에 있다면, 보류 중인 요청에 대한 이미지 요청을 중단시키고, 애니메이션 재시작이 설정되어 있다면 애니메이션을 재시작하기 위한 작업을 대기열에 넣고 이 단계들을 중단합니다.

    보류 중인 요청이 null이 아니라면, 보류 중인 요청에 대한 이미지 요청을 중단합니다.

    image request현재 URLabsolute URL인 새로운 이미지 요청으로 둡니다.

    현재 요청사용 불가 상태나 깨짐 상태에 있다면, 현재 요청image request로 둡니다. 그렇지 않으면 보류 중인 요청image request으로 둡니다.

    requestabsolute URL과 요소(element)의 crossorigin 콘텐트 속성(attribute)의 현재 상태가 주어지는 잠정적 CORS 요청을 생성한 결과로 둡니다.

    request클라이언트를 요소(element)의 노드 문서Window 객체의 환경 설정 객체유형을 "image"로 설정합니다.

    ⌛ 요소(element)가 srcsetpicture를 사용한다면, request개시자를 "imageset"로 설정합니다.

    request동일 출처 데이터 URL 플래그를 설정합니다.

    request가져옵니다(fetch). 페칭(fetch) 알고리즘의 이 인스턴스를 image request과 연관짓습니다.

    이 방식으로 얻어진 리소스가 있다면 이 리소스는 image request이미지 데이터입니다. 그것은 CORS 동일 출처이거나 CORS 교차 출처일 수 있습니다. 이것은 이미지 자체의 출처에 영향을 미칩니다 (예를 들어, canvas에 사용되는 경우).

    이미지를 가져오는 것(fetch)은 리소스가 가져와(fetch) 지자마자 (아래 정의된) 네트워킹 작업 소스에 의해 대기열에 넣어진 작업이 수행되었을 때까지 요소(element)의 노드 문서로드 이벤트를 지연시켜야(must) 합니다.

    불행히도, 이것은 사용자의 로컬 네트워크의 기본적인 포트 조사를 수행하는데 사용될 수 있습니다 (특히 스크립트와 함께, 그러한 공격을 수행하기 위해 실제로 스크립팅이 필요한 것은 아니지만). 유저 에이전트는 이 공격을 완화하기 위해 위에 설명된 것들보다 더 엄격한 교차 출처 접근 제어 정책들을 구현할 수 있지만, 불행히도 그러한 정책들은 일반적으로 현재 사용되는 웹 콘텐트와 호환되지 않습니다.

    리소스가 CORS 교차 출처라면, 이미지가 가져와지는(fetch) 동안 네트워킹 작업 소스에 의해 대기열에 넣어진작업img 요소(element)에 progress라는 진행 이벤트를 발생시켜야(must) 합니다.

  12. 병렬로 남은 단계들을 계속하되, 가져오는(fetch) 것에서 데이터 누락 없이 동기 섹션 종료시킵니다.
  13. 가능한 빨리, 다음 목록에서 처음 적절한 항목으로 건너뜁니다:

    리소스 유형이 multipart/x-mixed-replace라면

    이미지가 가져와지는(fetch) 동안 네트워킹 작업 소스에 의해 대기열에 넣어진 다음 작업은 다음 단계들을 수행해야(must) 합니다:

    1. image request보류 중 요청이고 적어도 하나의 본문 부분이 완전히 디코드되었다면, 현재 요청에 대한 이미지 요청을 중단하고 보류 중인 요청을 현재 요청으로 업그레이드 합니다.

    2. 그렇지 않고, image request보류 중인 요청이고 유저 에이전트가 image request의 이미지가 일부 치명적인 방법으로 손상되어 이미지의 치수들을 얻을 수 없다고 결정할 수 있다면, 현재 요청에 대한 이미지 요청을 중단하고, 보류 중인 요청을 현재 요청으로 업그레이드하고, 현재 요청의 상태를 깨짐으로 설정합니다.

    3. 그렇지 않고, image request현재 요청이고, 그것이 사용 불가 상태에 있으며, 유저 에이전트가 image request의 이미지의 너비와 높이를 결정할 수 있다면, 현재 요청의 상태를 일부 사용 가능으로 설정합니다.

    4. 그렇지 않고, image request현재 요청이고, 그것이 사용 불가 상태에 있으며, 유저 에이전트가 image request의 이미지가 일부 치명적인 방법으로 손상되어 치수들을 얻을 수 없다고 결정할 수 있다면, 현재 요청의 상태를 깨짐으로 설정합니다.

    이미지가 가져와지는(fetch) 동안 네트워킹 작업 소스에 의해 대기열에 넣어진작업은 이미지의 표현을 업데이트해야(must) 하지만, 각 새로운 본문 부분이 들어올 때 마다, 그것은 이전 이미지를 교체해야(must) 합니다. 하나의 본문 부분이 완전히 디코드되면, 유저 에이전트는 img 요소(element)를 완전히 사용 가능으로 설정하고 img 요소(element)에 load라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣어야(must) 합니다.

    progressloadend 이벤트들은 multipart/x-mixed-replace 이미지 스트림들에 대해 발생되지 않습니다.

    리소스 유형과 데이터가 지원되는 이미지 형식에 일치한다면, 아래 기술된 대로

    이미지가 가져와지는(fetch) 동안 네트워킹 작업 소스에 의해 대기열에 넣어진 다음 작업은 다음 단계들을 수행해야(must) 합니다:

    1. 유저 에이전트가 image request의 이미지의 너비와 높이를 결정할 수 있고 image request보류 중인 요청이라면, image request의 상태를 일부 사용 가능으로 설정합니다.

    2. 그렇지 않고, 유저 에이전트가 image request의 이미지의 너비와 높이를 결정할 수 있고 image request현재 요청이라면, img 요소(element)의 표현을 적절하게 업데이트하고 image request의 상태를 일부 사용 가능으로 설정합니다.

    3. 그렇지 않고, 유저 에이전트가 image request의 이미지가 어떤 치명적 오류로 이미지 치수들을 얻을 수 없다고 결정할 수 있고, image request보류 중인 요청이라면, 현재 요청보류 중인 요청에 대한 이미지 요청을 중단시키고, 보류 중인 요청을 현재 요청으로 업그레이드하고, 현재 요청깨짐 상태로 설정하고, img 요소(element)에 error라는 단순 이벤트를 발생시키고, img 요소(element)에 loadend라는 단순 이벤트를 발생시키고, 이 단계들을 중단시킵니다.

    4. 그렇지 않고, 유저 에이전트가 image request의 이미지가 어떤 치명적 오류로 이미지 치수들을 얻을 수 없다고 결정할 수 있고, image request현재 요청이라면, image request에 대한 이미지 요청을 중단시키고, img 요소(element)에 error라는 단순 이벤트를 발생시키고, img 요소(element)에 loadend라는 단순 이벤트를 발생시키고, 이 단계들을 중단합니다.

    이미지가 가져와지는(fetch) 동안 네트워킹 작업 소스에 의해 대기열에 넣어진작업, 그리고 각 차후 작업들은, image request현재 요청이라면, 이미지의 표현을 적절하게 업데이트 해야(must) 합니다 (예를 들어, 이미지가 점진적 JPEG라면, 각 패킷은 이미지의 해상도를 향상시킬 수 있습니다).

    게다가, 리소스가 가져와졌을(fetch) 때 네트워킹 작업 소스에 의해 대기열에 넣어진 마지막 작업은 추가적으로 이 단계들을 수행해야(must) 합니다:

    1. image request보류 중인 요청이라면, 현재 요청에 대한 이미지 요청을 중단시키고, 보류 중인 요청을 현재 요청으로 업그레이드하고, img 요소(element)의 표현을 적절하게 업데이트 합니다.
    2. image request완전히 사용 가능 상태로 설정합니다.
    3. key를 사용하여, 상위 계층 캐싱 무시 플래그 설정과 함께, 이미지를 사용 가능한 이미지들의 목록에 추가합니다.
    4. image request 내 리소스에 따라, img 요소에 load라는 진행 이벤트나 단순 이벤트를 발생시킵니다.
    5. image request 내 리소스에 따라, img 요소에 loadend라는 진행 이벤트나 단순 이벤트를 발생시킵니다.
    그렇지 않으면

    이미지 데이터가 지원되는 파일 형식에 없습니다; 유저 에이전트는 image request깨짐 상태로 설정하고, 현재 요청보류 중인 요청에 대한 이미지 요청을 중단시키고, image request보류 중인 요청이라면 보류 중인 요청을 현재 요청으로 업그레이드하고, 그 후 먼저 img 요소(element)에 error라는 단순 이벤트를 발생시키기고 이후 img 요소(element)에 loadend라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣습니다.

이미지 요청 image request에 대해 이미지 요청을 중단시키는 것은 다음 단계들을 수행하는 것을 의미합니다:

  1. image request이미지 데이터가 있다면 무시합니다.
  2. 그 알고리즘에 의해 생성된 모든 보류 중인 작업들을 폐기하여, image request에 대한 페칭(fetching) 알고리즘의 모든 인스턴스를 중단합니다.

img 요소(element)에 대한 보류 중인 요청을 현재 요청으로 업그레이드하는 것은 다음 단계들을 수행하는 것을 의미합니다:

  1. img 요소(element)의 현재 요청보류 중인 요청으로 둡니다.
  2. img 요소(element)의 보류 중인 요청을 null로 둡니다.

리소스 r에 따라 요소(element) etype이라는 진행 이벤트나 단순 이벤트를 발생시키는 것은 rCORS 동일 출처라면 etype이라는 진행 이벤트를 발생시키고, 그렇지 않으면 etype이라는 단순 이벤트를 발생시키는 것을 의미합니다.

유저 에이전트가 요소(element) x에 대한 위 알고리즘을 수행하는 동안, 그 요소(element)가 그것의 Document에 없더라도, 요소(element)의 노드 문서로부터 요소(element) x까지 강한 참조가 있어야(must) 합니다.

img 요소(element)는 명시된 srcset 속성(attribute)를 가지거나 picture 요소(element)인 부모를 가진다면 srcsetpicture를 사용한다라고 합니다.

img 요소(element)가 완전히 사용 가능 상태에 있 유저 에이전트가 오류 없이 미디어 데이터를 디코드할 수 있다면, img 요소(element)는 완전히 디코드 가능하다고 합니다.

이미지가 성공적으로 가져와(fetch)졌는지 아닌지는 (예를 들어, 응답 상태들이 ok 상태들이었는지) 이미지의 유형과 그것이 유효한 이미지인지 아닌지를 결정하는 중에는 무시되어야(must) 합니다.

이것은 오류 응답으로 이미지들을 반환하게 하는 것을 허용하고 그것들을 표시할 수 있습니다.

유저 에이전트는 official type을 제공하는 이미지의 연관된 Content-Type 헤더들을 가지고, 이미지의 유형을 결정하는데 이미지 스니핑 규칙들을 적용해야(should) 합니다. 이 규칙들이 적용되지 않았다면, 이미지의 유형은 이미지의 연관된 Content-Type 헤더들에 의해 주어진 유형이어야(must) 합니다.

유저 에이전트들은 img 요소(element)로 이미지가 아닌 리소스들을 지원하지 않아야(must) 합니다 (예를 들어, 루트 요소(element)가 HTML 요소(element)인 XML 파일들). 유저 에이전트들은 이미지 리소스에 삽입된 실행 가능한 코드를 (예를 들어, 스크립트) 수행하지 않아야(must) 합니다. 유저 에이전트들은 여러 페이지 리소스의 (예를 들어, PDF 파일) 첫 번째 페이지만을 표시해야(must) 합니다. 유저 에이전트들은 리소스가 상호 작용 방식으로 동작하는 것을 허용하지 않아야(must) 하지만, 리소스 내 애니메이션은 수행해야(should) 합니다.

이 명세는 지원되는 이미지 유형들을 명시하지 않습니다.


img 요소(element)는 소스 세트와 연관됩니다.

소스 세트는 0개 이상의 이미지 소스들소스 크기의 정렬된 집합입니다.

이미지 소스URL과, 선택적으로 밀도 설명자 혹은 너비 설명자입니다.

소스 크기<source-size-value>입니다. 소스 크기뷰포트와 관련된 단위를 가진다면, 그것은 img 요소(element)의 문서의 뷰포트와 관련하여 해석되어야(must) 합니다. 다른 단위들은 미디어 쿼리 내의 것와 동일하게 해석되어야(must) 합니다. [MEDIAQ]

주어진 img 요소(element) el에 대해 이미지 소스 선택이 요청되는 경우, 유저 에이전트들은 다음을 수행해야(must) 합니다:

  1. el에 대해 소스 세트를 업데이트합니다.
  2. el소스 세트가 비어있다면, URL로서 null을, 픽셀 밀도로 undefined를 반환하고 이 단계들을 중단합니다.
  3. 그렇지 않으면, el소스 세트를 취하고 그것을 source set로 둡니다.
  4. source setbsource set 내 앞선 항목 a와 동일한 연관된 밀도 설명자를 가진다면, 항목 b를 제거합니다. source set에 앞선 항목과 동일한 연관된 밀도 설명자를 가지는 항목이 없을 때까지 이 단계를 반복합니다.
  5. 유저 에이전트 특정 방식으로, source set로부터 이미지 소스하나를 선택합니다. 이것을 selected source로 둡니다.
  6. selected source과 그것의 연관된 픽셀 밀도를 반환합니다.

주어진 img 요소(element) el에 대해 소스 세트 업데이트가 요청되는 경우, 유저 에이전트는 다음을 수행해야(must) 합니다:

  1. el소스 세트를 빈 소스 세트로 설정합니다.
  2. el이 부모 노드를 가지고 그것이 picture 요소(element)라면, elements를 연관된 순서를 고정시켜, el의 부모 노드의 자식 요소(element)들을 포함하는 배열로 둡니다. 그렇지 않으면, elementsel만 포함하는 배열로 둡니다.
  3. elwidth 속성(attribute)을 가지고, 치수 값 해석에 대한 규칙 을 사용하여 그 속성(attribtue)의 값을 해석한 것이 오류나 퍼센트 값을 생성하지 않는다면, width를 반환된 정수 값으로 둡니다. 그렇지 않으면, width를 null로 둡니다.
  4. 각 항목 child에 대해 다음을 수행하여, elements를 반복합니다:

    1. childel라면:

      1. childsrcset 속성(attribute)을 가진다면, child의 srcset 속성(attribute)을 해석하고 반환 된 소스 세트source set로 둡니다. 그렇지 않으면, source set를 빈 소스 세트로 둡니다.
      2. 폴백 너비 width를 가지고 child의 sizes 속성(attribute)을 해석하고, source set소스 크기를 반환된 값으로 둡니다.
      3. child가 값이 빈 문자열이 아니고 source set가 1의 밀도 설명자 값을 가진 이미지 소스를 포함하지 않는 src 속성(attribute)을 가지고, 너비 설명자가 있는 이미지 소스가 없다면, childsrc 속성(attribute)을 source set에 추가(append) 합니다.
      4. source set소스 밀도를 정규화합니다.
      5. el소스 세트source set로 둡니다.
      6. 이 알고리즘을 중단합니다.
    2. childsource 요소(element)가 아니라면, 다음 자식에 대해 계속합니다. 그렇지 않으면, childsource 요소(element)입니다.
    3. childsrcset 속성(attribute)을 가지지 않으면, 다음 자식에 대해 계속합니다.
    4. childsrcset 속성(attribute)을 해석하고 반환된 소스 세트source set로 둡니다.
    5. source set가 0개의 소스 세트를 가진다면, 다음 자식에 대해 계속합니다.
    6. childmedia 속성(attribute)을 가지고 그 값이 환경에 일치하지 않으면, 다음 자식에 대해 계속합니다.
    7. 폴백 너비 width를 가지고 childsizes 속성(attribute)을 해석하고, source set소스 크기를 반환된 값으로 둡니다.
    8. childtype 속성(attribute)을 가지고, 그 값이 알 수 없거나 지원되지 않는 MIME 타입이라면, 다음 자식에 대해 계속합니다.
    9. source set소스 밀도를 정규화합니다.
    10. el소스 세트source set으로 둡니다.
    11. 이 알고리즘을 중단합니다.

img 요소(element)는 이미지 소스를 선택하기 위해 다른 (유효하지 않은) 요소(element)들을 무시하여, 동일한 picture 요소(element) 내 다른 img 요소(element)들이나, 관련된 img 요소(element)의 형제들을 따르는 source 요소(element)들을 포함하여, 독립적으로 그것의 이전 형제 source 요소(element)들과 img 요소(element) 자체를 고려합니다.

요소(element)로부터 srcset 속성(attribute) 해석이 from an element, 요청 되는 경우, 다음과 같이 요소(element)의 srcset의 값을 해석합니다:

  1. input을 이 알고리즘에 전달된 값으로 둡니다.
  2. position을 초기에 문자열의 시작을 가리키는 input 내 포인터로 둡니다.
  3. candidates를 초기에 빈 소스 세트로 둡니다.
  4. 분할 반복: 공백 문자들이나 U+002C 콤마 문자들인 일련의 문자들을 수집합니다. U+002C 콤마 문자들이 수집되었다면, 그것은 해석 오류입니다.
  5. positioninput의 끝을 지났다면, candidates를 반환하고 이 단계들을 중단합니다.
  6. 공백 문자들이 아닌 일련의 문자들을 수집하고, 그것을 url로 둡니다.
  7. descriptors를 새로운 빈 목록으로 둡니다
  8. url이 U+002C 콤마 문자 (,)로 끝난다면, 이 하위 단계들을 따릅니다:

    1. url로부터 뒤따르는 002C 콤마 문자들을 제거합니다. 이것이 여러 문자를 제거했다면, 그것은 해석 오류입니다.

    그렇지 않으면, 이 하위 단계들을 따릅니다:

    1. Descriptor tokenizer: 여백을 건너뜁니다.
    2. current descriptor를 빈 문자열로 둡니다.
    3. state설명자 안에 둡니다.
    4. cposition에 위치한 문자로 둡니다. state의 값에 따라 다음을 수행합니다. 이 단계의 목적에 따라, "EOF"는 positioninput의 끝을 지났음을 나타내는 특수한 문자입니다.

      설명자 내부

      c의 값에 따라 다음을 수행합니다:

      공백 문자
      current descriptor가 비어있지 않다면, current descriptordescriptors에 추가(append)하고 current descriptor를 빈 문자열로 둡니다. state다음 설명자로 설정합니다.
      U+002C 콤마 (,)
      positioninput 내 다음 문자로 전진시킵니다. current descriptor가 비어있지 않다면, current descriptordescriptors에 추가(append)합니다. 설명자 해석으로 라벨링 된 단계로 건너뜁니다.
      U+0028 왼쪽 괄호 (()
      ccurrent descriptor에 추가(append)합니다. state괄호(parens) 내부로 설정합니다.
      EOF
      current descriptor이 비어있지 않다면, current descriptordescriptors에 추가(append)합니다. 설명자 해석으로 라벨링된 단계로 건너뜁니다.
      그 밖에 다른 것들
      ccurrent descriptor에 추가(append) 합니다.
      괄호(parens) 내부

      c의 값에 따라 다음을 수행합니다:

      U+0029 오른쪽 괄호 ())
      ccurrent descriptor에 추가(append) 합니다. state설명자 내부로 설정합니다.
      EOF
      current descriptordescriptors에 추가(append) 합니다. 설명자 해석으로 라벨링 된 단계로 건너뜁니다.
      그 밖에 다른 것들
      ccurrent descriptor에 추가(append) 합니다.
      설명자 이후

      c의 값에 따라 다음을 수행합니다:

      공백 문자
      이 상태에 머무릅니다.
      EOF
      설명자 해석으로 라벨링 된 단계로 건너뜁니다.
      그 밖에 다른 것들
      state설명자 내부로 설정합니다. positioninput이전 문자로 설정합니다.

      positioninput 내 다음 문자로 전진시킵니다. 이 하위 단계를 반복합니다.

      향후 추가되는 것들과 호환이 되기 위해, 이 알고리즘은 여러 설명자들과 괄호를 가진 설명자들을 지원합니다.

  9. 설명자 해석: errorno로 둡니다.
  10. widthabsent로 둡니다.
  11. densityabsent로 둡니다.
  12. future-compat-habsent로 둡니다.
  13. descriptors 내 각 설명자에 대해, 다음 목록으로부터 첫 적절한 단계의 세트를 수행합니다:

    설명자가 U+0077 라틴 소문자 W가 뒤따르는 유효한 음이 아닌 정수로 구성된다면
    1. 유저 에이전트가 sizes 속성(attribute)을 지원하지 않는다면, erroryes로 둡니다.

      지침을 따르는 유저 에이전트는 sizes 속성(attribute)을 지원할 것입니다. 하지만, 유저 에이전트들은 일반적으로 실제로는 점진적인 방식으로 기능을 구현하고 제공합니다.

    2. widthdensity가 모두 absent가 아니라면, erroryes로 둡니다.
    3. 음이 아닌 정수 해석에 대한 규칙을 설명자에 적용합니다. 결과가 0이라면, erroryes로 둡니다. 그렇지 않으면, width를 그 결과로 둡니다.
    설명자가 U+0078 라틴 소문자 X가 뒤따르는 유효한 부동소수점 수로 구성된다면
    1. width, density, future-compat-h가 모두 absent가 아니라면, erroryes로 둡니다.
    2. 부동 소수점 수 값 해석에 대한 규칙을 설명자를 적용합니다. 결과가 0보다 작다면, erroryes로 둡니다. 그렇지 않으면, density를 그 결과로 둡니다.

      density가 0이라면, 고유 치수들은 무한대가 될 것입니다. 유저 에이전트들은 하드웨어 제한사항들 조항에 따라 허용된 큰 이미지들을 렌더링하는데 한계가 있을 것으로 예상됩니다.

    설명자가 U+0068 라틴 소문자 H가 뒤따르는 유효한 음이 아닌 정수로 구성된다면

    이것은 해석 오류입니다.

    1. future-compat-hdensity가 모두 absent가 아니라면, erroryes로 둡니다.
    2. 음이 아닌 정수 해석에 대한 규칙을 설명자에 적용합니다. 결과가 0이라면, erroryes로 둡니다. 그렇지 않으면, future-compat-h를 그 결과로 둡니다.
    그 밖에 다른 것들
    erroryes로 둡니다.
  14. future-compat-habsent가 아니고 widthabsent라면, erroryes로 둡니다.
  15. error가 여전히 no라면, URL이 url이고 widthabsent가 아니라면 너비 widthdensityabsent가 아니라면 픽셀 밀도가 density와 연관된, 새로운 이미지 소스candidates에 추가(append) 합니다. 그렇지 않으면 해석 오류가 있습니다.
  16. 분할 반복으로 라벨링 된 단계로 돌아갑니다.

요소(element)에 대해 크기 속성(attribute)을 해석하도록 요청 될 경우, 요소(element)의 sizes 속성(attribute)의 값으로부터 (속성(attribute)이 없다면, 빈 문자열로부터) 컴포넌트 값들의 콤마로 분리된 목록을 해석하고, unparsed sizes list를 그 결과로 둡니다. [CSS-SYNTAX-3]

unparsed sizes list 내 각 unparsed size에 대해:

  1. unparsed size의 끝에서 모든 연속된 <whitespace-token>들을 제거합니다. unparsed size가 현재 비어있다면, 그것은 해석 오류입니다; 이 알고리즘의 다음 반복으로 계속합니다.
  2. unparsed size 내 마지막 컴포넌트 값이 유효한 음이 아닌 <source-size-value>라면, size를 그것의 값으로 두고 unparsed size로부터 컴포넌트 값을 제거합니다. calc() 함수 이외의 CSS 함수는 유효하지 않습니다. 그렇지 않으면 해석 오류가 있습니다; 이 알고리즘의 다음 반복으로 계속합니다.
  3. unparsed size의 끝에서 모든 연속된 <whitespace-token>들을 제거합니다. unparsed size가 현재 비어있다면, size를 반환하고 이 알고리즘을 나갑니다. 이것이 unparsed sizes list의 마지막 항목이 아니었다면, 그것은 해석 오류입니다.
  4. unparsed size 내 나머지 컴포넌트 값들<media-condition>로 해석합니다. 정확하게 해석하지 않거나, 정확하게 해석하지만 <media-condition>가 false로 평가된다면, 이 알고리즘의 다음 반복으로 계속합니다. [MEDIAQ]
  5. size를 반환하고 이 알고리즘을 나갑니다.

위 알고리즘이 반환하는 size 값 없이 unparsed sizes list를 소진한다면, 이 단계들을 따릅니다:

  1. width가 null이 아니라면, 값 width과 단위 px을 가진 <length>를 반환합니다.
  2. 100vw을 반환합니다.

위 알고리즘들에 대한 해석 오류가 입력과 요구사항들 사이의 치명적이지 않은 불일치를 나타냅니다. 유저 에이전트들은 어떻게든 해석 오류들을 노출하도록 권장됩니다.

유효한 소스 크기 목록이 (<media-condition>를 수반하지 않고) <source-size-list> 내 마지막 항목으로 텅 빈 <source-size-value>만을 포함하는 동안, 해석 알고리즘은 기술적으로 목록 내 어느 지점에나 허용되고, 목록 내 이전 항목들이 사용되지 않았다면 즉시 사이즈로 그것을 받아들일 것입니다. 이것은 미래 확장들을 가능하게 하는 것이고, 마지막 쉼표와 같은 단순한 작성자 오류들로부터 보호합니다.

이미지 소스는 모든 수반하는 그것의 URL에 밀도 설명자나 너비 설명자를 가지거나 어떤 설명자도 가지지 않을 수 있습니다. 소스 세트를 정규화 하는 것은 모든 이미지 소스에 밀도 설명자를 제공합니다

소스 세트 source set소스 밀도 정규화가 요청 되는 경우, 유저 에이전트는 다음을 수행해야(must) 합니다:

  1. source sizesource set소스 크기로 둡니다.
  2. source set 내 각 이미지 소스에 대해:

    1. 이미지 소스가 밀도 설명자를 가진다면, 다음 이미지 소스로 계속합니다.
    2. 그렇지 않고, 이미지 소스너비 설명자를 가진다면, 너비 설명자너비 설명자의 값을 소스 크기로 나눈 값과 x 단위로 교체합니다.

      소스 크기가 0이라면, 밀도는 고유 치수들이 0 x 0이 되는 결과를 낳는 무한대가 될 것입니다.

    3. 그렇지 않으면, 이미지 소스1x의 밀도 설명자를 제공합니다.

유저 에이전트는 환경의 변화에 반응하도록 img 요소(element)의 이미지를 갱신하기 위해 언제든지 다음 알고리즘을 수행할 수 있습니다. (유저 에이전트들은 이 알고리즘을 전혀 수행할 필요가 없습니다; 예를 들어, 사용자가 더 이상 페이지를 보고 있지 않다면, 유저 에이전트는 사용자가 사용할 이미지를 결정하기 전에, 그 동안에 환경이 다시 변경되는 경우, 페이지로 돌아올 때까지 기다리기 원할 수 있습니다.)

유저 에이전트들은 특히 사용자가 뷰포트의 크기를 변경하는 경우 (예를 들어 윈도우를 리사이징하거나 페이지 줌을 변경하여), 그리고 img 요소(element)가 문서에 삽입되는 경우, 이 알고리즘이 수행되도록 권장되기 때문에, 밀도 보정 고유 너비와 높이는 새로운 뷰포트에 일치하고, 때문에 art direction이 수반되는 경우 올바른 이미지가 선택됩니다.

  1. 병렬로 안정 상태를 기다립니다. 동기 섹션은 알고리즘이 동기 섹션이 종료되었다고 알리기 전까지 이 알고리즘의 모든 나머지 단계들로 구성됩니다. (동기 섹션의 단계들은 ⌛로 표기 됩니다.)
  2. img 요소(element)가 srcsetpicture를 사용하지 않거나, 그것의 노드 문서활성 문서가 아니거나, 리소스 유형이 multipart/x-mixed-replace인 이미지 데이터를 가지거나, 보류 중인 요청이 null이 아니라면, 이 알고리즘을 중단합니다.
  3. selected sourceselected pixel density를 각각 URL과 이미지 소스 선택의 결과 픽셀 밀도로 둡니다.
  4. selected source가 null이라면, 이 단계들을 중단합니다.
  5. selected sourceselected pixel density가 요소(element)의 마지막 선택된 소스현재 픽셀 밀도와 동일하다면, 이 단계들을 중단합니다.
  6. selected source해석하고, 요소(element)의 노드 문서에 관련 짓고, absolute URL결과 URL 문자열로 둡니다. 그것이 성공적이지 않다면, 이 단계들을 중단합니다.
  7. corsAttributeState를 요소(element)의 crossorigin 콘텐트 속성(attriute)의 상태로 둡니다.
  8. originimg 요소(element)의 노드 문서출처(origin)로 둡니다.
  9. clientimg 요소(element)의 노드 문서Window 객체의 환경 설정 객체로 둡니다.
  10. ⌛ Let keyabsolute URLcorsAttributeState와, corsAttributeStateNo CORS라면 origin으로 구성되는 튜플로 둡니다.
  11. image request현재 URLabsolute URL인 새로운 이미지 요청으로 둡니다.
  12. ⌛ 요소의 보류 중인 요청이미지 요청으로 둡니다.
  13. 병렬로 나머지 단계들을 계속하여, 동기 섹션을 종료합니다.
  14. 사용 가능한 이미지들의 목록key에 대한 항목을 포함한다면, image request이미지 데이터를 항목의 그것으로 설정합니다. 다음 단계로 계속합니다.

    그렇지 않으면, 이 하위 단계들을 수행합니다:

    1. requestabsolute URLcorsAttributeState이 주어진 잠정적 CORS 요청을 생성한 결과로 둡니다.
    2. request클라이언트client로, 유형을 "image"로 설정하고, request동기 플래그를 설정합니다.
    3. responserequest가져온(fetch) 결과로 둡니다.
    4. response의 안전하지 않은 응답이 네트워크 오류이거나, (앞서 언급된 것 처럼, 이미지 스니핑 규칙들을 적용하여 결정된) 이미지 형식이 지원되지 않거나, 유저 에이전트가 image request의 이미지가 치명적인 방법으로 이미지 치수들을 얻을 수 없는 오류가 생겼다고 결정할 수 있거나, 리소스 유형이 multipart/x-mixed-replace라면, 보류 중인 요청을 null로 두고 이 단계들을 중단합니다.
    5. 그렇지 않으면, response의 안전하지 않은 응답은 image request이미지 데이터입니다. 이것은 CORS-동일-출처CORS 교차 출처일 수 있습니다; 이것은 아미지 자체의 출처(origin)에 영향을 줍니다 (예를 들어, canvas에 사용되는 경우).
  15. 다음 하위 단계들을 수해행하기 위한 작업을 대기열에 넣습니다:

    1. img 요소(element)가 이 알고리즘이 시작된 이후 관련 변경들 경험이 있다면, 보류 중인 요청을 null로 두고 이 단계들을 중단합니다.
    2. img 요소(element)의 마지막 선택된 소스selected source로 그리고 img 요소(element)의 현재 픽셀 밀도selected pixel density로 둡니다.
    3. image request완전히 사용 가능 상태로 설정합니다.
    4. key를 사용하여, 상위 계층 캐싱 무시 플래그 설정을 가지고 이미지를 사용 가능한 이미지들의 목록에 추가(add) 합니다.
    5. 지연 요청을 현재 요청으로 업그레이드 합니다.
    6. img 요소(element)의 표현을 적절하게 업데이트 합니다.
    7. img 요소(element)에 load라는 단순 이벤트를 발생시킵니다.

이 섹션내 알고리즘에 의해 대기열에 넣어진 작업들에 대한 작업 소스DOM 조작 작업 소스입니다.


img 요소(element)가 나타내는 것은 src 속성(attribute)과 alt 속성(attribute)에 따라 달라집니다.

src 속성(attribute)이 설정되었고 alt 속성(attribute)이 빈 문자열로 설정되었다면

이미지는 콘텐트의 나머지에 대해 문서 내 일부 다른 정보와 중복되는 장식적이거나 보조적인 것입니다.

이미지가 사용 가능하고 유저 에이전트가 그 이미지를 표현하도록 설정되었다면, 요소(element)는 요소(element)의 이미지 데이터를 나타냅니다.

그렇지 않으면, 요소(element)는 아무 것도 나타내지 않고, 렌더링으로부터 완전히 생략될 것입니다. 유저 에이전트들은 이미지가 존재하지만 렌더링으로부터 생략되었다는 알림을 사용자에게 제공할 수 있습니다.

src 속성(attribute)이 설정되었고 alt 속성(attribute)이 비어 있지 않은 값으로 설정되었다면

이미지는 콘텐트의 중요한 부분입니다; alt 속성(attribute)은 이미지에 대한 텍스트 형식의 동등한 것이나 대체를 제공합니다.

이미지가 사용 가능하고 유저 에이전트가 그 이미지를 표시하도록 설정되었다면, 요소(element)는 요소(element)의 이미지 데이터를 나타냅니다 .

그렇지 않으면, 요소(element)는 alt 속성(attribute)에 의해 주어진 텍스트를 나타냅니다. 유저 에이전트들은 이미지가 존재하지만 렌더링으로부터 생략되었다는 알림을 사용자에게 제공할 수 있습니다.

src 속성(attribute)이 설정되었고 alt 속성(attribute)이 설정되지 않았다면

사용 가능한 이미지의 텍스트 형식의 동등한 것이 존재하지 않습니다.

이미지가 사용 가능하고 유저 에이전트가 그 이미지를 표시하도록 설정되었다면, 요소(element)는 요소(element)의 이미지 데이터를 나타냅니다.

그렇지 않으면, 유저 에이전트는 렝더링 되지 않는 이미지가 있음을 나타내는 일종의 지시기를 표시해야(should) 하고, 사용자에 의해 요청되었거나 그렇게 설정되었거나, 탐색에 대한 응답으로 상황에 맞는 정보를 제공하도록 요구된 경우 다음과 같이 얻어진 이미지에 대한 캡션 정보를 제공할 수 있습니다:

  1. 이미지가 자식 figcaption 요소(element)를 가진 figure 요소(element)의 후손이고, figcaption 요소(element)와 그것의 후손을 무시하고 figure 요소(element)가 요소(element) 간 여백 외 다른 후손 Text 노드를 가지지 않고, img 요소(element) 외 후손 삽입(embedded) 콘텐트가 없다면, 첫 번째 그 figcaption 요소(element)의 콘텐츠가 캡션 정보입니다; 이 단계들을 중단합니다.
  2. 캡션 정보가 존재하지 않습니다.
src 속성(attribute)이 설정되지 않았거나, alt 속성(attribute)이 빈 문자열로 설정되었거나 alt 속성(attribute)이 전혀 설정되지 않았다면

요소(element)는 아무 것도 나타내지 않습니다.

그렇지 않으면

요소(element)는 alt 속성(attribute)에 의해 주어진 텍스트를 나타냅니다.

alt 속성(attribute)은 조언 정보를 나타내지 않습니다. 유저 에이전트들은 title 속성(attribute)의 콘텐트와 동일한 방식으로 alt 속성(attribute)의 콘텐츠를 표현하지 않아야(must) 합니다.

유저 에이전트들은 사용자에게 이미지를 표시하거나, 이미지가 표시되는 것을 막는 옵션을 옵션을 항상 제공할 수 있습니다. 유저 에이전트들은 또한 사용자가 그것을 볼 수 없을 경우, 예를 들어, 시각 장애 때문에 혹은 그들이 그래픽 기능이 없는 텍스트 단말기를 사용하기 때문에, 이미지를 사용할 수 있도록 휴리스틱을 적용할 수 있습니다. 그러한 휴리스틱들은 예를 들어, 이미지 내에서 발견된 텍스트의 광학 문자 인식 (OCR)을 포함할 수 있습니다.

유저 에이전트들이 alt 속성(attribute)들이 누락되는 케이스를 바로잡도록 권장되는 반면, 작성자들은 그러한 행위에 의존하지 않아야(must) 합니다. 이미지들에 대한 대체로서 수행하도록 텍스트를 제공하는 요구사항들은 아래 상세 내용에 기술됩니다.

img 요소(element)들의 콘텐츠가 있다면, 렌더링 목적을 위해 무시됩니다.


usemap 속성(attribute)이 존재한다면 이것은 이미지가 연관된 이미지 맵을 가진다는 것을 나타낼 수 있습니다.

ismap 속성(attribute)은, href 속성(attribute)을 가진 a 요소(element)의 후손인 요소(element)에 사용되는 경우, 그것의 존재로 인해 요소(element)가 서버측 이미지 맵에 대한 접근을 제공한다는 나타냅니다. 이것은 이벤트들이 해당하는 a 요소(element)에 처리되는 방법에 영향을 줍니다.

ismap 속성(attribute)은 불리언 속성(attribute)입니다. 속성(attribute)은 href 속성(attribute)를 가진 조상 a 요소(element)를 가지지 않는 요소(element)에 명시되지 않아야(must) 합니다.

usemapismap 속성(attribute)들은 picture 요소(element)에 명시된 media 속성(attribute)을 가진 source 요소(element)와 함께 사용되는 경우 혼란스러운 행동을 가져올 수 있습니다.

img 요소(element)는 치수 속성(attribute)들을 지원합니다.

alt, src, srcset, sizes IDL 속성(attribute)들은 각각 동일한 이름의 콘텐트 속성(attribute)들을 반영해야(must) 합니다.

crossOrigin IDL 속성(attribute)은 crossorigin 콘텐트 속성(attribute)을 반영해야(must) 합니다.

useMap IDL 속성(attribute)은 usemap 콘텐트 속성(attribute)을 반영해야(must) 합니다.

isMap IDL 속성(attribute)은 ismap 콘텐트 속성(attribute)을 반영해야(must) 합니다.

image . width [ = value ]
image . height [ = value ]

이 속성(attribute)들은 이미지의 실제 렌더링 된 치수들이나 치수를 알 수 없다면 0을 반환합니다.

그것들은 해당하는 콘텐트 속성(attribute)들을 변경하기 위해 설정 될 수 있습니다.

image . naturalWidth
image . naturalHeight

이 속성(attribute)들은 이미지의 고유 치수들이나 치수를 알 수 없다면 0을 반환합니다.

image . complete

이미지가 완전히 다운로드 되었거나 이미지가 명시되지 않았다면 true를 반환합니다; 그렇지 않으면 false를 반환합니다.

image . currentSrc

이미지의 절대 URL을 반환합니다.

image = new Image( [ width [, height ] ] )

관련된 인수로 전달된 값이 사용 가능하다면 그 값으로 설정된 widthheight 속성(attribute)를 가진 새로운 img 요소(element)를 반환합니다.

IDL 속성(attribute) widthheight는 이미지가 렌더링 되고 있고 시각 매체에 렌더링 되고 있다면 CSS 픽셀로 이미지의 렌더링 된 너비와 높이를 반환해야(must) 하거나; 이미지가 고유 치수들을 가지고 사용 가능 하지만 시각 매체에 렌더링 되고 있지 않다면 이미지의 밀도 보정 고유 너비와 높이를 CSS 픽셀로 반환해야(must) 하거나; 이미지가 사용 가능 하지않거나 고유 치수들을 가지지 않는다면 0을 반환해야(must) 합니다. [CSS-2015]

설정할 때, 그것들은 각각 동일한 이름의 콘텐트 속성(attribute)들을 반영한 것처럼 수행해야(must) 합니다.

IDL 속성(attribute)들 naturalWidthnaturalHeight는 이미지가 고유 치수들을 가지고 사용 가능 하다면 이미지의 밀도 보정 고유 너비와 높이를 CSS 픽셀로 반환해야(must) 하고, 그렇지 않으면 0을 반환해야(must) 합니다. [CSS-2015]

IDL 속성(attribue) complete는 다음 조건 중 어떤 것이라도 참이라면 true를 반환해야(must) 합니다:

그렇지 않으면, 속성(attribute)은 false를 반환해야(must) 합니다.

complete의 값은 따라서 script가 실행되는 동안 변경될 수 있습니다.

currentSrc IDL 속성(attribute)은 img 요소(element)의 현재 요청현재 URL을 반환해야(must) 합니다.

생성자는 HTMLImageElement 객체를 (이외에도 createElement() 같은 DOM에서 팩토리 메서드) 생성하기 위해 제공됩니다: Image(width, height). 생성자가 호출 될 때, 이것은 새로운 HTMLImageElement 객체를 (새로운 img 요소(element)를) 반환해야(must) 합니다. width 인자가 존재한다면, 새로운 객체의 width 콘텐트 속성(attribute)은 width로 설정되어야(must) 합니다. height 인자 역시 존재한다면, 새로운 객체의 height 콘텐트 속성(attribute)은 height로 설정되어야(must) 합니다. 요소(element)의 노드 문서는 호출된 생성자의 인터페이스 객체가 발견된 Window 객체의 브라우징 컨텍스트활성 문서이어야(must) 합니다.

4.7.5.1. 이미지에 대한 대체로 수행하기 위한 텍스트 제공에 대한 요구사항들

대체 텍스트는, [WCAG20], 사용자의 요구들에 해당하는 많은 감각 양식들을 (예를 들어, 시각, 오디오, 촉각) 통해 렌더링될 수 있기 때문에, 시각 정보를 접근 가능하게 만드는 주요한 방법입니다. 대체 텍스트를 제공하는 것은 정보가 다양한 유저 에이전트들에 의한 다양한 방법으로 렌더링되는 것을 허용합니다. 예를 들어, 그림을 볼 수 없는 사람은 음성 합성을 사용하여 대체 텍스트를 크게 읽는 것을 들을 수 있습니다.

이미지의 alt 속성(attribute)은 매우 중요한 접근성 속성(attribute)입니다. 유용한 alt 속성(attribute) 콘텐트를 작성하는 것은 작성자가 이미지가 나타나는 컨텍스트와 그 컨텍스트에서 이미지가 가질 수 있는 기능을 신중하게 고려할 것이 요구됩니다.

여기에 포함된 지침은 작성자들이 이미지들을 사용하는 가장 일반적인 방법을 다룹니다. 추가적인 지침과 기법들은 이미지들에 대한 대체 텍스트의 리소스들에 사용 가능합니다.

4.7.5.1.1. 이미지들에 대한 대체 텍스트들로부터 사용자가 이익을 얻는 시나리오의 예
  • 매우 느린 연결과 이미지를 사용할 수 없는 브라우징을 가진 경우.
  • 시각 장애를 가지고 음성 소프트웨어를 위해 텍스트를 사용하는 경우.
  • 인지 장애를 가지고 음성 소프트웨어를 위해 텍스트를 사용하는 경우.
  • 텍스트 전용 브라우저를 사용하고 있는 경우.
  • 음성 웹 브라우저가 읽고 있는 페이지를 듣고 있는 경우.
  • 다운로드 비용을 절감하기 위해 이미지들이 비활성화 된 경우.
  • 이미지를 로딩하는데 문제가 있거나 이미지의 소스가 잘못된 경우.
4.7.5.1.2. 일반 지침들

달리 명시된 경우를 제외하고, alt 속성(attribute)는 명시되어야(must) 하고 그것의 값은 비어있지 않아야(must) 합니다; 값은 이미지에 대해 적절한 기능적인 대체여야(must) 합니다. alt 속성(attribute) 콘텐트에 대한 특정한 요구사항들은 아래 섹션들에 기술된 대로, 페이지 내에서 이미지의 기능에 달려 있습니다.

적절한 대체 텍스트를 결정하기 위해서는 이미지가 페이지에 포함되는 이유에 대해서 생각하는 것이 중요합니다. 그 목적이 무엇인가? 이 처럼 생각하는 것이 의도된 대상을 위해 이미지에 관하여 무엇이 중요한지를 이해하는 것을 도울 것입니다. 모든 이미지들은 유용한 정보를 제공하거나, 기능을 수행하거나, 상호작용 요소(element)에 레이블을 달거나, 심미적 향상이나 순수하게 장식이기 때문에, 페이지에 존재하는 이유를 가집니다. 그러므로, 이미지가 무엇을 위한 것인지를 아는 것은, 더 쉽게 적절한 대체 텍스트를 작성하게 합니다.

하이퍼링크a 요소(element)나 button 요소(element)가 텍스트 콘텐트를 가지지 않고 하나 이상의 이미지들만을 포함하는 경우, 모두 링크나 버튼의 목적을 전달하는 alt 속성(attribute)들 내에 텍스트를 포함합니다.

이 예에서, 작성 인터페이스의 일부가 표시됩니다. 각 버튼은 사용자가 편집 중인 콘텐트를 취할 수 있는 동작을 나타내는 아이콘을 가집니다. 이미지들을 볼 수 없는 사용자들을 위해, 동작 이름들이 이미지들의 alt 속성(attribute)들 내에 포함됩니다.

5개의 버튼들: 굵게, 기울임, 취소선, 글머리 기호 목록과 숫자 목록.

<ul>
  <li><button><img src="b.png" alt="Bold"></button></li>
  <li><button><img src="i.png" alt="Italics"></button></li>
  <li><button><img src="strike.png" alt="Strike through"></button></li>
  <li><button><img src="blist.png" alt="Bulleted list"></button></li>
  <li><button><img src="nlist.png" alt="Numbered list"></button></li>
</ul>
이 예에서, 링크는 로고를 포함합니다. 링크는 외부 사이트로부터 W3C 웹 사이트를 가리킵니다. 대체 텍스트는 링크 대상에 대한 간략한 설명입니다.

링크 콘텐트로 사용된 W3C 로고

<a href="https://w3.org">
<img src="images/w3c_home.png" width="72" height="48" alt="W3C web site">
</a>
이 예는 링크가 W3C 웹 사이트에 있는 것을 제외하고 이전 예와 동일합니다. 대체 텍스트는 링크 대상에 대한 간략한 설명입니다.

링크 콘텐트로 사용된 W3C 로고

<a href="https://w3.org">
<img src="images/w3c_home.png" width="72" height="48" alt="W3C home">
</a>

로고의 이미지가 사용되는 상황에 따라 대체 텍스트의 일부로, 이미지가 로고라는 표시를 제공하는 것은 적절할 수 있습니다. 섹션 §4.7.5.1.19 로고, 휘장, 깃발, 엠블럼를 참조하세요.

이 예에서, 링크는 인쇄 미리보기 아이콘을 퐇마합니다. 링크는 적용된 인쇄 스타일시트를 가진 페이지의 버전을 가리킵니다. 대체 텍스트는 링크 대상에 대한 간단한 설명 입니다.

링크 콘텐트로 사용된 인쇄 미리보기 아이콘.

<a href="preview.html">
<img src="images/preview.png" width="32" height="30" alt="Print preview.">
</a>
이 예에서, 버튼은 검색 아이콘을 포함합니다. 버튼은 검색 양식을 전송합니다. 대체 텍스트는 버튼이 무엇을 하는지에 대한 간단한 설명입니다.

버튼 콘텐트로 사용된 검색 아이콘.

<button>
<img src="images/search.png" width="74" height="29" alt="Search">
</button>
이 예에서, PIP Corporation에 대한 회사 로고는 다음 두 개의 이미지들로 분리되고, 첫 번째 것은 단어 PIP를 포함하고 두 번째 것은 축약된 단어 CO를 가집니다. 이미지들은 PIPCO 홈페이지로의 링크의 단독 콘텐트 입니다. 이 경우 링크 대상에 대한 간단한 설명이 제공됩니다. 이미지들은 사용자에게 단일 항목으로 표현되기 대문에 대체 텍스트 PIP CO home이 첫 번째 이미지의 alt 내에 있습니다.

텍스트 'PIP'를 포함하는 이미지.텍스트 'CO'를 포함하는 이미지.

<a href="pipco-home.html">
<img src="pip.gif" alt="PIP CO home"><img src="co.gif" alt="">
</a>
4.7.5.1.4. 그래픽 표현: 차트, 도표, 그래프, 지도, 일러스트

사용자들은 콘텐트가 그래픽 형식, 예를 들어, 흐름도, 도표, 그래프, 방향들을 보여주는 지도로 표현되는 경우 유용할 수 있습니다. 이미지를 볼 수 없는 사용자들 역시 그래픽 형식으로 표현된 콘텐트가 텍스트 기반 형식으로 제공되는 경우 유용할 수 있습니다. 텍스트 콘텐트를 처리하지만 이미지들을 자동으로 처리할 수 없는 소프트웨어 에이전트들 (예를 들어, 번역 서비스들, 많은 검색 엔진들) 역시 텍스트 기반 설명으로부터 이점을 얻을 수 있습니다.

다음 예에 원형 차트 내에 보여진 데이터를 나타내는 alt 속성(attribute) 내에 텍스트를 가진 원형 차트의 이미지가 있습니다:

Browser Share: Internet Explorer 25%, Firefox 40%, Chrome 25%, Safari 6% and Opera 4%.

<img src="piechart.gif" alt="Pie chart: Browser Share - Internet Explorer 25%, Firefox 40%, Chrome 25%, Safari 6% and Opera 4%.">
이미지의 경우 그래픽 형식으로 이전 문단을 반복합니다. alt 속성(attribute) 콘텐트는 이미지를 라벨링 합니다.
<p id="graph7">According to a recent study Firefox has a 40% browser share,
  Internet Explorer has 25%, Chrome has 25%, Safari has 6% and Opera has 4%.</p>
<p><img src="piechart.gif" alt="The browser shares as a pie chart."></p>

이미지가 사용 불가능한 경우, 예를 들어 src 속성(attribute) 값이 부정확한 경우, 대체 텍스트가 사용자에게 이미지 콘텐트의 간단한 설명을 제공하는 것을 볼 수 있습니다:

위 코드 조각의 표현.

한 문장이나 두 문장 이상으로 대체 텍스트가 긴 경우나 혹은 구조적 마크업의 사용으로 이점을 얻는 경우, alt 속성(attribute)과 연관된 대체 텍스트를 사용하여 간단한 설명을 제공하거나 라벨을 답니다.

여기 alt 속성(attribute)에 포함된 짧은 대체 텍스트를 가진 흐름도 이미지의 예가 있고, 이 경우 대체 텍스트는 이미지가 링크의 단독 콘텐트로서 링크 대상에 대한 설명입니다. 링크는 동일한 문서 내에서 흐름도에서 표현된 처리의 설명을 가리킵니다.

흐름도: 고장난 램프 다루기.

<a href="#desc"><img src="flowchart.gif"
  alt="Flowchart: Dealing with a broken lamp."></a>

...

...

<div id="desc">
<h2>Dealing with a broken lamp</h2>
<ol>
<li>Check if it’s plugged in, if not, plug it in.</li>
<li>If it still doesn’t work; check if the bulb is burned out. If it is, replace the bulb.</li>
<li>If it still doesn’t work; buy a new lamp.</li>
</ol>
</div>
이 예에 차트 이미지가 있습니다. 정보가 데이터 집합이기 때문에 alt 속성(attribute) 내에 있는 평문 텍스트로서 차트 내에 그려진 정보를 제공하는 것은 적절하지 않을 것입니다. 대신 구조화된 대체 텍스트가 아래 이미지를 차트 이미지에 표현된 데이터를 사용하여 데이터 테이블의 형태로 제공됩니다.

막대 차트: 국가와 계절에 따른 강우량 평균. 전체 설명은 아래 테이블에 있습니다.

각 계절에 대한 최고와 최저 강우량의 표시자들은 표에 포함되었기 때문에, 차트 내에 쉽게 식별된 추세 역시 데이터 테이블에서도 사용 가능합니다.

국가와 계절에 따른 평균 강우량(mm).
영국 일본 오스트리아
5.3 (최고) 2.4 2 (최저)
여름 4.5 (최고) 3.4 2 (최저)
가을 3.5 (최고) 1.8 1.5 (최저)
겨울 1.5 (최고) 1.2 1 (최저)
<figure>
<figcaption>Rainfall Data</figcaption>
<img src="rainchart.gif" alt="Bar chart: average rainfall by Country and Season.
Full description in Table below.">
<table id="table-4">
<caption>Rainfall in millimetres by Country and Season.</caption>
<tr><td><th scope="col">UK <th scope="col">Japan<th scope="col">Australia</tr>
<tr><th scope="row">Spring <td>5.5 (highest)<td>2.4 <td>2 (lowest)</tr>
<tr><th scope="row">Summer <td>4.5 (highest)<td>3.4<td>2 (lowest)</tr>
<tr><th scope="row">Autumn <td>3.5 (highest) <td>1.8 <td>1.5 (lowest)</tr>
<tr><th scope="row">Winter <td>1.5 (highest) <td>1.2 <td>1 lowest</tr>
</table>
</figure>

figure 요소(element)는 막대 차트 이미지와 데이터 테이블을 그룹핑 하는데 사용됩니다. figcaption 요소(element)는 그룹화 된 콘텐트에 대한 캡션을 제공합니다.

이 섹션의 모든 예제에 대해 이미지들에 대한 텍스트 설명들이 필요할 때만 표시되도록 detailssummary 요소(element)가 사용될 수 있습니다:

닫힘 상태의 details 요소(element).

표시된 목록 콘텐트들을 가진 열림 상태의 details 요소(element).

<figure>
<img src="flowchart.gif" alt="Flowchart: Dealing with a broken lamp.">
<details>
<summary>Dealing with a broken lamp</summary>
<ol>
<li>Check if it’s plugged in, if not, plug it in.</li>
<li>If it still doesn’t work; check if the bulb is burned out. If it is, replace the bulb.</li>
<li>If it still doesn’t work; buy a new lamp.</li>
</ol>
</details>
</figure>

details and summary 요소(element)들은 현재 브라우저들에서 잘 지원되지 않기 때문에, 사용된다면 그것들이 지원될 때까지는 기능적으로 제공하기 위해 스크립팅을 사용해야 할 필요가 있을 것입니다. 비슷한 기능을 제공하는 대중적인 자바스크립트 UI 위젯 라이브러리들에 사용자 정의 컨트롤들이 사용 가능한 스크립팅 된 폴리필(polyfill)들이 많이 있습니다.

4.7.5.1.5. 텍스트 이미지들

때때로, 이미지는 텍스트만을 포함하고, 이미지의 목적은 시각적 효과와/혹은 글꼴을 사용하여 텍스트를 나타내는 것입니다. CSS를 사용하여 꾸며진 텍스트가 사용되도록 강력하게 권장되지만, 그것이 불가능하다면, 이미지에 있는 것과 같은 alt 속성(attribute)에 동일한 텍스트를 제공합니다.

이 예는 화려한 여러 색상의 손으로 그린 스타일로 쓰여진 텍스트 "Get Happy!"의 이미지를 보여줍니다. 이미지는 제목(heading)의 콘텐트를 구성합니다. 이 예에서 이미지에 대한 대체 텍스트는 "Get Happy!"입니다.

Get Happy!

<h1><img src="gethappy.gif" alt="Get Happy!"></h1>
이 예에는 텍스트로 구성된 광고 이미지가 있이며, 문구 "The BIG sale"이 3번 반복되고, 각 반목마다 텍스트는 작아지고 희미해지며, 마지막 줄은 "...ends Friday"라고 읽힙니다. 광고로서 사용되는 상황에서 이미지의 대체 텍스트는 반복은 시각적 효과를 위한 것이고 텍스트의 반복은 이미지를 볼 수 없는 사람들에 대해 불필요하고 혼란스러울 수 있기 때문에 텍스트 "The BIG sale"만을 포함하도록 권장됩니다.

The big sale ...ends Friday.

<p><img src="sale.gif" alt="The BIG sale ...ends Friday."></p>

텍스트 이미지와 함께 사진이나 다른 그래픽이 존재하는 상황에서, 이미지 텍스트 내의 단어들이 이미지를 볼 수 있는 사용자들에게 의미(meaning)를 전달하는 이미지의 다른 설명과 함께, 정보가 이미지를 볼 수 없는 사용자에게도 사용 가능하도록 대체 텍스트로 포함되는 것을 보장하세요.

이미지가 유니코드로 달리 표현될 수 없는 문자를 표현하는데 사용되는 경우, 예를 들어 가이지(がいじ, 外字), 이타이지(いたいじ, 異体字), 새로운 통화 표시 같은 새로운 문자, 대체 텍스트는 동일한 것을 작성하는 종래의 방법이 되어야 합니다, 예를 들어 문자의 발음을 제공하는 음성기호 히라가라나 카타카나를 사용하여.
1997년의 이 예에서, 중앙에 한 개 대신 두 개의 바가 있는 동그랗게 말린 E 같이 보이는 최신식 통화 기호가 이미지를 사용하여 표현됩니다. 대체 텍스트는 문자의 발음을 제공합니다.

Only euro 5.99!

<p>Only <img src="euro.png" alt="euro ">5.99!

유니코드 문자가 동일한 목적으로 제공한다면 이미지는 사용되지 않아야(should) 합니다. 유니코드를 사용하여 직접적으로 텍스트가 표현될 수 없을 경우에만, 예를 들어 장식이거나 문자가 유니코드 문자 세트에 없기 때문인 경우 (가이지의 경우처럼), 이미지가 적절할 것입니다.

기본 시스템 글꼴이 제공된 문자를 지원하지 않기 때문에 작성자가 이미지를 사용하도록 유인된다면, 이미지들 보다는 웹 폰트들이 더 나은 해결책입니다.

채색을 한 원고는 그것의 문자들에 대해 그래픽을 사용할 수 있습니다. 그러한 상황에서 대체 텍스트는 단지 이미지가 나타내는 문자입니다. Once upon a time and a long long time ago...
<p><img src="initials/fancyO.png" alt="O">nce upon a time and a long long time ago...
4.7.5.1.6. 텍스트를 포함하는 이미지들

종종, 이미지는 차트와 같은 그래픽과 연관된 텍스트로 구성됩니다. 이 경우 이미지 내 텍스트는 대체 텍스트에 포함되도록 권장됩니다.

원형 차트와 관련된 텍스트를 포함하는 이미지를 고려해보세요. 관련된 텍스트를 가능한 이미지 텍스트가 아니라 텍스트로서 제공하는 것이 권장됩니다. 이것이 불가능하다면 이미지로 전달되는 적절한 정보와 함께 대체 텍스트에 텍스트를 포함시키세요.

Figure 1. Distribution of Articles by Journal
  Category. Pie chart: Language=68%, Education=14% and Science=18%.

<p><img src="figure1.gif" alt="Figure 1. Distribution of Articles by Journal Category.
Pie chart: Language=68%, Education=14% and Science=18%."></p>
여기 alt 속성(attribute)에 포함된 짧은 텍스트와 텍스트로 긴 대체 텍스트를 보여주는, 동일한 원형 차트 이미지의 다른 예가 있습니다. figurefigcaption 요소(element)들이 이미지와 연관된 긴 대체 텍스트로 사용됩니다. alt 속성(attribute)은 이미지를 라벨링 하는데 사용됩니다.
<figure>
<img src="figure1.gif" alt="Figure 1">
<figcaption><strong>Figure 1.</strong> Distribution of Articles by Journal Category.
Pie chart: Language=68%, Education=14% and Science=18%.</figcaption>
</figure>

이전 예보다 이 방법이 유리한 것은 대체 텍스트가 항상 모든 사용자에게 사용 가능하다는 것입니다. alt 속성(attribute)을 사용하여 제공되는 대체 텍스트는 구조화 된 마크업을 허용되지 않는 반면, 이것은 또한 구조화 된 마크업이 대체 텍스트에 사용되는 것을 허용합니다.

4.7.5.1.7. 페이지 콘텐트의 테마나 주제를 향상시키는 이미지

주변 텍스트에 의해 직접적으로 논의되지 않지만 여전히 어떤 관련성을 가지는 이미지가 img 요소(element)를 사용하여 페이지에 포함될 수 있습니다. 그러한 이미지들은 단순한 장식 이상이고, 페이지의 테마나 주제를 증대시킬 수 있고 때문에 여전히 콘텐트의 일부를 형성합니다. 이러한 경우, 대체 텍스트가 제공되도록 권장됩니다.

페이지 콘텐트의 주제와 밀접하게 관련되지만 직접적으로 논의되지 않는 이미지의 예가 여기 있습니다. 시를 낭송하는 페이지에, 그림 이미지는 시에 의해 영감을 받았습니다. 다음 코드 조각은 예를 보여줍니다. 이미지는 "샬롯의 부인"이라는 제목의 그림이고, 그것은 시에서 영감을 받았고 그것의 주제는 시로부터 유래됩니다. 따러서 대체 텍스트가 제공되도록 강력히 권장됩니다. alt 속성(attribute) 내에 이미지의 콘텐트의 짧은 설명과 문서의 하단에 위치한 긴 설명으로의 링크가 이미지 아래에 있습니다. 긴 설명의 끝에 그림에 대한 더 자세한 정보로의 링크도 있습니다.

A painting inspired by Alfred Tennyson’s poem The Lady of Shalott

<header>
<h1>The Lady of Shalott</h1>
<p>A poem by Alfred Lord Tennyson</p>
</header>

<img src="shalott.jpeg" alt="Painting - a young woman with long hair, sitting in a wooden boat. Full description below.">
<p><a href="#des">Description of the painting</a>.</p>

<!-- Full Recitation of Alfred, Lord Tennyson’s Poem.  -->

...
...
...
<p id="des">The woman in the painting is wearing a flowing white dress. A large piece of intricately
patterned fabric is draped over the side. In her right hand she holds the chain mooring the boat. Her expression
is mournful. She stares at a crucifix lying in front of her. Beside it are three candles. Two have blown out.
<a href="https://bit.ly/5HJvVZ">Further information about the painting</a>.</p>

이 예는 페이지의 주요 주제의 사진으로서 이미지를 식별하는 대체 텍스트의 제공을 보여줍니다.

Portrait photo(black and white) of Robin, accompanied by a heading 'Robin Berjon' and a question
  'what more needs to be said?'

<img src="orateur_robin_berjon.png" alt="Portrait photo(black and white) of Robin.">
<h1>Robin Berjon</h1>
<p>What more needs to be said?</p>
4.7.5.1.8. 주변 텍스트의 일부의 그래픽 표현

많은 경우, 이미지는 실제로 단지 부수적일 뿐이고, 그것의 존재는 단순히 주변 텍스트를 보충합니다. 이러한 경우, alt 속성(attribute)는 존재해야 하지만 그 값은 빈 문자열이어야(must) 합니다.

일반적으로, 이미지를 삭제하는 것이 페이지를 전혀 덜 유용하게 만들지 않는다면 이 카테고리로 분류되지만, 이미지를 포함하는 것은 그것을 시각 브라우저들의 사용자에 대해 개념을 이해시키는데 많은 부분 쉽게 만듭니다.

이미지에 대한 유용한 대체 텍스트를 작성하는 것은 항상 쉬운 일은 아니며, 다른 옵션은 가능하다면 이미지에 대한 설명이나 더 상세한 정보로의 링크를 제공하는 것입니다. 동일한 이미지의 이 예에, alt 속성(attribute) 내에 포함된 짧은 대체 텍스트가 있고, 이미지 이후에 링크가 있습니다. 링크는 그림에 대한 정보를 포함하는 페이지를 가리킵니다.

The Lady of Shalott

A poem by Alfred Lord Tennyson.

Painting of a woman in a white flowing dress, sitting in a small boat.

About this painting

Full recitation of Alfred, Lord Tennyson’s poem.

<header><h1>The Lady of Shalott</h1>
<p>A poem by Alfred Lord Tennyson</p></header>
<figure>
<img src="shalott.jpeg" alt="Painting: a woman in a white flowing dress, sitting in a small boat.">
<p><a href="https://bit.ly/5HJvVZ">About this painting.</a></p>
</figure>
<!-- Full Recitation of Alfred, Lord Tennyson’s Poem.  -->
4.7.5.1.9. 어떤 정보도 추가하지 않는 순수한 장식 이미지

순수하게 장식적인 이미지들은 이미지들을 볼 수 있는 사람들에 대한 미학을 넘어선 기능이나 정보를 제공하지 않는 시각적 향상 이나 장식 혹은 꾸밈들입니다.

순수하게 장식적인 이미지들이 보조 기술에 의해 무시 될 수 있도록 빈 alt 속성(attribute)을 (alt="") 사용하여 마크업 하세요. 장식적인 이미지들을 인라인에 포함시키는 것은 용인할 수 없는 것이 아니지만, 그것들이 순수하게 장식적인 경우 CSS를 사용하여 이미지를 포함하는 것이 권장됩니다.

개인의 블로그에 대한 장식 배너로서 사용되는 이미지의 예가 여기 있습니다. 이 이미지는 어떠한 정보도 제공하지 않고 따라서 빈 alt 속성이 사용됩니다.

Clara’s Blog Welcome to my blog...

<header>
<div><img src="border.gif" alt="" width="400" height="30"></div>
<h1>Clara’s Blog</h1>
</header>
<p>Welcome to my blog...</p>
4.7.5.1.10. 인라인 이미지들

이미지들이 문장에서 텍스트의 흐름의 일부로 인라인으로 사용되는 경우, 떨어진 문장의 맥락에서 의미가 통하는 대체 텍스트로서 단어나 구문을 제공하세요.

I love you.
I <img src="heart.png" alt="love"> you.

My heart breaks.

My <img src="heart.png" alt="heart"> breaks.

그림이 나중에 다시 온전한 그림을 형성하도록 함께 표시되는 작은 이미지 파일들로 잘려진 경우, 전체로서 그림에 대한 관련 지침에 따라 alt 속성(attribute)을 사용하여 이미지들 중 하나에 대체 텍스트를 포함시키고, 이후 다른 이미지들에는 빈 alt 속성(attribute)을 포함시키세요.

이 예에서, PIP Corporation에 대한 회사 로고를 나타내는 그림이 두 개 조각, 글자 "PIP"를 포함하는 첫 번째와 단어 "CO"를 가진 두 번째로 분할되었습니다. 대체 텍스트 PIP CO는 첫 번째 이미지의 alt 속성(attribute)에 있습니다.

Image containing the text 'PIP'.Image containing the text 'CO'.

<img src="pip.gif" alt="PIP CO"><img src="co.gif" alt="">
다음 예에서, 비율이 세 개의 채워진 별과 두 개의 빈 별로 보여집니다. 대체 테스트는 "★★★☆☆"일 수 있지만, 작성자는 대신 "3 out of 5"의 형식으로 좀 더 유용하게 순위를 제공하기록 결정했습니다. 그것은 첫 번째 이미지의 대체 텍스트이고, 나머지는 빈 alt 속성(attribute)들을 가집니다. 3 out of 5.
<p>Rating:
<img src="1" alt="3 out of 5">
<img src="1" alt=""><img src="1" alt="">
<img src="0" alt=""><img src="0" alt="">
</p>
4.7.5.1.12. 이미지 지도
img 요소(element)가 href 속성(attribute)들을 가지는 area 요소(element)들을 포함하는 map 요소(element)를 참조하는 usemap 속성(attribute)을 가진다면, img는 상호 작용 콘텐트로 간주됩니다. 그러한 경우, alt 속성(attribute)을 사용하여 항상 이미지에 대한 대체 텍스트를 제공하세요.

카툼바의 지도인 다음 이미지를 고려해보세요, 그것은 북과 남 카툼바의 영역에 해당하는 두 상호 작용 영역을 가집니다:

Map of Katoomba.

North Katoomba South Katoomba 대체 텍스트는 이미지에 대한 간단한 설명입니다. area 요소(element)들의 각각의 alt 속성(attribute)은 각 링크된 영역의 대상 페이지의 콘텐트를 설명하는 텍스트가 제공됩니다:
<p>View houses for sale in North Katoomba or South Katoomba:</p>
  <p><img src="imagemap.png" width="209" alt="Map of Katoomba" height="249" usemap="#Map">

  <map name="Map">
  <area shape="poly" coords="78,124,124,10,189,29,173,93,168,132,136,151,110,130"
  href="north.html" alt="Houses in North Katoomba">
  <area shape="poly" coords="66,63,80,135,106,138,137,154,167,137,175,133,144,240,49,223,17,137,17,61"
  alt="Houses in South Katoomba" href="south.html">
  </map>

때때로, 여러 이미지들로부터 함성 사진을 생성하는 경우, 이미지들의 하나 이상을 링크하고 싶을 수 있습니다. 링크의 목적을 설명하기 위해 각 링크된 이미지에 대해 alt 속성(attribute)을 제공하세요.

다음 예에서, 합성 사진은 "crocoduck"을 나타내는데 사용됩니다; 악어의 일부와 오리의 일부가 되는 진화적 원리들을 무시하는 가상의 창조물. crocoduck과 상호 작용하도록 요구되고, 주의를 기울일 필요가 있습니다...

crocodile’s angry, chomping headduck’s soft, feathery body

<h1>The crocoduck</h1>
<p>You encounter a strange creature called a "crocoduck".
The creature seems angry! Perhaps some friendly stroking will help to calm
it, but be careful not to stroke any crocodile parts. This would just enrage
the beast further.</p>
<a href="?stroke=head"><img src="crocoduck1.png" alt="Stroke crocodile’s angry, chomping head"></a>
<a href="?stroke=body"><img src="crocoduck2.png" alt="Stroke duck’s soft, feathery body"></a>
4.7.5.1.14. 사진 이미지들

사진이나 그래픽 이미지는 개체, 사람, 풍경, 추상화, 기타 등등의 시각적 표현을 포함합니다. 이 비 텍스트 콘텐트는, [WCAG20] 정상 시력자에게 시각적으로 특별한 의미가 있는 대량의 정보를 전달하거나 특정한 감각적 경험을 제공, [WCAG20] 할 수 있습니다. 그 예들은 사진, 그림, 도안, 삽화를 포함합니다.

그림에 대한 적절한 대체 텍스트는 간단한 설명이나 이름입니다 [WCAG20]. 모든 대체 텍스트 작성 결정에서와 같이, 그림에 대한 적절한 대체 텍스트들을 작성하는 것은 사람의 판단을 요구합니다. 텍스트 값은 이미지가 사용되는 맥락과 페이지 작성자의 문체에 따라 주관적입니다. 따라서, 어떤 특정 이미지에 대해 "정확"하거나 "옳은" 하나의 alt 텍스트는 존재하지 않습니다. 비 텍스트 콘텐트의 간단한 설명을 제공하는 짧은 대체 텍스트를 제공하는 것뿐 아니라, 다른 도구들을 통해 보충 콘텐트를 제공하는 것은 적절한 경우 유용할 수 있습니다.

이 첫 번째 예는 사진 공유 사이트에 업로드 된 이미지를 보여줍니다. 사진은 욕조에 앉아있는 고양이입니다. 이미지는 img 요소(element)의 alt 속성(attribute)을 사용하여 제공된 대체 텍스트를 가집니다. 그것은 또한 figure 요소(element) 내에 img 요소(element)를 포함하는 것과 캡션 텍스트를 식별하기 위한 figcaption 요소(element)를 사용하는 것에 의해 제공된 캡션을 가집니다.

Lola the cat sitting under an umbrella in the bath tub.

Lola prefers a bath to a shower.

<figure>
<img src="664aef.jpg" alt="Lola the cat sitting under an umbrella in the bath tub.">
<figcaption>Lola prefers a bath to a shower.</figcaption>
</figure>
이 예는 이미지의 제목이 해석에 대해 열려있기 때문에 완전한 설명이 거의 불가능한 이미지의 예입니다. 이미지는 alt 속성(attribute)에 이미지를 볼 수 없는 사용자에게 이미지가 무엇인지의 느낌을 제공하는 대체 텍스트를 가집니다. 이것은 또한 figure 요소(element)에 img 요소(element)를 포함시키고 캡션 텍스트를 식별하기 위해 figcaption 요소(element)를 사용하여 제공된 캡션을 가집니다.

An abstract, freeform, vertically symmetrical, black inkblot on a light background.

The first of the ten cards in the Rorschach test.

<figure>
  <img src="Rorschach1.jpg" alt="An abstract, freeform, vertically symmetrical, black inkblot on a light background.">
  <figcaption>The first of the ten cards in the Rorschach test.</figcaption>
  </figure>
4.7.5.1.15. 웹캠 이미지

웹캠 이미지들은 주기적으로 자동으로 업데이트되는 정적 이미지들입니다. 일반적으로 이미지들은 고정된 시점에서의 이미지이고, 이미지들은 카메라로부터 업로드되는 각 새로운 이미지로서 자동으로 페이지에 업데이트 될 수 있거나 사용자가 업데이트 된 이미지를 보기 위해 페이지 새로 고침이 요구될 수 있습니다. 이 예들은 교통 상황과 날씨 카메라들을 포함합니다.

이 예는 꽤 전형적입니다; 제목(title)과 타임 스탬프가 웹캠 소프트웨어에 의해 자동으로 생성되어 이미지에 포함됩니다. 텍스트 정보가 이미지에 포함되지 않았다면 더 좋았을 것이지만, 그것이 이미지의 일부이기 때문에 대체 텍스트의 일부로 그것을 포함합니다. 캡션은 또한 figurefigcaption 요소(element)들을 사용하여 제공됩니다. 이미지가 건물 근처 현재 날씨의 시각적 정보를 전달하기 위해 제공되는 것처럼, 지역 일기 예보로의 링크가 제공 되고, 자동으로 생성되고 업로드 된 웹캠 이미지들처럼, 대체 텍스트로서 그 정보를 제공하는 것은 실행 불가능할 수 있습니다.

alt 속성(attribute)의 텍스트는 음성 소프트웨어에 텍스트를 알리는 경우 더 이해하기 쉽도록 설계된, 타임 스탬프의 문제 버전을 포함합니다. 대체 텍스트는 또한 기상 조건들과 하루의 시간이 변하기는 하지만, 이미지에서 보여질 수 있는 변하지 않는 것의 일부 양상의 설명을 포함합니다.

Sopwith house weather cam. Taken on the 21/04/10 at 11:51 and 34 seconds. In the foreground are the safety
  rails on the flat part of the roof. Nearby ther are low rize industrial buildings, beyond those are block of flats. In the distance there’s a
  church steeple.

View from the top of Sopwith house, looking towards North Kingston. This image is updated every hour.

View the latest weather details for Kingston upon Thames.

<figure>
  <img src="webcam1.jpg" alt="Sopwith house weather cam. Taken on the 21/04/10 at 11:51 and 34 seconds.
  In the foreground are the safety rails on the flat part of the roof. Nearby there are low rize industrial buildings,
  beyond are blocks of flats. In the distance there’s a church steeple.">
  <figcaption>View from Sopwith house, looking towards north Kingston. This image is updated every hour.</figcaption>
  </figure>
  <p>View the <a href="https://news.bbc.co.uk/weather/forecast/4296?area=Kingston">latest weather details</a> for Kingston upon Thames.</p>
4.7.5.1.16. 게시 시점에 대체 텍스트가 불가한 경우

어떤 경우 이미지는 발행된 문서에 포함되지만, 작성자가 적절한 대체 텍스트를 제공할 수 없습니다. 그러한 경우 최소한의 요구사항은 다음 조건 하에 figurefigcaption 요소(element)들을 사용하여 이미지에 대한 캡션을 제공하는 것입니다:

  • img 요소(element)가 figure 요소(element) 내에 위치
  • figure 요소(element)가 figcaption 요소(element)를 포함
  • figcaption 요소(element)가 요소간 공백이 아닌 콘텐트를 포함
  • figcaption 요소(element)와 그것의 후손들을 무시하고, 요소 간 공백 외 후손 Text 노드를 가지지 않고 img 요소(element) 외 다른 삽입(embedded) 콘텐트를 가지지 않는 figure 요소(element).

다시 말해, figure의 유일한 콘텐트는 img 요소(element)와 figcaption 요소(element)이고, figcaption 요소(element)는 (캡션) 콘텐트를 포함해야(must) 합니다.

그러한 경우는 최소한으로 유지되어야 합니다. 실제 대체 텍스트를 제공할 수 있는 능력을 가지는 작성자의 최소한의 가능성이라도 있다면, alt 속성(attribute)을 생략하는 것은 허용 될 수 없습니다.

이 예에서, 누군가 사진 공유 사이트에 다수의 이미지의 대량 업로드의 일부로 사진을 업로드 합니다. 사용자는 이미지에 대한 대체 텍스트나 캡션을 제공하지 않았습니다. 사이트의 작성 도구가 이미지에 대해 가지고 있는 어떤 유용한 정보를 사용하여 자동으로 캡션을 삽입합니다. 이 경우 그것은 파일 이름과 사진이 찍힌 날짜입니다.

아래 예에서 캡션 텍스트는 적절한 대체 텍스트가 아니며 웹 접근성 지침 2.0에 준하지 않습니다. [WCAG20]

no text alternative provided

clara.jpg, taken on 12/11/2010.

<figure>
<img src="clara.jpg">
<figcaption>clara.jpg, taken on 12/11/2010.</figcaption>
</figure>

이 예에서까지도 figcaption 요소(element)에 여전히 가능한 많은 유용한 정보가 포함되는 것에 주목하세요.

이 두 번째 예에서, 누군가 사진 공유 사이트에 사진을 업로드합니다. 그녀는 대체 텍스트가 아니라 이미지에 대한 캡션을 제공했습니다. 이는 사이트가 사용자에게 alt 속성(attribute)에 대체 텍스트를 추가하기 위한 수단을 제공하지 않기 때문일 수 있습니다.

no text alternative provided

Eloisa with Princess Belle

<figure>
<img src="elo.jpg">
<figcaption>Eloisa with Princess Belle</figcaption>
</figure>
때때로 이미지의 전체 의미는 텍스트로 설명이 불가능한 것이고, 사용자가 설명을 제공합니다. 예를 들어, 이미지를 표시하고 정확한 대체 텍스트를 가진 페이지를 작성하는 때의 목적을 위해 정확하게 대체 텍스트를 요구하는 소프트웨어. 그러한 페이지는 이와 같이, 이미지의 표를 가질 수 있습니다:
<table>
  <tr><tr> <th> Image <th> Description<tr>
  <td>
  <figure>
  <img src="2421.png">
  <figcaption>Image 640 by 100, filename 'banner.gif'</figcaption>
  </figure>
  <td> <input name="alt2421">
  <tr>
  <td> <figure>
  <img src="2422.png">
  <figcaption>Image 200 by 480, filename 'ad3.gif'</figcaption>
  </figure>
  <td> <input name="alt2422">
  </table>

어떤 사용자들은 이미지를 전혀 사용할 수 없기 때문에 (예를 들어, 눈이 보이지 않기 때문에) alt 속성(attribute)은 위의 예에서와 같이, 대체 텍스트가 사용 불가능하고 어떠한 것도 사용 가능하게 만들 수 없는 경우에만 생략되는 것이 허용됩니다.

4.7.5.1.17. 사용자에 대해 의도되지 않은 이미지

일반적으로 작성자들은 이미지들을 보여주는 것 외 다른 목적들로 img 요소(element)들을 사용하는 것을 피해야 합니다.

img 요소(element)가 이미지를 보여주는 것 외 다른 목적들로 사용되고 있다면, 예를 들어 페이지 뷰를 카운트하는 서비스의 일부로, 빈 alt 속성(attribute)을 사용하세요.

img 요소(element)의 예는 웹 페이지 통계를 수집하는데 사용됩니다. alt 속성(attribute)은 이미지가 의미(meaning)를 가지지 않기 때문에 비어있습니다.
<img src="https://server3.stats.com/count.pl?NeonMeatDream.com" width="0" height="0" alt="">

위 예에 대해서 widthheight 속성(attribute)들은 0으로 설정되도록 사용하는 것이 권장됩니다.

또 다른 사용 예는 spacer.gif와 같은 이미지가 콘텐트의 위치를 보조하는데 사용되는 경우입니다. alt 속성(attribute)은 이미지가 의미(meaning)를 가지지 않기 때문에 비어있습니다.
<img src="spacer.gif" width="10" height="10" alt="">

콘텐트를 배치하기 위해 img 요소(element)들을 사용하는 대신 CSS를 사용하도록 권장됩니다.

4.7.5.1.18. 아이콘 이미지

아이콘은 보통 프로그램, 동작, 데이터 파일, 컨셉을 나타내는 간단한 그림입니다. 아이콘들은 시각 브라우저들의 사용자들이 한 눈에 기능을 인식할 수 있도록 돕기 위해 의도됩니다.

아이콘이 동일한 의미(meaning)를 전달하는 텍스트에 대해 추가된 것인 경우 빈 alt 속성을 사용하세요.

이 예에서, 사이트의 홈 페이지를 가리키는 링크를 가지고 있고, 이 링크는 집 아이콘 이미지와 텍스트 "home"을 포함합니다. 이미지는 빈 alt 텍스트를 가집니다.

A house icon next to the word 'home'.

<a href="home.html"><img src="home.gif" width="15" height="15" alt="">Home</a>

이미지들이 이 방법으로 사용되는 경우, CSS를 사용하여 이미지를 추가하는 것 또한 적절할 것입니다.

#home:before
{
content: url(home.png);
}

<a href="home.html" id="home">Home</a>
이 예에, 경고 아이콘을 가진 경고 메세지가 있습니다. 단어 "Warning!"이 이미지 옆에 강조된 텍스트에 있습니다. 아이콘에 의해 전달된 정보는 불필요하기 때문에 img 요소(element)는 빈 alt 속성(attribute)이 제공되었습니다.

Warning! Warning! Your session is about to expire.

<p><img src="warning.png" width="15" height="15" alt="">
<strong>Warning!</strong>
Your session is about to expire</p>

아이콘이 텍스트 내에 사용 가능하지 않은 추가적인 정보를 전달하는 경우, 대체 텍스트를 제공하세요.

이 예에, 경고 아이콘을 가진 경고 메세지가 있습니다. 아이콘은 메세지의 중요성을 강조하고 콘텐트의 특정한 유형으로서 그것을 식별합니다.

Warning! Your session is about to expire.

<p><img src="warning.png" width="15" height="15" alt="Warning!">
Your session is about to expire</p>
4.7.5.1.19. 로고, 휘장, 깃발, 엠블럼

많은 페이지들은 회사, 조직, 프로젝트, 밴드, 소프트웨어 패키지, 국가, 기타 단체들을 대표하는 로고, 휘장, 깃발, 엠블럼들을 포함합니다. 모든 이미지가 그렇듯, 적절한 대체 텍스트로서 고려될 수 있는 것은 이미지가 사용되는 맥락과 주어진 맥락에서 그것이 어떤 기능을 제공하는가에 달려있습니다.

로고가 링크의 유일한 콘텐트라면, alt 속성(attribute)에 링크 대상에 대한 간단한 설명을 제공하세요.

이 예는 HTML 명세로의 링크의 유일한 콘텐트로서 HTML5 로고의 사용을 보여줍니다.

HTML 5.1 Nightly specification

<a href="https://w3c.github.io/html/">
<img src="HTML5_Logo.png" alt="HTML 5.1 specification"></a>

로고가 단체를 나타내는데 사용되는 것이라면, 예를 들어, 페이지 제목(heading)으로, 대체 텍스트로서 로고에 의해 표현되는 단체의 이름을 제공하세요.

이 예는 자신을 나타내는데 사용되는 WebPlatform.org 로고의 사용을 보여줍니다.

WebPlatform.org and other developer resources

<h2><img src="images/webplatform.png" alt="WebPlatform.org"> and other developer resources<h2>

위 예에서 대체 텍스트는 이미지 콘텐트의 유형을 설명하기 위해 단어 "logo"도 포함할 수 있습니다. 그러한 경우, 이 정보를 상세히 기술하기 위해 각괄호가 사용되도록 제안됩니다: alt="[logo] WebPlatform.org".

로고가 그것이 나타내는 것의 이름 옆에 사용된다면, 로고는 추가적인 것입니다. 대체 텍스트가 이미 제공된 것 처럼 빈 alt 속성(attribute)을 포함시키세요.

이 예는 조직의 이름 옆에 나타나는 로고의 사용을 보여줍니다.

WebPlatform.org

<img src="images/webplatform1.png" alt=""> WebPlatform.org

로고가 주제나 단체 로고가 나타내는 것을 설명하는 텍스트와 함께 사용된다면, 로고를 설명하는 대체 텍스트를 제공하세요.

이 예는 주제가 로고가 나타내는 것을 설명하는 텍스트 옆의 로고의 사용을 보여줍니다.

HTML5 logo: Shaped like a shield with the text 'HTML' above and the numeral '5' prominent on the face of the shield.

HTML is a language for structuring and presenting content for the World Wide Web, a core technology of the Internet. It is the latest revision of the HTML standard (originally created in 1990 and most recently standardized as HTML 4.01 in 1997) and currently remains under development. Its core aims have been to improve the language with support for the latest multimedia while keeping it easily readable by humans and consistently understood by computers and devices (web browsers, parsers etc.).

<p><img src="HTML5_Logo.png" alt="HTML5 logo: Shaped like a shield with the
text 'HTML' above and the numeral '5' prominent on the face of the shield."></p>

Information about HTML
4.7.5.1.20. CAPTCHA 이미지

CAPTCHA는 "컴퓨터와 인간을 구별하는 완전히 자동화 된 공공 튜링 테스트"를 나타냅니다. CAPTCHA 이미지들은 콘텐트가 컴퓨터가 아닌 사람에 의해 접근되고 있는지를 확인 하기 위한 보안 목적으로 사용됩니다. 이 인증은 이미지의 시각적 확인을 통해 이루어집니다. CAPTCHA는 일반적으로 사용자가 다시 타이핑하기 위한 글자나 단어를 가진 이미지를 나타냅니다. 이미지는 보통 왜곡되고 글자들을 읽기 어렵게 만들기 위해 적용된 일부 노이즈를 가집니다.

CAPTCHA의 접근성을 향상시키기 위해 이미지의 목적을 식별하고 설명하는 대체 텍스트들을 제공하고, 다른 유형의 감간 인식에 대한 출력 모드를 사용하여 CAPTCHA의 대체 형식을 제공하세요. 예를 들어 시각적인 이미지와 함께 대체 음성을 제공하세요. 시작적 이미지의 바로 옆에 음성 옵션을 위치 시키세요. 이것은 도움이 되지만, 사운드 카드가 없는 사람, 청각-시각장애인, 몇몇 제한된 청력을 가진 사람들에 대해 요전히 문제가 됩니다. 다른 방법은 시각 이미지와 함께 질문을 묻는 양식을 포함하는 것입니다. 이것은 도움이 되지만 인지 장애를 가진 사람들에 대해 문자가 될 수 있습니다.

CAPTCHA의 모든 형식은 장애를 가진 사용자들에 대해 허용 될 수 없는 참여 장벽을 가져오기 때문에, CAPTCHA에 대해 사용되는 대안들이 강력하게 권장됩니다. 좀 더 자세한 정보는 Inaccessibility of CAPTCHA에서 사용 가능합니다.

이 예는 텍스트의 왜곡된 이미지를 사용하는 CAPTCHA 검사를 보여줍니다. alt 속성(attribute) 내의 대체 텍스트는 이미지 콘텐트에 접근할 수 없는 경우의 사용자에 대한 지시사항들을 제공합니다.

captcha containing the words 'aides' and 'sprucest'. The letters are distorted and the color of the letters and background is partially inverted,

Example code:

<img src="captcha.png" alt="If you cannot view this image an audio challenge is provided.">
<!-- audio CAPTCHA option that allows the user to listen and type the word -->
<!-- form that asks a question -->
4.7.5.1.21. picture 요소(element) 내의 이미지

picture 요소(element)와 그것이 포함하는 source 요소(element)들은 사용자들에 대한 의미(semantic)을 가지지 않으므로, img 요소(element)나 그것의 대체 텍스트만이 사용자들에게 표시됩니다. img 요소(element)에 대한 대체 텍스트를 picture 요소(element)에 있는 것과 관계 없이 제공하세요. 이미지들에 대한 유용한 alt 텍스트를 제공하는 방법데 대한 자세한 내용을 위해 이미지들에 대한 대체 텍스트로서 동작하도록 텍스트를 제공하기 위한 요구사항을 참조하세요.

picture에 의존하는 art directed 이미지들은 동일한 콘텐트를 (크기, 픽셀 밀도, 다른 식별 요소에 관계 없이) 그리도록 요구됩니다. 따라서 브라우저에 의해 선택되는 소스 파일에 관계 없이 이미지에 대한 적절한 대체 텍스트가 항상 동일할 것입니다.

<h2>Is it a ghost?</h2>
<picture>
  <source media="(min-width: 32em)" srcset="large.jpg">
  <img src="small.jpg" alt="Reflection of a girls face in a train window.">
</picture>

이미지의 크고 작은 버전들은 (두 버전 모두 데모 용으로 표시됩니다) 동일한 장면을 묘사합니다: 열차 창에 소녀 얼굴의 반사 장면은, 작은 버전 (작은 화면에 표시되는)이 잘렸지만, 주제나 alt 텍스트의 적절성에 영향을 주지 않습니다.

Reflection of a girls face in a train window. Reflection of a girls face in a train window.

4.7.5.1.22. 마크업 생성기들을 위한 지침

마크업 생성기들은 (WYSIWYG 작성도구들 같은), 가능한 어디든지, 그것들의 사용자들로부터 대체 텍스트를 얻어야(should) 합니다. 하지만, 많은 경우에, 이것은 가능하지 않을 것으로 인정됩니다.

링크들의 유일한 콘텐트인 이미지들에 대해, 마크업 생성기들은 대상의 제목이나 대상의 URL을 결정하기 위해 링크 대상을 검토해야(should)하고, 이 방법으로 얻어진 정보를 대체 텍스트로 사용해야 합니다.

캡션을 가지는 이미지들에 대해, 마크업 생성기들은 이미지의 캡션을 제공하기 위해 figurefigcaption 요소(element)들을 사용해야(should) 합니다.

최후의 수단으로, 구현자는 이미지가 어떤 정보도 추가하지 않지만 여전히 주변 콘텐트에 따라 다른 순수하게 장식 이미지라는 가정 하에 alt 속성(attribute)을 빈 문자열로 설정 해야(should) 하거나, 이미지가 콘텐트의 핵심 부분이라는 가정하에alt 속성(attribute)을 완전히 생략해야(should) 합니다.

마크업 생성기들은 대체 텍스트를 얻는 것이 불가능하고 때문에 alt 속성(attribute)이 생략된 img 요소(element)들에 generator-unable-to-provide-required-alt 속성(attribute)을 명시할 수 있습니다. 이 속성(attribute)의 값은 빈 문자열이어야(must) 합니다. 그 속성(attribute)들을 포함하는 문서들은 적합하지 않지만, 적합성 검사기들은 이 오류를 묵시적으로 무시할 것입니다.

이것은 최신의 자동화 적합성 검사기들이 가짜 대체 텍스트들과 올바른 대체 텍스트들을 구별할 수 없기 때문에, alt 속성(attribute)의 생략 오류를 가짜 대체 텍스트들을 제공하는 훨씬 더 엄청난 오류로의 교체가 강제되는 것으로부터 마크업 생성기들을 방지하기 위해 의도된 것입니다.

마크업 생성기들은 일반적으로 대체 텍스트로서 이미지 자신의 파일 이름을 사용하는 것을 방지해야(should) 합니다. 마찬가지로, 마크업 생성기들은 프리젠테이션 유저 에이전트들에 (예를 들어, 웹 브라우저들) 동일하게 사용 가능한 콘텐트로부터 대체 텍스트들을 생성하는 것을 방지해야(should) 합니다.

이것은, 나중에 페이지를 읽는 브라우저들이 사용자에 의해 업데이트 될 수 있는 반면에, 일단 페이지가 생성되면 일반적으로 업데이트 될 수 없기 때문에, 브라우저는 페이지가 생성될 때 마크업 생성기가 하는 것 보다 좀 더 최신의 그리고 미세하게 조정된 휴리스틱을 가질 가능성이 높습니다.

4.7.5.1.23. 적합성 검사기들을 위한 지침

적합성 검사기들은 아래 나열된 조건들 중 하나에 적용되지 않는 한 alt 속성(attribute)의 결핍을 오류로 보고해야(must) 합니다:

  • img 요소(element)가 위에 기술 된 조건들을 만족시키는 figure 요소(element)에 있는 경우.

  • img 요소(element)가 (부적합 한) 값이 빈 문자열인 generator-unable-to-provide-required-alt 속성(attribute)을 가짐. alt 속성(attribute)의 결핍을 오류로 보고하지 않는 적합성 검사기는 빈 generator-unable-to-provide-required-alt 속성(attribute)의 존재를 오류로 보고하지 않아야(must) 합니다. (이 경우는 적절한 대체 텍스트를 결정할 수 없는 생성기를 제외하고, 문서가 적합한 경우를 나타내지 않습니다 — 그 오류는 마크업 생성기들이 검사기들을 침묵시킬 의도로 순전히 가짜 대체 텍스트를 포함하도록 권장할 수 있기 때문에 검사기들은 이 경우 오류를 보여주도록 요구 되지 않습니다. 물론, 적합성 검사기들은 generator-unable-to-provide-required-alt 속성(attribute)의 존재에도 불구하고 alt 속성(attribute)의 결핍을 오류로 보고 할 수 있습니다; 예를 들어, 심지어 마크업 생성기를 사용하여 많거나 적은 불가피한 결과가 될 수 있는 것 조차도 모든 적합성 오류들을 보고하기 위한 사용자 옵션이 있을 수 있습니다.)

4.7.6. iframe 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
삽입(embedded) 콘텐트.
대화형(interactive) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
삽입(embedded) 콘텐트가 예상되는 곳.
콘텐트 모델:
본문에 주어진 요구사항들을 따르는 텍스트
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
src - 리소스의 주소
srcdoc - iframe에 렌더링 할 문서
name - 중첩된 브라우징 컨텍스트의 이름
sandbox - 중첩된 콘텐트에 대한 보안 규칙들
allowfullscreen - iframe의 콘텐트가 requestFullscreen()를 사용하는 것을 허용할지 여부
width - 가로 치수
height - 세로 치수
허용된 ARIA 역할(role) 속성(attribute) 값들:
application, document, img.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
interface HTMLIFrameElement : HTMLElement {
  attribute DOMString src;
  attribute DOMString srcdoc;
  attribute DOMString name;
  [PutForwards=value] readonly attribute DOMTokenList sandbox;
  attribute boolean allowFullscreen;
  attribute DOMString width;
  attribute DOMString height;
  readonly attribute Document? contentDocument;
  readonly attribute WindowProxy? contentWindow;
};

iframe 요소(element)는 중첩된 브라우징 컨텍스트나타냅니다.

src 속성(attribute)은 중첩된 브라우징 컨텍스트가 포함하는 페이지의 주소를 제공합니다. 이 속성(attribute)이 존재한다면 유효한 잠정적으로 공백으로 둘러 싸일 수 있는 비어있지 않은 URL이어야(must) 합니다.

srcdoc 속성(attribute)은 중첩된 브라우징 컨텍스트가 포함하는 페이지의 콘텐트를 제공합니다. 이 속성(attribute)의 값은 iframe srcdoc 문서의 소스입니다.

srcdoc 속성(attribute)이 존재한다면 주어진 순서에 따라 다음 구문 컴포넌트들로 구성되는 HTML 문법을 사용하는 값을 가져야(must) 합니다:

  1. 얼마든지의 주석들공백 문자들.
  2. 선택적으로, DOCTYPE.
  3. 얼마든지의 주석들공백 문자들.
  4. html 요소(element)의 형식으로, 루트 요소(element).
  5. 얼마든지의 주석들공백 문자들.

XML 문서들에 있는 iframe 요소(element)들에 대해, srcdoc 속성(attribute)이 존재한다면 XML 명세에 document라고 라벨링 된 생산물에 일치하는 값을 가져야(must) 합니다. [XML]

여기 블로그가 블로그 게시물 댓글들에 스크립트 인젝션으로부터 보호 추가 레이어로 이 기능을 지원하는 유저 에이전트들의 사용자들에게 제공하기 위해 아래 기술된 sandbox 속성(attribute)과 함께 srcdoc 속성(attribute)을 사용합니다:
<article>
  <h1>I got my own magazine!</h1>
  <p>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!</p>
  <footer>
  <p>Written by <a href="/users/cap">cap</a>, 1 hour ago.
  </footer>
  <article>
  <footer> Thirteen minutes ago, <a href="/users/ch">ch</a> wrote: </footer>
  <iframe sandbox srcdoc="<p>did you get a cover picture yet?"></iframe>
  </article>
  <article>
  <footer> Nine minutes ago, <a href="/users/cap">cap</a> wrote: </footer>
  <iframe sandbox srcdoc="<p>Yeah, you can see it <a href=&quot;/gallery?mode=cover&amp;amp;page=1&quot;>in my gallery</a>."></iframe>
  </article>
  <article>
  <footer> Five minutes ago, <a href="/users/ch">ch</a> wrote: </footer>
  <iframe sandbox srcdoc="<p>hey that’s earl’s table.
<p>you should get earl&amp;amp;me on the next cover."></iframe>
  </article>

따옴표를 이스케이프 되어야(have to) 하는 (그렇지 않으면 srcdoc 속성(attribute)들이 일찍 종료될 것입니다) 방식과 샌드박스 된 콘텐트에 언급된 앰퍼샌드들이 (예를 들어, 본문에서 URL들의 앰퍼샌드) 이중으로 이스케이프되어야(have to)하는 방식에 주목하세요 — 한 번은 앰퍼센드가 본래 srcdoc 속성(attribute)을 해석 할 때 보존되고, 샌드박스 된 콘텐트를 해석 할 때 자롯 해석되는 것으로부터 앰퍼샌드를 방지하기 위해 한 번 더.

게다가, iframe srcdoc 문서들DOCTYPE이 선택적이고, html, head, body 요소(element)들이 선택적 시작/종료 태그들을 가지며, iframe srcdoc 문서들title 요소(element) 역시 선택적이기 때문에, body 요소(element)의 콘텐츠만이 구문에서 문자 그대로 나타날 필요가 있으므로 srcdoc 속성(attribute) 내의 마크업은 전체 문서를 나타내는 것에도 불구하고 비교적 간결할 수 있습니다. 다른 요소(element)들은 암묵적으로만 여전히 존재합니다.

HTML 문법에서, 작성자들은 단지 속성(attribute) 콘텐트를 감싸기 위해 U+0022 따옴표 문자들 (")을 사용하고 이후 모든 U+0022 따옴표 문자 (")와 0026 앰퍼샌드 (&) 문자들을 이스케이프하고, 콘텐트의 안전한 삽입을 보장하기 위해 sandbox 속성(attribute)을 명시하는 것을 기억하기만 하면 됩니다.

XHTML 문법의 제한 때문에, XML에서 U+003C ~보다 작다 기호 문자 (<)도 이스케이프 될 필요가 있습니다. 속성(attribute)-값 정규화를 방지하기 위해, 일부 XML의 공백 문자들 — 특별히 U+0009 탭 문자 (tab), U+000A 라인피드 (LF), U+000D 캐리지 리턴 (CR) — 또한 이스케이프 될 필요가 있습니다. [XML]

src 속성(attribute)과 srcdoc 속성(attribute)이 모두 함께 명시되어 있다면, srcdoc 속성(attribute)이 우선됩니다. 이것은 작성자가 srcdoc 속성(attribute)을 지원하지 않는 레거시 유저 에이전트들에 대한 폴백 URL을 제공하는 것을 허용합니다.


iframe 요소(element)가 브라우징 컨텍스트를 가지는 문서에 삽입 되는 경우, 유저 에이전트는 중첩된 브라우징 컨텍스트를 생성해야(must) 하고, "처음"으로 iframe 속성(attribute)들을 처리해야(must) 합니다.

iframe 요소(element)가 문서로부터 제거 되는 경우, 유저 에이전트는 중첩된 브라우징 컨텍스트가 있다면 이를 폐기해야(must) 합니다.

이것은 unload 이벤트 발생 없이 일어납니다 (중첩된 브라우징 컨텍스트와 그것의 Document언로드가 아니라 폐기됩니다).

중첩된 브라우징 컨텍스트를 가진 iframe 요소(element)가 그것의 srcdoc 속성(attribute)이 설정, 변경, 제거 될 때마다, 유저 에이전트는 iframe 속성(attribute)들을 처리해야(must) 합니다.

마찬가지로, 중첩된 브라우징 컨텍스트를 가지지만 명시된 srcdoc 속성(attribute)이 없는 iframe 요소(element)가 그것의 src 속성(attribute)이 설정, 변경, 제거 될 때마다, 유저 에이전트는 iframe 속성(attribute)들을 처리해야(must) 합니다.

유저 에이전트가 iframe 속성(attribute)들을 처리하는 경우, 다음 목록에서 첫 번째 적절한 단계들을 수행해야(must) 합니다:

srcdoc 속성(attribute)이 명시되어 있다면

요소(element)의 자식 브라우징 컨텍스트url 목록about:srcdoc로 구성되고, 헤더 목록Content-Type/text/html로 구성되며, body가 속성(attribute)의 값이고, CSP 목록iframe 요소(element)의 노드 문서CSP 목록이며, HTTPS 상태iframe 요소(element)의 노드 문서HTTPS 상태인 새로운 응답으로 이동(navigate)시키세요.

결과 Documentiframe srcdoc 문서로 간주되어야(must) 합니다.

그렇지 않고, 요소(element)가 명시된 src 속성(attribute)을 가지지 않고 유저 에이전트가 "처음"으로 iframe 속성(attribute)들을 처리하고 있다면

iframe load event 단계들을 수행하기 위한 작업을 대기열에 넣습니다.

작업에 대한 작업 소스DOM 조작 작업 소스입니다.

그렇지 않으면
  1. 요소(element)가 명시된 src 속성(attribute)을 가지지 않거나, 그것의 값이 빈 문자열이라면, url을 문자열 "about:blank"로 둡니다.

    그렇지 않으면, src 속성(attribute)의 값을 iframe 요소(element)와 관련하여 해석 하세요.

    그것이 성공적이지 않다면, url를 문자열 "about:blank"로 둡니다. 그렇지 않으면 url결과 URL 문자열로 둡니다.

  2. 문서 조각 식별자를 무시하여, 활성 문서주소url가 동일한 조상 브라우징 컨텍스트가 존재한다면, 이 단계들을 중단합니다.

  3. 요소(element)의 자식 브라우징 컨텍스트url이동(navigate) 시키세요.

게다가, 그 이동 전에 요소(element)의 자식 브라우징 컨텍스트활성 문서가 새로운 이동의 시점에 완전히 로드 되지 않았다면, 이동교체 활성화를 가지고 완료되어야(must) 합니다.

마찬가지로, iframe 속성(attribute)들 처리 알고리즘이 호출되는 경우, 자식 브라우징 컨텍스트세션 히스토리가 오직 하나의 Document를 포함하고, 그것이 자식 브라우징 컨텍스트가 생성 될 때 생성 된 about:blank Document였다면, 그 알고리즘에서 유저 에이전트의 요구된 모든 이동교체 활성화를 가지고 완료되어야(must) 합니다.

iframe 내의 Document완전히 로드 된것으로 표기되는 경우, 유저 에이전트는 병렬로 iframe load 이벤트 단계들을 수행해야(must) 합니다.

그것이 생성될 때 어떤 다른 데이터도 그 내부에서 로드되지 않는다면 load 이벤트도 iframe 요소(element)에서 발생됩니다.

Documentiframe load in progress 플래그와 mute iframe load 플래그를 가집니다. Document가 생성될 때, 이 플래그들은 그 Document에 대해 해제되어야(must) 합니다.

iframe load 이벤트 단계들은 다음과 같습니다:

  1. child documentiframe 요소(element)의 중첩된 브라우징 컨텍스트활성 문서로 둡니다.
  2. child document가 그것의 설정된 mute iframe load 플래그를 가진다면, 이 단계들을 중단합니다.
  3. child documentiframe load in progress 플래그를 설정합니다.
  4. iframe 요소(element)에 load라는 단순 이벤트를 발생 시킵니다.
  5. child documentiframe load in progress 플래그를 해제합니다.

이것은, 스크립팅과 함께, 로컬 네트워크의 HTTP 서버들의 URL 공간을 살피는데 사용될 수 있습니다. 유저 에이전트들은 이 공격을 완화시키기 위해 위에 기술된 것 보다 엄격한 cross-origin 접근 제어 정책들을 구현할 수 있지만, 불행하게도 그 정책들은 일반적으로 기존의 웹 콘텐트와 호환되지 않습니다.

iframe브라우징 컨텍스트활성 문서post-load 작업들에 대해 준비되지 않은 경우와, iframe 내의 모든 것이 iframe브라우징 컨텍스트활성 문서load 이벤트를 지연 중인 경우와, iframe브라우징 컨텍스트load 이벤트 지연 모드에 있는 경우, iframe은 그 문서의 load 이벤트를 지연시켜야(must) 합니다.

load 이벤트의 처리 동안, iframe 내의 브라우징 컨텍스트가 다시 이동되었다면, 좀 더 load 이벤트를 지연시킬 것입니다.

요소(element)가 생성되었을 때, srcdoc 속성(attribute)이 설정되어 있지 않고, src 속성(attribute) 또한 설정되어 있지 않거나 설정되었지만 그 값이 분석(resolve)될 수 없다면, 브라우징 컨텍스트는 초기 about:blank 페이지에 남을 것입니다.

사용자가 이 페이지로부터 다른 곳으로 이동한다면, iframe의 해당하는 WindowProxy 객체는 새로운 Document 객체들에 대한 새로운 Window 객체들을 대리(proxy)할 것이지만, src 속성(attribute)는 변경하지 않을 것입니다.


name 속성(attribute)이 있다면, 유효한 브라우징 컨텍스트 이름이어야(must) 합니다. 주어진 값은 중첩된 브라우징 컨텍스트를 이름 짓는데 사용됩니다. 브라우징 컨텍스트가 생성될 때, 속성(attribute)이 존재한다면 브라우징 컨텍스트 이름은 이 속성(attribute)의 값으로 설정되어야(must) 합니다; 그렇지 않으면, 브라우징 컨텍스트 이름은 빈 문자열로 설정되어야(must) 합니다.

name 속성(attribute)이 설정될 때 마다, 중첩된 브라우징 컨텍스트이름은 새로운 값으로 변경되어야(must) 합니다. 속성(attribute)이 제거 되었다면, 브라우징 컨텍스트 이름은 빈 문자열로 설정되어야(must) 합니다.


sandbox 속성(attribute)이 명시된 경우, iframe에 의해 관리되는 모든 콘텐트에 대한 별도의 제한 사항들의 세트를 가능하게 합니다. 그 값은 ASCII 대소문자 구분 없이 공백으로 분리된 고유한 토큰들의 순서없는 세트이어야(must) 합니다. 허용된 값들은 allow-forms, allow-pointer-lock, allow-popups, allow-same-origin, allow-scripts, allow-top-navigation 입니다.

속성(attribute)이 설정 된 경우, 콘텐트는 고유 출처, 양식, 스크립트들, 비활성화 된 다양한 곤란한 가능성이 있는 API들로 취급되고, 링크들은 다른 브라우징 컨텍스트들을 대상으로 하는 것을 방지하고, 플러그인들은 보호됩니다. allow-same-origin 키워드는 콘텐트가 고유 출처에 강제되는 것 대신 그것의 실제 출처의 것으로 취급되는 것을 야기합니다; allow-top-navigation 키워드는 콘텐트가 그것의 최상위 브라우징 컨텍스트이동하는 것을 허용하고; allow-forms, allow-pointer-lock, allow-popups, allow-scripts 키워드들은 각각 양식들, 포인터 잠금 API, 팝업, 스크립트들을 재활성화 시킵니다. [POINTERLOCK]

삽입 된(embedded) 페이지가 iframe을 포함하는 페이지로서 동일 출처를 가지는 경우 allow-scriptsallow-same-origin 키워드들을 모두 함께 설정하는 것은 효과적으로 완전히 샌드박스에서 벗어나, 삽입 된(embedded) 페이지가 sandbox 속성(attribute)를 쉽게 제거하고 그것을 리로드 하는 것을 허용합니다.

이 플래그들은 iframe중첩된 브라우징 컨텍스트이동 되는 경우에만 적용됩니다. 그것들을 제거하거나, 전체 sandbox 속성(attribute)을 제거하는 것은 이미 로드된 페이지에 아무런 영향을 가지지 않습니다.

잠재적으로 악의적인 파일들은 iframe 요소(element)를 포함하는 파일로 동일한 서버로부터 제공되지 않아야(should) 합니다. 공격자가 사용자에게 악의적인 콘텐트로 직접 방문하도록 납득 시킬 수 있다면, 샌드박스 된 악의적인 콘텐트는 iframe 안에서보다 최소한의 도움입니다. 악의적인 HTML 콘텐트에 의해 야기될 수 있는 피해를 최소화 하기 위해, 별도로 지정된 도메인으로부터 제공되어야(should) 합니다. 다른 도메인을 사용하는 것은, 사용자가 sandbox 속성(attribute)의 보호 없이 그 페이지들을 직접 방문하도록 속임에도 불구하고, 파일 내 스크립트가 사이트를 공격하는 것을 불가능하게 만드는 것을 보장합니다.

sandbox 속성(attribute)을 가진 iframe 요소(element)가 그것의 생성된 중첩 브라우징 컨텍스트를 가지는 (초기 about:blank Document가 생성되기 전에) 경우와, iframe 요소(element)가 중첩 브라우징 컨텍스트를 가지는 동안 sandbox 속성(attribute)이 설정되거나 변경되는 경우, 유저 에이전트는 input으로서 속성(attribute)의 값과 출력으로서 iframe 요소(element)의 중첩된 브라우징 컨텍스트iframe sandboxing 플래그 설정을, 그리고 iframeallowfullscreen 속성(attribute)를 가진다면 allow fullscreen flag를 사용하여 샌드박싱 지시를 해석해야(must)합니다.

iframe 요소(element)가 중첩된 브라우징 컨텍스트를 가지는 동안 sandbox 속성(attribute)이 제거되는 경우, 유저 에이전트는 출력으로 iframe 요소(element)의 중첩된 브라우징 컨텍스트iframe 샌드박싱 플래그 설정을 비워야(must) 합니다.

이 예에서, 완전히 알수 없는, 잠재적으로 악의적일 수 있는, 사용자가 제공한 HTML 콘텐트가 페이지에 삽입되어 있습니다. 그것은 별도의 도메인으로부터 제공되었기 때문에, 모든 정상 교차 사이트 제약사항들에 의해 영향을 받습니다. 게다가, 삽입된 페이지는 스크립팅 비활성화, 플러그인 비활성화, 양식 비활성화 되고, 다른 프레임들이나 자신 이외의 창들을 (혹은 다른 프레임들이나 그 자신을 삽입하는 창들) 이동할 수 없습니다.
<p>We’re not scared of you! Here is your content, unedited:</p>
<iframe title="Example iframe" sandbox src="https://usercontent.example.net/getusercontent.cgi?id=12193"></iframe>

공격자가 사용자로 하여금 그 페이지에 직접 방문하도록 납득시킨다면, 페이지는 사용자가 페이지 내에서 발견되는 공격에 취약하도록 만드는 사이트의 출처의 컨텍스트에서 수행하지 않기 때문에 별도의 도메인을 사용하는 것이 중요합니다.

이 예에서, 다른 사이트로부터 가젯이 삽입됩니다. 가젯은 스크립팅과 양식이 활성화 되어있고, 그것의 발신 서버와 통신하는 것을 허용하여, 원본 샌드박스 제약 사항들이 해제 되어 있습니다. 하지만 플러그인들과 팝업들이 비활성화 된 것처럼, 멀웨어와 다른 교란에 노출되는 사용자의 위험을 줄이는 것에 여전히 유용합니다.
<iframe title="Maps" sandbox="allow-same-origin allow-forms allow-scripts"
        src="https://maps.example.com/embedded.html"></iframe>
다음 코드 조각을 포함하는 파일 A를 가정해보세요:
<iframe title="Example iframe" sandbox="allow-same-origin allow-forms" src=B></iframe>

아이프레임을 포함하는 파일 B도 가정해보세요:

<iframe title="Example iframe" sandbox="allow-scripts" src=C></iframe>

또, 링크를 포함하는 파일 C를 가정해보세요:

<a href=D>Link</a>

이 예에서, 모들 파일들이 text/html로 제공된다고 가정하세요.

이 시나리오에서 페이지 C는 모두 샌드박싱 플래그 설정을 가집니다. A의 iframe은 비활성화된 스크립트들을 가지므로 스크립트들은 비활성화 되고, 이것은 B의 iframe에서 allow-scripts 키워드 설정을 재정의합니다. (B의) 내부 iframeallow-scripts 키워드를 가지지 않으므로 양식들 또한 비활성화됩니다.

이제 A의 스크립트가 A와 B의 모든 sandbox 속성(attribute)들을 제거한다고 가정해보세요. 이것은 즉시 아무 것도 변경시키지 않을 것입니다. 사용자가 B의 iframe으로 페이지 D를 로딩하는 C의 링크를 클릭했다면, 페이지 D는 이제 B의 iframe이 페이지 B가 로드되었을 때 A의 iframe에서 중첩된 브라우징 컨텍스트의 상태를 가졌기 때문에 allow-same-originallow-forms 키워드 설정을 가진 것처럼 수행합니다.

일반적으로 말해서, 동적으로 sandbox 속성(attribute)을 제거하거나 변경하는 것은 그것이 무엇을 허용할 것이고 무엇을 허용하지 않을 것인지에 대해 판단하는 것을 꽤 어렵게 만들기 때문에 문제의 소지가 있습니다.


allowfullscreen 속성(attribute)은 불리언 속성(attribute)입니다. 이 속성(attribute)이 명시된 경우, iframe 요소(element)의 브라우징 컨텍스트 내의 Document 객체들이 requestFullscreen()를 사용하도록 설정되어야 합니다(다른 이유로 예를 들어, 이 속성 설정이 없는 다른 조상 iframe이 존재하여 차단되지 않는다면).

여기에서, iframe는 비디오 사이트로부터 플레이어를 삽입하는데 사용됩니다. allowfullscreen 속성(attribute)는 플레이어가 그것의 비디오를 전체화면으로 보여주도록 활성화 할 필요가 있습니다.
<article>
  <header>
  <p><img src="/usericons/1627591962735"> <b>Fred Flintstone</b></p>
  <p><a href="/posts/3095182851" rel=bookmark>12:44</a><a href="#acl-3095182851">Private Post</a></p>
  </header>
  <main>
  <p>Check out my new ride!</p>
  <iframe title="Video" src="https://video.example.com/embed?id=92469812" allowfullscreen></iframe>
  </main>
</article>

iframe 요소(element)는 삽입된 콘텐트가 특정 치수들을 (예를 들어, 명확하게 정의된 치수들을 가지는 광고) 명시하는 경우들에 대해 치수 속성(attribute)들을 지원합니다.

iframe 요소(element)는 명시된 초기 콘텐츠가 성공적으로 사용되든 상관없이 항상 중첩된 브라우징 컨텍스트를 생성하기 때문에, 결코 폴백 콘텐트를 가지지 않습니다.


iframe 요소(element)들의 후손들은 아무 것도 나타내지 않습니다. (iframe 요소(element)들을 지원하지 않는 레거시 유저 에이전트들에서, 콘텐츠는 폴백 콘텐트로 수행될 수 있는 마크업으로 해석될 것입니다.)

HTML 문서들에 사용되는 경우, 컨텍스트 요소(element)로서 iframe 요소와 input으로서 텍스트 콘텐츠를 가지고 HTML 조각 해석 알고리즘을 수행하는 것이 해석 오류 발생 없이, 목록 내 아무 곳에 있거나 요소(element)들의 후손들로 존재하는 script 요소(element)들 없이, 자체적으로 규칙을 준수하는 목록 내 모든 요소(element)들 (그들의 후손들을 포함하여)과 함께 모든 어구(phrasing) 콘텐트인 노드들의 목록을 야기해야(must) 하는 텍스트를 제외하고, iframe 요소(element)들의 허용된 콘텐트 모델은 텍스트입니다.

iframe 요소(element)는 XML 문서들에서 비어 있어야(must) 합니다.

HTML 해석기iframe 요소(element) 내부 마크업을 텍스트로 취급합니다.


IDL 속성(attribute)들 src, srcdoc, name, sandbox는 각각 동일한 이름의 콘텐트 속성(attribute)들을 반영해야(must) 합니다.

sandboxDOMTokenList에 대한 지원되는 토큰들sandbox 속성(attribute)에 정의된 값들이 허용되고 유저 에이전트들에 의해 지원됩니다.

allowFullscreen IDL 속성(attribute)는 allowfullscreen 콘텐트 속성(attribute)을 반영해야(must) 합니다.

contentDocument IDL 속성(attribute)은 iframe 요소(element)의 중첩된 브라우징 컨텍스트가 있다면 그리고 그것의 출처현직 설정 객체에 의해 명시된 출처로서 동일 출처 도메인활성 문서Document 객체를 반환해야(must) 하고, 그렇지 않으면 null을 반환해야(must) 합니다.

contentWindow IDL 속성(attribute)은 iframe 요소(element)의 중첩된 브라우징 컨텍스트WindowProxy 객체가 있다면 WindowProxy 객체를 반환해야(must) 하고, 그렇지 않으면 null을 반환해야(must) 합니다.

여기 광고 중개인으로부터의 광고를 포함하기 위해 iframe을 사용하는 페이지의 예가 있습니다:
<iframe title="Advert" src="https://ads.example.com/?customerid=923513721&amp;format=banner"
        width="468" height="60"></iframe>

4.7.7. embed 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
삽입(embedded) 콘텐트.
대화형(interactive) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
삽입(embedded) 콘텐트가 예상되는 곳.
콘텐트 모델:
없음.
text/html에서 태그 생략:
종료 태그 없음.
콘텐트 속성(attribute)들:
범용 속성(attribute)들
src - Address of the resource
type - Type of embedded resource
width - Horizontal dimension
height- Vertical dimension
네임스페이스를 가지지 않는 모든 다른 속성(attribute) (본문 참고).
허용된 ARIA 역할(role) 속성(attribute) 값들:
application, documentimgpresentation.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
interface HTMLEmbedElement : HTMLElement {
  attribute DOMString src;
  attribute DOMString type;
  attribute DOMString width;
  attribute DOMString height;
  legacycaller any (any... arguments);
};
embed 요소(element)에 의해 인스턴스화 된 콘텐트의 유형에 따라, 노드 또한 다른 인터페이스들을 지원할 수 있습니다.

embed 요소(element)는 외부 (일반적으로 비 HTML) 어플리케이션이나 대화형 콘텐트에 대한 통합점을 제공합니다.

src 속성(attribute)은 삽입되는 리소스의 주소를 제공합니다. 속성(attribute)이 존재한다면 유효한 잠정적으로 공백으로 둘러 싸일 수 있는 비어있지 않은 URL을 포함해야(must) 합니다.

type 속성(attribute)이 존재한다면 인스턴스화 할 플러그인이 선택되는 MIME 타입 을 제공합니다. 값은 유효한 MIME 타입이어야(must) 합니다. type 속성(attribute)과 src 속성(attribute)이 모두 존재한다면, type 속성(attribute)은 src 속성(attribute)에 의해 주어진 리소스의 명시적인 Content-Type 메타데이터와 동일한 타입으로 명시해야(must) 합니다.

다음 조건들 중 하나라도 발생한다면, 요소(element)에 대해 인스턴스화 된 모든 플러그인은 제거되어야(must)하고, embed 요소(element )는 아무 것도 나타내지 않습니다:

  • 요소(element)가 src 속성(attribute)과 type 속성(attribute) 중 어떠한 것도 가지지 않는 경우.
  • 요소(element)가 조상 미디어 요소(element)를 가지는 경우 .
  • 요소(element)가 그것의 폴백 콘텐트를 보여주지 않는 조상 object 요소(element)를 가지는 경우.

embed 요소(element)가 다음 조건들을 모두 동시에 만족하는 경우 잠재적으로 활성이라고 불립니다:

잠재적으로 활성이 아니었던 embed 요소(element)가 잠재적으로 활성화 될 때마다, 그리고 잠재적 활성 embed 요소(element)가 남아있는 잠재적으로 활성이고 그것의 src 속성(attribute)이 설정, 변경, 혹은 제거되거나, 그것의 type 속성(attribute)이 설정, 변경, 혹은 제거 될 때 마다, 유저 에이전트는 embed 요소(element) 설정 단계들을 수행하기 위한 삽입(embed) 작업 소스를 사용하여 작업을 대기열에 넣어야(must) 합니다.

embed 요소(element) 설정 단계들은 다음과 같습니다:

  1. 이 요소(element)에 대해 embed 요소(element) 설정 단계들을 수행하기 위해 다른 작업이 대기열에 넣어진 이후라면, 이 단계들을 중단합니다.
  2. 요소(element)가 설정 된 src 속성(attribute)을 가진다면

    유저 에이전트는 요소(element)의 src 속성(attribute)의 값을 요소(element)에 관련하여 해석해야(must) 합니다. 그것이 성공적이라면, 유저 에이전트는 이 단계들을 수행해야(should) 합니다:

    1. requestURL결과 URL 문자열이고, 클라이언트가 요소(element)의 노드 문서Window 객체의 환경 설정 객체이고, 목적지가 "unknown"이며, 요소(element)가 브라우징 컨테스트 범위 출처를 가지지 않는다면 출처 헤더 생략 플래그가 설정되어 있고, 자격 증명 모드가 "include"이며, URL 자격 증명 사용 플래그가 설정된 새로운 요청으로둡니다.
    2. request가져옵니다(fetch).

    네트워킹 작업 소스에 의해 대기열에 넣어진 작업은 리소스가 가져와졌을(fetch) 때 다음 단계들을 수행해야(must) 합니다:

    1. 이 요소(element)에 대해 embed 요소(element) 설정 단계를 수행하기 위해 다른 작업이 대기열에 넣어진 이후라면, 이 단계들을 중단합니다.
    2. 삽입되는 콘텐트의 유형을 (유형을 결정하는 첫 번째 하위 단계에서 중지하여) 다음과 같이 결정합니다:

      1. 요소(element)가 type 속성(attribute)을 가지고 그 속성(attribute)의 값이 플러그인이 지원하는 유형이라면, type 속성(attribute)의 값은 콘텐트의 유형입니다.
      2. 그렇지 않고, 명시된 리소스의 URLURL 해석 알고리즘을 적용하는 것이 (모든 리다이렉트들 이후) 경로 컴포넌트가 플러그인이 지원하는 패턴과 일치하는 URL 레코드를 야기한다면, 콘텐트의 유형은 플러그인이 처리할 수 있는 유형입니다.

        예를 들어, 플러그인은 네 개 문자 문자열 ".swf"로 끝나는 경로 컴포넌트들을 가진 리소스를 처리할 수 있다고 말할 수 있습니다.

      3. 그렇지 않고, 명시된 리소스가 명시적 Content-Type 메타데이터를 가진다면, 그것이 콘텐트의 유형입니다.
      4. 그렇지 않으면 콘텐트는 유형을 가지지 않고 그것에 대한 적절한 플러그인이 없을 수 있습니다.
    3. 이전 단계가 콘텐트의 유형이 image/svg+xml이라고 결정했다면, 다음 하위 단계들을 수행합니다:

      1. embed 요소(element)가 중첩된 브라우징 컨텍스트와 연관되지 않는다면, 새롭게 생성된 중첩된 브라우징 컨텍스트와 연관짓고, 요소(element)가 name 속성(attribute)을 가진다면, 요소(element)의 중첩된 브라우징 컨텍스트브라우징 컨텍스트 이름을 이 속성(attribute)의 값으로 설정합니다.
      2. 중첩된 브라우징 컨텍스트를 가져와진 리소스로 교체 활성화소스 브라우징 컨텍스트로서 embed 요소(element)의 노드 문서브라우징 컨텍스트를 가지고 이동시킵니다. (embed 요소(element)의 src 속성(attribute)은 브라우징 컨텍스트가 다른 위치들로 더 이동된다면 업데이트 되지 않습니다.)
      3. embed 요소(element)는 이제 그것의 연관된 중첩된 브라우징 컨텍스트나타냅니다.
    4. 그렇지 않으면, 콘텐트 유형을 기반으로 적절한 플러그인을 찾고 인스턴스화 하고, 리소스의 콘텐트를 요소(element)에 대해 이전에 인스턴스화 된 플러그인들을 대신하여 그 플러그인에 전달합니다. embed 요소(element)는 이제 이 플러그인 인스턴스를 나타냅니다.

    5. 리소스나 플러그인이 완전히 로드되었을 때, 요소(element)에 load라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣습니다.

    리소스가 성공적으로 가져와(fetch)졌는지 아닌지의 여부는 (예를 들어, 응답 상태가 ok 상태였는지 여부) 콘텐트의 유형을 결정하는 중인 경우 와 리소스를 플러그인에 전달하는 중인 경우 무시되어야(must) 합니다.

    이것은 오류 응답들에도 불구하고 플러그인들에 대해 데이터를 반환하는 것을 허용합니다 (예를 들어, HTTP 500 서버 내부 오류 코드들은 여전히 플러그인 데이터를 포함할 수 있습니다).

    리소스를 가져오는(fetch) 것은 요소(element)의 노드 문서load 이벤트를 지연시켜야(must) 합니다.

    요소(element)가 설정된 src 속성(attribute)을 가지지 않는다면

    유저 에이전트는 type 속성(attribute)의 값을 기반으로 적절한 플러그인을 찾고 인스턴스화 해야(should)합니다. embed 요소(element)는 이제 이 플러그인 인스턴스를 나타냅니다.

    플러그인이 완전히 로드되었을 때, 요소(element)에 load라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣습니다.

embed 요소(element)는 폴백 콘텐트를 가지지 않습니다. 유저 에이전트가 위 알고리즘에 대한 것을 찾고 인스턴스화 하기 위해 시도하는 경우 적절한 플러그인을 찾을 수 없다면, 유저 에이전트는 기본 플러그인을 사용해야(must)합니다. 이 기본 플러그인은 "지원되지 않는 형식"으로 나타내는 것처럼 단순할 수 있습니다.

잠재적으로 활성이었던 embed 요소(element)가 잠재적으로 활성화 되는 것을 중단 할 때마다, 그 요소(element)에 대해 인스턴스화 된 모든 플러그인은 언로드 되어야(must) 합니다.

플러그인이 인스턴스화 되어야 하지만 보호될 수 없고 embed 요소(element)의 노드 문서샌드박싱 활성화 플래그 설정샌드박스 된 플러그인들 브라우징 컨텍스트 플래그가 설정되는 경우, 유저 에이전트는 플러그인을 인스턴스화 하지 않아야(must)하고, 대신 플러그인이 비활성화 되었음을 전달하는 방법으로 embed 요소(element)를 렌더링해야(must) 합니다. 유저 에이전트는 사용자에게 샌드박스를 재정의하고 그래도 플러그인을 인스턴스화 하기 위한 옵션을 권할 수 있습니다; 사용자가 그러한 옵션을 호출한다면, 유저 에이전트는 위 조건들이 이 요소(element)의 목적에 대해 적용하지 않는 것처럼 수행해야(must) 합니다.

보호될 수 없는 플러그인들은 샌드박스에 의해 부여된 제약사항들을 이행하지 않을 것이기 때문에 (예를 들어, 샌드박스 내 스크립팅이 비활성화 되었을 때 조차 스크립팅을 허용할 수 있습니다) 샌드박스 된 브라우징 컨텍스트들 내에서 비활성화 될 수 있습니다. 유저 에이전트들은 그렇게 하기 위한 옵션이 제공된다면 사용자에게 샌드박스를 재정의하는 것의 위험을 전달해야(should) 합니다.

embed 요소(element)가 중첩된 브라우징 컨텍스트를 나타내는 경우: embed 요소(element)의 중첩된 브라우징 컨텍스트활성 문서로드 후 작업들에 대해 준비되지 않았고, 무엇이든 embed 요소(element)의 브라우징 컨텍스트활성 문서load 이벤트를 지연 시키는 중인 경우, 그리고 embed 요소(element)의 브라우징 컨텍스트load 이벤트들 지연 중 모드에 있는 경우, embed는 그것의 문서의 load 이벤트를 지연시켜야(must) 합니다.

이 섹션에 언급된 작업들에 대한 작업 소스DOM 조작 작업 소스입니다.

name, align, hspace, vspace을 제외한 네임스페이스 없는 속성(attribute)은 그것의 이름이 XML 호환 가능하고 대문자 ASCII 문자들을 포함하지 않기만 하면 embed 요소(element)에 명시될 수 있습니다. 이 속성(attribute)들은 이후에 플러그인에 파라미터들로 전달됩니다.

HTML 문서들 내의 모든 속성(attribute)들은 대문자의 제약 사항들이 그 문서에 영향을 주지 않기 때문에 자동으로 소문자로 바뀐 것을 얻습니다.

4개의 예외들은 플러그인에 파라미터들을 전달하는 것을 넘어 부작용을 가지는 레거시 속성(attribute)들을 제외하는 것입니다.

유저 에이전트는 embed가 인스턴스화 될 때, 사용된 플러그인에 대한 네임스페이스를 갖지 않는 embed의 모든 속성(attribute)들의 이름들과 값들을 전달해야(should) 합니다.

요소(element)를 나타내는 HTMLEmbedElement 객체는 embed 요소(element)에 대해 인스턴스화 된 플러그인의 스크립트 가능한 인터페이스가 있다면 이를 노출해야(must) 합니다. 최소한, 이 인터페이스는 레거시 호출 연산을 구현해야(must) 합니다. (이 레거시 호출 연산의 기본 동작은, 예를 들어 기본 플러그인의 레거시 호출자 연산의 동작은, NotSupportedError 예외를 던지는 것이 되도록 제안됩니다.)

embed 요소(element)는 치수 속성(attribute)들을 지원합니다.

IDL 속성(attribute)들 srctype는 각각 동일한 이름의 각 콘텐트 속성(attribute)들을 반영해야(must) 합니다.

여기 Flash와 같이, 특허 플러그인을 요구하는 리소스를 삽입하는 방법이 있습니다.
<embed src="catgame.swf">

사용자가 플러그인을 가지고 있지 않다면 (예를 들어 플러그인 제공자가 사용자의 플랫폼을 지원하지 않는다며), 사용자는 리소스를 사용하는 것이 불가능할 것입니다.

플러그인에 "high" 값을 가진 "quality" 파라미터를 전달하기 위해, 속성(attribute)이 명시될 수 있습니다:

<embed src="catgame.swf" quality="high">

object 요소(element)를 대신 사용하는 경우, 이것은 다음과 동등할 것입니다:

<object data="catgame.swf">
  <param name="quality" value="high">
</object>

4.7.8. object 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
삽입(embedded) 콘텐트.
나열된, 제출 가능한, 다시 연관 시킬 수 있는 양식 관련 요소(element).
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
삽입(embedded) 콘텐트가 예상되는 곳.
콘텐트 모델:
0개 이상의 param 요소(element)들, 이후, 투명.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
data - 리소스의 주소
type - 삽입된 리소스의 유형
typemustmatch - 사용되는 리소스에 대해 type 속성(attribute)와 Content-Type 값이 일치해야 할 필요가 있는지 여부
name - 중첩된 브라우징 컨텍스트의 이름
form - form 요소(element)와 컨트롤을 연결
width - 가로 치수
height - 세로 치수
허용된 ARIA 역할(role) 속성(attribute) 값들:
application, document 또는 img 또는 presentation.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
interface HTMLObjectElement : HTMLElement {
  attribute DOMString data;
  attribute DOMString type;
  attribute boolean typeMustMatch;
  attribute DOMString name;
  readonly attribute HTMLFormElement? form;
  attribute DOMString width;
  attribute DOMString height;
  readonly attribute Document? contentDocument;
  readonly attribute WindowProxy? contentWindow;

  readonly attribute boolean willValidate;
  readonly attribute ValidityState validity;
  readonly attribute DOMString validationMessage;
  boolean checkValidity();
  boolean reportValidity();
  void setCustomValidity(DOMString error);

  legacycaller any (any... arguments);
};
object 요소(element)에 의해 인스턴스화 된 콘텐트의 유형에 따라, 노드도 다른 인터페이스들을 지원합니다.

object 요소(element)는 리소스의 유형에 따라 이미지로, 중첩된 브라우징 컨텍스트로, 또는 플러그인에 의해 처리되는 외부 리소스로 다루어지는 외부 리소스를 나타낼 수 있습니다.

data 속성(attribute)이 존재한다면, 이는 리소스의 주소를 명시합니다. 이 속성(attribute)이 존재한다면, 속성(attribute)은 유효한 잠정적으로 공백으로 둘러 싸일 수 있는 비어있지 않은 URL이어야(must) 합니다.

신뢰하지 않는 다른 출처들로부터의 리소스를 참조하는 작성자들은 아래 정의된 typemustmatch 속성(attribute)을 사용하도록 강력히 권고됩니다. 그 속성(attribute)이 없으면, 작성자가 Flash "allowScriptAccess" 파라미터와 같은 기능을 사용했다 하더라도, 어떤 경우들에서 공격자가 원격 호스트에서 임의의 스크립트를 수행시키기 위한 플러그인 메커니즘을 사용하는 것이 가능합니다.

type 속성(attribute)이 존재한다면, 이 속성(attribute)은 리소스의 유형을 명시합니다. 이 속성(attribute)이 존재한다면, 속성(attribute)은 유효한 MIME 타입이어야(must) 합니다.

적어도 data 속성(attribute)이나 type 속성(attribute) 중 하나는 존재해야(must) 합니다.

typeMustMatch 속성(attribute)은 그 존재가 data 속성(attribute)에 의해 명시된 리소스가 type 속성(attribute)의 값과 앞서 언급된 리소스의 Content-Type과 일치하는 경우에만 사용 됨을 나타내는 불리언 속성(attribute) 입니다.

typemustmatch 속성(attribute)은 data 속성(attribute)과 type 속성(attribute)이 모두 존재하지 않는 한 명시되지 않아야(must) 합니다.

name 속성(attribute)이 존재한다면, 이 속성(attribute)은 유효한 브라우징 컨텍스트 이름이어야(must) 합니다. 주어진 값은 적용 가능하다면, 중첩된 브라우징 컨텍스트를 이름을 붙이는데 사용됩니다.

다음 조건들 중 하나가 발생할 때마다:

...유저 에이전트는 object 요소(element)가 무엇을 나타내는지를 (재)결정하기 위한 다음 단계들을 수행하기 위한 작업을 대기열에 넣어야(must) 합니다. 대기열에 넣어지거나 활발히 수행 중인 이 작업은 요소(element)의 노드 문서load 이벤트를 지연시켜야(must) 합니다.

  1. 사용자가 이 object 요소(element)의 폴백 콘텐트가 요소(element)의 보통의 동작 대신 보여지도록 설정을 지시했다면, 아래 fallback으로 라벨링 된 단계로 건너 뜁니다.

    예를 들어, 콘텐트는 사용자가 더 접근 가능한 것을 찾는 형식을 사용하기 때문에 사용자는 요소(element)의 폴백 콘텐트가 보여지도록 요청할 수 있습니다.

  2. 요소(element)가 후손 미디어 요소(element)를 가지거나, 폴백 콘텐트를 보여주고 있지 않은 후손 object 요소(element)를 가지거나, 요소(element)가 브라우징 컨텍스트를 가진 Document 안에 있지 않거나, 요소(element)의 노드 문서완전히 활성화가 아니거나, 요소(element)가 여전히 HTML 해석기XML 해석기열린 요소(element)들의 스택 안에 있거나, 요소(element)가 렌더링 되는 것이 아니라면, fallback으로 라벨링 된 단계로 건너뜁니다.

  3. classid 속성(attribute)이 존재하고 빈 문자열이 아닌 값을 가진다면: 유저 에이전트가 classid 속성(attribute)의 값에 따라 적절한 플러그인을 찾을 수 있고, 플러그인들이 샌드박스 되지 않는 것이거나 그 플러그인보호될 수 있다면, 그 플러그인사용되어야(should)하고, data 속성(attribute)의 값이 있다면 그것은 플러그인으로 전달되어야(should) 합니다. 적절한 플러그인을 찾을 수 없거나, 플러그인이 오류를 보고한다면, fallback으로 라벨링 된 단계로 점프합니다.

  4. data 속성(attribute)이 존재하고 그 값이 빈 문자열이 아니라면 :
    1. type 속성(attribute)이 존재하고 그 값이 유저 에이전트가 지원하는 유형이 아니며, 유저 에이전트가 그 속성(attribute) 값에 대한 플러그인을 찾을 수 있는 유형이 아니라면, 유저 에이전트는 그것의의 실제 유형을 검사하기 위해 콘텐트를 가져오는(fetch) 것 없이 아래 fallback으로 라벨링 된 단계로 건너뛸 수 있습니다.
    2. data 속성(attribute)에 의해 명시된 URL을 요소(element)에 관련하여 해석 합니다.
    3. 그것이 실패했다면, 요소(element)에 error라는 단순 이벤트를 발생시키고, 아래 fallback으로 라벨링 된 단계로 건너뜁니다.
    4. requestURL결과 URL 문자열이고, 클라이언트가 요소(element)의 노드 문서Window 객체의 환경 설정 객체이며, 목적지가 "unknown"이고, 요소(element)가 브라우징 컨텍스트 범위 출처를 가지지 않는다면 출처 헤더 생략 플래그가 설정되어 있으며, 자격 증명 모드가 "include"이고 URL 자격 증명 사용 플래그가 설정 된 새로운 요청으로 둡니다.
    5. request가져옵니다(fetch).

      리소스를 가져오는(fetch) 것은 리소스가 가져와(fetch)졌을 때 네트워킹 작업 소스에 의해 대기열에 넣어진 작업이 (다음으로 정의된) 수행 될 때까지 요소(element)의 노드 문서load 이벤트를 지연시켜야(must) 합니다.

    6. 리소스가 아직 사용 가능하지 않다면 (예를 들어, 리소스가 캐시에서 아직 사용할 수 없기 때문에, 리소스를 로딩하는 것은 네트워크를 통해 요청을 만드는 것을 요구합니다), 아래 fallback으로 라벨링 된 단계로 건너뜁니다. 리소스가 사용 가능 할 때 네트워킹 작업 소스에 의해 대기열에 넣어진 작업은 이 단계로부터 이 알고리즘을 재시작해야(must) 합니다. 리소스들이 점차적으로 로드될 수 있습니다; 유저 에이전트들은 리소스를 처리하는 것을 시작하기 위해 충분한 데이터라가 얻어질 때마다 리소스를 "사용 가능"한 것으로 간주되도록 선택할 수 있습니다.
    7. 로드가 실패되었다면 (예를 들어, HTTP 404 오류가 있었거나, DNS 오류가 있었거나), 요소(element)에 error라는 단순 이벤트를 발생시키고, 아래 fallback으로 라벨링 된 단계로 건너뜁니다.
    8. 다음과 같이, resource type을 결정합니다:

      1. resource type를 알 수 없음으로 둡니다.

      2. object 요소(element)가 type 속성(attribute)과 typemustmatch 속성(attribute)을 가지고, 리소스가 연관된 Content-Type 메타데이터를 가지며, 리소스의 Content-Type 메타데이터에 명시된 유형이 요소(element)의 type 속성(attribute)의 값에 ASCII 대소문자 구분 없이 일치한다면, resource type을 그 유형으로 두고 아래 handler라고 라벨링 된 단계로 건너뜁니다.

      3. object 요소(element)가 typemustmatch 속성(attribute)을 가진다면, 아래 handler라고 라벨링 된 단계로 건너뜁니다.

      4. 유저 에이전트가 이 리소스에 대해 Content-Type 헤더들을 엄격히 준수하도록 설정되어 있고, 리소스가 연관된 Content-Type 메타데이터를 가진다면, resource type리소스의 Content-Type 메타데이터 내에 명시된 유형으로 두고, 아래 handler라고 라벨링 된 단계로 건너뜁니다.

        이것은 사이트가 특정 플러그인을 사용하는 삽입된 리소스를 시도하고 있다는 점에서 취약성을 끌어들일 수 있지만, 원격 사이트는 그것을 무시하고 대신 유저 에이전트에 다른 보안성들을 가진 다른 플러그인을 작동시키는 리소스를 제공합니다.

      5. object 요소(element)에 type 속성(attribute)이 존재하고, 그 속성(attribute)의 값이 유저 에이전트들이 지원하는 유형이 아니라, 플러그인이 지원하는 유형이라면, resource type을 그 type 속성(attribute)에 명시된 유형으로 두고, 아래 handler라고 라벨링 된 단계로 건너뜁니다.

      6. 다음 목록에서 적절한 단계들의 세트를 수행합니다:

        리소스가 연관된 Content-Type 메타데이터를 가진다면
        1. binary를 false로 둡니다.

        2. 리소스의 Content-Type 메타데이터에 명시된 유형이 "text/plain"이고, 리소스가 텍스트인지 바이너리인지 결정하기 위한 규칙들을 리소스에 적용한 결과가 리소스는 text/plain이 아니다는 것이라면, binary를 true로 설정합니다.

        3. 리소스의 Content-Type 메타데이터에 명시된 유형이 "application/octet-stream"이라면, binary를 true로 설정합니다.

        4. binary가 false라면, resource type리소스의 Content-Type 메타데이터에 명시된 유형으로 두고, 아래 handler라고 라벨링 된 단계로 건너뜁니다.

        5. object 요소(element)에 type 속성(attribute)이 존재하고, 그 값이 application/octet-stream이 아니라면, 다음 단계들을 수행합니다:

          1. 속성(attribute)의 값이 플러그인이 지원하는 유형이거나, 속성(attribute)의 값이 XML MIME 타입이 아닌 "image/"로 시작하는 유형이라면, resource type을 그 type 속성(attribute)에 명시된 유형으로 둡니다.

          2. 아래 handler라고 라벨링 된 단계로 건너뜁니다.

        그렇지 않고, 리소스가 연관된 Content-Type 메타데이터를 가지지 않는다면
        1. object 요소(element)에 type 속성(attribute)이 존재한다면, tentative type을 그 type 속성(attribute)에 명시된 유형으로 둡니다.

          그렇지 않으면, tentative type계산된 리소스의 유형으로 둡니다.

        2. tentative typeapplication/octet-stream아니라면, resource typetentative type로 두고 아래 handler라고 라벨링 된 단계로 건너뜁니다.

      7. URL 해석 알고리즘을 명시된 리소스의 URL에 적용 하는 것이 (다른 리다이렉트들 이후) 경로 컴포넌트가 플러그인이 지원하는 패턴에 일치하는 URL 레코드를 야기한다면, resource type을 그 플러그인이 처리할 수 있는 유형으로 둡니다.

        예를 들어, 플러그인은 네 개 문자열 ".swf"로 끝나는 경로 컴포넌트들을 가진 리소스들을 처리할 수 있다로 말 할 수 있습니다.

      이 단계가 종료되는 것이나, 위 하위 단계들 중 하나가 여전히 알 수 없는 resource type을 가지고 다음 단계로 바로 건너 뛰는 것이 가능합니다. 이 두 경우들에, 다음 단계는 폴백을 작동 시킬 것입니다.

    9. Handler: 다음 경우들의 첫 번째 일치하는 것에 의해 주어진 것으로 콘텐트를 처리합니다:
      resource type이 유저 에이전트가 지원하는 유형이 아니라, 플러그인이 지원하는 유형이라면,

      플러그인들이 샌드박스 되는 것이고 resource type을 지원한는 플러그인이 보호될 수 없다면, 아래 fallback으로 라벨링 된 단계로 건너뜁니다.

      그렇지 않으면, 유저 에이전트는 resource type을 지원하는 플러그인을 사용해야(should) 하고, 그 플러그인에 리소스의 콘텐트를 전달해야(should) 합니다. 플러그인이 오류를 보고한다면, fallback으로 라벨링 된 단계로 건너뜁니다.

      resource typeXML MIME 타입이거나 resource type이 "image/"로 시작하지 않는다면
      object 요소(element)는 새롭게 생성된 중첩된 브라우징 컨텍스트를 이미 가지고 있지 않다면 이와 연관되어야(must) 합니다.

      주어진 리소스의 URLabout:blank가 아니라면, 요소(element)의 중첩된 브라우징 컨텍스트교체 활성화와, 소스 브라우징 컨텍스트로서 object 요소(element)의 노드 문서브라우징 컨텍스트를 가지고 그 리소스로 이동되어야(must) 합니다. (브라우징 컨텍스트가 다른 위치들로 더 이동한다면 object 요소(element)의 data 속성(attribute)은 업데이트 되지 않습니다.)

      주어진 리소스의 URLabout:blank라면, 대신에, 유저 에이전트는 object 요소(element)에 load라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣어야(must) 합니다. load 이벤트는 about:blank 문서 자체에 발생되지 않습니다.

      object 요소(element)는 중첩된 브라우징 컨텍스트를 나타냅니다.

      name 속성(attribute)이 존재한다면, 브라우징 컨텍스트 이름은 이 속성(attribute)의 값으로 설정 되어야(must) 합니다; 그렇지 않으면, 브라우징 컨텍스트 이름은 빈 문자열로 설정 되어야(must) 합니다.

      resource type이 "image/"로 시작하고, 이미지에 대한 지원이 비활성화되지 않았다면

      이미지 스니핑 규칙을 이미지의 유형을 결정하는데 적용합니다.

      object 요소(element)는 명시된 이미지를 나타냅니다. 이미지는 중첩된 브라우징 컨텍스트가 아닙니다.

      이미지가 렌더링 될 수 없다면, 예를 들어 그것이 잘못되었거나 지원되지 않는 형식이라면, 아래 fallback으로 라벨링 된 단계로 건너뜁니다.

      그렇지 않으면

      주어진 resource type은 지원되지 않습니다. 아래 fallback으로 라벨링 된 단계로 건너뜁니다.

      앞선 단계가 알 수 없는 것이 되는 resource type으로 끝났다면, 이것은 작동 된 경우입니다.

    10. 요소(element)의 콘텐트는 object 요소(element)가 나타내는 것의 일부가 아닙니다.
    11. 이 단계들을 중단시킵니다. 리소스가 완전히 로드되었을 때, 요소(element)에 load라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣습니다.

  5. data 속성(attribute)이 없지만 type 속성(attribute)이 존재하고, 유저 에이전트가 type 속성(attribute)의 값에 따라 적절한 플러그인을 찾을 수 있고, 플러그인들이 샌드박스 되는 것이 아니거나 플러그인보호될 수 있다면, 그 플러그인사용되어야(should) 합니다. 이 조건을 만나지 못하거나, 플러그인이 오류를 보고한다면, 아래 fallback으로 라벨링 된 단계로 건너뜁니다. 그렇지 않으면 이 단계들을 중단합니다; 플러그인이 완전히 로드될 때, 요소(element)에 load라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣습니다.
  6. Fallback: object 요소(element)는 다른 선두의 자식 param 요소(element)들을 무시하고, 요소(element)의 자식을 나타냅니다. 이것이 요소(element)의 폴백 콘텐트입니다. 요소(element)가 인스턴스화 된 플러그인을 가진다면, 그것은 언로드 됩니다.

위 알고리즘이 플러그인을 인스턴스화 할 때, 유저 에이전트는 요소(element)의 사용된 모든 모든 속성(attribute)들의 이름들과 값들을, 그것들이 요소(element)에 추가된 순서에 따라, 소스 순서에 따라 정렬되는 해석기 의해 추가된 속성(attribute)들, 그 뒤로 값이 null인 "PARAM"이라는 파라미터, 그 뒤로 object 요소(element)의 자식인 param 요소(element)에 의해 주어진 파라미터들의 모든 이름들과 값들을 트리 순서에 따라 플러그인에 전달해야(should) 합니다. 플러그인이 스트립트 가능한 인터페이스를 지원한다면, 요소(element)를 나타내는 HTMLObjectElement 객체는 그 인터페이스를 노출해야(should) 합니다. object 요소(element)는 플러그인나타냅니다. 플러그인은 중첩된 브라우징 컨텍스트가 아닙니다.

object 요소(element)의 노드 문서샌드박싱 활성화 플래그 설정샌드박스 된 플러그인 브라우징 컨텍스트 플래그가 설정 되었다면 플러그인들은 object 요소(element)의 목적을 위해 샌드박스 된 것으로 간주됩니다.

위 알고리즘 때문에, object 요소(element)들의 콘텐츠는 참조된 리소스들이 보여질 수 없을 때에만 (예를 들어, 그것이 404 오류를 반환했기 때문에) 사용되는 폴백 콘텐트로서 동작합니다. 이것은 다른 능력들을 가진 여러 유저 에이전트들을 타게팅하여, 유저 에이전트가 지원하는 처음 것을 선택하도록 여러 object 요소(element)들이 서로의 내부에 중첩되는 것을 허용합니다.

object 요소(element)가 중첩된 브라우징 컨텍스트를 나타내는 경우: object 요소(element)의 중첩된 브라우징 컨텍스트활성 문서로드 후 작업들에 대해 준비되지 않고, 어떤 것이든 object 요소(element)의 브라우징 컨텍스트활성 문서load 이벤트를 지원시키고 있는 경우와, object 요소(element)의 브라우징 컨텍스트load 이벤트들 지연 중 모드에 있다면, object는 그것의 문서의 load 이벤트를 지연시켜야(must) 합니다.

이 섹션에 언급된 작업들에 대한 작업 소스DOM 조작 작업 소스입니다.

name 속성(attribute)이 설정될 때마다, object 요소(element)가 중첩된 브라우징 컨텍스트를 가진다면, 그것의 이름은 새로운 값으로 변경되어야(must) 합니다. 속성(attribute)이 제거된다면, object 요소(element)가 브라우징 컨텍스트를 가진다면, 브라우징 컨텍스트 이름은 빈 문자열로 설정 되어야(must) 합니다.

form 속성(attribute)은 object 요소(element)를 그것의 양식 소유자와 명시적으로 연관시키기 위해 사용됩니다.

제약조건 확인: object 요소(element)들은 항상 제약 조건 확인을 금지됩니다.

object 요소(element)는 치수 속성(attribute)들을 지원합니다.

IDL 속성(attribute)들 data, type, name은 각각 동일한 이름의 각 콘텐트 속성(attribute)들을 반영해야(must) 합니다. typeMustMatch IDL 속성(attribute)은 typemustmatch 콘텐트 속성(attribute)을 반영해야 합니다. useMap IDL 속성은 usemap 콘텐트 속성을 반영해야(must) 합니다.

contentDocument IDL 속성(attribute)은 object 요소(element)의 중첩된 브라우징 컨텍스트활성 문서Document 객체가 존재하고 그것의 출처현직 설정 객체에 의해 명시된 출처로서 동일 출처 도메인이라면 object 요소(element)의 중첩된 브라우징 컨텍스트활성 문서Document 객체를 반환해야(must) 하고, 그렇지 않으면 null을 반환해야(must) 합니다.

contentWindow IDL 속성(attribute)은 object 요소(element)의 중첩된 브라우징 컨텍스트WindowProxy 객체를 가진다면 이를 반환해야(must) 하고 그렇지 않으면 null을 반환해야(must) 합니다.

willValidate, validity, validationMessage 속성(attribute)들과 checkValidity(), reportValidity(), setCustomValidity() 메서드들은 제약 조건 확인 API의 일부입니다. form IDL 속성(attribute)은 요소(element)의 forms API의 일부입니다.

모든 object 요소(element)는 레거시 호출자 연산을 가집니다. object 요소(element)가 레거시 호출자 연산을 정의하는 스크립트 가능한 인터페이스를 지원하는 인스턴스화 된 플러그인을 가진다면, 그것은 객체의 레거시 호출자 연산의 동작이어야(must) 합니다. 그렇지 않으면, 객체의 레거시 호출자 연산은 NotSupportedError 예외를 던져야(must) 합니다.

다음 예에서, 자바 애플릿은 object 요소(element)를 사용하여 페이지에 삽입됩니다. (일반적으로 말해서, 이것들과 같은 애플릿들을 사용하는 것은 피하고 대신 기능성을 제공하기 위해 네이티브 JavaScript와 HTML을 사용하는 것이, 어플리케이션이 서드 파티 플러그인을 요구하지 않고 모든 웹 브라우저들에서 동작할 것이기 때문에, 더 좋습니다. 많은 기기들, 특히 임베디드 기기는 Java와 같은 서드 파티 기술을 지원하지 않습니다.)
<figure>
  <object type="application/x-java-applet">
  <param name="code" value="MyJavaClass">
  <p>You do not have Java available, or it is disabled.</p>
  </object>
  <figcaption>My Java Clock</figcaption>
</figure>
이 예에서, HTML 페이지는 object 요소(element)를 사용하여 다른 HTML에 삽입됩니다.
<figure>
  <object data="clock.html"></object>
  <figcaption>My HTML Clock</figcaption>
</figure>
다음 예는 HTML에 플러그인이 어떻게 사용될 수 있는지를 (이 경우 비디오 파일을 보여주기 위한 플래시 플러그인) 보여줍니다. 폴백은 활성화 된 Flash를 가지지 않은 사용자들에 대해, 이 경우에 비디오를 보여주기 위해 video를 지원하는 유저 에이전트들을 사용하는 사용자에 대해서는 video 요소(element)를 사용하고, 마지막으로 플래시나 video-가능 브라우저를 가지지 않은 사용자들에 대해서는 비디오로의 링크를 제공하여 제공됩니다.
<p>Look at my video:
  <object type="application/x-shockwave-flash">
  <param name=movie value="https://video.example.com/library/watch.swf">
  <param name=allowfullscreen value=true>
  <param name=flashvars value="https://video.example.com/vids/315981">
  <video controls src="https://video.example.com/vids/315981">
    <a href="https://video.example.com/vids/315981">View video</a>.
  </video>
  </object>
</p>

4.7.9. param 요소(element)

카테고리:
없음.
이 요소(element)가 사용될 수 있는 컨텍스트:
object 요소(element)의 자식으로서, 모든 흐름(flow) 콘텐트 이전에.
콘텐트 모델:
없음.
text/html에서 태그 생략:
종료 태그 없음.
콘텐트 속성(attribute)들:
범용 속성(attribute)들
name - 파라미터의 이름
value - 파라미터의 값
허용된 ARIA 역할(role) 속성(attribute) 값들:
없음
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
DOM 인터페이스:
interface HTMLParamElement : HTMLElement {
  attribute DOMString name;
  attribute DOMString value;
};

param 요소(element)는 object 요소(element)들에 의해 작동되는 플러그인들에 대한 파라미터들을 정의 합니다. 이 요소(element)는 스스로 어떠한 것도 나타내지 않습니다.

name 속성(attribute)은 파라미터의 이름을 제공합니다.

value 속성(attribute)은 파라미터의 값을 제공합니다.

두 속성은 모두 존재해야(must) 합니다. 그것들은 어떠한 값이든 가질 수 있습니다.

두 속성(attribute)들이 모두 존재하고, param의 부모 요소(element)가 object 요소(element)라면, 요소(element)는 주어진 이름-값 쌍으로 파라미터를 정의합니다.

인스턴스화 된 플러그인을 나타내는 object 요소(element)의 자식인 param 요소(element)에 의해 정의된 파라미터의 이름과 값이 변경되고, 그 플러그인파라미터의 이름과 값이 변경될 때 플러그인을 업데이트 할 수 있는 특징을 가진 API를 사용하는 유저 에이전트와 통신 중이라면, 유저 에이전트는 변경된 플러그인을 통지할 수 있도록 적절하게 수행해야(must) 합니다.

IDL 속성(attribute)들 namevalue는 모두 동일한 이름의 각각의 콘텐트 속성(attribute)들을 반영해야(must) 합니다.

다음 예는 param 요소(element)가 플러그인에, 이 경우에는 O3D 플러그인에, 파라미터를 전달하기 위해 사용될 수 있는 방법을 보여줍니다.
<!DOCTYPE HTML>
<html lang="en">
  <head>
    <title>O3D Utah Teapot</title>
  </head>
  <body>
    <p>
    <object type="application/vnd.o3d.auto">
      <param name="o3d_features" value="FloatingPointTextures">
      <img src="o3d-teapot.png"
          title="3D Utah Teapot illustration rendered using O3D."
          alt="When O3D renders the Utah Teapot, it appears as a squat
          teapot with a shiny metallic finish on which the
          surroundings are reflected, with a faint shadow caused by
          the lighting.">
      <p>To see the teapot actually rendered by O3D on your
      computer, please download and install the <a
      href="https://code.google.com/apis/o3d/docs/gettingstarted.html#install">O3D plugin</a>.</p>
    </object>
    <script src="o3d-teapot.js"></script>
    </p>
  </body>
</html>

4.7.10. video 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
삽입(embedded) 콘텐트.
요소(element)가 controls 속성(attribute)을 가진다면: 대화형(interactive) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
삽입(embedded) 콘텐트가 예상되는 곳.
콘텐트 모델:
요소(element)가 src 속성(attribute)을 가진다면: 0개 이상의 track 요소(element)들, 그 뒤로 후손 미디어 요소(element)들이 없는 투명.
요소(element)가 src 속성(attribute)을 가지 않는다면: 0개 이상의 source 요소(element)들, 그 뒤로 0개 이상의 track 요소(element)들, 그 뒤로 후손 미디어 요소(element)들이 없는 투명.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
src - 리소스의 주소
crossorigin - 요소(element)가 crossorigin 요청들을 처리하는 방법
poster - 비디오 재생 이전에 보여 줄 포스터 프레임
preload - 미디어 리소스를 얼마나 많이 버퍼링 해야 하는지에 대한 힌트
autoplay - 페이지가 로드 될 때 미디어 리소스가 자동으로 시작될 수 있는지에 대한 힌트
loop - 미디어 리소스를 반복할지 여부
muted - 기본적으로 미디어 리소스를 음소거 할지 여부
controls - 유저 에이전트 컨트롤들 표시
width - 가로 치수
height - 세로 치수
허용된 ARIA 역할(role) 속성(attribute) 값들:
application.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
interface HTMLVideoElement : HTMLMediaElement {
  attribute unsigned long width;
  attribute unsigned long height;
  readonly attribute unsigned long videoWidth;
  readonly attribute unsigned long videoHeight;
  attribute DOMString poster;
};

video 요소(element)는 비디오들이나 영화, 오디오 파일들을 캡션과 함께 재생하는데 사용됩니다.

콘텐트는 video 요소(element) 안에 제공될 수 있습니다. 유저 에이전트들은 사용자에게 이 콘텐트를 보여주지 않아야(should) 합니다; 이것은 video를 지원하지 않는 오래된 웹 브라우저들을 위해 의도된 것이기 때문에, 레거시 비디오 플러그인들이 시도될 수 있거나, 또는 이 구형 브라우저들의 사용자들에게 비디오 콘텐츠에 접근하는 방법의 유용한 텍스트를 보여주기 위한 것입니다.

특히, 이 콘텐트는 접근성 문제들을 다루기 위해 의도된 것이 아닙니다. 비디오 콘텐트를 약시, 전맹, 난청, 청각 장애, 기타 신체적 혹은 인지 장애들을 가진 사람들에게 접근 가능하도록 만들기 위해 다양한 기능들이 사용 가능합니다. 캡션들이 비디오 스트림에 삽입되거나, track 요소(element)를 사용하여 외부 파일로서 제공될 수 있습니다. 수화 트랙들이 비디오 스트림에 또 삽입되어 제공될 수 있습니다. 오디오 설명들이 비디오 스트림에 삽입된 별도의 트랙으로서, 혹은 track 요소(element)를 사용하여 참조되고 유저 에이전트에 의해 음성으로 합성되는 WebVTT 파일을 사용하여 텍스트 형식으로 제공될 수 있습니다. WebVTT는 또한 장면의 표제(chapter title)들을 제공하는데 사용될 수 있습니다. 모든 미디어 요소(element)를 전혀 사용하지 않을 사용자들을 위해, 원고나 다른 대체 텍스트들이 본문 내 video 요소(element) 가까이에 간단히 연결되는 것을 통해 제공될 수 있습니다. [WEBVTT]

video 요소(element)는 연관된 오디오 데이터를 가질 수 있는, 미디어 데이터가 표면상 비디오 테이터인 미디어 요소 입니다.

src, preload, autoplay, loop, muted, controls 속성(attribute)들은 모든 미디어 요소(element)들에 대해 공통 속성(attribute)들 입니다.

poster 콘텐트 속성(attribute)은 사용 가능한 비디오 데이터가 없을 경우 유저 에이전트가 보여줄 수 있는 이미지 파일의 주소를 제공합니다. 이 속성(attribute)이 존재한다면 유효한 잠정적으로 공백으로 둘러 싸일 수 있는 비어있지 않은 URL을 포함해야(must) 합니다.

명시된 리소스가 사용된다면, 요소(element)가 생성될 때나 poster 속성(attribute)이 설정, 변경, 제거 될 경우, 유저 에이전트는 요소(element)의 포스터 프레임을 결정하기 위해 (요소(element)의 포스터 표시 플래그의 값에 상관없이) 다음 단계들을 수행해야(must) 합니다:

  1. video 요소(element)에 대해 수행하는 이 알고리즘의 기존의 인스턴스가 존재한다면, 포스터 프레임 변경 없이 이 알고리즘의 그 인스턴스를 중단합니다.
  2. poster 속성(attribute)의 값이 빈 문자열 이거나, 이 속성(attribute)이 없다면, 포스터 프레임은 존재하지 않습니다; 이 단계들을 중단합니다.
  3. poster 속성(attribute)의 값을 요소(element)에 관련하여 해석합니다. 이것이 실패한다면, 포스터 프레임은 존재하지 않습니다; 이 단계들을 중단합니다.
  4. requestURL결과 URL 문자열이고, 클라이언트가 요소(element)의 노드 문서Window 객체의 환경 설정 객체이며, 유형이 "image"이고, 목적지가 "subresource"이며, 자격 증명 모드가 "include"이고 URL 자격 증명 사용 플래그가 설정 된 새로운 요청으로 둡니다.
  5. request가져(fetch)옵니다. 이것은 요소(element)의 노드 문서load 이벤트를 지연시켜야(must) 합니다.
  6. 이미지가 얻어졌다면, 포스터 프레임은 그 이미지 입니다. 그렇지 않으면, 포스터 프레임은 존재하지 않습니다.

poster 속성(attribute)에 의해 주어진 이미지, 포스터 프레임은 사용자에게 비디오가 무엇인지의 느낌을 전달하는 비디오의 대표 프레임이 되도록 (일반적으로 첫 번째 비어 있지 않은 프레임의 하나) 의도된 것입니다.


video 요소(element)는 다음 목록에 처음 일치하는 조건에 대해 주어진 것을 나타냅니다:

사용 가능한 비디오 데이터가 없는 경우 (요소(element)의 readyState 속성(attribute)이 HAVE_NOTHING 이거나, HAVE_METADATA이지만 비디오 데이터가 아직 전혀 얻어지지 않았거나, 요소(element)의 readyState 속성(attribute)이 차후의 값이지만 미디어 리소스가 비디오 채널을 가지지 않는 경우)
video 요소(element)는 그것의 포스터 프레임이 있다면 포스터 프레임을, 그렇지 않으면 고유 치수들이 없는 투명한 검정 화면을 나타냅니다.
video 요소(element)가 일시 중지되고, 현재 재생 위치가 비디오의 첫 번째 프레임이고, 요소(element)의 포스터 표시 플래그가 설정 된 경우
video 요소(element)는 그것의 포스터 프레임이 있다면 포스터 프레임을, 그렇지 않으면 비디오의 첫 번째 프레임을 나타냅니다.
video 요소(element)가 일시 중지되었고, 현재 재생 위치에 해당하는 비디오의 프레임이 사용 가능하지 않은 경우(예를 들어, 비디오가 탐색 중이거나 버퍼링 중이기 때문에)
video 요소(element)가 재생 중 일 수 있지도 일시 중지 되지도 않은 경우 (예를 들어 탐색 중이거나 멈춘(stalled) 경우)
video 요소(element)는 렌더링 된 비디오의 마지막 프레임을 나타냅니다.
video 요소(element)가 일시 중지 된 경우
video 요소(element)는 현재 재생 위치에 해당하는 비디오의 프레임을 나타냅니다.
그 외 (video 요소(element)가 비디오 채널을 가지며 재생 중 일 수있는)
video 요소(element)는 계속적으로 증가하는 "현재" 위치의 비디오 프레임을 나타냅니다. 현재 재생 위치가 렌더링 된 마지막 프레임이 비디오에서 더 이상 현재 재생 위치에 일치하지 않는 프레임으로 변경하는 경우, 새로운 프레임이 렌더링 되어야(must) 합니다.

비디오의 프레임들은 마지막으로 이벤트 루프가 단계 1에 도달했을 때 선택 되었던 비디오 트랙으로부터 얻어져야(must) 합니다.

특정 재생 위치에 해당하는 비디오 스트림에서 프레임은 비디오 스트림의 형식에 의해 정의됩니다.

video 요소(element)는 또한 현재 재생 위치에, 텍스트 트랙 큐 활성화 플래그가 설정되고 텍스트 트랙표시 모드에 있는 모든 텍스트 트랙 큐들미디어 리소스로부터의 오디오를 나타냅니다.

미디어 리소스와 연관된 모든 오디오는, 재생 되었다면, 요소(element)의 유효한 미디어 볼륨현재 재생 위치와 동시에 재생 되어야(must) 합니다. 유저 에이전트는 마지막으로 이벤트 루프가 단계 1에 도달했을 때 활성화 되었던 오디오 트랙들로부터 오디오를 재생해야(must) 합니다.

위의 것에 추가적으로, 유저 에이전트는 사용자에게 메세지를 ("버퍼링 중", "로드된 비디오 없음", "오류", 또는 더 자세한 정보와 같은) 비디오 위 혹은 요소(element)의 재생 영역의 다른 영역들에 텍스트나 아이콘들을 중첩시키거나, 다른 적절한 방법으로 제공 할 수 있습니다.

비디오를 렌더링 할 수 없는 유저 에이전트들은 대신 외부 비디오 재생 유틸리티로의 링크나 비디오 데이터 자체로의 링크를 나타내는 요소(element)를 만들 수 있습니다.

video 요소(element)의 미디어 리소스가 비디오 채널을 가지는 경우, 요소(element)는 너비가 미디어 리소스고유 너비이고, 높이가 미디어 리소스고유 높이이며, 모양이 현재 재생 위치에 해당하는 비디오의 프레임이 가능하다면 그 프레임인, 그렇지 않으면 (예를 들어 비디오가 탐색 중이거나 버퍼링 중인 경우) 이전 모양이 있다면 이전 모양을, 그렇지 않으면 (예를 들어 비디오가 여전히 첫 번째 프레임을 로딩 중이기 때문에) 검은색 그림 소스를 제공합니다.


video . videoWidth
video . videoHeight

이 속성(attribute)들은 비디오의 고유 치수들을 반환하거나, 치수들을 알 수 없다면 0을 반환합니다.

미디어 리소스고유 너비고유 높이는 리소스에 의해 사용되는 형식에 대해 정의된 것으로서, 리소스의 치수들, 화면 종횡비, clean aperture, 해상도, 기타 등등을 고려하여 CSS 픽셀로 리소스의 치수입니다. 아나모픽(anamorphic) 형식이 "올바른" 치수들을 얻어오기 위해 종횡비를 비디오 데이터의 치수들에 적용하는 방법을 정의하지 않는다면, 유저 에이전트는 한쪽 치수를 증가시키고 다른 변하지 않은 것은 그대로 둠으로 비율을 적용해야(must) 합니다.

videoWidth IDL 속성(attribute)은 비디오의 고유 너비를 CSS 픽셀로 반환해야(must) 합니다. videoHeight IDL 속성(attribute)은 비디오의 고유 높이를 CSS 픽셀로 반환해야(must) 합니다. 요소(element)의 readyState 속성(attribute)이 HAVE_NOTHING이라면, 속성(attribute)은 0을 반환해야(must) 합니다.

비디오의 고유 너비고유 높이가 변경될 때 마다 (예를들어, 선택 된 비디오 트랙이 변경되는 경우를 포함하여), 요소(element)의 readyState 속성이 HAVE_NOTHING이 아니라면, 유저 에이전트는 미디어 요소resize라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣어야(must) 합니다.

video 요소(element)는 치수 속성(attribute)들을 지원합니다.

반대로 스타일 규칙이 없는 경우, 비디오 콘텐트는 비디오 콘텐트의 종횡비가 보존되면서 비디오 콘텐트가 그 내부에 완전히 맞는 가능한 가장 큰 사이즈의 재생 영역 가운데로 보여지는 요소(element)의 재생 영역 안에 렌더링 되어야(should) 합니다. 따라서, 재생 영역의 종횡비가 비디오의 종횡비와 매칭되지 않는다면, 비디오는 레터박스나 필러박스로 보여질 것입니다. 비디오를 포함하지 않는 요소(element)의 재생 영역의 영역은 아무 것도 나타내지 않습니다.

레터박스(letterboxed)
16 : 9를 4 : 3에 맞추는 방법
필러박스(pillarboxed)
4 : 3을 16 : 9에 맞추는 방법

CSS를 구현하는 유저 에이전트들에서, 위 요구사항은 §10 Rendering에 제안된 스타일 규칙을 사용하여 구현될 수 있습니다.

포스터 프레임고유 너비가 사용 가능하고 요소(element)가 현재 그것의 포스터 프레임을 나타낸다면, video 요소(element)의 재생 영역의 고유 너비포스터 프레임고유 너비이고; 그렇지 않고 비디오 리소스의 고유 너비가 사용 가능하다면 비디오 리소스의 고유 너비이며; 그렇지 않으면 고유 너비는 누락 된 것입니다.

포스터 프레임고유 높이가 사용 가능하고 요소(element)가 현재 그것의 포스터 프레임을 나타낸다면, video 요소(element)의 재생 영역의 고유 높이포스터 프레임고유 높이이고; 그렇지 않고 비디오 리소스의 고유 높이가 사용 가능하다면 비디오 리소스의 고유 높이이며; 그렇지 않으면 고유 높이는 누락 된 것입니다.

기본 객체 크기는 너비 300px과 높이 150px 입니다. [CSS3-IMAGES]


유저 에이전트들은 폐쇄 자막(closed caption)들의 표시, 오디오 설명 트랙들, 비디오 스트림과 연관된 다른 추가적인 데이터를 활성화 혹은 비활성화하는 컨트롤들을 제공해야(should)하지만, 그 기능들이 페이지의 일반적인 렌더링을 방해하지 않아야(should) 합니다.

유저 에이전트들은 사용자에게 좀 더 적절한 방법들로 (예를 들어, 풀 스크린이나 독립된 사이즈 조절 가능한 창에서) 비디오 콘텐트를 보는 것을 허용할 수 있습니다. 다른 유저 인터페이스 기능의 경우, 이를 활성화하기 위한 컨트롤은 유저 에이전트가 유저 인터페이스를 노출 중이 아닌 한 페이지의 일반적인 렌더링을 방해하지 않아야(should) 합니다. 그러나 그러한 독립적인 컨텍스트에서, 유저 에이전트들은 controls 속성(attribute)이 없다하더라도 전체 유저 인터페이스들을 표시할 수 있습니다.

유저 에이전트들은 비디오 재생이 사용자 경험을 방해할 수 있는 시스템 기능들에 영향을 주는 것을 허용할 수 있습니다; 예를 들어, 유저 에이전트들은 비디오 재생이 처리 중인 동안 화면보호기들을 비활성화 할 수 있습니다.


poster IDL 속성(attribute)은 poster 콘텐트 속성(attribute)을 반영해야(must) 합니다.

이 예는 비디오가 제대로 재생하지 못한 경우를 감지하는 방법을 보여줍니다:
<script>
  function failed(e) {
    // video playback failed - show a message saying why
    switch (e.target.error.code) {
      case e.target.error.MEDIA_ERR_ABORTED:
        alert('You aborted the video playback.');
        break;
      case e.target.error.MEDIA_ERR_NETWORK:
        alert('A network error caused the video download to fail part-way.');
        break;
      case e.target.error.MEDIA_ERR_DECODE:
        alert('The video playback was aborted due to a corruption problem or because the video used features your browser did not support.');
        break;
      case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:
        alert('The video could not be loaded, either because the server or network failed or because the format is not supported.');
        break;
      default:
        alert('An unknown error occurred.');
        break;
    }
  }
</script>
<p><video src="tgif.vid" autoplay controls onerror="failed(event)"></video></p>
<p><a href="tgif.vid">Download the video file</a>.</p>

4.7.11. audio 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
삽입(embedded) 콘텐트.
요소(element)가 controls 속성(attribute)을 가진다면: 대화형(interactive) 콘텐트.
요소(element)가 controls 속성(attribute)을 가진다면: 분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
삽입(embedded) 콘텐트가 예상되는 곳.
콘텐트 모델:
요소(element)가 src 속성(attribute)을 가진다면: 0개 이상의 track 요소(element)들, 그 뒤로 후손 미디어 요소(element)들이 없는 투명
요소(element)가 src 속성(attribute)을 가지지 않는다면: 0개 이상의 source 요소(element)들, 그 뒤로 0개 이상의 track 요소(element)들, 그 뒤로 후손 미디어 요소(element)들이 없는 투명.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
src - 리소스의 주소
crossorigin - 요소(element)가 crossorigin 요청들을 처리하는 방법
preload - 미디어 리소스를 얼마나 많이 버퍼링 해야 하는지에 대한 힌트
autoplay - 페이지가 로드 될 때 미디어 리소스가 자동으로 시작될 수 있는지에 대한 힌트
loop - 미디어 리소스를 반복할지 여부
muted - 기본적으로 미디어 리소스를 음소거 할지 여부
controls - 유저 에이전트 컨트롤들 표시
허용된 ARIA 역할(role) 속성(attribute) 값들:
application.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
[NamedConstructor=Audio(optional DOMString src)]
interface HTMLAudioElement : HTMLMediaElement {};

audio 요소(element)는 사운드나 오디오 스트림을 나타냅니다.

콘텐트는 audio 요소(element) 내에 제공될 수 있습니다. 유저 에이전트들은 사용자에게 이 콘텐트를 보여주지 않아야(should) 합니다.; 이는 audio를 지원하지 않는 구형 웹 브라우저를 위해 의도된 것이기 때문에, 레거시 오디오 플러그인들이 시도될 수 있거나, 또는 이 구형 브라우저들의 사용자들에게 오디오 콘텐트에 접근하는 방법의 유용한 텍스트를 보여주기 위한 것입니다.

특히, 이 콘텐트는 접근성 문제를 다루기 위해 의도된 것이 아닙니다. 오디오 콘텐트를 청각 장애나 기타 신체적 혹은 인지 장애를 가진 사람들에게 접근 가능하도록 만들기 위해 다양한 기능들이 사용 가능합니다. 캡션들이나 수화 동영상이 사용 가능하다면, 사용자에게 시각적 대안들을 가능하도록 하는 video 요소(element)가 오디오를 재생하기 위해 audio 요소(element) 대신 사용될 수 있습니다. track 요소(element)와 WebVTT 파일을 사용하여, 장면의 표제(chapter title)들이 탐색을 돕기 위해 제공될 수 있습니다. 그리고, 당연히, 원고나 다른 대체 텍스트들이 본문 내 audio 요소(element) 가까이에 간단히 연결되는 것을 통해 제공될 수 있습니다. [WEBVTT]

audio 요소(element)는 미디어 데이터가 표면상 오디오 데이터인 미디어 요소입니다.

src, preload, autoplay, loop, muted, controls 속성(attribute)들은 모든 미디어 요소(element)들에 대해 공통 속성(attribute)들 입니다.

audio 요소(element)가 재생 중 일 수있는 경우, 요소(element)의 유효한 미디어 볼륨현재 재생 위치와 동시에 재생 되어야(must) 합니다. 유저 에이전트는 마지막으로 이벤트 루프가 단계 1에 도달했을 때 활성화 되었던 오디오 트랙들로부터 오디오를 재생해야(must) 합니다.

audio 요소(element)가 재생 중 일 수있지 않을 때, 오디오는 요소(element)에 대해 재생하지 않아야(must) 합니다.

audio = new Audio( [ url ] )

인자로 전달된 값으로 설정된 src 속성(attribute)이 적절하다면 이 속성(attribute)을 가지고 새로운 audio 요소(element)를 반환합니다.

(createElement()과 같은 DOM 팩토리 메서드들 뿐 아니라) HTMLAudioElement 객체들을 생성하기 위한 생성자가 제공됩니다: Audio(src)). 생성자로서 호출 될 경우, 이는 새로운 HTMLAudioElement 객체 (새로운 audio 요소(element))를 반환해야(must) 합니다. 요소(element)는 리터럴 값 "auto"로 설정 된 preload 속성(attribute)을 가지고 생성되어야(must) 합니다. src 인자가 존재한다면, 객체는 제공된 값으로 설정된 src 콘텐트 속성을 가지고 생성되어여(must) 합니다 (이것은 유저 에이전트가 반환 이전에 객체의 리소스 선택 알고리즘을 호출하게 될 것입니다). 요소(element)의 노드 문서는 작동된 생성자의 인터페이스 객체가 발견되는 Window 객체의 브라우징 컨텍스트활성 문서이어야(must) 합니다.

4.7.12. source 요소(element)

카테고리:
없음.
이 요소(element)가 사용될 수 있는 컨텍스트:
미디어 요소(element)의 자식으로서, 모든 흐름(flow) 콘텐트track 요소(element)들 이전에.
콘텐트 모델:
없음.
text/html에서 태그 생략:
종료 태그 없음.
콘텐트 속성(attribute)들:
범용 속성(attribute)들
src - 리소스의 주소
type - 삽입된 리소스의 유형
허용된 ARIA 역할(role) 속성(attribute) 값들:
없음
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
DOM 인터페이스:
interface HTMLSourceElement : HTMLElement {
  attribute DOMString src;
  attribute DOMString type;
};

source 요소(element)는 작성자들이 미디어 요소(element)들에 대한 여러 대체 미디어 리소스들을 명시하는 것이 허용됩니다. 이 요소(element)는 스스로 아무 것도 나타내지 않습니다.

src 속성(attribute)은 미디어 리소스의 주소를 제공합니다. 값은 유효한 잠정적으로 공백으로 둘러 싸일 수 있는 비어있지 않은 URL이어야(must) 합니다. 이 속성(attribute)은 반드시 존재해야(must) 합니다.

source 요소(element)가 이미 videoaudio 요소(element)에 삽입 되었을 경우 동적으로 source 요소(element)와 그것의 속성(attribute)을 수정하는 것은 아무런 영향을 가지지 않습니다. 재생되고 있는 것을 변경하기 위해서는, 단지 사용 가능한 리소스들 중에서 선택하기 위해 아마도 canPlayType() 메서드를 활용하여, 직접적으로 미디어 요소(element)src 속성(attribute)을 사용하세요. 일반적으로, 문서가 해석된 이후 source 요소(element)를 수동으로 조작하는 것은 불필요하게 복잡한 접근입니다.

type 콘텐트 속성(attribute)은 미디어 리소스를 가져오기(fetch) 전에 이 미디어 리소스를 재생할 수 있는지의 여부를 유저 에이전트가 판단하는 것을 돕기 위해 미디어 리소스의 유형을 제공합니다. 명시된 경우, 그것의 값은 유효한 MIME 타입이어야(must) 합니다. 특정 MIME 타입들이 정의하는 codecs 파라미터는 리소스가 인코드 되는 방법을 정확하게 지정하기 위해 필요할 수 있습니다. [RFC6381]

다음 목록은 type 속성(attribute)에 codecs= MIME 파라미터를 사용하는 방법의 몇 가지 예를 보여줍니다.
MP4 컨테이너 내 H.264 CBP 비디오 (main, extended video와 호환가능) 레벨 3과 AAC LC 오디오
<source src='video.mp4' type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
    
MP4 컨테이너 내 H.264 Extended profile 비디오 (baseline-compatible) 레벨 3과 AAC LC 오디오
<source src='video.mp4' type='video/mp4; codecs="avc1.58A01E, mp4a.40.2"'>
    
MP4 컨테이너 내 H.264 Main profile 비디오 레벨 3과 AAC LC 오디오
<source src='video.mp4' type='video/mp4; codecs="avc1.4D401E, mp4a.40.2"'>
    
MP4 컨테이너 내 H.264 High profile 비디오 (main, baseline, extended profiles과 호환되지 않음) 레벨 3과 AAC LC 오디오
<source src='video.mp4' type='video/mp4; codecs="avc1.64001E, mp4a.40.2"'>
    
MP4 컨테이너 내 MPEG-4 Visual SP 레벨 0과 AAC LC 오디오
<source src='video.mp4' type='video/mp4; codecs="mp4v.20.8, mp4a.40.2"'>
    
MP4 컨테이너 내 MPEG-4 ASP 레벨 0과 AAC LC 오디오
<source src='video.mp4' type='video/mp4; codecs="mp4v.20.240, mp4a.40.2"'>
    
3GPP 컨테이너 내 MPEG-4 Visual SP 레벨 0과 AMR 오디오
<source src='video.3gp' type='video/3gpp; codecs="mp4v.20.8, samr"'>
    
ogg 컨테이너 내 theora 비디오와 vorbis 오디오
<source src='video.ogv' type='video/ogg; codecs="theora, vorbis"'>
    
ogg 컨테이너 내 theora 비디오 speex 오디오
<source src='video.ogv' type='video/ogg; codecs="theora, speex"'>
    
ogg 컨테이너 내 단독 vorbis 오디오
<source src='audio.ogg' type='audio/ogg; codecs=vorbis'>
    
ogg 컨테이너 내 단독 speex 오디오
<source src='audio.spx' type='audio/ogg; codecs=speex'>
    
ogg 컨테이너 내 단독 FLAC 오디오
<source src='audio.oga' type='audio/ogg; codecs=flac'>
    
ogg 컨테이너 내 dirac 비디오와 vorbis 오디오
<source src='video.ogv' type='video/ogg; codecs="dirac, vorbis"'>
    

source 요소(elemet)가 src 속성(attribute)이 없고 networkStateNETWORK_EMPTY 값을 가지는 미디어 요소(element)의 자식으로 삽입된다면, 유저 에이전트는 미디어 요소(element)리소스 선택 알고리즘을 호출해야(must) 합니다.

IDL 속성(attribute)들 src, type은 동일한 이름의 각 콘텐트 속성(attribute)들을 반영해야(must) 합니다.

유저 에이전트들이 제공된 미디어 리소스들을 렌더링 할 수 있는지의 여부를 작성자가 확신할 수 없다면, 작성자는 마지막 source 요소(element)에 error 이벤트를 두고 폴백 동작을 작동시킬 수 있습니다:
<script>
  function fallback(video) {
    // replace <video> with its contents
    while (video.hasChildNodes()) {
      if (video.firstChild instanceof HTMLSourceElement)
        video.removeChild(video.firstChild);
      else
        video.parentNode.insertBefore(video.firstChild, video);
    }
    video.parentNode.removeChild(video);
  }
</script>
<video controls autoplay>
  <source src='video.mp4' type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
  <source src='video.ogv' type='video/ogg; codecs="theora, vorbis"'
          onerror="fallback(parentNode)">
  ...
</video>

4.7.13. track 요소(element)

카테고리:
없음.
이 요소(element)가 사용될 수 있는 컨텍스트:
미디어 요소(element)의 자식으로, 모든 흐름 콘텐트 이전에.
콘텐트 모델:
없음.
text/html에서 태그 생략:
종료 태그 없음.
콘텐트 속성(attribute)들:
범용 속성(attribute)들
kind - 텍스트 트랙 유형
src - 리소스의 주소
srclang - 텍스트 트랙의 언어
label - 사용자에게 보이는 레이블
default - 적절한 다른 텍스트 트랙이 없을 경우 트랙 활성화
허용된 ARIA 역할(role) 속성(attribute) 값들:
없음
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
DOM 인터페이스:
interface HTMLTrackElement : HTMLElement {
  attribute DOMString kind;
  attribute DOMString src;
  attribute DOMString srclang;
  attribute DOMString label;
  attribute boolean default;

  const unsigned short NONE = 0;
  const unsigned short LOADING = 1;
  const unsigned short LOADED = 2;
  const unsigned short ERROR = 3;
  readonly attribute unsigned short readyState;

  readonly attribute TextTrack track;
};

track 요소(element)는 작성자들이 미디어 요소들에 대해 명시적인 외부 텍스트 리소스들을 명시하는 것을 허용합니다. 이 요소(element)는 스스로 아무 것도 나타내지 않습니다.

kind 속성(attribute)은 열거 속성(attribute)입니다. 다음 표는 이 속성(attribute)에 대해 정의된 키워드들을 나열합니다. 각 행의 첫 번째 칸에 주어진 키워드는 두 번째 칸에 주어진 상태에 대응됩니다.

키워드 상태 간단한 설명
subtitles Subtitles 사운드가 사용 가능하지만 이해할 수 없는 경우에 대한 (예를 들어, 사용자가 미디어 리소스의 오디오 트랙의 언어를 이해할 수 없기 때문에) 적절한, 대화의 원고나 번역. 비디오에 오버레이 됩니다.
captions Captions 사운드가 사용 할 수 없거나 깨끗하게 들리지 않는 경우에 대한 적절한 (예를 들어, 음소거, 주변 소음으로 들리지 않거나 사용자가 청각 장애인이기 때문에), 대화, 사운드 효과들, 관련 음악적 신호, 기타 관련 오디오 정보의 원고나 번역. 비디오에 오버레이 됩니다; 난청자에 대해 적절하게 표시 됨.
descriptions Descriptions 시각 컴포넌트가 보기 어렵거나, 사용할 준비가 되지 않거나, 사용 할 수 없는 경우에 대해 (예를 들어, 사용자가 운정 중인 동안 화면 없이 어플리케이션과 상호작용 하고 있기 때문에, 혹은 사용자가 시각장애인이기 때문에) 의도된, 미디어 리소스의 비디오 컴포넌트의 텍스트 형식의 설명들. 오디오로 합성됨.
chapters Chapters 미디어 리소스를 탐색하기 위해 사용되도록 의도된 챕터 제목. 유저 인터페이스에서 인터랙티브 한 것으로(중첩될 수 있음) 표시 됨.
metadata Metadata 스크립트에서의 사용을 위해 의도된 트랙. 유저 에이전트에 의해 표시되지 않음.

속성(attribute)은 생략될 수 있습니다. 생략 기본 값subtitles 상태 입니다. 유효하지 않은 기본 값metadata 상태 입니다.

src 속성(attribute)은 텍스트 트랙 데이터의 주소를 제공합니다. 값은 유효한 잠정적으로 공백으로 둘러 싸일 수 있는 비어있지 않은 URL이어야(must) 합니다. 이 속성(attribute)은 존재해야(must) 합니다.

요소(element)가 값이 빈 문자열이 아니고 src 속성(attribute)이 설정 되었을 때 그 값이 요소(element)의 노드 문서에 관련하여 성공적으로 해석 될 수 있는 src 속성(attribute)을 가진다면, 요소(element)의 트랙 URL결과 URL 문자열입니다. 그렇지 않으면, 요소(element)의 트랙 URL은 빈 문자열입니다.

요소(element)의 트랙 URLWebVTT 리소스를 식별하고, 요소(element)의 kind 속성(attribute)이 Metadata 상태에 있지 않다면, WebVTT 파일은 큐 텍스트를 사용하는 WebVTT 파일이어야(must) 합니다. [WEBVTT]

뿐만 아니라, 요소(element)의 트랙 URLWebVTT 리소스를 식별하고, 요소(element)의 kind 속성(attribute)이 chapters 상태에 있다면, WebVTT 파일은 챕터 제목 텍스트를 사용하는 WebVTT 파일이어야(must) 하고, 중첩된 큐만을 사용하는 WebVTT 파일이어야(must) 합니다. [WEBVTT]

srclang 속성(attribute)은 텍스트 트랙 데이터의 언어를 제공합니다. 값은 유효한 BCP 47 언어 태그이어야(must) 합니다. 이 속성(attribute)은 요소(element)의 kind 속성(attribute)이 subtitles 상태에 있다면 존재해야(must) 합니다. [BCP47]

요소(element)가 값이 빈 문자열이 아닌 srclang 속성(attribute)을 가진다면, 요소(element)의 트랙 언어는 속성(attribute)의 값입니다. 그렇지 않으면, 요소는 트랙 언어를 가지지 않습니다.

label 속성(attribute)은 트랙에 대한 사용자가 읽을 수 있는 제목을 제공합니다. 이 제목은 유저 에이전트들의 유저 인터페이스에서 자막(subtitle), 자막(caption), 오디오 설명을 나열하는 경우 유저 에이전트들에 의해 사용됩니다.

label 속성(attribute)이 존재한다면, 그 속성(attribute)의 값은 빈 문자열이지 않아야(must) 합니다. 뿐만 아니라, kind 속성(attribute)들이 동일한 상태에 있고, srclang 속성(attribute)들이 누락되었거나 동일한 언어를 나타내는 값을 가지며, label 속성(attribute)들이 모두 누락되었거나 모두 같은 값을 가지는 같은 미디어 요소(element)의 두 track 자식 요소(element)가 존재하지 않아야(must) 합니다.

요소(element)가 값이 빈 문자열이 아닌 label 속성(attribute)을 가진다면, 요소(element)의 트랙 레이블은 속성(attribute)의 값입니다. 그렇지 않으면, 요소의 트랙 레이블은 빈 문자열 입니다.

default 속성(attribute)은, 명시된다면 사용자의 설정이 다른 트랙이 더 적절하다는 것을 나타내지 않는다면 트랙이 활성화 되는 것을 나타내는, 불리언 속성(attribute)입니다.

미디어 요소(element)kind 속성(attribute)이 SubtitlesCaptions 상태에 있고 default 속성(attribute)이 명시된 자식 track 요소(element)를 하나를 초과하여 가지지 않아야(must) 합니다.

미디어 요소(element)kind 속성(attribute)이 Descriptions 상태에 있고 default 속성(attribute)이 명시된 자식 track 요소(element)를 하나를 초과하여 가지지 않아야(must) 합니다.

미디어 요소(element)kind 속성(attribute)이 Chapters 상태에 있고 default 속성(attribute)이 명시된 자식 track 요소(element)를 하나를 초과하여 가지지 않아야(must) 합니다.

kind 속성(attribute)이 Metadata 상태에 있고 default 속성(attribute)이 명시된 track 요소(element)들의 수에는 제한이 없습니다.

track . readyState
다음 목록으로부터 번호로 나타나는 텍스트 트랙 준비 상태를 반환합니다:
track . NONE (0)
텍스트 트랙이 로드되지 않은 상태.
track . LOADING (1)
텍스트 트랙 로딩 중 상태.
track . LOADED (2)
The 텍스트 트랙이 로드 된 상태.
track . ERROR (3)
The 텍스트 트랙 로드 실패 상태.
track . track

track 요소(element)의 텍스트 트랙에 해당하는 TextTrack 객체를 반환합니다.

readyState 속성(attribute)은 다음 목록에 의해 정의된, track 요소(element)의 텍스트 트랙텍스트 트랙 준비 상태에 해당하는 숫자 값을 반환해야(must) 합니다:

NONE (numeric value 0)
텍스트 트랙이 로드되지 않은 상태.
LOADING (numeric value 1)
텍스트 트랙 로딩 중 상태.
LOADED (numeric value 2)
텍스트 트랙이 로드 된 상태.
ERROR (numeric value 3)
텍스트 트랙 로드 실패 상태.

track IDL 속성(attribute)은, 가져올 때, track 요소(element)의 텍스트 트랙의 해당하는 TextTrack 객체를 반환해야(must) 합니다.

src, srclang, label, default IDL 속성(attribute)들은 각각 동일한 이름의 각 콘텐트 속성(attribute)들을 반영해야(must) 합니다. kind 속성(attribute)은 알려진 값들로만 제한 된 동일한 이름의 콘텐트 속성(attribute)을 반영해야(must) 합니다.

이 비디오는 몇 가지 언어로 자막들을 가집니다:
<video src="brave.webm">
  <track kind=subtitles src=brave.en.vtt srclang=en label="English">
  <track kind=captions src=brave.en.hoh.vtt srclang=en label="English for the Hard of Hearing">
  <track kind=subtitles src=brave.fr.vtt srclang=fr lang=fr label="Français">
  <track kind=subtitles src=brave.de.vtt srclang=de lang=de label="Deutsch">
</video>

(마지막 두 개의 lang 속성(attribute)들은 자막(subtitle)들 자체의 언어가 아니라, label 속성(attribute)의 언어를 기술합니다. 자막(subtitle)들의 언어는 srclang 속성에 의해 주어집니다.)

4.7.14. 미디어 요소(element)들

HTMLMediaElement 객체들은 (이 명세에서 audiovideo) 간단히 미디어 요소(element)들로 알려져 있습니다.

enum CanPlayTypeResult { "" /* empty string */, "maybe", "probably" };
typedef (MediaStream or MediaSource or Blob) MediaProvider;
interface HTMLMediaElement : HTMLElement {

  // error state
  readonly attribute MediaError? error;

  // network state
  attribute DOMString src;
  attribute MediaProvider? srcObject;
  readonly attribute DOMString currentSrc;
  attribute DOMString? crossOrigin;
  const unsigned short NETWORK_EMPTY = 0;
  const unsigned short NETWORK_IDLE = 1;
  const unsigned short NETWORK_LOADING = 2;
  const unsigned short NETWORK_NO_SOURCE = 3;
  readonly attribute unsigned short networkState;
  attribute DOMString preload;
  readonly attribute TimeRanges buffered;
  void load();
  CanPlayTypeResult canPlayType(DOMString type);

  // ready state
  const unsigned short HAVE_NOTHING = 0;
  const unsigned short HAVE_METADATA = 1;
  const unsigned short HAVE_CURRENT_DATA = 2;
  const unsigned short HAVE_FUTURE_DATA = 3;
  const unsigned short HAVE_ENOUGH_DATA = 4;
  readonly attribute unsigned short readyState;
  readonly attribute boolean seeking;

  // playback state
  attribute double currentTime;
  void fastSeek(double time);
  readonly attribute unrestricted double duration;
  object getStartDate();
  readonly attribute boolean paused;
  attribute double defaultPlaybackRate;
  attribute double playbackRate;
  readonly attribute TimeRanges played;
  readonly attribute TimeRanges seekable;
  readonly attribute boolean ended;
  attribute boolean autoplay;
  attribute boolean loop;
  void play();
  void pause();

  // controls
  attribute boolean controls;
  attribute double volume;
  attribute boolean muted;
  attribute boolean defaultMuted;

  // tracks
  [SameObject] readonly attribute AudioTrackList audioTracks;
  [SameObject] readonly attribute VideoTrackList videoTracks;
  [SameObject] readonly attribute TextTrackList textTracks;
  TextTrack addTextTrack(TextTrackKind kind, optional DOMString label = "", optional DOMString language = "");
};

미디어 요소 속성(attribute)들, src, crossorigin, preload, autoplay, loop, muted, controls은 모든 미디어 요소(element)들에 적용됩니다. 그것들은 이 섹션에 정의됩니다.

미디어 요소(element)들은 사용자에게 오디오 데이터나 비디오와 오디오 데이터를 보여주기 위해 사용됩니다. 이것은 이 섹션이 오디오나 비디오에 대한 미디어 요소(element)들에 동일하게 적용하기 때문에, 이 섹션에서 미디어 데이터로 언급됩니다.

용어 미디어 리소스는 미디어 데이터의 완전한 집합, 예를 들어 완전한 비디오 파일이나 완전한 오디오 파일을 참조하는데 사용됩니다.

미디어 리소스는 여러 개의 오디오와 비디오 트랙들을 가질 수 있습니다. 미디어 요소(element)의 목적에 대해, 미디어 리소스의 비디오 데이터는 마지막으로 이벤트 루프가 단계 1에 도달했을 때 요소(element)의 videoTracks 속성(attribute)에 의해 현재 주어진 선택된 트랙의 (선택된 트랙이 있다면) 비디오 데이터일 뿐이고, 미디어 리소스의 오디오 데이터는 마지막으로 이벤트 루프가 단계 1에 도달했을 때 요소(element)의 audioTracks 속성(attribute)에 의해 주어진 모든 현재 활성화 된 트랙들을 (활성화 된 트랙들이 있다면) 믹싱한 결과입니다.

audiovideo 요소(element)들 모두 오디오와 비디오 모두에 대해 사용될 수 있습니다. 둘 사이의 주요한 다른 점은 단지 video 요소(element)가 시각적 콘텐트에 대한 (비디오나 자막(caption)들 같은) 재생 영역을 가지는 반면, audio 요소(element)는 가지지 않는다는 것 뿐입니다.

달리 명시적으로 명시된 경우를 제외하고, 이 섹션과 그 섹션의 하위 섹션에서 대기열에 넣어진 모든 작업들에 대한 작업 소스는 문제의 미디어 요소(element)미디어 요소 이벤트 작업 소스입니다.

4.7.14.1. 오류 코드들
media . error

요소(element)의 현재 오류 상태를 나타내는 MediaError 객체를 반환합니다.

오류가 없다면 null을 반환합니다.

모든 미디어 요소(element)들은 그것의 리소스 선택 알고리즘이 마지막으로 호출 된 이후 요소(element)가 만난 마지막 오류를 보여주는, 연관된 오류 상태를 가집니다. 가져올 때 error 속성(attribute)은 이 마지막 오류에 대해 생성된 MediaError 객체를 반환하거나, 오류가 없었다면 null을 반환해야(must) 합니다.

interface MediaError {
  const unsigned short MEDIA_ERR_ABORTED = 1;
  const unsigned short MEDIA_ERR_NETWORK = 2;
  const unsigned short MEDIA_ERR_DECODE = 3;
  const unsigned short MEDIA_ERR_SRC_NOT_SUPPORTED = 4;
  readonly attribute unsigned short code;
};
media . error . code

다음 목록으로부터 현재 오류의 오류 코드를 반환합니다.

MediaError 객체의 code 속성(attribute)은 다음 중 하나이어야(must) 하는 오류에 대한 코드를 반환해야(must) 합니다:

MEDIA_ERR_ABORTED (숫자 값 1)
미디어 리소스에 대해 가져오는(fetch) 프로세스가 사용자의 요청에 유저 에이전트에 의해 중단되었을 경우.
MEDIA_ERR_NETWORK (숫자 값 2)
리소스가 사용 가능한 것으로 확정된 후, 일부 종류의 네트워크 오류가 유저 에이전트가 미디어 리소스를 가져오는(fetch) 것을 중지시키는 것을 야기한 경우.
MEDIA_ERR_DECODE (숫자 값 3)
리소스가 사용 가능한 것으로 확정된 후, 미디어 리소스를 디코딩하는 동안 일부 조율의 오류가 발생된 경우.
MEDIA_ERR_SRC_NOT_SUPPORTED (숫자 값 4)
src 속성(attribute)에 의해 나타난 미디어 리소스할당된 미디어 제공자 객체가 적합하지 않은 경우.
4.7.14.2. 미디어 리소스 위치

미디어 요소(element)들src 콘텐트 속성(attribute)은 보여질 미디어 리소스의 (비디오, 오디오) 주소를 제공합니다. 이 속성(attribute)이 존재한다면 유효한 잠정적으로 공백으로 둘러 싸일 수 있는 비어있지 않은 URL을 포함해야(must) 합니다.

미디어 요소(element)들crossorigin 콘텐트 속성(attribute)은 CORS 설정 속성(attribute)입니다.

미디어 요소(element)src 속성(attribute)을 가지고 생성된다면, 유저 에이전트는 미디어 요소(element)리소스 선택 알고리즘즉시 호출해야(must) 합니다.

미디어 요소(element)src 속성(attribute)이 설정되거나 변경된다면, 유저 에이전트는 미디어 요소(element)미디어 요소 로드 알고리즘을 호출해야(must) 합니다. (src 속성(attribute)을 제거하는 것은 source 요소(element)들이 존재함에도 불구하고 이를 수행하지 않습니다.)

미디어 요소(element)들src IDL 속성(attribute)은 동일한 이름의 콘텐트 속성(attribute)을 반영해야(must) 합니다.

crossOrigin IDL 속성은 crossorigin 콘텐트 속성(attribute)을 반영해야(must) 합니다.

미디어 제공 객체URL과 별도로, 미디어 리소스를 나타낼 수 있는 객체입니다. MediaStream 객체들, MediaSource 객체들, Blob 객체들, File 객체들은 모두 미디어 제공 객체들입니다.

미디어 요소(element)미디어 제공 객체할당된 미디어 제공 객체를 가질 수 있습니다. 미디어 요소(element)가 생성될 때, 할당된 미디어 제공 객체를 가지지 않습니다.

media . srcObject [ = source ]
미디어 요소(element)미디어 제공 객체에 할당되는 것을 허용합니다.
media . currentSrc
현재 미디어 리소스URL이 있다면, 이를 반환합니다.

미디어 리소스가 없거나 이것이 URL을 가지지 않는다면, 빈 문자열을 반환합니다.

currentSrc IDL 속성(attribute)은 초기에 빈 문자열입니다. 그 값은 아래 정의된 리소스 섹션 알고리즘에 의해 변경됩니다.

srcObject IDL 속성(attribute)은 가져올 때, 요소(element)의 할당된 미디어 제공 객체가 있다면 이를 반환해야(must)하고, 그렇지 않으면 null을 반환해야(must) 합니다. 설정 할 때, 요소(element)의 할당된 미디어 제공 객체를 새로운 값으로 설정해야(must)하고 그 후 요소(element)의 미디어 요소(element) 로드 알고리즘을 호출해야(must) 합니다.

미디어 리소스를 명시하는 방법으로 srcObject IDL 속성(attribute), src 콘텐트 속성(attribute), source 요소(element) 세 가지 방법이 있습니다. IDL 속성(attribute)이 우선 순위를 가지며, 그 다음으로 콘텐트 속성(attribute), 그 다음으로 요소(element)입니다.

4.7.14.3. MIME 타입들

미디어 리소스codecs 파라미터를 가진 어떤 경우, 그것의 유형, 특히 MIME 타입의 관점에서 설명될 수 있습니다. (MIME 타입에 따라 codecs codecs 허용되는지 아닌지의 여부) [RFC6381]

유형들은 일반적으로 다소 불완전한 설명들입니다; 예를 들어 "video/mpeg"는 컨테이너 유형이 무엇인지를 제외하고 어떤 것도 알리지 않으며, "video/mp4; codecs="avc1.42E01E, mp4a.40.2""와 같은 유형 조차도 실제 비트전송률 (최대 비트전송률만) 같은 정보를 포함하지 않습니다. 따라서, 유형이 주어지는 것은, 유저 에이전트가 그 유형의 (신뢰 수준의 변화와 함께) 미디어를 재생할 수 있을지도 모를 여부나, 그 유형의 미디어를 분명히 재생 할 수 없는지의 여부 만을 알 수 있을 뿐입니다.

유저 에이전트가 렌더링 할 수 없음을 아는 유형은 유저 에이전트가, 예를 들어 컨테이너 유형을 인식하지 않거나 열거된 코덱들을 지원하지 않기 때문에, 분명하게 지원하지 않는 리소스를 설명하는 것입니다.

파라미터가 없는 MIME 타입 "application/octet-stream"은 결코 유저 에이전트가 렌더링 할 수 없음을 아는 유형이 아닙니다. 유저 에이전트들은 잠재적인 미디어 리소스를 레이블을 지정하는데 사용되는 경우 명시적인 Content-Type 메타데이터의 결핍과 동등한 것으로 그 유형을 취급해야(must) 합니다.

여기서 파라미터들이 없는 MIME 타입 "application/octet-stream"만은 특별 케이스입니다; 어떤 파라미터가 그것을 가지고 나타난다면, 다른 MIME 타입과 같이 취급될 것입니다. 이는 알 수 없는 MIME 타입 파라미터들이 무시되어야 하는 규칙 위반입니다.

media . canPlayType(type)

유저 에이전트가 주어진 유형의 미디어 리소스들을 재생활 수 있는지를 확신하는 방법을 기반으로 빈 문자열이나 (부정 응답), "maybe"나, "probably"를 반환합니다.

canPlayType(type) 메서드는 type유저 에이전트가 렌더링 할 수 없음을 아는 유형이거나, "application/octet-stream" 유형이라면 빈 문자열을 반환해야(must) 하고; 그것은 유저 에이전트가 유형이 이 audiovideo 요소(element)에서 사용하면 렌더링 할 수 있는 미디어 리소스를 나타낸다고 확신한다면 "probably"를 반환해야(must) 하며; 그렇지 않으면 "maybe"를 반환해야(must) 합니다. 구현자들은 유형이 확실히 지원되거나 지원되지 않는 것으로 확인 될 수 있지 않은 한 "maybe"를 반환하도록 권장됩니다. 일반적으로, 유저 에이전트는 codecs 파라미터가 존재하지 않는다면 이 파라미터를 허용하는 유형에 대해 "probably"를 결코 반환하지 않아야(should) 합니다.

이 스크립트는 유저 에이전트가 video 요소(element)나 플러그인을 사용할지 여부를 동적으로 결정하기 위한 (가상의) 새로운 형식을 지원하는지를 테스트 합니다:
<section id="video">
  <p><a href="playing-cats.nfv">Download video</a></p>
</section>
<script>
  var videoSection = document.getElementById('video');
  var videoElement = document.createElement('video');
  var support = videoElement.canPlayType('video/x-new-fictional-format;codecs="kittens,bunnies"');
  if (support != "probably" && "New Fictional Video Plugin" in navigator.plugins) {
    // not confident of browser support
    // but we have a plugin
    // so use plugin instead
    videoElement = document.createElement("embed");
  } else if (support == "") {
    // no support from browser and no plugin
    // do nothing
    videoElement = null;
  }
  if (videoElement) {
    while (videoSection.hasChildNodes())
      videoSection.removeChild(videoSection.firstChild);
    videoElement.setAttribute("src", "playing-cats.nfv");
    videoSection.appendChild(videoElement);
  }
</script>

source 요소(element)의 type 속성(attribute)은 유저 에이전트가 렌더링 할 수 없는 형식들을 사용하는 리소스들을 다운로드 하는 것을 피하는 것을 허용합니다.

4.7.14.4. 네트워크 상태들
media . networkState

아래 목록의 코드로부터, 요소(element)에 대한 네트워크 활동의 현재 상태를 반환합니다.

미디어 요소(element)들이 네트워크와 상호작용 하는 것과 같이, 그것들의 현재 네트워크 활동은 networkState 속성(attribute)에 의해 나타납니다. 가져올 때, 다음 값들 중 하나이어야(must) 하는, 요소(element)의 현재 네트워크 활동을 반환해야(must) 합니다:

NETWORK_EMPTY (숫자 값 0)
요소(element)가 아직 초기화되지 않은 경우. 모든 속성(attribute)들이 그것들의 초기 상태들에 있는 경우.
NETWORK_IDLE (숫자 값 1)
요소(element)리소스 선택 알고리즘이 활성화 되고 리소스를 선택했지만, 실제로는 이 시점에 네트워크를 사용 중이지 않은 경우.
NETWORK_LOADING (숫자 값 2)
유저 에이전트가 활동적으로 데이터를 다운로드하려고 시도 중인 경우.
NETWORK_NO_SOURCE (숫자 값 3)
요소(element)리소스 선택 알고리즘이 활동적이지만, 알고리즘이 아직 사용할 리소스를 찾지 못한 경우.

아래 정의된 리소스 선택 알고리즘networkState 속성(attribute)이 값을 변경하는 시기와 이 상태에서 변경을 나타내기 위해 발생하는 이벤트들을 정확히 설명합니다.

4.7.14.5. 미디어 리소스 로딩
media . load()

요소(element)가 스크래치(scratch)로부터 새로운 미디어 리소스를 선택하고 로드하는 것을 재설정하고 시작하게 합니다.

모든 미디어 요소(element)들들 true 상태로 시작해야(must) 하는 autoplaying flag값과, false 상태로 시작해야(must) 하는 delaying-the-load-event flag를 가집니다. delaying-the-load-event flag가 true인 경우, 요소(element)는 요소(element)의 문서의 load 이벤트를 지연시켜야(must) 합니다.

미디어 요소(element)load() 메서드가 호출 되었을 때, 유저 에이전트는 미디어 요소(element) 로드 알고리즘을 수행해야(must) 합니다.

미디어 요소(element) 로드 알고리즘은 다음 단계들로 구성됩니다.

  1. 이 요소(element)에 대한 리소스 선택 알고리즘의 이미 실행 중인 인스턴스를 중단합니다.
  2. 작업 대기열들의 하나에 미디어 요소(element)미디어 요소(element) 이벤트 작업 소스로부터의 작업들이 있다면, 그 작업들을 제거합니다.

    기본적으로, 미디어 요소(element)가 새로운 리소스를 로딩하는 것을 시작하는 경우 미디어 요소(element)에 대해 보류 중인 이벤트들과 콜백들은 폐기 됩니다.

  3. 미디어 요소(element)networkStateNETWORK_LOADINGNETWORK_IDLE로 설정되었다면, 미디어 요소(element)abort라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣습니다.
  4. 미디어 요소(element)networkStateNETWORK_EMPTY로 설정되지 않았다면, 이 하위 단계들을 수행합니다:

    1. 미디어 요소(element)emptied라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣습니다.
    2. 가져오는(fetching) 프로세스가 미디어 요소(element)에 대한 프로세스 내에 있다면, 유저 에이전트는 그것을 멈추어야(should) 합니다.
    3. 미디어 요소(element)할당된 미디어 제공 객체MediaSource 객체라면, 그것을 분리시킵니다.
    4. 미디어 요소(element)의 미디어 리소스 별 트랙을 무시합니다..
    5. readyStateHAVE_NOTHING으로 설정되지 않았다면, 그 상태로 설정합니다.
    6. paused 속성(attribute)가 false라면, true로 설정합니다.
    7. seeking이 true라면, false로 설정합니다.
    8. 현재 재생 위치를 0으로 설정합니다.

      공식 재생 위치를 0으로 설정합니다.

      이것이 공식 재생 위치를 변경시킨다면, 미디어 요소(element)timeupdate이라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣습니다.

    9. 초기 재생 위치를 0로 설정합니다.
    10. 타임라인 오프셋을 Not-a-Number (NaN)로 설정합니다.
    11. duration 속성(attribute)을 to Not-a-Number (NaN)으로 업데이트합니다.

      유저 에이전트는 이 재생 시간의 특정한 변화에 대한 durationchange 이벤트를 발생시키지 않을 것입니다.

  5. playbackRate 속성(attribute)을 defaultPlaybackRate 속성(attribute)의 값으로 설정합니다.
  6. error 속성(attribute)을 null로 설정하고, 자동 재생 플래그를 true로 설정합니다.
  7. 미디어 요소(element)리소스 선택 알고리즘을 호출합니다.
  8. 이 요소(element)에 대해 모든 이전에 재생 중인 미디어 리소스의 재생을 중단시킵니다.

미디어 요소(element)에 대한 리소스 선택 알고리즘은 다음과 같습니다. 이 알고리즘은 항상 작업의 일부로 호출되지만, 알고리즘의 첫 번째 단계들의 것은 나머지 단계들을 반환하고 병렬로 계속 수행하기 위한 것입니다. 게다다, 이 알고리즘은 이벤트 루프 메커니즘과 밀접하게 상호작용합니다; 특히, 그것은 (이벤트 루프 알고리즘의 일부로 작동되는) 동기 섹션입니다. 그 섹션에서 단계들은 ⌛로 표기됩니다.

  1. 요소(element)의 networkState 속성(attribute)를 NETWORK_NO_SOURCE 값으로 설정합니다.
  2. 요소(element)의 포스터 표시 플래그를 true로 설정합니다.
  3. 미디어 요소(element)로드 이벤트 지연 플래그를 true로 설정합니다(이것은 로드 이벤트를 지연시킵니다).
  4. 이 알고리즘을 호출한 작업들이 계속되도록 허용하여, 병렬로 안정 상태를 기다립니다. 동기 섹션은 알고리즘이 동기 섹션이 끝났다고 알리기 전까지 모든 나머지 단계들로 구성됩니다(동기 섹션 내의 단계들은 ⌛로 표기됩니다).
  5. 미디어 요소(element)blocked-on-parser 플래그가 false라면, 보류 중인 텍스트 트랙들의 목록을 채웁니다.

  6. 미디어 요소(element)할당된 미디어 제공 객체를 가진다면, modeobject로 둡니다.

    ⌛ 그렇지 않고, 미디어 요소(element)할당된 미디어 제공 객체를 가지지 않지만 src 속성(attribute)를 가진다면, modeattribute로 둡니다.

    ⌛ 그렇지 않고, 미디어 요소(element)할당된 미디어 제공 객체를 가지지 않고, src 속성(attribute)를 가지지 않지만, 자식 source 요소(element)를 가진다면, modechildren로 두고 candidate트리 순서에 따라 그 첫 번째 자식 source 요소(element)로 둡니다.

    ⌛ 그렇지 않으면 미디어 요소(element)할당된 미디어 제공 객체를 가지지 않고 src 속성(attribute)이나 자식 source 요소(element)도 가지지 않습니다: networkStateNETWORK_EMPTY로 설정하고 이 단계들을 중단합니다; 동기 섹션이 종료됩니다.

  7. 미디어 요소(element)networkStateNETWORK_LOADING로 설정합니다.
  8. 미디어 요소(element)loadstart라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣습니다.
  9. 다음 목록에서 적절한 단계들을 수행합니다:

    modeobject라면
    1. currentSrc 속성(attribute)을 빈 문자열로 설정합니다.
    2. 병렬로 나머지 단계들을 계속하여, 동기 섹션을 종료합니다.
    3. 할당된 미디어 제공 객체를 가지고 리소스 페치(fetch) 알고리즘을 수행합니다. 그 알고리즘이 것을 중단하지 않고 반환한다면, 로드가 실패됩니다.
    4. Failed with media provider: 이 단계에 도달한다는 것은 미디어 리소스가 로드되는 것이 실패했다는 것을 나타냅니다. 전용 미디어 리소스 실패 단계들을 수행하기 위한 작업을 대기열에 넣습니다.
    5. 이전 단계에 의해 대기열에 넣어진 작업이 실행되기를 기다립니다.
    6. 이 단계들을 중단합니다. 이 알고리즘이 다시 작동될 때까지 요소(element)는 다른 리소스를 로드하는 것을 시도하지 않을 것입니다.
    modeattribute라면
    1. src 속성(attribute)의 값이 빈 문자열이라면, 동기 섹션을 종료하고 아래 failed with attribute 단계로 건너뜁니다.
    2. absolute URLsrc 속성(attribute)이 마지막으로 변경되었을 때 src 속성(attribute)의 값에 의해 명시된 URL미디어 요소(element)에 관련하여 해석하는 결과로 얻어지는 절대 URL로 둡니다.
    3. absolute URL이 성공적으로 얻어졌다면, currentSrc 속성(attribute)을 absolute URL로 설정합니다.
    4. 병렬로 나머지 단계들을 계속하여, 동기 섹션을 종료합니다.
    5. absolute URL이 성공적으로 얻어졌다면, absolute URL을 가지고 리소스 페치(fetch) 알고리즘을 수행합니다. 그 알고리즘이 것을 중단하지 않고 반환한다면, 로드는 실패됩니다.
    6. Failed with attribute: 이 단계에 도달한다는 것은 미디어 리소스가 로드되는 것이 실패했거나 주어진 URL분석(resolve) 될 수 없다는 것을 나타냅니다. 전용 미디어 리소스 실패 단계들을 수행하기 위한 작업을 대기열에 넣습니다.
    7. 이전 단계에 의해 대기열에 넣어진 작업이 실행되기를 기다립니다.
    8. 이 단계들을 중단합니다. 이 알고리즘이 다시 작동될 때까지 요소(element)는 다른 리소스를 로드하는 것을 시도하지 않을 것입니다.
    그렇지 않으면 (modechildren)
    1. pointer를 목록의 시작과 (목록 내 첫 번째 자식 이전에 있다면) 목록의 끝을 (목록 내 마지막 자식 이후에 있다면) 그들 자신의 노드들로 취급하는 미디어 요소(element)의 자식 목록 내의 두 인접한 노드들에 의해 정의된 위치로 둡니다. 한 노드는 pointer 앞의 노드이고, 다른 노드는 pointer 이후의 노드입니다. 초기에, pointercandidate 노드와 그 다음 노드가 있다면 그 노드와의 사이의 위치로, 혹은 그것이 마지막 노드라면 목록의 끝과의 사이의 위치로 둡니다.

      미디어 요소(element)노드들이 삽입되고 제거될 경우, pointer는 다음과 같이 업데이트 되어야(must) 합니다:

      새로운 노드가 pointer를 정의하는 두 노드들 사이에 삽입된다면
      pointerpointer 이전 노드와 새로운 노드 사이의 위치로 둡니다. 다시 말해, pointer에 삽입물들은 pointer 이후로 갑니다.
      pointer 이전의 노드가 제거된다면
      pointerpointer 이후 노드와 pointer 이후 노드 이전 노드 사이의 위치로 둡니다. 다시 말해, pointer는 나머지 노드들과 관련하여 이동하지 않습니다.
      pointer 이후 노드가 제거된다면
      pointerpointer 앞의 노드와 pointer 앞의 노드 이후 노드 사이 위치로 둡니다. 이전 경우와 마찬가지로, pointer는 나머지 노드들과 관련하여 이동하지 않습니다.

      다른 변경들은 pointer에 영향을 주지 않습니다.

    2. Process candidate: candidatesrc 속성(attribute)을 가지지 않거나, src 속성(attribute)의 값이 빈 문자열이라면, 동기 섹션을 종료하고, 아래 failed with elements 단계로 건너뜁니다.
    3. absolute URLsrc 속성(attribute)이 마지막으로 변경되었을 때 candidatesrc 속성(attribute)의 값에 의해 명시된 URLcandidate에 관련하여 해석하는 결과로 얻어지는 절대 URL로 둡니다.
    4. absolute URL이 성공적으로 얻어지지 않았다면, 동기 섹션을 종료하고 아래 failed with elements 단계로 건너뜁니다.
    5. candidate가, MIME 타입으로 해석 된 경우 유저 에이전트가 렌더링 할 수 없는 유형임을 나타내는 값을 가진 type 속성(attribute)을 가진다면, 동기 섹션을 종료하고 아래 failed with elements 단계로 건너 뜁니다.
    6. currentSrc 속성(attribute)을 absolute URL로 설정합니다.
    7. 병렬로 나머지 단계들을 계속하여, 동기 섹션을 종료합니다.
    8. absolute URL를 가지고 리소스 페치(fetch) 알고리즘을 수행합니다. 그 알고리즘이 것을 중단하지 않고 반환한다면 로드가 실패됩니다.
    9. Failed with elements: candidate 요소(element)에 error라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣습니다.
    10. 안정 상태를 기다립니다. 동기 섹션은 알고리즘이 동기 섹션이 종료되었다고 말할 때까지 이 알고리즘의 모든 나머지 단계들로 구성됩니다. (동기 섹션 내의 단계들은 ⌛로 표기됩니다.)
    11. 미디어 요소(element)의 미디어 리소스 별 트랙을 무시합니다.
    12. Find next candidate: candidate를 null로 둡니다.
    13. Search loop: pointer 이후 노드가 목록의 끝이라면, 아래 waiting 단계로 건너뜁니다.
    14. pointer 이후 노드가 source 요소(element)라면, candidate를 그 요소(element)로 둡니다.
    15. pointer 앞의 노드가 이제 pointer 이후인 노드이고 pointer 이후 노드는 pointer 이후에 사용되는 노드가 있다면 그 노드 이후 노드가 되도록 pointer를 전진시킵니다.
    16. candidate가 null이라면, search loop 단계로 건너뜁니다. 그렇지 않으면, process candidate 단계로 건너뜁니다.
    17. Waiting: 요소(element)의 networkState 속성(attribute)을 NETWORK_NO_SOURCE 값으로 설정합니다.
    18. ⌛ 요소(element)의 포스터 표시 플래그를 true로 설정합니다.
    19. ⌛ 요소(element)의 로드 이벤트 지연 플래그를 false로 설정하기 위한 작업을 대기열에 넣습니다. 이것은 로드 이벤트를 지연시키는 것을 중단합니다.
    20. 병렬로 나머지 단계들을 계속하여, 동기 섹션을 종료합니다.
    21. pointer 이후 노드가 목록의 끝이 아닌 노드가 될 때까지 기다립니다. (이 단계는 영원히 기다릴 수 있습니다.)
    22. 안정 상태를 기다립니다. 동기 섹션은 알고리즘이 동기 섹션이 종료되었다고 말할 때까지 이 알고리즘의 모든 나머지 단계들로 구성됩니다. (동기 섹션 내의 단계들은 ⌛로 표기됩니다.)
    23. ⌛ 요소(element)의 로드 이벤트 지연 플래그를 다시 true로 설정합니다 (아직 로드 이벤트가 발생되지 않은 경우, 이것은 다시 로드 이벤트를 지연시킵니다).
    24. networkState를 다시 NETWORK_LOADING로 설정합니다.
    25. ⌛ 아래 find next candidate 단계로 건너뜁니다.

    전용 미디어 리소스 실패 단계들은 다음 단계들입니다:

    1. error 속성(attribute)을 code 속성(attribute)이 MEDIA_ERR_SRC_NOT_SUPPORTED로 설정 된 새로운 MediaError 객체로 설정합니다.
    2. 미디어 요소(element)의 미디어 리소스 별 트랙을 무시합니다.
    3. 요소(element)의 networkState 속성(attribute)을 NETWORK_NO_SOURCE 값을 설정합니다.
    4. 요소(element)의 포스터 표시 플래그를 true로 설정합니다.
    5. 미디어 요소(element)error라는 단순 이벤트를 발생시킵니다.
    6. 요소(element)의 로드 이벤트 지연 플래그를 false로 설정합니다. 이것은 로드 이벤트를 지연시키는 것을 중단합니다.

미디어 요소(element)와 주어진 절대 URL이나 미디어 제공 객체에 대한 리소스 페치(fetch) 알고리즘은 다음과 같습니다:

  1. 알고리즘이 URL을 가지고 호출되었다면, moderemote로 두고, 그렇지 않으면 modelocal로 둡니다.
  2. moderemote라면, current media resource를 이 알고리즘에 전달된 절대 URL에 의해 주어진 리소스로 둡니다; 그렇지 않으면, current media resource미디어 제공 객체에 의해 주어진 리소스로 둡니다. 어느 쪽이든, current media resource는 이제 요소(element)의 미디어 리소스 입니다.
  3. 미디어 요소(element)보류 중인 텍스트 트랙들의 목록으로부터 모든 미디어 리소스 별 텍스트 트랙들을 제거합니다.
  4. 다음 목록에서 적절한 단계들을 수행합니다:

    mode가 remote라면
    1. 선택적으로, 다음 하위 단계들을 수행합니다. 이것은 사용자가 리소스를 명시적으로 요청할 때까지 유저 에이전트가 리소스를 가져오지 않으려는 경우 (예를 들어, preload 속성(attribute)의 none 키워드를 구현하는 방법으로) 예상되는 동작입니다.

      1. networkStateNETWORK_IDLE로 설정합니다.
      2. 요소(element)에 suspend라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣습니다.
      3. 요소(element)의 로드 이벤트 지연 플래그를 false로 설정하기 위한 작업을 대기열에 넣습니다. 이것은 로드 이벤트를 지연시키는 것을 중단합니다.
      4. 작업이 수행되기를 기다립니다.
      5. 구현 정의 이벤트를 (예를 들어, 사용자가 미디어 요소(element)가 재생을 시작하는 것을 요청하는 것) 기다립니다.
      6. 요소(element)의 로드 이벤트 지연 플래그를 다시 true로 설정합니다 (아직 로드 이벤트가 발생되지 않은 경우, 이것은 다시 로드 이벤트를 지연시킵니다).).
      7. networkStateNETWORK_LOADING로 설정합니다.
    2. requestcurrent media resource절대 URL미디어 요소(element)crossorigin 콘텐트 속성(attribute) 값이 주어진 potential-CORS 요청을 생성한 결과로 둡니다.

      request클라이언트미디어 요소(element)노드 문서Window 객체의 환경 설정 객체로 설정하고 type미디어 요소(element)audio 요소(element)라면 "audio"로 그렇지 않으면 "video"로 설정합니다.

      request가져옵니다.

      이 방법으로 얻어진 response의 안전하지 않은 응답이 있다면, 이 응답은 미디어 데이터를 포함합니다. 그것은 CORS-same-originCORS-cross-origin이 될 수 있습니다; 이것은 미디어 데이터에 참조된 자막(subtitle)들이 API에 노출되는지의 여부와, video 요소(element)들에 대해, 비디오가 canvas에 그려질 경우 canvas가 손상된 것을 얻는지 여부에 영향을 줍니다.

      stall timeout은 대략 3초가 되는 유저 에이전트가 정의한 시간의 길이입니다. 미디어 데이터를 얻기 위해 능동적으로 시도하는 미디어 요소(element)stall timeout과 동일한 기간 동안 어떤 데이터도 받는 것을 실패한 경우, 유저 에이전트는 요소(element)에 stalled라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣어야(must) 합니다.

      유저 에이전트들은 사용자들이 미디어 데이터 다운로드를 선택적으로 차단하거나 느리게 하는 것을 허용할 수 있습니다. 미디어 요소(element)의 다운로드가 완전히 차단되었을 경우, 유저 에이전트는 그것이 지연된 것처럼 (연결이 종료된 것 처럼 행동하는 것과 달리) 행동해야(must) 합니다. 다운로드의 속도는, 예를 들어 동일한 대역폭을 공유하는 다른 연결들과의 다운로드 균형을 위해, 유저 에이전트에 의해 자동으로 조절될 수도 있습니다.

      유저 에이전트들은 언제든지, 예를 들어, 한 시간 짜리 미디어 리소스의 5분 버퍼링 이후, 사용자가 리소스를 재생할지 말지를 결정하기를 기다리는 동안, 혹은 상호작용 리소스에 사용자가 입력을 기다리는 동안, 혹은 유저 에이전트가 다른 페이지로 이동하는 경우, 더 많은 콘텐트를 다운로드 하지 않기로 결정할 수 있습니다. 미디어 요소(element)의 다운로드가 연기된 경우, 유저 에이전트는 networkStateNETWORK_IDLE로 설정하고 요소(element)에 NETWORK_IDLE라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣어야(must) 합니다. 리소스의 다운로드가 재개되는 경우, 유저 에이전트는 networkStateNETWORK_LOADING로 설정하기 위한 작업을 대기열에 넣어야(must) 합니다. 이 작덥들의 대기열 사이에, 로드는 잠시 유예됩니다 (그래서 위에 기술된 대로, progress 이벤트는 발생하지 않습니다).

      preload 속성(attribute)은 autoplay 속성(attribute)이 없는 경우에도 작성자가 얼마나 많이 버퍼링하는 것이 바람직하다고 생각하는지에 관하여 힌트를 제공합니다.

      유저 에이전트가 다운로드를 완전히 유예시키기로 결정한 경우, 예를 들어 더 많은 콘텐트를 다운로드하기 전에 사용자가 재생을 시작하기까지 기다린다면, 유저 에이전트는 요소(element)의 로드 이벤트 지연 플래그를 false로 설정하기 위한 작업을 대기열에 넣어야(must) 합니다. 이것은 로드 이벤트를 지연시키는 것을 중단합니다.

      유저 에이전트는 리소스를 가져오는데 필요하게 되는 무엇이든 (이 명세와 다른 명세에 의해 제시된 제약 조건 내에서) 사용할 수 있습니다; 예를 들어, 네트워크 오류에 직면한 서버에 재접속하는 것이나, HTTP 범위 검색 요청들을 사용하는 것이나, 스트리밍 프로토콜로 전환하는 것. 유저 에이전트는 그것을 가져오는 것을 포기한 경우에만 리소스 오류를 고려해야(must) 합니다.

      미디어 리소스의 형식을 결정하기 위해, 유저 에이전트는 오디오와 비디오를 구체적으로 스니핑하기 위한 규칙들을 사용해야(must) 합니다.

      로드가 유예되지 않는 경우 (아래 참고), 매 350ms (±200ms)마다 혹은 수신 된 모든 바이트에 대해 어느 쪽이든 가장 적게 빈번하게 요소(element)에 progress라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣습니다.

      가져와지고 있는 데이터로서 데이터를 처리하기 위한 네트워킹 작업 소스 작업들은 각각 즉시 아래 미디어 데이터 처리 단계들 모록에서 첫 번째 적절한 단계들을 수행하기 위한 작업을 대기열에 넣어야(must) 합니다. (새로운 작업이 아래 기술된 작업이 네트워킹 작업 소스보다 미디어 요소(element) 이벤트 작업 소스에 관련하여 발생되기 위해 이것에 사용됩니다.)

      네트워킹 작업 소스미디어 리소스를 가져오는(fetch) 것의 일부로 마지막 작업대기열에 넣었을 때 (즉, 다운로드가 완료되면), 가져오는(fetch) 처리가 미디어 데이터를 디코딩하는 것을 포함하여 오류 없이 완료되고, 모든 데이터가 네트워크 접근 없이 유저 에이전트에 사용 가능하다면, 유저 에이전트는 아래 final step으로 이동해야(must) 합니다. 이것은, 웹 라디오 같은 무한 리소스를 스트리밍하는 경우나 리소스가 유저 에이전트의 데이터를 캐시하는 능력보다 길다면 절대로 발생하지 않을 수 있습니다.

      유저 에이전트가 미디어 리소스의 일부를 획득하기 위해 여전히 네트워크에 접속할 필요가 있는 경우, 유저 에이전트는 이 단계에 남아있어야(must) 합니다.

      예를 들어, 유저 에이전트가 동영상의 절반 전반부를 폐기했다면, 유저 에이전트는 사용자가 시작점으로 다시 탐색할 기회가 항상 있기 때문에 재생이 종료 된 때에도 이 단계에 남아있을 것입니다. 실제로, 앞서 설명한 것처럼, 유저 에이전트는 suspend 이벤트를 발생하게 될 것 입니다.

    그렇지 않으면 (modelocal이라면)

    current media resource로 기술된 리소스가 있다면 이것은 미디어 데이터를 포함합니다. 이것은 CORS-same-origin 입니다.

    current media resource가 원시 자료 스트림이라면 (예를 들어, File 객체로부터의), 미디어 리소스의 형식을 결정하기 위해, 유저 에이전트는 오디오와 비디오를 구체적으로 스니핑하기 위한 규칙들을 사용해야(must) 합니다. 그렇지 않고 데이터 스트림이 선-디코드(pre-decoded) 되었다면, 형식은 연관 명세에 의해 주어진 형식입니다.

    current media resource에 대한 새로운 데이터가 사용 가능해 질때마다, 아래 미디어 데이터 처리 단계 목록의 첫 적절한 단계들을 수행하기 위한 작업을 대기열에 넣습니다.

    current media resource가 영구적으로 고갈된 경우 (예를 들어, Blob의 모든 바이트가 처리된 경우), 디코딩 오류가 없다면, 유저 에이전트는 아래 final step로 이동해야(must) 합니다. 이것은 예를 들어, current media resourceMediaStream이라면 결코 발생하지 않습니다.

    미디어 데이터 처리 단계 목록은 다음과 같습니다:

    네트워크 오류로 인해, 유저 에이전트가 리소스를 가져 오기를 시도하는 것을 포기하게 하여, 미디어 데이터가 전혀 가져와(fetch) 질 수 없다면
    미디어 데이터가 가져와(fetch)질 수 있지만 검사에 의해 발견된 것이 지원되지 않는 형식이거나, 가져와(fetch)질 수 있지만 전혀 렌더링 될 수 없다면

    유저 에이전트가 current media resource가 사용 가능한지 수립하기 이전에 발생하는 DNS 오류들, HTTP 4xx와 5xx 오류들 (다른 프로토콜에서 동등한 것들), 그리고 다른 치명적인 네트워크 오류들은, 지원되지 않는 컨테이너 형식을 사용하거나, 모든 데이터에 대해 지원되지 않는 코덱을 사용하는 파일과 마찬가지로 유저 에이전트가 다음 단계들을 실행하도록 해야(must) 합니다:

    1. 유저 에이전트는 가져오는(fetch) 과정을 취소해야(should) 합니다.
    2. 리소스 선택 알고리즘으로 돌아가, 이 하위 알고리즘을 중단시킵니다.
    미디어 리소스가 오디오 트랙을 가지는 것이 발견된다면
    1. 오디오 트랙을 나타내기 위한 AudioTrack 객체를 생성합니다.
    2. 미디어 요소(element)audioTracks 속성(attribute)의 AudioTrackList객체를 새로운 AudioTrack 객체로 갱신합니다.
    3. enableunknown으로 둡니다.
    4. media resourcecurrent media resource의 주소가 활성화 할 특정 오디오 트랙들의 집합을 나타내거나, 유저 에이전트가 사용자의 경험을 향상시키기 위해 특정 오디오 트랙들의 선택을 용이하게 해주는 정보를 가진다면: 이 오디오 트랙이 활성화 할 것들 중 하나라면, enabletrue로 설정하고 그렇지 않으면 enablefalse로 설정합니다.

      이는 Media Fragments URI 조각 식별자 구문에 의해 동작될 수 있지만, 예를 들어, 유저 에이전트가 스테레오 오디오 트랙을 통해 5.1 서라운드 사운드 오디오 트랙을 선택함으로써 동작될 수도 있습니다. [MEDIA-FRAGS]

    5. enable이 여전히 unknown라면, 미디어 요소(element)가 활성화 된 오디오 트랙을 아직 가지지 않는다면 enabletrue로 설정하고 그렇지 않으면 enablefalse로 설정합니다.
    6. enabletrue라면, 이 오디오 트랙을 활성화시키고, 그렇지 않으면 이 오디오 트랙을 활성화 시키지 않습니다.
    7. AudioTrackList 객체에 새로운 AudioTrack 객체로 초기화 된 track 속성(attribute)을 가지는, 버블되지 않고 취소 가능하지 않으며 TrackEvent 인터페이스를 사용하는 addtrack이라는 이름을 가진 trusted 이벤트를 발생 시킵니다.
    미디어 리소스가 비디오 트랙을 가지는 것이 발견된다면
    1. 비디오 트랙을 나타내기 위한 VideoTrack 객체를 생성합니다.
    2. 미디어 요소(element)videoTracks 속성(attirbute)의 VideoTrackList 객체를 새로운 VideoTrackList 객체로 갱신합니다.
    3. enableunknown로 둡니다.
    4. 미디어 리소스current media resource의 주소가 활성화 할 특정 비디오 트랙들의 집합을 나타내거나, 유저 에이전트가 사용자의 경험을 향상시키기 위해 특정 비디오 트랙들의 선택을 용이하게 해주는 정보를 가진다면: 이 비디오 트랙이 첫 그 비디오 트랙이라면, enabletrue로 설정하고 그렇지 않으면 enablefalse로 설정합니다.

      이는 Media Fragments URI 조각 식별자 구문에 의해 동작될 수 있습니다.

    5. enable이 여전히 unknown이라면, 미디어 요소(element)가 아직 선택된 비디오 트랙을 가지지 않는다면 enabletrue로 설정하고 그렇지 않으면 enablefalse로 설정합니다.
    6. enabletrue라면, 이 트랙을 선택하고 이전에 선택된 다른 트랙들을 선택 해제 합니다. 그렇지 않으면 이 비디오 트랙을 선택하지 않습니다. 다른 트랙들이 선택 해제 되었다면, change 이벤트가 발생될 것입니다.
    7. VideoTrackList 객체에 새로운 VideoTrack 객체로 초기화 된 track 속성(attribute)을 가지는, 버블 되지 않고 취소 가능하지 않으며 TrackEvent 인터페이스를 사용하는 addtrack이라는 이름을 가진 trusted 이벤트를 발생 시킵니다.
    미디어 리소스의 시간, 치수, 다른 메타데이터들을 결정하기 위해 미디어 데이터가 충분히 가져와졌을 때

    이것은 리소스가 사용 가능하다는 것을 나타냅니다. 유저 에이전트는 이 하위 단계들을 따라야(must) 합니다:

    1. 미디어 데이터에 근거하여, 현재 재생 위치가장 빠른 가능한 위치의 목적을 위해 미디어 타임라인을 수립합니다.

    2. 이전 단계에서 수립된 미디어 타임라인의 제로 타임에 부합하는 날짜와 시간이 있다면 타임라인 오프셋을 그 일시로 갱신합니다. 미디어 리소스에 의해 주어진 명시적인 시간과 날짜가 없다면, 타임라인 오프셋은 NaN으로 설정되어야(must) 합니다.

    3. 현재 재생 위치공식 재생 위치가장 빠른 가능한 위치로 설정합니다.
    4. 위에서 수립된 미디어 타임라인에 리소스의 마지막 프레임의 시간이 알려져 있다면, duration 속성(attribute)을 그 시간으로 갱신합니다. 그것이 알려져 있지 않다면(예를 들어, 원칙적으로 무한대인 스트림) duration를 양의 무한대 값으로 갱신합니다.

      유저 에이전트는 이 지점에 요소(element)에 durationchange라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣을 것입니다.

    5. video 요소(element)들에 대해, videoWidthvideoHeight 속성(attribute)들을 설정하고, 미디어 요소(element)resize라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣습니다.

      게다가 이후에 치수가 변경된다면 resize 이벤트가 발생될 것입니다.

    6. readyState 속성(attribute)를 HAVE_METADATA로 설정합니다.

      loadedmetadata DOM 이벤트는 readyState 속성(attribute)을 새로운 값으로 설정하는 것의 일부로 발생될 것입니다.

    7. jumped를 false로 둡니다.
    8. 미디어 요소(element)기본 재생 시작 위치가 0보다 크면 그 시간으로 탐색하고, jumped를 true로 둡니다.
    9. 미디어 요소(element)기본 재생 시작 위치를 0으로 둡니다.
    10. initial playback position를 0으로 둡니다.
    11. 미디어 리소스current media resource의 주소가 특정 시작 시간을 나타낸다면, initial playback position을 그 시간으로 설정하고, jumped가 여전히 false라면 그 시간으로 탐색하고 jumped를 true로 둡니다.

      예를 들어, Media Fragments URI 조각 식별자 구문을 지원하는 미디어 형식들의 경우, 조각 식별자는 시작 위치를 타나내기 위해 사용될 수 있습니다. [MEDIA-FRAGS]

    12. 활성화 된 오디오 트랙이 없다면, 오티오 트랙을 활성화 합니다. 이것은 change 이벤트가 발생되는 것을 야기할 것입니다.
    13. 선택된 비디오 트랙이 업사면, 비디오 트랙을 선택합니다. 이것은 change이벤트가 발생되는 것을 야기할 것입니다.

    loadeddata 이벤트가 발생된 이후 readyState 속성(attribute)이 HAVE_CURRENT_DATA에 도달하자마자, 요소(element)의 로드 이벤트 지연 플래그를 false로 설정합니다. 이것은 로드 이벤트를 지연시키는 것을 중단시킵니다.

    미디어 리소스에 대해 메타데이터를 여전히 가져오는 동안 네트워크 사용량을 줄이기 위해 시도하고 있는 유저 에이전트는 또한 networkState 속성(attribute)을 NETWORK_IDLE 값으로 교체하고 suspend 이벤트를 발생시키는 이전에 기술된 규칙에 따라, 이 지점에서 버퍼링을 중단시킬 것입니다.

    유저 에이전트는 미디어 리소스의 재생 시간을 결정하고 재생 이전에 이 단계를 통과하도록 요구됩니다.

    전체 미디어 리소스가 가져와졌을(fetch) 때 (그러나 잠재적으로 어떤 것도 디코드 되기 전에)

    미디어 요소(element)progress라는 단순 이벤트를 발생시킵니다.

    networkStateNETWORK_IDLE로 설정하고 미디어 요소(element)suspend라는 단순 이벤트를 발생시킵니다.

    유저 에이전트가 미디어 데이터를 폐기하고 다시 가져오기 위해 네트워크 활동을 재개해야 할 필요가 있다면, 그것은 networkStateNETWORK_LOADING로 설정하기 위한 작업을 대기열에 넣어야(must) 합니다.

    유저 에이전트가 로드 된 미디어 리소스를 유지할 수 있다면, 알고리즘은 아래 알고리즘을 중단하는 Final step으로 계속할 것입니다.

    유저 에이전트가 리소스를 가져오기(fetch) 위해 시도하는 것을 포기하여, 연결이 일부 미디어 데이터가 수신된 이후 차단되었다면,

    유저 에이전트가 current media resource가 사용 가능한지 (즉, 미디어 요소(element)readyState 속성(attribute)이 더 이상 HAVE_NOTHING이 아닌) 여부가 결정된 이후에 발생하는 치명적 네트워크 오류는 유저 에이전트가 다음 단계들을 수행하도록 야기해야(must) 합니다:

    1. 유저 에이전트는 가져오는(fetch) 과정을 취소해야(should) 합니다.
    2. error 속성(attribute)을 code 속성(attribute)이 MEDIA_ERR_NETWORK로 설정된 새로운 MediaError 객체로 설정합니다.
    3. 요소(element)의 networkState 속성(attribute)을 NETWORK_IDLE 값으로 설정합니다.
    4. 요소(element)의 로드 이벤트 지연 플래그를 false로 설정합니다. 이것은 로드 이벤트를 지연시키는 것을 중단시킵니다.
    5. 미디어 요소(element)error라는 단순 이벤트를 발생시킵니다.
    6. 전체 리소스 선택 알고리즘을 중단시킵니다.
    미디어 데이터가 손상되었다면

    유저 에이전트가 current media resource가 사용 가능한지 (즉, 미디어 요소(element)readyState 속성(attriute)이 더 이상 HAVE_NOTHING이 아닌 때) 여부를 결정한 이후 발생하는 미디어 데이터 디코딩에서의 치명적인 오류는 유저 에이전트가 다음 단계들을 수행하는 것을 야기해야(must) 합니다:

    1. 유저 에이전트는 가져오는(fetch) 과정을 취소해야(should)합니다.
    2. error 속성(attribute)을 code 속성(attribute)이 MEDIA_ERR_DECODE로 설정 된 새로운 MediaError 객체로 설정합니다.
    3. 요소(element)의 networkState 속성(attribute)을 NETWORK_IDLE 값으로 설정합니다.
    4. 요소(element)의 로드 이벤트 지연 플래그를 false로 설정합니다. 이것은 로드 이벤트를 지연시키는 것을 중단시킵니다.
    5. 미디어 요소(eleemtn)error라는 단순 이벤트를 발생시킵니다.
    6. 전체 리소스 선택 알고리즘을 중단시킵니다.
    미디어 데이터를 가져오는(fetch) 과정이 사용자에 의해 중단되었다면

    예를 들어 사용자가 "stop" 버튼을 눌러서 가져오는 과정이 사용자에 의해 중단되었다면, 유저 에이전트는 다음 단계들을 실행해야(must) 합니다. 이 단계들은 특정 유형의 중단을 처리하므로, 이 단계들이 실행하는 동안 load() 메서드가 호출되는 경우에는 따르지 않습니다.

    1. 유저 에이전트는 가져오는(fetch) 과정을 취소해야(should) 합니다.
    2. error 속성(attribute)를 code 속성(attribute)이 MEDIA_ERR_ABORTED로 설정된 새로운 MediaError 객체로 설정합니다.
    3. 미디어 요소(element)abort라는 단순 이벤트를 발생시킵니다.
    4. 미디어 요소(element)readyState 속성(attribute)이 HAVE_NOTHING과 동일한 값을 가진다면, 요소(element)의 networkState 속성(attribute)을 NETWORK_EMPTY 값으로 설정하고, 요소(element)의 포스터 표시 플래그를 true로 설정하고, 요소(element)에 emptied라는 단순 이벤트를 발생시킵니다.

      그렇지 않으면, 요소(element)의 networkState 속성(attribute)를 NETWORK_IDLE 값으로 설정합니다.

    5. 요소(element)의 로드 이벤트 지연 플래그를 false로 설정합니다. 이것은 로드 이벤트를 지연시키는 것을 중단시킵니다.
    6. 전체 리소스 선택 알고리즘을 중단시킵니다.
    미디어 데이터가 가져와(fetch) 질 수 있지만 치명적이지 않은 오류가 있거나 부분적으로 유저 에이전트가 모든 재생을 막지 않지만 콘텐트를 완전히 올바르게 렌더링하는 것을 막는 지원되지 않는 코덱을 사용한다면

    부분적으로 사용 가능 하지만 최적으로 렌더링 될 수 없는 렌더링 데이터를 반환하는 서버는 유저 에이전트가 딱 처리 가능한 비트를 렌더링하고 나머지를 무시하도록 야기해야 합니다.

    미디어 리소스가 유저 에이전트가 지원하는 미디어 리소스 별 텍스트 트랙을 선언하는 것이 발견된다면

    미디어 데이터CORS-same-origin이라면, 관련된 데이터를 가지고 미디어 리소스 별 텍스트 트랙을 노출시키기 위한 단계들을 수행합니다.

    Cross-origin 비디오들은 사용자의 인트라넷에서 기밀 비디오로부터 자막(subtitle)들을 읽는 적대적인 사이트들 같은 공격을 허용할 수 있기 때문에 자막(subtitle)들을 노출하지 않습니다.

  5. Final step: 유저 에이전트가 언제든 이 단계에 도달한다면 (전체 리소스가 적재되고 사용 가능하게 유지되는 경우에만 일어날 수 있는): 전체 리소스 선택 알고리즘을 중단시킵니다.

미디어 요소(element)미디어 요소(element)의 미디어 리소스 별 트랙들을 무시하는 경우, 유저 에이전트는 미디어 요소(element)텍스트 트랙들 목록으로부터 모든 미디어 리소스 별 텍스트 트랙들을 제거한 후, 미디어 요소(element)audioTracks 속성(attribute)의 AudioTrackList 객체를 비우고, 미디어 요소(element)videoTracks 속성(attribute)의 VideoTrackList 객체를 비워야(must) 합니다. 이것의 일부로 어떤 이벤트도 (특히, removetrack 이벤트들도) 발생되지 않습니다; 이것을 호출하는 알고리즘들에 의해 발생 된 erroremptied 이벤트들이 대신 사용될 수 있습니다.


preload 속성(attribute)은 열거 속성(attribute)입니다. 다은 표는 속성(attribute)에 대한 키워드와 상태를 나열합니다 — 왼쪽 열에 있는 키워드들은 키워드와 동일한 행의 두 번째 열에 있는 셀의 상태들에 대응됩니다. 속성(attribute)은 미디어 리소스가 버퍼되거나 재생되는 때조차도 변경될 수 있습니다; 아래 표의 설명은 이 점에 유의하여 이해되어야 합니다.

키워드 상태 간단한 설명
none None 유저 에이전트에게 작성자가 사용자가 미디어 리소스를 요구할 것으로 기대하지 않거나, 서버가 불필요한 트래픽을 최소화 하기를 원한다는 힌트를 줍니다. 이 상태는 어떻게든 버퍼링이 시작된다면 (예를 들어, 사용자가 "재생"을 누를 때) 미디어 리소스를 실제로 적극적으로 다운로드하는 방법에 관한 힌트를 제공하지 않습니다.
metadata Metadata 유저 에이전트에게 작성자가 사용자가 미디어 리소스를 필요로 할 것이라고 기대하지 않지만, 리소스 메타데이터(치수, 트랙 목록, 재생 시간 등)와 어쩌면 첫 약간의 프레임들을 가져오는(fetch) 것이 타당하다는 힌트를 줍니다. 유저 에이전트가 정확히 더 이상의 메타데이터를 가져오지 않으면, 미디어 요소(element)readyState 속성(attribute)을 HAVE_METADATA로 설정하는 결과를 가져올 것입니다; 하지만 일반적으로, 몇 프레임들은 잘 얻어질 것이고 그것은 HAVE_CURRENT_DATAHAVE_FUTURE_DATA일것입니다. 미디어 리소스가 재생 중인 경우, 유저 에이전트에게 대역폭이 부족한 것이 고려되어야 한다는 힌트를, 예를 들어, 미디어 데이터가 가능한 일관된 재생을 여전히 유지하는 가장 느린 속도에서 얻어질 수 있기 때문에 다운로드를 조절하도록 제안하는 것, 줍니다.
auto Automatic 유저 에이전트에게 전체 리소스를 긍적적으로 다운로드하는 것을 포함하여, 유저 에이전트가 서버에 위험을 주지 않고 사용자의 요구를 먼저 줄 수 있다는 힌트를 줍니다.

빈 문자열도 유효한 키워드이고, Automatic 상태에 대응됩니다. Metadata 상태는 서버 부하를 낮추는 것과 최적의 사용자 경험을 제공하는 것 사이의 절충으로 제시되기는 하지만, 속성(attribute)의 누락 기본 값은 유저 에이전트가 정의한 값입니다.

작성자들은 사용자가 재생을 시작할 때 속성(attribute)을 "none"나 "metadata"로부터 "auto"로 동적으로 교체할 수 있습니다. 예를 들어, 많은 비디오가 있는 페이지에서 이것은 많은 비디오들이 요청되지 않는 한 다운로드 되지 않아야 하지만, 요청 면 적극적으로 다운로드 되어야 하는 것임을 나타내기 위해 사용될 수 있습니다.

preload 속성(attribute)은 유저 에이전트에게 작성자가 최고의 사용자 경험으로 이어질 것으로 생각하는 것이 무엇인지에 대한 힌트를 제공하도록 의도된 것입니다. 속성(attribute)은, 예를 들어 명시적인 사용자 환경 기반에서 혹은 사용 가능한 연결 기반에서, 완전히 무시될 수 있습니다.

preload IDL 속성(attribute)은 알려진 값들로만 제한 된, 동일한 이름의 콘텐트 속성을 반영해야(must) 합니다.

autoplay 속성(attribute)은 preload 속성(attribute)을 재정의 할 수 있습니다 (미디어가 재생되면, preload 속성(attribute)에 주어진 힌트에 상관없이 자연적으로 우선 버퍼링해야 할 필요가 있기 때문에). 그러나, 둘 모두를 포함하는 것은 오류가 아닙니다.


media . buffered

유저 에이전트가 버퍼링 한 미디어 리소스의 범위를 나타내는 TimeRanges 객체를 반환합니다.

buffered 속성(attribute)은 속성(attribute)이 평가되는 시점에 유저 에이전트가 버퍼링한 미디어 리소스의 범위를 나타내는 새로운 정적 정규화 된 TimeRanges 객체를 반환해야(must) 합니다. 유저 에이전트들은 지루한 검사에 의해서만 결정될 수 있는 미디어 스트림들에 대해 조차, 사용 가능한 범위를 정확히 결정해야(must) 합니다.

일반적으로 이것은 영점에 놓인 하나의 범위 일 것이지만, 만약 예를 들어, 유저 에이전트가 탐색(seek)에 대한 응답으로 HTTP 범위 요청을 사용한다면, 여러 범위들이 있을 수 있습니다.

유저 에이전트들은 이전에 버퍼링 된 데이터를 폐기할 수 있습니다.

따라서, 한번에 buffered 속성(attribute)에 의해 반환되는 객체들의 범위들에 포함된 시간 위치는 나중에 동일한 속성(attribute)에 의해 반환 된 객체들의 범위(들)에 포함되지 않게 될 수 있습니다.

4.7.14.6. 미디어 리소스에 대한 오프셋
media . duration

미디어 리소스의 시작 시간이 0이라고 가정하여, 미디어 리소스의 길이를 초단위로 반환합니다.

재생 시간이 사용 가능하지 않다면 NaN을 반환합니다.

무한한 스트림에 대해 Infinity를 반환합니다.

media . currentTime [ = value ]

공식 재생 위치를 초 단위로 반환합니다.

주어진 시간으로 탐색(seek)하기 위해 설정될 수 있습니다.

미디어 리소스미디어 리소스의 위치에 대응하는 시간(초)인 미디어 타임라인을 가집니다. 타임라인의 원점은 가장 초기에 정의된 위치입니다. 타임라인의 재생 시간은 마지막 정의된 위치입니다.

미디어 타임라인 수립하기: 미디어 리소스가 어떻게든 원점이 음수가 아닌 명시적인 타임라인을 명시한다면 (즉, 각 프레임에 특정 시간 오프셋을 제공하고 첫 번째 프레임에 0이나 양의 오프셋을 제공), 미디어 타임라인 그 타임라인이 되어야(should) 합니다. (미디어 리소스가 타임라인을 명시할 수 있는지 아닌지의 여부는 미디어 리소스의 형식에 달려있지 않습니다.) 미디어 리소스가 명시적인 시작 시간과 날짜를 명시한다면, 그 시간과 날짜는 미디어 타임라인에서 영점으로 간주되어야(should) 합니다; 타임라인 오프셋getStartDate() 메서드를 사용하여 노출된 시간과 날짜일 것입니다.

미디어 리소스가 불연속적인 타임라인을 가진다면, 유저 에이전트는 전체 리소스에 걸쳐 리소스의 시작에 사용된 타임라인을 확장해야 하기 때문에, 미디어 데이터가 정리되지 않거나 겹치는 타임 코드를 가지는 경우라도, 미디어 리소스미디어 타임라인은 (아래 설명된 대로) 가장 빠른 가능한 위치로부터 시작하여 선형적으로 증가시킵니다.

예를 들어, 두 개의 클립이 하나의 파일로 연결되어 있지만, 비디오 형식이 두 클립에 대해 최초 시간을 노출한다면, 비디오 데이터는 진행되는 타임라인을 노출할 것입니다, 예를 들어, 00:15..00:29 그리고 그 후 00:05..00:38. 그러나, 유저 에이전트는 그 시간을 노출하지 않을 것입니다; 그것은 단일 비디오로서 00:15..00:29와 00:29..01:02의 시간을 대신 노출할 것입니다.

명시적인 타임라인이 없는 미디어 리소스의 드문 경우, 미디어 타임라인에서 제로 타임은 미디어 리소스의 첫 번째 프레임과 일치해야(should) 합니다. 어떤 종류의 명시적인 타이밍도 없고 심지어 프레임 재생 시간도 없는 미디어 리소스의 더욱 드문 경우, 유저 에이전트는 유저 에이전트가 정의한 방식으로 각 프레임에 대한 시간을 스스로 결정해야(must) 합니다. (이것은 지문 그림입니다.)

명시적인 타임라인은 없지만 명시적인 프레임 재생 시간이 있는 파일 형태의 예로 GIF 형식이 있습니다. 전혀 명시적 타이밍이 없는 파일 형식의 예로는 JPEG-push 형식이 (MJPEG 스트림에 대한 형식으로 종종 사용되는, JPGE 프레임들을 가진 multipart/x-mixed-replace) 있습니다.

타이밍 정보가 없는 리소스의 경우, 유저 에이전트가 서버에 의해 제공된 본래의 첫 프레임보다 빠른 지점으로 탐색할 수 있다 하더라도, 제로 타임은 미디어 리소스의 가장 빠른 탐색 가능한 시간과 일치해야(should) 합니다; 그렇지 않으면, 서버로부터 수신된 첫 번째 프레임에 (유저 에이전트가 스트림을 수신하기 시작하는 미디어 리소스의 지점) 일치해야(should) 합니다.

글을 쓰는 시점에서, 서버에 의해 보내진 첫 번째 프레임 이전의 프레임으로 탐색(seek)하는 것을 여전히 지원하는 명시적 프레임 시간 오프셋이 부족한 알려진 형식은 없습니다.

10월의 화창한 금요일 오후 스트리밍을 시작하는 TV 방송사의 스트림과, 연결된 유저 에이전트에게 항상 동일한 미디어 타임라인에 미디어 테이터를 이 스트림의 시작으로 설정된 제로 타임과 함께 전송한다고 가정해보세요. 수 개월 후, 이 스트림에 연결하는 유저 에이전트는 수신하는 첫 번째 프레임에 수백만 초의 시간이 있음을 발견하게 될 것입니다. getStartDate() 메서드는 항상 방송이 시작된 날짜를 반환할 것입니다; 이는 컨트롤러들이 방송이 시작된 때와 ("8개월 4시간 12분 23초") 관련된 시간 보다 그들의 스크러버의 실제 시간을 (예를 들어 "2:30pm") 노출하는 것을 허용할 것입니다.

유저 에이전트가 특정 시간을 요청하는 것을 허용하지 않는 대신 항상 제로 타임을 가진 프레임으로 식별되는 전달 된 첫 번째 프레임과 함께, 미리 정해진 순서에 따라 비디오 데이터를 스트림하는 서버에 의해 여러 조각과 방송들이 연결된 비디오를 전달하는 스트림을 고려해보세요. 유저 에이전트가 이 스트림에 연결하고 2010-03-20 23:15:00 UTC부터 2010-03-21 00:05:00 UTC까지와 2010-02-12 14:25:00 UTC부터 2010-02-12 14:35:00 UTC까지의 타임스탬프들을 포함하는 정의된 조각들을 수신한다면, 0초에 시작하여 3,600초 (1 시간)으로 확장하는 미디어 타임라인으로 노출할 것입니다. 두 번째 클립의 종료 시점에 스트리밍 서버가 연결이 끊긴다고 가정하면, 재생 시간 속성(attribute)은 3,600을 반환할 것입니다. getStartDate() 메서드는 2010-03-20 23:15:00 UTC에 해당하는 시간을 가진 Date 객체를 반환할 것입니다. 그러나, 다른 유저 에이전트가 5분 뒤에 연결된다면, 그것은 (아마도) 2010-03-20 23:20:00 UTC부터 2010-03-21 00:05:00 UTC까지 그리고 2010-02-12 14:25:00 UTC부터 2010-02-12 14:35:00 UTC까지의 타임스탬프들을 포함하는 조각들을 수신할 것이고, 0초에서 시작하여 3,300초(55분)으로 확장하는 미디어 타임라인으로 이것을 노출할 것입니다. 이 경우, getStartDate() 메서드는 2010-03-20 23:20:00 UTC에 해당하는 시간을 가진 Date 객체를 반환할 것입니다.

이 예 모두에서, seekable 속성(attribute)은 컨트롤러가 그것의 UI에 실제로 표시하려는 범위를 제공할 것입니다; 일반적으로, 서버가 임의의 시간으로 탐색(seek)하는 것을 지원하지 않는다면, 이것은 유저 에이전트가 스트림에 연결한 순간부터 유저 에이전트가 얻은 최신 프레임까지의 시간 범위가 될 것입니다; 그러나 유저 에이전트가 이전 정보를 폐기하기 시작하면, 실제 범위는 더 짧아질 수 있습니다.

어떤 경우에도 유저 에이전트는 수립된 미디어 타임라인을 사용하여 (아래 정의된 대로) 가장 빠른 가능한 위치가 0보다 크거나 같은지 확인해야(must) 합니다.

미디어 타임라인은 또한 연관된 시계를 가집니다. 사용되는 시계는 유저 에이전트에 의해 정의된 것이며, 미디어 리소스에 따라 다르지만, 사용자의 벽시계에 비슷해야(should) 합니다.

미디오 요소(element)들현재 재생 위치를 가지며, 이 위치는 초기에 (즉, 미디어 데이터가 없을 때) 0초여야(must) 합니다. 현재 재생 위치미디어 타임라인 상의 시간입니다.

미디어 요소(element)들은 또한 공식 재생 위치를 가지고, 이는 초기에 0초로 설정되어야(must) 합니다. 공식 재생 위치는 스크립트들이 실행되는 동안 안정적으로 유지되는 현재 재생 위치의 근사치입니다.

미디어 요소(element)들은 또한 기본 재생 시작 위치를 가지고, 이 위치는 초기에 0초로 설정되어야(must) 합니다. 이 시간은 요소(element)가 미디어가 로드되기 전에 탐색(seek)되는 것을 허용하는데 사용됩니다.

미디어 요소(element)포스터 표시 플래그를 가집니다. 미디어 요소(element)가 생성될 때, 이 플래그는 true로 설정되어야(must) 합니다. 이 플래그는 유저 에이전트가 비디오 콘텐츠를 표시하는 대신 video 요소(element)에 대한 포스터 프레임을 표시하는 때를 제어하는데 사용됩니다.

설정 할 때, 미디어 요소가 현재 미디어 컨트롤러를 가진다면, 유저 에이전트는 InvalidStateError 예외를 던져야 합니다; 그렇지 않고, 미디어 요소의 readyState가 HAVE_NOTHING라면, 미디어 요소의 기본 재생 시작 위치를 새로운 값으로 설정해야 합니다; 그렇지 않으면, 공식 재생 위치를 새로운 값으로 설정하고 그 뒤 새로운 값으로 탐색해야 합니다. 새로운 값은 초 단위로 해석되어야 합니다. 설정 할 때, 미디어 요소(element)readyStateHAVE_NOTHING라면, 미디어 요소(element)기본 재생 시작 위치를 새로운 값으로 설정해야(must) 합니다; 그렇지 않으면, 공식 재생 위치를 새로운 값으로 설정하고 새로운 값으로 탐색(seek) 시켜야(must) 합니다. 새로운 값은 초 단위로 해석 되어야(must) 합니다.

미디어 요소(element)들초기 재생 위치를 가지며, 이는 초기에 (즉, 미디어 데이터가 없을 때) 0초 이어야 (must) 합니다. 초기 재생 위치미디어 리소스가 로드될 때 갱신 됩니다. 초기 재생 위치미디어 타임라인 상의 시간입니다.

미디어 리소스가 스트리밍 리소스라면, 유저 에이전트는 그것의 버퍼로부터 만료된 이후 리소스의 특정한 부분을 얻어오는 것은 불가능할 수 있습니다. 마찬가지로, 어떤 미디어 리소스들은 0에서 시작하지 않는 미디어 타임라인을 가질 수 있습니다. 가장 빠른 가능한 위치는 유저 에이전트가 다시 얻을 수 있는 스트림이나 리소스에서 가장 빠른 위치입니다. 그것 또한 미디어 타임라인 상의 시간입니다.

가장 빠른 가능한 위치는 API에 명시적으로 노출되지 않습니다; 그것은 seekable 속성(attribute)의 TimeRanges 객체의 첫 번째 범위의 시작 시간이 있다면 그 시간에 일치하고 그렇지 않으면 현재 재생 위치에 일치합니다.

가장 빠른 가능한 위치가 변경되는 경우, 현재 재생 위치가장 빠른 가능한 위치 이전이라면, 유저 에이전트는 가장 빠른 가능한 위치탐색(seek)해야(must) 합니다; 그렇지 않고 유저 에이전트가 지난 15 ~ 250ms 동안 요소(element)에서 timeupdate 이벤트가 발생하지 않았고 여전히 그 이벤트에 대한 이벤트 핸들러가 수행 중이 아니라면, 유저 에이전트는 요소(element)에 timeupdate라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣어야(must) 합니다.

위 요구사항과 클립의 메타데이터가 알려지는 경우 효과가 나타나기 시작하는 리소스 페치(fetch) 알고리즘의 요구사항 때문에, 현재 재생 위치가장 빠른 가능한 위치보다 결코 작을 수 없습니다.

언제라도 유저 에이전트가 오디오나 비디오 트랙이 종료되고 모든 그 트랙에 관련된 미디어 데이터가장 빠른 가능한 위치 이전미디어 타임라인의 일부에 일치하는 것을 알게된다면, 유저 에이전트는 먼저 audioTracks 속성(attribute)의 AudioTrackList 객체나 videoTracks 속성(attribute)의 VideoTrackList 객체로부터 적절한 트랙을 제거하고 미디어 요소(element)의 앞서 언급된 AudioTrackListVideoTrackList 객체에 트랙을 나타내는 AudioTrackVideoTrack으로 초기화 된 track 속성(attribute)를 가진 버블되지 않고 취소 불가능며 TrackEvent 인터페이스를 사용하는 removetrack라는 신뢰 되는 이벤트를 발생시키기 위한 작업을 대기열에 넣을 수 있습니다.

duration 속성(attribute)은 미디어 타임라인 상의 미디어 리소스의 끝 시간을 초 단위로 반환해야(must) 합니다. 어떤 미디어 데이터도 사용 가능하지 않다면, 속성(attribute)들은 Not-a-Number (NaN) 값을 반환해야(must) 합니다. 미디어 리소스가 한계가 있는 것으로 알려져있지 않다면 (예를 들어, 스트리밍 라디오나, 알려진 종료 시간이 없는 라이브 이벤트), 속성(attribute)은 양의 Infinity 값을 반환해야(must) 합니다.

유저 에이전트는 그렇게 하는 것이 리소스의 여러 부분을 가져오는 것을 요구함에도 불구하고, 미디어 데이터의 일부를 재생하기 이전에 그리고 readyStateHAVE_METADATA보다 크거나 같은 값으로 설정하기 이전에 미디어 리소스의 재생 시간을 결정해야(must) 합니다.

미디어 리소스의 길이가 알려진 값으로 (예를 들어, 알 수 없는 값에서 알려진 값으로, 혹은 이전에 수립된 길이에서 새로운 길이로) 변경되는 경우, 유저 에이전트는 미디어 요소(element)durationchange라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣어야(must) 합니다. (재생 시간이 새로운 미디어 리소스를 로딩하여 재설정 되는 경우 이벤트는 발생하지 않습니다.) 재생 시간이 현재 재생 위치미디어 리소스의 끝 시간보다 크게 변경된다면, 유저 에이전트는 미디어 리소스의 끝 시간으로 탐색(seek)해야(must) 합니다.

어떤 이유로 "무한" 스트림이 종료된다면, 재생 시간은 양의 Infinity에서 스트림의 마지막 프레임이나 샘플의 시간으로 변경될 것이고, durationchange 이벤트가 발생될 것입니다. 마찬가지로, 유저 에이전트가 초기에 정확하게 결정하는 대신 미디어 리소스의 재생 시간을 추정했고 나중에 새로운 정보를 기반으로 추정치를 수정한다면, 재생 시간은 변경되고 durationchange 이벤트가 발생될 것입니다.

일부 비디오 파일들은 또한 타임라인 오프셋으로 알려진 미디어 타임라인의 제로 타임에 일치하는 명시적인 날짜와 시간을 가집니다. 초기에, 타임라인 오프셋은 Not-a-Number (NaN)으로 설정되어야(must) 합니다.

getStartDate() 메서드는 현재 타임라인 오프셋을 나타내는 새로운 Date 객체를 반환해야(must) 합니다.


loop 속성(attribute)은 명시되었다면 미디어 요소(element)가 끝에 도달하면 미디어 리소스의 처음으로 다시 탐색(seek)한다는 것을 나타내는 불리언 속성(attribute)입니다.

loop IDL 속성(attribute)은 동일한 이름의 콘텐트 속성(attribute)을 반영해야(must) 합니다.

4.7.14.7. 준비 상태들
media . readyState

아래 목록의 코드들로부터, 현재 재생 위치 렌더링과 관련하여 요소(element)의 현재 상태를 나타내는 값을 반환합니다.

미디어 요소(element)들준비 상태를 가지며 이는 현재 재생 위치에서 렌더링 할 준비가 되어 있는 정도를 설명합니다. 가능한 값들은 다음과 같습니다; 특정 시간에서 미디어 요소(element)의 준비 상태는 요소(element)의 상태를 설명하는 최대 값입니다:

HAVE_NOTHING (숫자 값 0)
미디어 리소스에 관한 어떤 정보도 사용 가능하지 않습니다. 현재 재생 위치에 대한 어떤 데이터도 사용가능하지 않습니다. networkState 속성(attribute)이 NETWORK_EMPTY로 설정 된 미디어 요소(element)들은 항상 HAVE_NOTHING 상태 입니다.
HAVE_METADATA (숫자 값 1)
리소스의 재생 시간이 사용 가능한 충분한 리소스가 확보되었습니다. video 요소(element)의 경우 비디오의 치수도 사용 가능합니다. 가장 가까운 현재 재생 위치에 대해 사용할 수 있는 미디어 데이터가 없습니다.
HAVE_CURRENT_DATA (숫자 값 2)
가장 가까운 현재 재생 위치에 대한 데이터가 사용 가능하지만, 유저 에이전트가 즉시 HAVE_METADATA 상태로 복귀하지 않고 성공적으로 재생 방향으로 현재 재생 위치를 전진 시킬 수 있을 만큼 전혀 충분한 데이터가 사용 가능하지 않거나, 재생 방향으로 얻을 데이터가 더 없습니다. 예를 들어, 비디오에서 이것은 현재 재생 위치가 현재 프레임의 끝에 있을 때 다음 프레임이 아닌 현재 프레임으로부터; 그리고 재생이 종료 되었을 때 까지의 데이터를 가지는 유저 에이전트에 해당합니다.
HAVE_FUTURE_DATA (숫자 값 3)
가장 가까운 현재 재생 위치에 대한 데이터가 사용 가능할 뿐 아니라 유저 에이전트가 HAVE_METADATA 상태로 즉시 복귀하지 않고 적어도 조금이라도 재생 방향으로 현재 재생 위치를 재생시키기에 충분한 데이터가 사용 가능하며, 텍스트 트랙들이 준비됩니다. 예를 들어, 비디오에서 이것은 현재 재생 위치가 두 프레임 사이의 순간에 있을 때 적어도 현재 프레임과 다음 프레임에 대한 데이터를 가지는 유저 에이전트나 또는 현재 재생 위치가 프레임의 중간에 있을 때 적어도 조금이라도 재생을 유지하도록 현재 프레임과 오디오 데이터에 대한 비디오 데이터를 가지는 유저 에이전트에 해당합니다. 재생이 종료된다면, 이 경우에 현재 재생 위치는 결코 전진할 수 없기 때문에 유저 에이저트는 이 상태에 있을 수 없습니다.
HAVE_ENOUGH_DATA (숫자 값 4)

HAVE_FUTURE_DATA 상태에 대해 설명된 모든 조건들이 충족되고, 게다가 다음 조건들 중 하나라도 충족됩니다:

  • 유저 에이전트는 현재 재생 위치유효 재생 속도에서 진행된다면 재생이 미디어 리소스의 끝에 도달하기 이전에 사용 가능한 데이터를 추월하지 않을 속도로 데이터가 가져와지는(fetch) 것으로 추정합니다.
  • 유저 에이전트가 오래 대기한다고 해서 더 많은 데이터를 얻지 못하는 상태가 되었고, 따라서 더 이상 재생을 지연시켜도 아무 것도 없을 수 없을 것입니다. (예를 들어, 버퍼가 가득 찼을 수 있습니다.)

실제로, HAVE_METADATAHAVE_CURRENT_DATA의 차이는 무시해도 될 정도입니다. 실제로 차이가 관련되는 유일한 시기는 canvasvideo 요소(element)를 그릴 때이며, 아무것도 그려지지 않은 경우에서 (HAVE_METADATA나 그 이하) 무언가가 그려지는 경우를 (code>HAVE_CURRENT_DATA나 그 이상) 구분합니다. 마찬가지로, HAVE_CURRENT_DATA(현재 프레임만)와 HAVE_FUTURE_DATA(적어도 이 프레임과 다음 프레임) 사이의 차이는 무시해도 될 정도일 수 있습니다 (극단적으로 한 프레임 만). 구별이 정말로 중요한 유일한 시기는 페이지가 "프레임 단위" 탐색을 위한 인터페이스를 제공하는 경우입니다.

networkStateNETWORK_EMPTY가 아닌 미디어 요소(element)의 준비 상태가 변경되는 경우, 유저 에이전트는 아래 주어진 단계들을 따라야(must) 합니다:

  1. 다음 목록에서 첫 번째 적용 가능한 하위 단계 세트를 적용합니다:

    이전 준비 상태가 HAVE_NOTHING였고, 새로운 준비 상태가 HAVE_METADATA이라면

    요소(element)에 loadedmetadata라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣습니다.

    이 작업이 수행되기 전, 이벤트 반복 메커니즘의 일부로서, 적절하다면 렌더링은 video 요소(element)의 크기를 조정하도록 업데이트 될 것입니다.

    이전 준비 상태가 HAVE_METADATA였고 새로운 준비 상태가 HAVE_CURRENT_DATA나 그 이상이라면

    load() 알고리즘이 마지막으로 호출 된 이후 이 미디어 요소(element)에 대해 이것이 발생한 것이 처음이라면, 유저 에이전트는 요소(element)에 loadeddata라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣어야(must) 합니다.

    새로운 준비 상태가 HAVE_FUTURE_DATAHAVE_ENOUGH_DATA라면, 아래 관련 단계들도 수행 되어야(must) 합니다.

    이전 준비 상태가 HAVE_FUTURE_DATA나 그 이상이었고, 새로운 준비 상태가 HAVE_CURRENT_DATA나 그 이하라면

    미디어 요소(element)readyState 속성(attribute)이 HAVE_FUTURE_DATA 보다 낮은 값으로 변경되기 전에 재생 중 일 수 있었고, 요소(element)가 재생을 종료하지 않았으며, 재생이 오류로 인해 중지되지 않았거나 유저 인터렉션을 위해 일시 중지되지 않았거나 대역 내 콘텐트에 대해 일시 중지되지 않았다면, 유저 에이전트는 요소(element)에 timeupdate라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣어야(must) 하고, 요소(element)에 waiting라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣어야(must) 합니다.

    이전 준비 상태가 HAVE_CURRENT_DATA나 그 이하였고, 새로운 준비 상태가 HAVE_FUTURE_DATA라면

    유저 에이전트는 요소(element)에 canplay라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣어야(must) 합니다.

    요소(element)의 paused 속성(attribute)가 false라면, 유저 에이전트는 요소(element)에 playing이라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣어야(must) 합니다.

    새로운 준비 상태가 HAVE_ENOUGH_DATA라면

    이전 준비 상태가 HAVE_CURRENT_DATA나 그 이하였다면, 유저 에이전트는 요소(element)에 canplay라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣어야(must) 하고, 요소(element)의 paused 속성(attribute)이 false라면, 요소(element)에 playing이라는 단순 이벤트를 발생 시키기 위한 작업을 대기열에 넣어야(must) 합니다.

    자동 재생 플래그가 true이고 paused 속성(attribute)가 true이며, 미디어 요소(element)가 명시된 autoplay 속성(attribute)을 가지고, 미디어 요소(element)노드 문서활성화 샌드박싱 플래그 설정샌드박스 된 자동 기능 브라우징 컨텍스트 플래그 설정를 가지지 않으면, 유저 에이전트는 다음 하위 단계들을 수행할 수도 있습니다:

    1. paused 속성(attribute)을 false로 설정합니다.
    2. 요소(element)의 포스터 표시 플래그가 true라면, false로 설정하고 time marches on 단계들을 수행합니다.
    3. 요소(element)에 play라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣습니다.
    4. 요소(element)에 playing이라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣습니다.
    5. 자동 재생 플래그를 false로 설정합니다.

    유저 에이전트들은 자동 재생을 지원할 필요가 없고, 유저 에이전트가 해당 문제에 대한 사용자 환경 설정을 존중해 줄 것이 제안됩니다. 작성자들은 스크립트를 사용하여 동영상 재생을 강제하는 것 보다 사용자가 원하는 경우 동작을 재설정할 수 있도록 autoplay 속성(attribute)을 사용하도록 권장됩니다.

    어떤 경우에도, 유저 에이전트는 최종적으로 요소(element)에 canplaythrough라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣어야(must) 합니다.

미디어 요소(element)의 준비 상태가 불연속적으로 이 상태들 사이를 건너 뛰는 것이 가능합니다. 예를 들어, 미디어 요소(element)의 상태는 HAVE_CURRENT_DATAHAVE_FUTURE_DATA 상태를 거치지 않고 HAVE_METADATA에서 HAVE_ENOUGH_DATA로 바로 건너뛰는 것이 가능합니다.

readyState IDL 속성(attribute)은 가져올 때 위에서 설명된 미디어 요소(element)의 현재 준비 상태를 설명하는 값을 반환해야(must) 합니다.

autoplay 속성(attribute)은 불리언 속성(attribute)입니다. 이 속성(attribute)이 존재할 경우, 유저 에이전트는 (여기 기술된 알고리즘에 설명된 대로) 멈추지 않으면서 재생할 수 있는 즉시 미디어 리소스의 재생을 자동으로 시작할 것입니다.

작성자들은 사용자가 자동 재생을 원하지 않을 때, 예를 들어 스크린리더를 사용하는 경우, 사용자가 자동 재생을 재설정 하는 것을 허용하도록 자동 재생을 동작시키기 위해 스크립트를 사용하는 것 보다 autoplay 속성(attribute)을 사용하도록 권장됩니다. 작성자들은 또한 자동 재생 동작을 전혀 사용하지 않는 것을 고려하는 대신 유저 에이전트가 사용자가 명시적으로 재생을 시작하는 것을 기다리도록 하는 것이 권장됩니다.

autoplay IDL 속성(attribute)은 동일한 이름의 콘텐트 속성(attribute)을 반영해야(must) 합니다.

4.7.14.8. 미디어 리소스 재생
media . paused

재생이 일시 중지되었다면 true를 그렇지 않으면 false를 반환합니다.

media . ended

재생이 미디어 리소스의 끝에 도달했다면 true를 반환합니다.

media . defaultPlaybackRate [ = value ]

사용자가 미디어 리소스를 통해 빨리 감기나 되감기 하지 않을 때에 대한, 기본 재생 속도를 반환합니다.

기본 재생 속도를 변경하기 위해 설정 될 수 있습니다.

기본 속도는 재생에 직접적인 영향을 주지 않지만, 사용자가 빨리 감기 모드로 전환하면, 일반 재생 모드로 돌아갈 때, 재생 속도가 기본 재생 속도로 되돌아 올 것으로 예상됩니다.

media . playbackRate [ = value ]

현재 재생 속도를 반환합니다. 여기서 1.0은 정상 속도입니다.

재생의 속도를 변경하기 위해 설정될 수 있습니다.

media . played

유저 에이전트가 재생한 미디어 리소스의 범위를 나타내는 TimeRanges 객체를 반환합니다.

media . play()

미디어 리소스를 로딩하고 필요하다면 재생을 시작하여 paused 속성(attribute)을 false로 설정합니다. 재생이 종료되었다면, 처음부터 재시작 할 것입니다.

media . pause()

필요하다면 미디어 리소스를 로딩하여, paused 속성(attribute)을 true로 설정합니다.

paused 속성(attribute)은 미디어 요소(element)가 일시 중지 되었는지 아닌지의 여부를 나타냅니다. 이 속성(attribute)은 초기에 true이어야 합니다.

미디어 요소(element)는 그것의 readyState 속성(attribute)이 HAVE_NOTHING 상태나 HAVE_METADATA 샹태 혹은 HAVE_CURRENT_DATA 상태에 있거나, 또는 요소(element)가 유저 인터렉션을 위해 일시 중지 되었거나 대역 내 콘텐트에 대해 일시 중지 되었다면, 차단된 미디어 요소(element)입니다.

미디어 요소(element)는 그것의 paused 속성(attribute)이 false이고, 요소(element)가 재생을 종료하지 않았으며, 재생이 오류로 인해 중단되지 않았고, 요소(element)가 차단된 미디어 요소(element)가 아닌 경우 재생 중 일 수 있다고 합니다.

waiting DOM 이벤트는 재생 중 일 수 있는 요소(element)를 그것의 readyState 속성(attribute)을 HAVE_FUTURE_DATA 보다 낮은 값으로 변경함으로 인해 재생이 중단되는 결과로 발생 될 수 있습니다.

미디어 요소(element)는 다음 같은 경우 재생을 종료했다고 말합니다.

ended 속성(attribute)은 마지막에 이벤트 반복이 1단계에 도달했고 미디어 요소(element)재생을 종료 했으며 재생 방향이 정방향이었다면 true를 반환해야(must) 하고, 그렇지 않으면 false를 반환해야(must) 합니다.

미디어 요소(element)는 요소(element)의 readyState 속성(attribute)이 HAVE_METADATA나 그 이상이고, 유저 에이전트가 미디어 데이터의 처리 중에 치명적이지 않은 오류에 부딪히고, 그 오류로 인해 현재 재생 위치에서 콘텐트를 재생할 수 없는 경우, 오류로 인해 중지되었다고 합니다.

미디어 요소(element)는 그것의 paused 속성(attribute)이 false이고 readyState 속성(attribute)이 HAVE_FUTURE_DATAHAVE_ENOUGH_DATA이며 유저 에이전트가 미디어 리소스에서 사용자가 이어갈 리소스를 선택해야 하는 위치에 도달했을 경우 유저 인터렉션을 위해 일시 중지되었다고 합니다.

미디어 요소(element)는 동시에 재생 종료되고 유저 인터렉션을 위해 일시 중지 될 수 있습니다.

재생 중 일 수 있는 미디어 요소(element)유저 인터렉션을 위해 일시 중지되었기 때문에 재생을 중단하는 경우, 유저 에이전트는 요소(element)에 timeupdate라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣어야(must) 합니다.

미디어 요소(element)는 그것의 paused 속성(attribute)이 false이고, readyState 속성(attribute)이 HAVE_FUTURE_DATAHAVE_ENOUGH_DATA이며 유저 에이전트가 일시적으로 미디어 리소스에 머무르게 했고 0이 아닌 길이를 가진 콘텐트를 재생시키기 위하여 혹은 일시적으로 미디어 리소스의 세그먼트에 머무르게 했고 그 세그먼트보다 긴 길이를 가진 콘텐트를 재생시키기 위하여 미디어 리소스의 재생을 유보시킨 경우 대역 내 콘텐트에 대해 일시 중지했다고 합니다.

미디어 요소(element)대역 내 콘텐트에 대해 일시 중지되는 경우의 한가지 예는 유저 에이전트가 외부 WebVTT로부터 오디오 설명을 재생 중이고 큐에 대해 생성된 합성 음성이 텍스트 트랙 큐 시작 시간텍스트 트랙 큐 종료 시간 사이보다 긴 경우입니다.


재생 방향이 정방향일 때 현재 재생 위치미디어 리소스의 끝에 도달한 경우, 유저 에이전트는 이 단계들을 따라야(must) 합니다:

  1. 미디어 요소(element)가 명시된 loop 속성(attribute)을 가진다면, 미디어 리소스가장 빠른 가능한 위치탐색(seek)하고 이 단계들을 중단합니다.
  2. 위에서 정의된 대로, ended IDL 속성(attribute)은 이벤트 반복이 1단계로 돌아오면 true를 반환하기 시작합니다.
  3. 미디어 요소(element)timeupdate라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣습니다.
  4. 미디어 요소(element)가 여전히 재생을 종료했고 재생 방향이 여전히 정방향이고, paused가 false라면, paused를 true로 변경하고 미디어 요소(element)pause라는 단순 이벤트를 발생시키는 작업을 대기열에 넣습니다.
  5. 미디어 요소(element)ended라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣습니다.

재생 방향이 역방향일 때, 현재 재생 위치미디어 리소스가장 빠른 가능한 위치에 도달하는 경우, 유저 에이전트는 요소(element)에 오직 timeupdate라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣어야(must) 합니다.

"도달하다"라는 단어는 일반 재생 중에 현재 재생 위치를 변경해야 한다는 것을 의미하지 않습니다; 예를 들어, 탐색(seek)을 통해서 될 수 있습니다.


defaultPlaybackRate 속성(attribute)은 미디어 리소스에 재생될 원하는 속도를 그것의 고유의 속도의 배수로 제공합니다. 속성(attribute)은 변경할 수 있습니다: 가져올 때 설정 되었던 마지막 값이나 설정된 적이 없다면 1.0을 반환해야(must) 합니다; 설정할 때 속성(attribute)은 새로운 값으로 설정되어야(must) 합니다.

defaultPlaybackRate사용자에게 유저 인터페이스를 노출할 때 유저 에이전트에 의해 사용됩니다.

playbackRate 속성(attribute)은 미디어 리소스가 재생되는 속도인 유효 재생 속도를 그것의 고유 속도의 배수로 제공합니다. 그것이 defaultPlaybackRate과 동일하지 않으면, 사용자가 빨리 감기나 느린 동작 재생과 같은 기능을 사용 중이라는 것을 의미합니다. 이 속성(attribute)은 변경 가능합니다. 가져올 때 설정 되었던 마지막 값이나 설정된 적이 없다면 1.0을 반환해야(must) 합니다; 설정할 때 속성(attribute)은 새로운 값으로 설정되어야(must) 하고, 재생은 속도가 변경될 것입니다 (요소(element)가 재생 중 일 수 있는 경우).

defaultPlaybackRate이나 playbackRate 속성(attributes)이 값을 변경하는 경우 (스크립트나 유저 에이전트에 의해 직접 변경되는 등, 예를 들어 사용자 제어에 대한 응답으로) 유저 에이전트는 미디어 요소(element)ratechange라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣어야(must) 합니다.


played 속성(attribute)은 속성(attribute)이 평가될 때, 정상 재생 중에 현재 재생 위치의 일반적인 단조 증가를 통해 도달 된 미디어 리소스미디어 타임라인 상의 지점들의 범위를 나타내는 새로운 정적 정규화 된 TimeRanges 객체를 반환해야(must) 합니다.


미디어 요소(element)play() 메서드가 동작될 때, 유저 에이전트는 다음 단계들을 수행해야(must) 합니다.

  1. 미디어 요소(element)networkState 속성(attribute)이 NETWORK_EMPTY 값을 가진다면, 미디어 요소(element)리소스 선택 알고리즘을 호출합니다.
  2. 재생이 종료 되었재생 방향이 정방향이라면, 미디어 리소스가장 빠른 가능한 위치탐색(seek)합니다.

    이것은 유저 에이전트가 미디어 요소(element)timeupdate라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣는것을 야기할 것입니다.

  3. 미디어 요소(element)paused 속성(attribute)이 true라면, 다음 단계들을 수행합니다:

    1. paused의 값을 false로 변경합니다.
    2. 포스터 표시 플래그가 true라면, 요소(element)의 포스터 표시 플래그를 false로 설정하고 time marches on 단계들을 수행합니다.
    3. 요소(element)에 play라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣습니다.
    4. 미디어 요소(element)readyState 속성(attribute)이 HAVE_NOTHINGHAVE_METADATAHAVE_CURRENT_DATA 값을 가진다면, 요소(element)에 waiting이라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣습니다.

      그렇지 않고, 미디어 요소(element)readyState 속성(attribute)이 HAVE_FUTURE_DATAHAVE_ENOUGH_DATA 값을 가진다면: 요소(element)에 playing이라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣습니다

  4. 미디어 요소(element)자동 재생 플래그를 false로 설정합니다.

pause() 메서드가 동작되는 경우, 그리고 유저 에이전트가 미디어 요소(element)를 일시 중지하도록 요구되는 경우, 유저 에이전트는 다음 단계들을 수행해야(must) 합니다:

  1. 미디어 요소(element)networkState 속성(attribute)이 NETWORK_EMPTY 값을 가진다면, 미디어 요소(element)리소스 선택 알고리즘을 호출합니다.
  2. 미디어 요소(element)에 대해 내부 일시 중지 단계들을 수행합니다.

미디어 요소(element)에 대한 내부 일시 중지 단계들은 다음과 같습니다:

  1. 미디어 요소(element)자동 재생 플래그를 false로 설정합니다.
  2. 미디어 요소(element)paused 속성(attribute)이 false라면, 다음 단계들을 수행합니다:
    1. paused의 값을 true로 변경합니다.
    2. 요소(element)에 timeupdate라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣습니다.
    3. 요소(element)에 pause라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣습니다.
    4. 공식 재생 위치현재 재생 위치로 설정합니다.

유효 재생 속도는 단지 요소(element)의 playbackRate입니다.

유효 재생 속도가 양수 또는 0이면, 재생 방향은 정방향입니다. 그렇지 않으면 역방향입니다.

미디어 요소(element)재생 중 일 수 있고 그것의 Document완전히 활성 Document인 경우, 그것의 현재 재생 위치미디어 타임라인의 시계의 단위 시간 당 미디어 타임의 유효 재생 속도에서 단조롭게 증가해야(must) 합니다. (이 명세는 항상 이것을 증가로 간주하지만, 그 증가는 유효 재생 속도가 음수라면 실제로는 감소 될 수 있습니다.)

유효 재생 속도는 0.0일 수 있고, 이 경우 재생이 일시 중지 되지 않았음에도 불구하고 현재 재생 위치는 움직이지 않습니다 (paused는 true가 되지 않고 pause 이벤트가 발생하지 않습니다).

이 명세는 유저 에이전트가 적절한 재생 속도를 달성하는 방법을 정의하지 않습니다 — 사용 가능한 프로토콜과 미디어를 따라 유저 에이전트가 적절한 속도로 미디어 데이터를 제공하도록 서버와 협상할 수 있는 것이 타당하기 때문에, (속도가 변경될 때와 서버가 스트림의 재생 속도를 갱신 할 때 사이의 기간을 제외하고) 클라이언트는 실제로 어떤 프레임도 빠뜨리거나 보간할 필요가 없습니다.

유저 에이전트가 안정된 상태를 제공할 때 마다, 공식 재생 위치현재 재생 위치로 설정되어야(must) 합니다.

재생 방향이 역방향인 경우, 모든 해당 오디오는 음소거 되어야(must) 합니다. 유효 재생 속도가 유저 에이전트가 유용하게 오디오를 재생할 수 없을 만큼 너무 낮거나 너무 높은 경우, 해당하는 오디오도 음소거 되어야(must) 합니다. 유효 재생 속도가 1.0이 아니라면, 유저 에이전트는 충실하게 렌더링 하기 위해 오디오에 피치 조정을 적용할 수 있습니다.

재생 중 일 수 있는 미디어 요소(element)들 Document 내에 존재하지 않는 동안 어떤 비디오도 재생하지 않아야(must)하지만, 모든 오디오 컴포넌트는 재생해야(should) 합니다. 미디어 요소(element)들은 모두 참조가 제거되었다고해서 재생을 중단하지 않아야(must) 합니다; 미디어 요소(element)가 그 미디어 요소(element)에 의해 더 이상 재생될 수 없는 상태에 있는 경우에만 요소(element)는 가비지 콜렉션 될 수 있습니다.

명시적 참조가 존재하지 않는 요소(element)는 그 요소(element)가 여전히 재생 중이지 않더라도 오디오를 재생할수 있습니다: 여를 들어, 오디오 트랙들이 없는 미디어 리소스미디어 요소(element)미디어 리소스를 변경하는 이벤트 리스너를 가진다면 결국 오디오를 다시 재생할 수 있습니다.


미디어 요소(element)는 초기에 비어있어야(must) 하는 새롭게 도입된 큐들의 목록을 가집니다. 텍스트 트랙 큐미디어 요소(element)에 대한 텍스트 트랙들의 목록에 있는 텍스트 트랙큐들의 목록에 추가될 때 마다, 그 미디어 요소(element)새롭게 도입된 큐들의 목록에 추가되어야(must) 합니다. 텍스트 트랙미디어 요소(element)에 대한 텍스트 트랙들의 목록에 추가될 때 마다, 그 텍스트 트랙큐들의 목록에 있는 모든 큐들미디어 요소(element)새롭게 도입된 큐들의 목록에 추가되어야(must) 합니다. 미디어 요소(element)포스터 표시 플래그가 설정되지 않은 동안 미디어 요소(element)새롭게 도입된 큐들의 목록이 새로운 큐들을 가지는 경우, 유저 에이전트는 time marches on 단계들을 수행해야(must) 합니다.

텍스트 트랙 큐미디어 요소(element)에 대한 텍스트 트랙들의 목록에 있는 텍스트 트랙큐들의 목록으로부터 제거되는 경우, 그리고 텍스트 트랙미디어 요소(element)텍스트 트랙들의 목록으로부터 제거될 때마다, 미디어 요소(element)포스터 표시 플래그가 설정되지 않았다면, 유저 에이전트는 time marches on 단계들을 수행해야(must) 합니다.

미디어 요소(element)현재 재생 위치가 변경될 때 (예를 들어, 재생이나 탐색으로 인해), 유저 에이전트는 time marches on 단계들을 수행해야(must) 합니다. 단계들이 수행되는 동안 현재 재생 위치가 변경된다면, 유저 에이전트는 단계들이 완료되기를 기다려야(must)하고, 이 후 즉시 단계드을 다시 수행해야(must) 합니다. (따라서 이 단계들은 가능한 혹은 필요에 따라 자주 수행됩니다 — 하나의 반복 작업에 오랜 시간이 걸리면, 이것은 유저 에이전트가 "따라잡기"를 진행할 때 특정 큐들이 건너뛰는 것을 야기할 수 있습니다.)

time marches on 단계들은 다음과 같습니다:

  1. current cues시작 시간현재 재생 위치보다 작거나 같고 종료 시간현재 재생 위치보다 큰 미디어 요소(element)의 모든 숨겨진 혹은 표시 모드 인 (비활성화 된 것이 아닌) 텍스트 트랙들의 모든 큐들로 초기화 된, 큐들의 목록으로 둡니다.
  2. other cuescurrent cues에 존재하지 않는 미디어 요소(element)숨겨진 혹은 표시 모드 인 텍스트 트랙들의 모든 큐들을 포함하도록 초기화 된 큐들의 목록으로 둡니다.
  3. 이 알고리즘이 처음 수행된 것이 아니라면, last time를 이 미디어 요소(element)에 대해 마지막으로 수행된 시점의 현재 재생 위치로 둡니다.
  4. 이 알고리즘이 마지막으로 수행 된 이후, 현재 재생 위치가 정상 재생 중에 일반적인 단조 증가를 통해서만 변경되었다면, missed cues시작 시간last time보다 크거나 같고 종료 시간현재 재생 위치보다 작거나 같은 other cues내의 큐들의 목록으로 둡니다. 그렇지 않으면 missed cues를 빈 목록으로 둡니다.
  5. 미디어 요소(element)새롭게 도입된 큐들의 목록에도 있는 missed cues 내의 모든 큐들을 제거하고, 요소(element)의 새롭게 도입된 큐들의 목록을 비웁니다.
  6. 시간이 정상 재생 동안 현재 재생 위치의 일반적인 단조 증가를 통해 도달되었고, 유저 에이전트가 지난 15ms ~ 250ms 동안 요소(element)에 timeupdate 이벤트를 발생하지 않았고 그 이벤트에 대한 이벤트 처리기들이 여전히 수행 중이 아니라면, 유저 에이전트는 요소(element)에 timeupdate라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣어야(must) 합니다. (명시적 탐색과 같은 다른 경우에는 현재 재생 위치를 변경하는 전체 프로세스의 일부로 관련 이벤트가 발생됩니다.)

    따라서 이벤트는 66Hz보다 빠르게 또는 4Hz보다 느리게 발생되지 않습니다 (이벤트 처리기가 수행하는데 250ms이상 걸리지 않는다고 가정하여). 유저 에이전트들은 시스템 부하를 기반으로 한 이벤트의 빈도와 매 번 이벤트 처리의 평균 비용을 변경하여, UI 업데이트는 비디오를 디코딩 하는 동안 유저 에이전트가 편안하게 처리할 수 있는 횟수보다 더 자주 발생하지 않습니다.

  7. current cues 내의 모든 큐들텍스트 트랙 큐 활성화 플래그 설정을 가지고 있고, other cues 내의 어떤 큐들텍스트 트랙 큐 활성화 플래그 설정을 가지지 않고, missed cues가 비어있다면, 이 단계들을 중단합니다.
  8. 시간이 정상 재생 동안 현재 재생 위치의 일반적인 단조 증가를 통해 도달되었고, 텍스트 트랙 큐 종료(exit) 시 일시 중지 플래그 설정과 텍스트 트랙 큐 활성화 플래그 설정을 가진 other cues 내의 큐들이 있다면, 즉시 미디어 요소(element)일시 중지합니다.

    명시적 탐색과 같은 다른 경우에는 재생이 텍스트 트랙 큐 종료(exit) 시 일시 중지 플래그 설정을 가지고 있어도 의 종료 시간을 지남으로 인해 일시 중지되지 않습니다.

  9. events를 초기에 비어있는 작업들의 목록으로 둡니다. 이 목록의 각 작업텍스트 트랙, 텍스트 트랙 큐, 시간과 연관될 것이고, 이는 작업들이 대기열에 넣어지기 전에 목록을 정렬하는데 사용됩니다.

    affected tracks를 초기에 비어있는 텍스트 트랙들의 목록으로 둡니다.

    아래 단계들이 시간 time을 가진 텍스트 트랙 큐 target에 대해 event라는 이벤트를 준비에 응할 때, 유저 에이전트는 다음 하위 단계들을 수행해야(must) 합니다:

    1. track텍스트 트랙 큐 target과 연관된 텍스트 트랙으로 둡니다.
    2. targetevent라는 단순 이벤트를 발생시키기 위한 작업을 생성합니다.
    3. 새롭게 생성된 작업을 시간 time, 텍스트 트랙 track, 텍스트 트랙 큐 target에 연관된 events에 추가합니다.
    4. trackaffected tracks에 추가합니다.
  10. missed cues 내의 각 텍스트 트랙 큐에 대해, 텍스트 트랙 큐 시작 시간을 가진 TextTrackCue 객체에 대해 enter라는 이벤트를 준비합니다.
  11. 텍스트 트랙 큐 활성화 플래그 설정을 가지거나 missed cues에 있는 other cues 내의 각 텍스트 트랙 큐에 대해, 텍스트 트랙 큐 종료 시간 이후와 텍스트 트랙 큐 시작 시간을 가진 TextTrackCue 객체에 대한 exit라는 이벤트를 준비합니다.
  12. 텍스트 트랙 큐 활성화 플래그 설정을 가지지 않은 current cues 내의 각 텍스트 트랙 큐에 대해, 텍스트 트랙 큐 시작 시간을 가진 TextTrackCue 객체에 대한 enter라는 이벤트를 준비합니다.
  13. events작업들을 시간 오름차순으로 정렬합니다 (이른 시간의 작업들을 먼저).

    작업들과 연관된 테스트 트랙 큐들의 관련 텍스트 트랙 큐 순서에 의해 동일한 시간을 가지는 events 내의 작업들을 추가로 정렬합니다.

    마지막으로, exit 이벤트들을 발생시키는 작업들 전으로 enter 이벤트들을 발생시키는 작업들 배치에 의해 동일한 시간과 동일한 텍스트 트랙 큐 순서를 가지는 events 내의 작업들을 정렬합니다.

  14. 순서대로 events 내의 각 작업대기열에 넣습니다.
  15. affected tracks텍스트 트랙들미디어 요소(element)텍스트 트랙들의 목록에 나타나는 것과 동일한 순서로 정렬하고 중복들을 제거합니다.
  16. affected tracks의 각 텍스트 트랙에 대해 목록 순서대로 TextTrack 객체에 cuechange라는 단순 이벤트를 발생시키기 위한, 그리고 텍스트 트랙이 대응하는 track 요소(element)를 가진다면, track 요소(element)에도 cuechange라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣습니다.
  17. current cues 내의 모든 큐들텍스트 트랙 큐 활성화 플래그를 설정하고, other cues 내의 모든 큐들텍스트 트랙 큐 활성화 플래그를 해제합니다.
  18. 텍스트 트랙텍스트 트랙 언어가 빈 문자열이 아니라면 이를 폴백 언어로 제공하여, 표시 모드인 affected tracks 내의 각 텍스트 트랙들텍스트 트랙 렌더링 업데이트에 대한 규칙들을 수행합니다. 예를 들어, WebVTT를 기반으로하는 텍스트 트랙들에 대해, WebVTT 텍스트 트랙들의 표시 업데이트에 대한 규칙. [WEBVTT]

위 알고리즘의 목적상, 텍스트 트랙 큐는 단지 텍스트 트랙과 연관되는 경우가 아니라 큐들의 텍스트 트랙 목록에 나열된 경우에만 텍스트 트랙의 일부로 간주됩니다.

미디어 요소(element)노드 문서완전히 활성화 문서가 되는 것을 중단한다면 재생은 문서가 다시 활성화 될때까지 중지될 것입니다.

미디어 요소(element)Document로부터 제거될 때, 유저 에이전트는 다음 단계들을 수행해야(must) 합니다:

  1. Document로부터 미디어 요소(element)를 제거되는 작업이 계속 진행되도록 안정 상태를 기다립니다. 동기 섹션은 이 알고리즘의 나머지 모든 단계들로 구성됩니다. (동기 섹션은 ⌛로 표기됩니다.)
  2. 미디어 요소(element)Document 내에 있다면, 이 단계들을 중단합니다.
  3. 미디어 요소(element)에 대한 내부 일시 중지 단계들을 수행합니다.
4.7.14.9. 탐색
media . seeking

유저 에이전트가 현재 탐색 중이라면 true를 반환합니다.

media . seekable

유저 에이전트가 탐색 할 수 있는 미디어 리소스의 범위를 나타내는 TimeRanges 객체를 반환합니다.

media . fastSeek( time )

속도를 위해 정확도를 포기하여, 가능한 빨리 주어진 time 가까이로 탐색합니다. (정확한 시간으로 탐색하려면, currentTime 속성(attribute)를 사용합니다.)

미디어 리소스가 로드되지 않았다면 아무 것도 수행하지 않습니다.

seeking 속성(attribute)은 초기에 false 값을 가져야(must) 합니다.

fastSeek() 메서드는 approximate-for-speed 플래그 설정과 함께 메서드의 인수로 주어진 시간으로 탐색해야(must) 합니다.

유저 에이저트가 선택적으로 approximate-for-speed 플래그 설정을 가지고 미디어 리소스 내의 특정 new playback position탐색이 요구되는 경우, 이는 유저 에이전트가 다음 단계들을 수행해야(must)함을 의미합니다. 이 알고리즘은 이벤트 반복 매커니즘과 밀접하게 상호작용합니다; 특히, (이벤트 반복 알고리즘의 일부로 작동하는) 동기 섹션을 가집니다. 그 섹션의 단계들은 ⌛로 표기됩니다.

  1. 미디어 요소(element)포스터 표시 플래그를 false로 설정합니다.
  2. 미디어 요소(element)readyStateHAVE_NOTHING라면, 이 단계들을 중단합니다.
  3. 요소(element)의 seeking IDL 속성(attribute)이 ture라면, 이 알고리즘의 다른 인스턴스가 이미 수행 중인 것입니다. 수행 중인 단계가 완료되기를 기다리지 않고 알고리즘의 다른 인스턴스를 중단합니다.
  4. seeking IDL 속성(attribute)을 true로 설정합니다.
  5. 탐색이 DOM 메서드 호출이나 IDL 속성의 설정에 대한 응답이었다면 스크립트를 계속합니다. 이 단계들의 나머지는 병렬로 수행되어야(must) 합니다. ⌛로 표기된 단계들을 제외하고, 호출되는 이 알고리즘의 다른 인스턴스에 의해 언제든지 중단될 수 있습니다.
  6. new playback position미디어 리소스의 끝보다 늦는다면, 그것을 미디어 리소스의 끝으로 둡니다.
  7. new playback position가장 빠른 가능한 위치보다 작으면, 대신 그 위치로 둡니다.
  8. (아마도 변경된) new playback positionseekable 속성(attribute)에 주어진 범위 중 하나가 아니라면, 이를 seekable 속성(attribute)에 주어진 범위 중 new playback position에 가장 가까운 위치 중 하나로 둡니다. 두 위치가 모두 그 제약사항을 충족시킨다면 (즉, new playback positionseekable 속성(attribute)의 두 범위 사이의 정확히 중간에 있는 경우), 현재 재생 위치에 가장 가까운 위치를 사용합니다. seekable 속성(attribute)에 주어진 범위가 없다면, seeking IDL 속성(attribute)을 false로 설정하고 이 단계들을 중단합니다.
  9. approximate-for-speed 플래그가 설정되었다면, new playback position를 재생을 즉시 재개할 수 있는 값으로 조정합니다. 이 단계 이전의 new playback position현재 재생 위치 이전이라면, 조정된 new playback position현재 재생 위치 이전이어야(must) 합니다. 마찬가지로, 이 단계 이전의 new playback position현재 재생 위치 이후라면, 조정된 new playback position현재 재생 위치 이후여야(must) 합니다.

    예를 들어, 유저 에이전트가 가까운 키 프레임으로 스냅할 수 있으므로, 재생을 재개하기 전에 중간 프레임들을 디코딩 한 후 폐기하는데 시간을 낭비할 필요가 없습니다.

  10. 요소(element)에 seeking이라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣습니다
  11. 현재 재생 위치new playback position로 설정합니다.

    미디어 요소(element)가 탐색이 시작되기 직전에 재생 중 일수 있었지만, 탐색이 readyState 속성(attribute)을 HAVE_FUTURE_DATA보다 낮은 값으로 변경하는 것을 야기했다면, 요소(element)에 waiting 이벤트가 발생될 것입니다.

    이 단계는 현재 재생 위치를 설정하고, 따라서 재생이 "미디어 리소스의 끝에 도달" (반복을 처리하는 로직의 일부) 할 때에 관한 규칙들 같은 다른 조건들을, 유저 에이전트가 (다음 단계에 결정된 대로) 실제로 그 위치에 대한 미디어 데이터를 렌더링 할 수 있기 전에 조차 즉시 작동시킬 수 있습니다.

    currentTime 속성(attribute)은 현재 재생 위치가 아니라 공식 재생 위치를 반환하므로, 이 알고리즘과 별도로 스크립트 실행 전에 업데이트 됩니다.

  12. 유저 에이전트가 new playback position에 대한 미디어 데이터가 사용 가능한지 아닌지의 여부를 결정할 때 까지, 그리고 그것이 존재한다면 그 위치를 재생하기에 충분한 데이터를 디코딩 할 때까지 기다립니다.
  13. 안정 상태를 기다립니다. 동기 섹션은 이 알고리즘의 모든 나머지 단계들로 구성됩니다. (동기 섹션 내 단계들은 ⌛로 표기됩니다.)
  14. seeking IDL 속성(attribute)을 false로 설정합니다.
  15. time marches on 단계들을 수행합니다.
  16. ⌛ 요소(element)에 timeupdate라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣습니다
  17. ⌛ 요소(element)에 seeked라는 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣습니다

seekable 속성(attribute)은 속성이 평가될 때 유저 에이전트가 탐색 가능한 미디어 리소스의 범위를 나타내는 새로운 정적 정규화 된 TimeRanges 객체를 반환해야(must) 합니다.

유저 에이전트가 미디어 리소스 내 어느 곳으로든 탐색할 수 있다면, 예를 들어, 간단한 영상 파일이고 유저 에이전와 서버가 HTTP 범위 요청을 지원하기 때문에, 속성(attribute)은 시작이 첫 번째 프레임의 시간 (일반적으로 0인 가장 빠른 가능한 위치)이고, 끝이 첫 번째 프레임에 duration 속성(attribute)의 값을 (마지막 프레임의 시간과 동일하고, 양의 무한대일 수 있는) 더한 시간과 동일한 하나의 범위를 가진 객체를 반환할 것입니다.

범위는 예를 들어 유저 에이전트가 무한 스트림에서 슬라이딩 윈도우를 버퍼링하고 있다면, 계속적으로 변경될 수 있습니다. 이는 예를 들어 실시간 TV를 시청하는 DVR에서 나타나는 동작입니다.

유저 에이전트들은 탐색 가능한 것에 대해 매우 자유롭고 낙관적인 시선을 채택해야(should) 합니다. 유저 에이전트들은 또한 가능한 빠르게 탐색 할 수 있는 최신 콘텐트를 버퍼해야(should) 합니다.

예를 들어, HTTP 범위 요청을 지원하지 않는 HTTP 서버에서 제공되는 대형 비디오 파일을 고려해보세요. 브라우저는 재생을 재시작하는 것에 의해 초기로 탐색하는 것을 제외하고 탐색을 허용하지 않고 현재 프레임과 이후 프레임들에 대해 얻은 데이터를 버퍼링하는 것만으로 이를 구현할 있습니다. 하지만, 이것은 좋지 못한 구현 일 것입니다. 고품질 구현은 콘텐츠의 마지막 몇 분을 (또는 충분한 저장 공간이 사용 가능 하다면 좀 더) 사용자가 뒤로 건너뛰고 지연 없이 불시의 어떤 것을 다시 볼 수 있도록 하여 버퍼하는 것이고, 추가로 필요하다면 시작부터 파일을 다시 로딩하여 임의의 탐색을 허용하는 것이며, 이는 느리지만 여전히 비디오를 완전히 다시 시작하고 이전의 버퍼링 되지 않은 지점을 얻기 위한 방법으로 끝까지 시청해야 하는 것보다 간편할 것입니다.

미디어 리소스들은 내부적으로 스크립팅 되거나 대화형일 수 있습니다. 따라서, 미디어 요소(element)는 비선형 방식으로 재생될 수 있습니다. 이것이 발생되면, 유저 에이전트는 비선형 방식으로 현재 재생 위치가 변경될 때마다 (관련 이벤트가 발생되도록) 탐색에 대한 알고리즘이 사용된 것 처럼 행동해야(must) 합니다.

4.7.14.10. 여러 미디어 트랙들을 가진 미디어 리소스들

미디어 리소스는 여러 개의 삽입 오디오와 비디오 트랙들을 가질 수 있습니다. 예를 들어, 주 비디오와 오디오 트랙들에 더하여, 미디어 리소스는 외국어로 더빙 된 대화 상자, 감독의 설명, 오디오 설명, 대체 앵글, 수화 오버레이를 가질 수 있습니다.

media . audioTracks

미디어 리소스의 사용 가능한 오디오 트랙들을 나타내는 AudioTrackList 객체를 반환합니다.

media . videoTracks

미디어 리소스의 사용 가능한 비디오 트랙들을 나타내는 VideoTrackList 객체를 반환합니다.

미디어 요소(element)audioTracks 속성(attribute)은 미디어 요소(element)미디어 리소스의 오디오 트랙들을 나타내는 존속되는 AudioTrackList 객체를 반환해야(must) 합니다.

미디어 요소(element)videoTracks 속성(attribute)은 미디어 요소(element)미디어 리소스의 사용 가능한 비디오 트랙들을 나타내는 존속되는 VideoTrackList 객체를 반환해야(must) 합니다.

다른 미디어 리소스가 요소(element)에 로드되더라도, 미디어 요소(element) 당 하나의 미디어 요소(element) 객체와 하나의 VideoTrackList 객체만이 존재합니다: 객체들은 재사용됩니다. (AudioTrackVideoTrack 객체들은 그렇지 않습니다.)

이 예에서, 스크립트는 비디오에 대한 URL과 비디오가 배치될 요소(element)에 대한 참조를 취하는 함수를 정의합니다. 이 함수는 비디오를 로드하려고 시도하고, 로드 되면 사용 가능한 수화 트랙이 있는지를 확인합니다. 두 트랙은 주어진 컨테이너에 배치됩니다; 스타일이 이 영상이 예쁘게 되도록 적용되었다고 가정합니다!
<script>
  function loadVideo(url, container) {
    var video = document.createElement('video');
    video.src = url;
    video.autoplay = true;
    video.controls = true;
    container.appendChild(video);
    video.onloadedmetadata = function (event) {
      for (var i = 0; i < video.videoTracks.length; i += 1) {
        if (video.videoTracks[i].kind == 'sign') {
          var sign = document.createElement('video');
          sign.src = url + '#track=' + video.videoTracks[i].id;
          sign.autoplay = true;
          container.appendChild(sign);
          return;
        }
      }
    };
  }
</script>
4.7.14.10.1. AudioTrackList and VideoTrackList objects

The AudioTrackList and VideoTrackList interfaces are used by attributes defined in the previous section.

interface AudioTrackList : EventTarget {
  readonly attribute unsigned long length;
  getter AudioTrack (unsigned long index);
  AudioTrack? getTrackById(DOMString id);

  attribute EventHandler onchange;
  attribute EventHandler onaddtrack;
  attribute EventHandler onremovetrack;
};
interface AudioTrack {
  readonly attribute DOMString id;
  readonly attribute DOMString kind;
  readonly attribute DOMString label;
  readonly attribute DOMString language;
  attribute boolean enabled;
};
interface VideoTrackList : EventTarget {
  readonly attribute unsigned long length;
  getter VideoTrack (unsigned long index);
  VideoTrack? getTrackById(DOMString id);
  readonly attribute long selectedIndex;

  attribute EventHandler onchange;
  attribute EventHandler onaddtrack;
  attribute EventHandler onremovetrack;
};
interface VideoTrack {
  readonly attribute DOMString id;
  readonly attribute DOMString kind;
  readonly attribute DOMString label;
  readonly attribute DOMString language;
  attribute boolean selected;
};
media . audioTracks . length
media . videoTracks . length

Returns the number of tracks in the list.

audioTrack = media . audioTracks[index]
videoTrack = media . videoTracks[index]

Returns the specified AudioTrack or VideoTrack object.

audioTrack = media . audioTracks . getTrackById( id )
videoTrack = media . videoTracks . getTrackById( id )

Returns the AudioTrack or VideoTrack object with the given identifier, or null if no track has that identifier.

audioTrack . id
videoTrack . id

Returns the ID of the given track. This is the ID that can be used with a fragment identifier if the format supports the Media Fragments URI syntax, and that can be used with the getTrackById() method. [MEDIA-FRAGS]

audioTrack . kind
videoTrack . kind

Returns the category the given track falls into. The possible track categories are given below.

audioTrack . label
videoTrack . label

Returns the label of the given track, if known, or the empty string otherwise.

audioTrack . language
videoTrack . language

Returns the language of the given track, if known, or the empty string otherwise.

audioTrack . enabled [ = value ]

Returns true if the given track is active, and false otherwise.

Can be set, to change whether the track is enabled or not. If multiple audio tracks are enabled simultaneously, they are mixed.

media . videoTracks . selectedIndex

Returns the index of the currently selected track, if any, or -1 otherwise.

videoTrack . selected [ = value ]

Returns true if the given track is active, and false otherwise.

Can be set, to change whether the track is selected or not. Either zero or one video track is selected; selecting a new track while a previous one is selected will unselect the previous one.

An 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 AudioTrack object.

A 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 VideoTrack object.

Tracks in AudioTrackList and VideoTrackList objects must be consistently ordered. If the 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 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 media resource dynamically adds or removes audio or video tracks, then the indices of the tracks will change dynamically. If the media resource changes entirely, then all the previous tracks will be removed and replaced with new tracks.

The AudioTrackList.length and VideoTrackList.length attributes must return the number of tracks represented by their objects at the time of getting.

The supported property indices of AudioTrackList and 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 AudioTrackList or VideoTrackList object represents no tracks, it has no supported property indices.

To determine the value of an indexed property for a given index index in an AudioTrackList or VideoTrackList object list, the user agent must return the AudioTrack or VideoTrack object that represents the indexth track in list.

The AudioTrackList.getTrackById(id) and VideoTrackList.getTrackById(id) methods must return the first AudioTrack or VideoTrack object (respectively) in the AudioTrackList or 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 AudioTrack and VideoTrack objects represent specific tracks of a 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 media resource’s AudioTrackList or VideoTrackList objects, those aspects do not change.

In addition, AudioTrack objects can each be enabled or disabled; this is the audio track’s enabled state. When an AudioTrack is created, its enabled state must be set to false (disabled). The resource fetch algorithm can override this.

Similarly, a single VideoTrack object per VideoTrackList object can be selected, this is the video track’s selection state. When a VideoTrack is created, its selection state must be set to false (not selected). The resource fetch algorithm can override this.

The AudioTrack.id and VideoTrack.id attributes must return the identifier of the track, if it has one, or the empty string otherwise. If the media resource is in a format that supports the Media Fragments URI fragment identifier 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 fragment identifier. [MEDIA-FRAGS] [INBANDTRACKS]

For example, in Ogg files, this would be the Name header field of the track. [OGGSKELETON]

The AudioTrack.kind and 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 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 AudioTrack objects if they are appropriate for audio, and must only be returned for VideoTrack objects if they are appropriate for video.

Return values for AudioTrack.kind and VideoTrack.kind
Category Definition Applies to...
"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.
"captions" A version of the main video track with captions burnt in. (For legacy content; new content would use text tracks.) Video only.
"descriptions" An audio description of a video track. Audio only.
"main" The primary audio or video track. Audio and video.
"main-desc" The primary audio track, mixed with audio descriptions. Audio only.
"sign" A sign-language interpretation of an audio track. Video only.
"subtitles" A version of the main video track with subtitles burnt in. (For legacy content; new content would use text tracks.) Video only.
"translation" A translated version of the main audio track. Audio only.
"commentary" Commentary on the primary audio or video track, e.g., a director’s commentary. Audio and video.
"" (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 AudioTrack.label and VideoTrack.label attributes must return the label of the track, if it has one, or the empty string otherwise. [INBANDTRACKS]

The AudioTrack.language and 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 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.

Source attribute values for id, kind, label and language of multitrack audio and video tracks as described for the relevant media resource format. [INBANDTRACKS]

The 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 AudioTrackList object, then the track being enabled or disabled has no effect beyond changing the value of the attribute on the AudioTrack object.)

Whenever an audio track in an AudioTrackList that was disabled is enabled, and whenever one that was enabled is disabled, the user agent must queue a task to fire a simple event named change at the AudioTrackList object.

An audio track that has no data for a particular position on the media timeline, or that does not exist at that position, must be interpreted as being silent at that point on the timeline.

The VideoTrackList.selectedIndex attribute must return the index of the currently selected track, if any. If the VideoTrackList object does not currently represent any tracks, or if none of the tracks are selected, it must instead return -1.

The 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 VideoTrackList, then all the other VideoTrack objects in that list must be unselected. (If the track is no longer in a VideoTrackList object, then the track being selected or unselected has no effect beyond changing the value of the attribute on the VideoTrack object.)

Whenever a track in a VideoTrackList that was previously not selected is selected, and whenever the selected track in a VideoTrackList is unselected without a new track being selected in its stead, the user agent must queue a task to fire a simple event named change at the VideoTrackList object. This task must be queued before the task that fires the resize event, if any.

A video track that has no data for a particular position on the media timeline must be interpreted as being fully 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 media resource but was simply transparent until one hour in.


The following are the event handlers (and their corresponding event handler event types) that must be supported, as event handler IDL attributes, by all objects implementing the AudioTrackList and VideoTrackList interfaces:

Event handler Event handler event type
onchange change
onaddtrack addtrack
onremovetrack removetrack
4.7.14.10.2. Selecting specific audio and video tracks declaratively

The audioTracks and videoTracks attributes allow scripts to select which track should play, but it is also possible to select specific tracks declaratively, by specifying particular tracks in the fragment identifier of the URL of the media resource. The format of the fragment identifier depends on the MIME type of the media resource. [RFC2046] [URL]

In this example, a video that uses a format that supports the Media Fragments URI fragment identifier syntax is embedded in such a way that the alternative angles labeled "Alternative" are enabled instead of the default video track. [MEDIA-FRAGS]
<video src="myvideo#track=Alternative"></video>
4.7.14.11. Timed text tracks
4.7.14.11.1. Text track model

A media element can have a group of associated text tracks, known as the media element’s list of text tracks. The text tracks are sorted as follows:

  1. The text tracks corresponding to track element children of the media element, in tree order.
  2. Any text tracks added using the addTextTrack() method, in the order they were added, oldest first.
  3. Any media-resource-specific text tracks (text tracks corresponding to data in the media resource), in the order defined by the media resource’s format specification.

A text track consists of:

The kind of text track

This decides how the track is handled by the user agent. The kind is represented by a string. The possible strings are:

  • subtitles
  • captions
  • descriptions
  • chapters
  • metadata

The kind of track can change dynamically, in the case of a text track corresponding to a track element.

A label

This is a human-readable string intended to identify the track for the user.

The label of a track can change dynamically, in the case of a text track corresponding to a track element.

When a text track label is the empty string, the user agent should automatically generate an appropriate label from the text track’s other properties (e.g., the kind of text track and the text track’s language) for use in its user interface. This automatically-generated label is not exposed in the API.

An in-band metadata track dispatch type

This is a string extracted from the media resource specifically for in-band metadata tracks to enable such tracks to be dispatched to different scripts in the document.

For example, a traditional TV station broadcast streamed on the Web and augmented with Web-specific interactive features could include text tracks with metadata for ad targeting, trivia game data during game shows, player states during sports games, recipe information during food programs, and so forth. As each program starts and ends, new tracks might be added or removed from the stream, and as each one is added, the user agent could bind them to dedicated script modules using the value of this attribute.

Other than for in-band metadata text tracks, the in-band metadata track dispatch type is the empty string. How this value is populated for different media formats is described in steps to expose a media-resource-specific text track.

A language

This is a string (a BCP 47 language tag) representing the language of the text track’s cues. [BCP47]

The language of a text track can change dynamically, in the case of a text track corresponding to a track element.

A readiness state

One of the following:

Not loaded

Indicates that the text track’s cues have not been obtained.

Loading

Indicates that the text track is loading and there have been no fatal errors encountered so far. Further cues might still be added to the track by the parser.

Loaded

Indicates that the text track has been loaded with no fatal errors.

Failed to load

Indicates that the text track was enabled, but when the user agent attempted to obtain it, this failed in some way (e.g., URL could not be resolved, network error, unknown text track format). Some or all of the cues are likely missing and will not be obtained.

The readiness state of a text track changes dynamically as the track is obtained.

A mode

One of the following:

Disabled

Indicates that the text track is not active. Other than for the purposes of exposing the track in the DOM, the user agent is ignoring the text track. No cues are active, no events are fired, and the user agent will not attempt to obtain the track’s cues.

Hidden

Indicates that the text track is active, but that the user agent is not actively displaying the cues. If no attempt has yet been made to obtain the track’s cues, the user agent will perform such an attempt momentarily. The user agent is maintaining a list of which cues are active, and events are being fired accordingly.

Showing

Indicates that the text track is active. If no attempt has yet been made to obtain the track’s cues, the user agent will perform such an attempt momentarily. The user agent is maintaining a list of which cues are active, and events are being fired accordingly. In addition, for text tracks whose kind is subtitles or captions, the cues are being overlaid on the video as appropriate; for text tracks whose kind is descriptions, the user agent is making the cues available to the user in a non-visual fashion; and for text tracks whose kind is chapters, the user agent is making available to the user a mechanism by which the user can navigate to any point in the media resource by selecting a cue.

A list of zero or more cues

A list of text track cues, along with rules for updating the text track rendering. For example, for WebVTT, the rules for updating the display of WebVTT text tracks. [WEBVTT]

The list of cues of a text track can change dynamically, either because the text track has not yet been loaded or is still loading, or due to DOM manipulation.

Each text track has a corresponding TextTrack object.


Each media element has a list of pending text tracks, which must initially be empty, a blocked-on-parser flag, which must initially be false, and a 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 media element, the user agent must add to the element’s list of pending text tracks each text track in the element’s list of text tracks whose text track mode is not disabled and whose text track readiness state is loading.

Whenever a track element’s parent node changes, the user agent must remove the corresponding text track from any list of pending text tracks that it is in.

Whenever a text track’s text track readiness state changes to either loaded or failed to load, the user agent must remove it from any list of pending text tracks that it is in.

When a media element is created by an HTML parser or XML parser, the user agent must set the element’s blocked-on-parser flag to true. When a media element is popped off the stack of open elements of an HTML parser or XML parser, the user agent must honor user preferences for automatic text track selection, populate the list of pending text tracks, and set the element’s blocked-on-parser flag to false.

The text tracks of a media element are ready when both the element’s list of pending text tracks is empty and the element’s blocked-on-parser flag is false.

Each media element has a pending text track change notification flag, which must initially be unset.

Whenever a text track that is in a media element’s list of text tracks has its text track mode change value, the user agent must run the following steps for the media element:

  1. If the media element’s pending text track change notification flag is set, abort these steps.
  2. Set the media element’s pending text track change notification flag.
  3. Queue a task that runs the following substeps:

    1. Unset the media element’s pending text track change notification flag.
    2. Fire a simple event named change at the media element’s textTracks attribute’s TextTrackList object.
  4. If the media element’s show poster flag is not set, run the time marches on steps.

The task source for the tasks listed in this section is the DOM manipulation task source.


A text track cue is the unit of time-sensitive data in a text track, corresponding for instance for subtitles and captions to the text that appears at a particular time and disappears at another time.

Each text track cue consists of:

An identifier
An arbitrary string.
A start time
The time, in seconds and fractions of a second, that describes the beginning of the range of the media data to which the cue applies.
An end time
The time, in seconds and fractions of a second, that describes the end of the range of the media data to which the cue applies.
A pause-on-exit flag
A boolean indicating whether playback of the media resource is to pause when the end of the range to which the cue applies is reached.
Some additional format-specific data
Additional fields, as needed for the format. For example, WebVTT has a text track cue writing direction and so forth. [WEBVTT]
Rules for extracting the chapter title
An algorithm which, when applied to the cue, returns a string that can be used in user interfaces that use the cue as a chapter title.

The text track cue start time and text track cue end time can be negative. (The current playback position can never be negative, though, so cues entirely before time zero cannot be active.)

Each text track cue has a corresponding TextTrackCue object (or more specifically, an object that inherits from TextTrackCue — for example, WebVTT cues use the VTTCue interface). A text track cue’s in-memory representation can be dynamically changed through this TextTrackCue API. [WEBVTT]

A text track cue is associated with rules for updating the text track rendering, as defined by the specification for the specific kind of text track cue. These rules are used specifically when the object representing the cue is added to a TextTrack object using the addCue() method.

In addition, each text track cue has two pieces of dynamic information:

The active flag

This flag must be initially unset. The flag is used to ensure events are fired appropriately when the cue becomes active or inactive, and to make sure the right cues are rendered.

The user agent must immediately unset this flag whenever the text track cue is removed from its text track’s text track list of cues; whenever the text track itself is removed from its media element’s list of text tracks or has its text track mode changed to disabled; and whenever the media element’s readyState is changed back to HAVE_NOTHING. When the flag is unset in this way for one or more cues in text tracks that were showing prior to the relevant incident, the user agent must, after having unset the flag for all the affected cues, apply the rules for updating the text track rendering of those text tracks. For example, for text tracks based on WebVTT, the rules for updating the display of WebVTT text tracks. [WEBVTT]

The display state

This is used as part of the rendering model, to keep cues in a consistent position. It must initially be empty. Whenever the text track cue active flag is unset, the user agent must empty the text track cue display state.

The text track cues of a media element’s text tracks are ordered relative to each other in the text track cue order, which is determined as follows: first group the cues by their text track, with the groups being sorted in the same order as their text tracks appear in the media element’s list of text tracks; then, within each group, cues must be sorted by their start time, earliest first; then, any cues with the same start time must be sorted by their end time, latest first; and finally, any cues with identical end times must be sorted in the order they were last added to their respective text track list of cues, oldest first (so e.g., for cues from a WebVTT file, that would initially be the order in which the cues were listed in the file). [WEBVTT]

4.7.14.11.2. Sourcing in-band text tracks

A media-resource-specific text track is a text track that corresponds to data found in the 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 media resource is a video. Details for some legacy formats can be found in the Sourcing In-band Media Resource Tracks from Media Containers into HTML specification. [INBANDTRACKS]

When a media resource contains data that the user agent recognizes and supports as being equivalent to a text track, the user agent 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 text track and its corresponding new TextTrack object. The text track is a media-resource-specific text track.
  2. Set the new text track’s kind, label, and language based on the semantics of the relevant data, as defined for the relevant format [INBANDTRACKS]. If there is no label in that data, then the label must be set to the empty string.
  3. Associate the text track list of cues with the rules for updating the text track rendering appropriate for the format in question.
  4. If the new text track’s kind is metadata, then set the text track in-band metadata track dispatch type as follows, based on the type of the media resource:

    If the media resource is an Ogg file
    The text track in-band metadata track dispatch type must be set to the value of the Role header field. [OGGSKELETON]
    If the media resource is a WebM file
    The text track in-band metadata track dispatch type must be set to the value of the CodecID element. [WEBM]
    If the 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 the MPEG-2 specification. Let descriptor bytes be the length bytes following the "ES_info_length" field. The 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 uppercase ASCII hex digits. [MPEG2TS]
    If the 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 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 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 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 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.

    [MPEG4]

    If the media resource is a DASH media resource
    The text track in-band metadata track dispatch type must be set to the concatenation of the "AdaptationSet" element attributes and all child Role descriptors. [MPEGDASH]
  5. Populate the new text track’s list of cues with the cues parsed so far, following the guidelines for exposing cues, and begin updating it dynamically as necessary.
  6. Set the new text track’s readiness state to loaded.
  7. Set the new text track’s 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 text track to the media element’s list of text tracks.
  9. Fire a trusted event with the name addtrack, that does not bubble and is not cancelable, and that uses the TrackEvent interface, with the track attribute initialized to the text track’s TextTrack object, at the media element’s textTracks attribute’s TextTrackList object.
4.7.14.11.3. Sourcing out-of-band text tracks

When a track element is created, it must be associated with a new text track (with its value set as defined below) and its corresponding new TextTrack object.

The text track kind is determined from the state of the element’s kind attribute according to the following table; for a state given in a cell of the first column, the kind is the string given in the second column:

State String
Subtitles subtitles
Captions captions
Descriptions descriptions
Chapters chapters
Metadata metadata

The text track label is the element’s track label.

The text track language is the element’s track language, if any, or the empty string otherwise.

As the kind, label, and srclang attributes are set, changed, or removed, the text track must update accordingly, as per the definitions above.

Changes to the track URL are handled in the algorithm below.

The text track readiness state is initially not loaded, and the text track mode is initially disabled.

The text track list of cues is initially empty. It is dynamically modified when the referenced file is parsed. Associated with the list are the rules for updating the text track rendering appropriate for the format in question; for WebVTT, this is the rules for updating the display of WebVTT text tracks. [WEBVTT]

When a track element’s parent element changes and the new parent is a media element, then the user agent must add the track element’s corresponding text track to the media element’s list of text tracks, and then queue a task to fire a trusted event with the name addtrack, that does not bubble and is not cancelable, and that uses the TrackEvent interface, with the track attribute initialized to the text track’s TextTrack object, at the media element’s textTracks attribute’s TextTrackList object.

When a track element’s parent element changes and the old parent was a media element, then the user agent must remove the track element’s corresponding text track from the media element’s list of text tracks, and then queue a task to fire a trusted event with the name removetrack, that does not bubble and is not cancelable, and that uses the TrackEvent interface, with the track attribute initialized to the text track’s TextTrack object, at the media element’s textTracks attribute’s TextTrackList object.


When a text track corresponding to a track element is added to a media element’s list of text tracks, the user agent must queue a task to run the following steps for the media element:

  1. If the element’s blocked-on-parser flag is true, abort these steps.
  2. If the element’s did-perform-automatic-track-selection flag is true, abort these steps.
  3. 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 media element, the user agent must run the following steps:

  1. Perform automatic text track selection for subtitles and captions.
  2. Perform automatic text track selection for descriptions.
  3. Perform automatic text track selection for chapters.
  4. If there are any text tracks in the media element’s list of text tracks whose text track kind is metadata that correspond to track elements with a default attribute set whose text track mode is set to disabled, then set the text track mode of all such tracks to hidden
  5. Set the element’s did-perform-automatic-track-selection flag to true.

When the steps above say to perform automatic text track selection for one or more text track kinds, it means to run the following steps:

  1. Let candidates be a list consisting of the text tracks in the media element’s list of text tracks whose text track kind is one of the kinds that were passed to the algorithm, if any, in the order given in the list of text tracks.
  2. If candidates is empty, then abort these steps.
  3. If any of the text tracks in candidates have a text track mode set to showing, abort these steps.
  4. If the user has expressed an interest in having a track from candidates enabled based on its text track kind, text track language, and text track label, then set its text track mode to 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 text tracks in candidates that correspond to track elements with a default attribute set whose text track mode is set to disabled, then set the text track mode of the first such track to showing.

When a text track corresponding to a track element experiences any of the following circumstances, the user agent must start the track processing model for that text track and its track element:

When a user agent is to start the track processing model for a text track and its track element, it must run the following algorithm. This algorithm interacts closely with the event loop mechanism; in particular, it has a synchronous section (which is triggered as part of the event loop algorithm). The steps in that section are marked with ⌛.

  1. If another occurrence of this algorithm is already running for this text track and its track element, abort these steps, letting that other algorithm take care of this element.
  2. If the text track’s text track mode is not set to one of hidden or showing, abort these steps.
  3. If the text track’s track element does not have a media element as a parent, abort these steps.
  4. Run the remainder of these steps in parallel, allowing whatever caused these steps to run to continue.
  5. Top: Await a stable state. The synchronous section consists of the following steps. (The steps in the synchronous section are marked with ⌛.)
  6. ⌛ Set the text track readiness state to loading.
  7. ⌛ Let URL be the track URL of the track element.
  8. ⌛ If the track element’s parent is a media element then let corsAttributeState be the state of the parent media element’s crossorigin content attribute. Otherwise, let corsAttributeState be No CORS.
  9. End the synchronous section, continuing the remaining steps in parallel.
  10. If URL is not the empty string, run these substeps:

    1. Let request be the result of creating a potential-CORS request given URL, corsAttributeState, and with the same-origin fallback flag set.
    2. Set request’s client to the track element’s node document’s Window object’s environment settings object and type to "track".
    3. Fetch request.

    The tasks queued by the fetching algorithm on the 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 WebVTT parser) as it is received, with the text track list of cues being used for that parser’s output. [WEBVTT]

    The appropriate parser will incrementally update the text track list of cues during these networking task source 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. Implementors 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 specification’s 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 the fetching algorithm fails for any reason (network error, the server returns an error code, a cross-origin check fails, etc), or if URL is the empty string, then queue a task to first change the text track readiness state to failed to load and then fire a simple event named error at the track element. This task must use the DOM manipulation task source.

    If the fetching algorithm 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 the XML specification requires be detected and reported to the application), then the task that is queued by the networking task source in which the aforementioned problem is found must change the text track readiness state to failed to load and fire a simple event named error at the track element.

    If the fetching algorithm does not fail, and the file was successfully processed, then the final task that is queued by the networking task source, after it has finished parsing the data, must change the text track readiness state to loaded, and fire a simple event named load at the track element.

    If, while fetching is ongoing, either:

    ...then the user agent must abort fetching, discarding any pending tasks generated by that algorithm (and in particular, not adding any cues to the text track list of cues after the moment the URL changed), and then queue a task that first changes the text track readiness state to failed to load and then fires a simple event named error at the track element. This task must use the DOM manipulation task source.

  11. Wait until the text track readiness state is no longer set to loading.
  12. Wait until the track URL is no longer equal to URL, at the same time as the text track mode is set to hidden or showing.
  13. Jump to the step labeled top.

Whenever a track element has its src attribute set, changed, or removed, the user agent must immediately empty the element’s text track’s 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.7.14.11.4. Guidelines for exposing cues in various formats as 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 [INBANDTRACKS]. 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 text track model of HTML, each unit of timed data is converted to a text track cue. Where the mapping of the format’s features to the aspects of a 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 text track cue as defined above, as well as with the following constraints:

The text track cue identifier
Should be set to the empty string if the format has no obvious analog to a per-cue identifier.
The text track cue pause-on-exit flag
Should be set to false.

For media-resource-specific text tracks of kind metadata, text track cues are exposed using the DataCue object unless there is a more appropriate TextTrackCue interface available. For example, if the media-resource-specific text track format is WebVTT, then VTTCue is more appropriate.

4.7.14.11.5. Text track API
interface TextTrackList : EventTarget {
  readonly attribute unsigned long length;
  getter TextTrack (unsigned long index);
  TextTrack? getTrackById(DOMString id);

  attribute EventHandler onchange;
  attribute EventHandler onaddtrack;
  attribute EventHandler onremovetrack;
};
media . textTracks . length
Returns the number of text tracks associated with the media element (e.g., from track elements). This is the number of text tracks in the media element’s list of text tracks.
media . textTracks[ n ]
Returns the TextTrack object representing the nth text track in the media element’s list of text tracks.
textTrack = media . textTracks . getTrackById( id )

Returns the TextTrack object with the given identifier, or null if no track has that identifier.

A TextTrackList object represents a dynamically updating list of text tracks in a given order.

The textTracks attribute of media elements must return a TextTrackList object representing the TextTrack objects of the text tracks in the media element’s list of text tracks, in the same order as in the list of text tracks.

The length attribute of a TextTrackList object must return the number of text tracks in the list represented by the TextTrackList object.

The supported property indices of a TextTrackList object at any instant are the numbers from zero to the number of text tracks in the list represented by the TextTrackList object minus one, if any. If there are no text tracks in the list, there are no supported property indices.

To determine the value of an indexed property of a TextTrackList object for a given index index, the user agent must return the indexth text track in the list represented by the TextTrackList object.

The getTrackById(id) method must return the first TextTrack in the TextTrackList object whose 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.


enum TextTrackMode { "disabled",  "hidden",  "showing" };

enum TextTrackKind { "subtitles",  "captions",  "descriptions",  "chapters",  "metadata" };

interface TextTrack : EventTarget {
  readonly attribute TextTrackKind kind;
  readonly attribute DOMString label;
  readonly attribute DOMString language;

  readonly attribute DOMString id;
  readonly attribute DOMString inBandMetadataTrackDispatchType;

  attribute TextTrackMode mode;

  readonly attribute TextTrackCueList? cues;
  readonly attribute TextTrackCueList? activeCues;

  void addCue(TextTrackCue cue);
  void removeCue(TextTrackCue cue);

  attribute EventHandler oncuechange;
};
textTrack = media . addTextTrack( kind [, label [, language ] ] )

Creates and returns a new TextTrack object, which is also added to the media element’s list of text tracks.

textTrack . kind

Returns the text track kind string.

textTrack . label

Returns the text track label, if there is one, or the empty string otherwise (indicating that a custom label probably needs to be generated from the other attributes of the object if the object is exposed to the user).

textTrack . language
Returns the text track language string.
textTrack . id

Returns the ID of the given track.

For in-band tracks, this is the ID that can be used with a fragment identifier if the format supports the Media Fragments URI syntax, and that can be used with the getTrackById() method. [MEDIA-FRAGS]

For TextTrack objects corresponding to track elements, this is the ID of the track element.

textTrack . inBandMetadataTrackDispatchType

Returns the text track in-band metadata track dispatch type string.

textTrack . mode [ = value ]

Returns the text track mode, represented by a string from the following list:

"disabled"
The text track disabled mode.
"hidden"
The text track hidden mode.
"showing"
The text track showing mode.

Can be set, to change the mode.

textTrack . cues
Returns the text track list of cues, as a TextTrackCueList object.
textTrack . activeCues

Returns the text track cues from the text track list of cues that are currently active (i.e., that start before the current playback position and end after it), as a TextTrackCueList object.

textTrack . addCue( cue )
Adds the given cue to textTrack’s text track list of cues.
textTrack . removeCue( cue )
Removes the given cue from textTrack’s text track list of cues.

The addTextTrack(kind, label, language) method of media elements, when invoked, must run the following steps:

  1. Create a new TextTrack object.

  2. Create a new text track corresponding to the new object, and set its text track kind to kind, its text track label to label, its text track language to language, its text track readiness state to the text track loaded state, its text track mode to the text track hidden mode, and its text track list of cues to an empty list.

    Initially, the text track list of cues is not associated with any rules for updating the text track rendering. When a text track cue is added to it, the text track list of cues has its rules permanently set accordingly.

  3. Add the new text track to the media element’s list of text tracks.

  4. Queue a task to fire a trusted event with the name addtrack, that does not bubble and is not cancelable, and that uses the TrackEvent interface, with the track attribute initialized to the new text track’s TextTrack object, at the media element’s textTracks attribute’s TextTrackList object.

  5. Return the new TextTrack object.


The kind attribute must return the text track kind of the text track that the TextTrack object represents.

The label attribute must return the text track label of the text track that the TextTrack object represents.

The language attribute must return the text track language of the text track that the 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 track elements, the track’s identifier is the value of the element’s id attribute, if any. For in-band tracks, the track’s identifier is specified by the media resource. If the media resource is in a format that supports the Media Fragments URI fragment identifier 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 fragment identifier. [MEDIA-FRAGS]

The inBandMetadataTrackDispatchType attribute must return the text track in-band metadata track dispatch type of the text track that the TextTrack object represents.

The mode attribute, on getting, must return the string corresponding to the text track mode of the text track that the TextTrack object represents, as defined by the following list:

"disabled"
The text track disabled mode.
"hidden"
The text track hidden mode.
"showing"
The 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 "disabled"

Set the text track mode of the text track that the TextTrack object represents to the text track disabled mode.

If the new value is "hidden"

Set the text track mode of the text track that the TextTrack object represents to the text track hidden mode.

If the new value is "showing"

Set the text track mode of the text track that the TextTrack object represents to the text track showing mode.

If the text track mode of the text track that the TextTrack object represents is not the text track disabled mode, then the cues attribute must return a live TextTrackCueList object that represents the subset of the text track list of cues of the text track that the TextTrack object represents whose end times occur at or after the earliest possible position when the script started, in text track cue order. Otherwise, it must return null. For each TextTrack object, when an object is returned, the same TextTrackCueList object must be returned each time.

The earliest possible position when the script started is whatever the earliest possible position was the last time the event loop reached step 1.

If the text track mode of the text track that the TextTrack object represents is not the text track disabled mode, then the activeCues attribute must return a live TextTrackCueList object that represents the subset of the text track list of cues of the text track that the TextTrack object represents whose active flag was set when the script started, in text track cue order. Otherwise, it must return null. For each TextTrack object, when an object is returned, the same TextTrackCueList object must be returned each time.

A text track cue’s active flag was set when the script started if its text track cue active flag was set the last time the event loop reached step 1.


The addCue(cue) method of TextTrack objects, when invoked, must run the following steps:

  1. If the text track list of cues does not yet have any associated rules for updating the text track rendering, then associate the text track list of cues with the rules for updating the text track rendering appropriate to cue.
  2. If text track list of cues' associated rules for updating the text track rendering are not the same rules for updating the text track rendering as appropriate for cue, then throw an InvalidStateError exception and abort these steps.
  3. If the given cue is in a text track list of cues, then remove cue from that text track list of cues.
  4. Add cue to the method’s TextTrack object’s text track’s text track list of cues.

The removeCue(cue) method of TextTrack objects, when invoked, must run the following steps:

  1. If the given cue is not currently listed in the method’s TextTrack object’s text track’s text track list of cues, then throw a NotFoundError exception and abort these steps.
  2. Remove cue from the method’s TextTrack object’s text track’s text track list of cues.
In this example, an audio element is used to play a specific sound-effect from a sound file containing many sound effects. A cue is used to pause the audio, so that it ends exactly at the end of the clip, even if the browser is busy running some script. If the page had relied on script to pause the audio, then the start of the next clip might be heard if the browser was not able to run the script at the exact time specified.
var sfx = new Audio('sfx.wav');
var sounds = sfx.addTextTrack('metadata');

// add sounds we care about
function addFX(start, end, name) {
  var cue = new VTTCue(start, end, '');
  cue.id = name;
  cue.pauseOnExit = true;
  sounds.addCue(cue);
}
addFX(12.783, 13.612, 'dog bark');
addFX(13.612, 15.091, 'kitten mew'))

function playSound(id) {
  sfx.currentTime = sounds.getCueById(id).startTime;
  sfx.play();
}

// play a bark as soon as we can
sfx.oncanplaythrough = function () {
  playSound('dog bark');
}
// meow when the user tries to leave
window.onbeforeunload = function () {
  playSound('kitten mew');
  return 'Are you sure you want to leave this awesome page?';
}

interface TextTrackCueList {
  readonly attribute unsigned long length;
  getter TextTrackCue (unsigned long index);
  TextTrackCue? getCueById(DOMString id);
};
cuelist . length
Returns the number of cues in the list.
cuelist[index]
Returns the text track cue with index index in the list. The cues are sorted in text track cue order.
cuelist . getCueById( id )
Returns the first text track cue (in text track cue order) with text track cue identifier id. Returns null if none of the cues have the given identifier or if the argument is the empty string.

A TextTrackCueList object represents a dynamically updating list of text track cues in a given order.

The length attribute must return the number of cues in the list represented by the TextTrackCueList object.

The supported property indices of a TextTrackCueList object at any instant are the numbers from zero to the number of cues in the list represented by the TextTrackCueList object minus one, if any. If there are no cues in the list, there are no supported property indices.

To determine the value of an indexed property for a given index index, the user agent must return the indexth text track cue in the list represented by the TextTrackCueList object.

The getCueById(id) method, when called with an argument other than the empty string, must return the first text track cue in the list represented by the TextTrackCueList object whose text track cue identifier is id, if any, or null otherwise. If the argument is the empty string, then the method must return null.


interface TextTrackCue : EventTarget {
  readonly attribute TextTrack? track;

  attribute DOMString id;
  attribute double startTime;
  attribute double endTime;
  attribute boolean pauseOnExit;

  attribute EventHandler onenter;
  attribute EventHandler onexit;
};
cue . track
Returns the TextTrack object to which this text track cue belongs, if any, or null otherwise.
cue . id [ = value ]
Returns the text track cue identifier. Can be set.
cue . startTime [ = value ]
Returns the text track cue start time, in seconds. Can be set.
cue . endTime [ = value ]
Returns the text track cue end time, in seconds. Can be set.
cue . pauseOnExit [ = value ]
Returns true if the text track cue pause-on-exit flag is set, false otherwise. Can be set.

The track attribute, on getting, must return the TextTrack object of the text track in whose list of cues the text track cue that the TextTrackCue object represents finds itself, if any; or null otherwise.

The id attribute, on getting, must return the text track cue identifier of the text track cue that the TextTrackCue object represents. On setting, the text track cue identifier must be set to the new value.

The startTime attribute, on getting, must return the text track cue start time of the text track cue that the TextTrackCue object represents, in seconds. On setting, the text track cue start time must be set to the new value, interpreted in seconds; then, if the TextTrackCue object’s text track cue is in a text track’s list of cues, and that text track is in a media element’s list of text tracks, and the media element’s show poster flag is not set, then run the time marches on steps for that media element.

The endTime attribute, on getting, must return the text track cue end time of the text track cue that the TextTrackCue object represents, in seconds. On setting, the text track cue end time must be set to the new value, interpreted in seconds; then, if the TextTrackCue object’s text track cue is in a text track’s list of cues, and that text track is in a media element’s list of text tracks, and the media element’s show poster flag is not set, then run the time marches on steps for that media element.

The pauseOnExit attribute, on getting, must return true if the text track cue pause-on-exit flag of the text track cue that the TextTrackCue object represents is set; or false otherwise. On setting, the text track cue pause-on-exit flag must be set if the new value is true, and must be unset otherwise.

4.7.14.11.6. Text tracks exposing in-band metadata

The use of text tracks exposing in-band metadata is "at risk". If testing during the Candidate Recommendation phase does not identify at least two interoperable implementations in current shipping browsers of text tracks exposing in-band metadata this section will be removed from the HTML 5.1 Specification.

Media resources often contain one or more media-resource-specific text tracks containing data that browsers don’t render, but want to expose to script to allow being dealt with.

If the browser is unable to identify a TextTrackCue interface that is more appropriate to expose the data in the cues of a media-resource-specific text track, the DataCue object is used. [INBANDTRACKS]

[Constructor(double startTime, double endTime, ArrayBuffer data)]
interface DataCue : TextTrackCue {
  attribute ArrayBuffer data;
};
cue = new DataCue( [ startTime, endTime, data ] )
Returns a new DataCue object, for use with the addCue() method. The startTime argument sets the text track cue start time. The endTime argument sets the text track cue end time. The data argument is copied as the text track cue data.
cue . data [ = value ]
Returns the text track cue data in raw unparsed form. Can be set.

The data attribute, on getting, must return the raw text track cue data of the text track cue that the TextTrackCue object represents. On setting, the text track cue data must be set to the new value.

The user agent will use DataCue to expose only text track cue objects that belong to a text track that has a text track kind of metadata.

DataCue has a constructor to allow script to create DataCue objects in cases where generic metadata needs to be managed for a text track.

The rules for updating the text track rendering for a DataCue simply state that there is no rendering, even when the cues are in showing mode and the text track kind is one of subtitles or captions or descriptions or chapters.

4.7.14.11.7. Text tracks describing chapters

Chapters are segments of a media resource with a given title. Chapters can be nested, in the same way that sections in a document outline can have subsections.

Each text track cue in a text track being used for describing chapters has three key features: the text track cue start time, giving the start time of the chapter, the text track cue end time, giving the end time of the chapter, and the text track rules for extracting the chapter title.

The rules for constructing the chapter tree from a text track are as follows. They produce a potentially nested list of chapters, each of which have a start time, end time, title, and a list of nested chapters. This algorithm discards cues that do not correctly nest within each other, or that are out of order.

  1. Let list be a copy of the list of cues of the text track being processed.
  2. Remove from list any text track cue whose text track cue end time is before its text track cue start time.
  3. Let output be an empty list of chapters, where a chapter is a record consisting of a start time, an end time, a title, and a (potentially empty) list of nested chapters. For the purpose of this algorithm, each chapter also has a parent chapter.
  4. Let current chapter be a stand-in chapter whose start time is negative infinity, whose end time is positive infinity, and whose list of nested chapters is output. (This is just used to make the algorithm easier to describe.)
  5. Loop: If list is empty, jump to the step labeled end.
  6. Let current cue be the first cue in list, and then remove it from list.
  7. If current cue’s text track cue start time is less than the start time of current chapter, then return to the step labeled loop.
  8. While current cue’s text track cue start time is greater than or equal to current chapter’s end time, let current chapter be current chapter’s parent chapter.
  9. If current cue’s text track cue end time is greater than the end time of current chapter, then return to the step labeled loop.
  10. Create a new chapter new chapter, whose start time is current cue’s text track cue start time, whose end time is current cue’s text track cue end time, whose title is current cue’s text track cue data interpreted according to its rules for rendering the cue in isolation, and whose list of nested chapters is empty.

  11. Append new chapter to current chapter’s list of nested chapters, and let current chapter be new chapter’s parent.
  12. Let current chapter be new chapter.
  13. Return to the step labeled loop.
  14. End: Return output.
The following snippet of a WebVTT file shows how nested chapters can be marked up. The file describes three 50-minute chapters, "Astrophysics", "Computational Physics", and "General Relativity". The first has three subchapters, the second has four, and the third has two. [WEBVTT]
WEBVTT
00:00:00.000 --> 00:50:00.000
Astrophysics

00:00:00.000 --> 00:10:00.000
Introduction to Astrophysics

00:10:00.000 --> 00:45:00.000
The Solar System

00:00:00.000 --> 00:10:00.000
Coursework Description

00:50:00.000 --> 01:40:00.000
Computational Physics

00:50:00.000 --> 00:55:00.000
Introduction to Programming

00:55:00.000 --> 01:30:00.000
Data Structures

01:30:00.000 --> 01:35:00.000
Answers to Last Exam

01:35:00.000 --> 01:40:00.000
Coursework Description

01:40:00.000 --> 02:30:00.000
General Relativity

01:40:00.000 --> 02:00:00.000
Tensor Algebra

02:00:00.000 --> 02:30:00.000
The General Relativistic Field Equations
4.7.14.11.8. Event handlers for objects of the text track APIs

The following are the event handlers that (and their corresponding event handler event types) must be supported, as event handler IDL attributes, by all objects implementing the TextTrackList interface:

Event handler Event handler event type
onchange change
onaddtrack addtrack
onremovetrack removetrack

The following are the event handlers that (and their corresponding event handler event types) must be supported, as event handler IDL attributes, by all objects implementing the TextTrack interface:

Event handler Event handler event type
oncuechange cuechange

The following are the event handlers that (and their corresponding event handler event types) must be supported, as event handler IDL attributes, by all objects implementing the TextTrackCue interface:

Event handler Event handler event type
onenter enter
onexit exit
4.7.14.11.9. 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 overlayed 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
...

05:10:00.000 --> 05:12:15.000
matchtype:qual
matchnumber:37

...

05:11:02.251 --> 05:11:17.198
red:78

05:11:03.672 --> 05:11:54.198
blue:66

05:11:17.198 --> 05:11:25.912
red:80

05:11:25.912 --> 05:11:26.522
red:83

05:11:26.522 --> 05:11:26.982
red:86

05:11:26.982 --> 05:11:27.499
red:89

...

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 cuechange event to update the current annotations. (In particular, using the 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 timeupdate events are rate-limited.)

4.7.14.12. User interface

The controls attribute is a boolean attribute. If present, it indicates that the author has not provided a scripted controller and would like the user agent to provide its own set of controls.

If the attribute is present, or if scripting is disabled for the 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.

A user agent 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 media element’s context menu, platform media keys, or a remote control. The user agent may implement this simply by exposing a user interface to the user as described above (as if the controls attribute was present).

If the user agent exposes a user interface to the user by displaying controls over the 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, 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.

For the purposes of listing chapters in the media resource, only text tracks in the media element’s list of text tracks that are showing and whose text track kind is chapters should be used. Such tracks must be interpreted according to the rules for constructing the chapter tree from a text track. When seeking in response to a user manipulating a chapter selection interface, user agents should not use the approximate-for-speed flag.

The controls IDL attribute must reflect the content attribute of the same name.


media . volume [ = value ]

Returns the current playback volume, as a number in the range 0.0 to 1.0, where 0.0 is the quietest and 1.0 the loudest.

Can be set, to change the volume.

Throws an IndexSizeError exception if the new value is not in the range 0.0 .. 1.0.

media . muted [ = value ]

Returns true if audio is muted, overriding the volume attribute, and false if the volume attribute is being honored.

Can be set, to change whether the audio is muted or not.

A 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 playback volume of any audio portions of the media element. On setting, if the new value is in the range 0.0 to 1.0 inclusive, the media element’s 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 IndexSizeError exception must be thrown instead.

A media element can also be muted. If anything is muting the element, then it is muted. (For example, when the 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 media element is created, if the element has a muted content attribute specified, then the 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 muted IDL attribute is set to true, the media element must be muted.

Whenever either of the values that would be returned by the volume and muted IDL attributes change, the user agent must queue a task to fire a simple event named volumechange at the media element.

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 the element’s effective media volume is the volume desired by the user. Abort these steps.
  2. If the element’s audio output is muted, the element’s effective media volume is zero. Abort these steps.
  3. Let volume be the playback volume of the audio portions of the media element, in range 0.0 (silent) to 1.0 (loudest).
  4. The element’s effective media volume is 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 media elements is a boolean attribute that controls the default state of the audio output of the media resource, potentially overriding user preferences.

The defaultMuted IDL attribute must reflect the 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.
<video src="adverts.cgi?kind=video" controls autoplay loop muted></video>
4.7.14.13. Time ranges

Objects implementing the TimeRanges interface represent a list of ranges (periods) of time.

interface TimeRanges {
  readonly attribute unsigned long length;
  double start(unsigned long index);
  double end(unsigned long index);
};
media . length

Returns the number of ranges in the object.

time = media . start(index)

Returns the time for the start of the range with the given index.

Throws an IndexSizeError exception if the index is out of range.

time = media . end(index)

Returns the time for the end of the range with the given index.

Throws an IndexSizeError exception if the index is out of range.

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 IndexSizeError exceptions if called with an index argument greater than or equal to the number of ranges represented by the object.

When a 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 media resource except for the current frame, when a media element is paused.

Ranges in a 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 buffered, seekable and played IDL attributes of media elements must be that element’s media timeline.

4.7.14.14. The TrackEvent interface
[Constructor(DOMString type, optional TrackEventInit eventInitDict)]
interface TrackEvent : Event {
  readonly attribute (VideoTrack or AudioTrack or TextTrack)? track;
};

dictionary TrackEventInit : EventInit {
  (VideoTrack or AudioTrack or TextTrack)? track;
};
event . track

Returns the track object (TextTrack, AudioTrack, or VideoTrack) to which the event relates.

The track attribute must return the value it was initialized to. When the object is created, this attribute must be initialized to null. It represents the context information for the event.

4.7.14.15. Event summary

This section is non-normative.

The following events fire on media elements as part of the processing model described above:

Event name Interface Fired when... Preconditions
loadstart Event The user agent begins looking for media data, as part of the resource selection algorithm. networkState equals NETWORK_LOADING
progress Event The user agent is fetching media data. networkState equals NETWORK_LOADING
suspend Event The user agent is intentionally not currently fetching media data. networkState equals NETWORK_IDLE
abort Event The user agent stops fetching the media data before it is completely downloaded, but not due to an error. error is an object with the code MEDIA_ERR_ABORTED. networkState equals either NETWORK_EMPTY or NETWORK_IDLE, depending on when the download was aborted.
error Event An error occurs while fetching the media data or the type of the resource is not supported media format. error is an object with the code MEDIA_ERR_NETWORK or higher. networkState equals either NETWORK_EMPTY or NETWORK_IDLE, depending on when the download was aborted.
emptied Event A media element whose networkState was previously not in the NETWORK_EMPTY state has just switched to that state (either because of a fatal error during load that’s about to be reported, or because the load() method was invoked while the resource selection algorithm was already running). networkState is NETWORK_EMPTY; all the IDL attributes are in their initial states.
stalled Event The user agent is trying to fetch media data, but data is unexpectedly not forthcoming. networkState is NETWORK_LOADING.
loadedmetadata Event The user agent has just determined the duration and dimensions of the media resource and the text tracks are ready. readyState is newly equal to HAVE_METADATA or greater for the first time.
loadeddata Event The user agent can render the media data at the current playback position for the first time. readyState newly increased to HAVE_CURRENT_DATA or greater for the first time.
canplay Event The user agent can resume playback of the media data, but estimates that if playback were to be started now, the media resource could not be rendered at the current playback rate up to its end without having to stop for further buffering of content. readyState newly increased to HAVE_FUTURE_DATA or greater.
canplaythrough Event The user agent estimates that if playback were to be started now, the media resource could be rendered at the current playback rate all the way to its end without having to stop for further buffering. readyState is newly equal to HAVE_ENOUGH_DATA.
playing Event Playback is ready to start after having been paused or delayed due to lack of media data. readyState is newly equal to or greater than HAVE_FUTURE_DATA and paused is false, or paused is newly false and readyState is equal to or greater than HAVE_FUTURE_DATA. Even if this event fires, the element might still not be potentially playing, e.g., if the element is paused for user interaction or paused for in-band content.
waiting Event Playback has stopped because the next frame is not available, but the user agent expects that frame to become available in due course. readyState is equal to or less than HAVE_CURRENT_DATA, and paused is false. Either seeking is true, or the current playback position is not contained in any of the ranges in buffered. It is possible for playback to stop for other reasons without paused being false, but those reasons do not fire this event (and when those situations resolve, a separate playing event is not fired either): e.g., the playback ended, or playback stopped due to errors, or the element has paused for user interaction or paused for in-band content.
seeking Event The seeking IDL attribute changed to true, and the user agent has started seeking to a new position.
seeked Event The seeking IDL attribute changed to false after the current playback position was changed.
ended Event Playback has stopped because the end of the media resource was reached. currentTime equals the end of the media resource; ended is true.
durationchange Event The duration attribute has just been updated.
timeupdate Event The current playback position changed as part of normal playback or in an especially interesting way, for example discontinuously.
play Event The element is no longer paused. Fired after the play() method has returned, or when the autoplay attribute has caused playback to begin. paused is newly false.
pause Event The element has been paused. Fired after the pause() method has returned. paused is newly true.
ratechange Event Either the defaultPlaybackRate or the playbackRate attribute has just been updated.
resize Event One or both of the videoWidth and videoHeight attributes have just been updated. Media element is a video element; readyState is not HAVE_NOTHING
volumechange Event Either the volume attribute or the muted attribute has changed. Fired after the relevant attribute’s setter has returned.

The following event fires on source element:

Event name Interface Fired when...
error Event An error occurs while fetching the media data or the type of the resource is not supported media format.

The following events fire on AudioTrackList, VideoTrackList, and TextTrackList objects:

Event name Interface Fired when...
change Event One or more tracks in the track list have been enabled or disabled.
addtrack TrackEvent A track has been added to the track list.
removetrack TrackEvent A track has been removed from the track list.

The following event fires on TextTrack objects and track elements:

Event name Interface Fired when...
cuechange Event One or more cues in the track have become active or stopped being active.

The following events fire on track elements:

Event name Interface Fired when...
error Event An error occurs while fetching the track data or the type of the resource is not supported text track format.
load Event A track data has been fetched and successfully processed.

The following events fire on TextTrackCue objects:

Event name Interface Fired when...
enter Event The cue has become active.
exit Event The cue has stopped being active.
4.7.14.16. Security and privacy considerations

The main security and privacy implications of the video and 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 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 top-level browsing context.

For instance, if an SVG animation was embedded in a 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 browsing context 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 be obtained using the 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 or chapter titles. Such information is therefore only exposed if the video resource passes a CORS resource sharing check. The crossorigin attribute allows authors to control how this check is performed. [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.7.14.17. 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 media elements when they are done playing, either by being very careful about removing all references to the element and allowing it to be garbage collected, or, even better, by removing the element’s src attribute and any source element descendants, and invoking the element’s load() method.

Similarly, when the playback rate is not exactly 1.0, hardware, software, or format limitations can cause video frames to be dropped and audio to be choppy or muted.

4.7.14.18. Best practices for implementors of media elements

This section is non-normative.

How accurately various aspects of the media element API are implemented is considered a quality-of-implementation issue.

For example, when implementing the 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-bit-rate 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 media element that is paused is removed from a document and not reinserted before the next time the event loop reaches 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 media element. (User agents still have to keep track of the playback position and so forth, though, in case playback is later restarted.)

4.7.15. The map element

Categories:
Flow content.
Phrasing content.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Transparent.
Tag omission in text/html:
Neither tag is omissible
Content attributes:
Global attributes
name - Name of image map to reference from the usemap attribute
Allowed ARIA role attribute values:
None
Allowed ARIA state and property attributes:
Global aria-* attributes
DOM interface:
interface HTMLMapElement : HTMLElement {
  attribute DOMString name;
  [SameObject] readonly attribute HTMLCollection areas;
  [SameObject] readonly attribute HTMLCollection images;
};

The map element, in conjunction with an img element and any area element descendants, defines an image map. The element represents its children.

The name attribute gives the map a name so that it can be referenced. The attribute must be present and must have a non-empty value with no space characters. The value of the name attribute must not be a compatibility caseless match for the value of the name attribute of another map element in the same document. If the id attribute is also specified, both attributes must have the same value.

map . areas

Returns an HTMLCollection of the area elements in the map.

map . images

Returns an HTMLCollection of the img and object elements that use the map.

The areas attribute must return an HTMLCollection rooted at the map element, whose filter matches only area elements.

The images attribute must return an HTMLCollection rooted at the Document node, whose filter matches only img and object elements that are associated with this map element according to the image map processing model.

The IDL attribute name must 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.
<!DOCTYPE HTML>
<TITLE>Babies™: Toys</TITLE>
<HEADER>
  <h1>Toys</h1>
  <IMG SRC="/images/menu.gif"
      ALT="Babies™ navigation menu. Select a department to go to its page."
      USEMAP="#NAV">
</HEADER>
  ...
<FOOTER>
  <MAP NAME="NAV">
  <P>
    <A HREF="/clothes/">Clothes</A>
    <AREA ALT="Clothes" COORDS="0,0,100,50" HREF="/clothes/"> |
    <A HREF="/toys/">Toys</A>
    <AREA ALT="Toys" COORDS="100,0,200,50" HREF="/toys/"> |
    <A HREF="/food/">Food</A>
    <AREA ALT="Food" COORDS="200,0,300,50" HREF="/food/"> |
    <A HREF="/books/">Books</A>
    <AREA ALT="Books" COORDS="300,0,400,50" HREF="/books/">
  </P>
  </MAP>
</FOOTER>

4.7.16. The area element

Categories:
Flow content.
Phrasing content.
Contexts in which this element can be used:
Where phrasing content is expected, but only if there is a map element ancestor or a template element ancestor.
Content model:
Nothing.
Tag omission in text/html:
No end tag
Content attributes:
Global attributes
alt - Replacement text for use when images are not available
coords - Coordinates for the shape to be created in an image map
download - Whether to download the resource instead of navigating to it, and its file name if so
href - Address of the hyperlink
hreflang - Language of the linked resource
rel - Relationship of this document (or subsection/topic) to the destination resource
shape - The kind of shape to be created in an image map
target - browsing context for hyperlink navigation
type - Hint for the type of the referenced resource
Allowed ARIA role attribute values:
link role (default - do not set).
Allowed ARIA state and property attributes:
Global aria-* attributes
Any aria-* attributes applicable to the allowed roles.
DOM interface:
interface HTMLAreaElement : HTMLElement {
  attribute DOMString alt;
  attribute DOMString coords;
  attribute DOMString shape;
  attribute DOMString target;
  attribute DOMString download;
  attribute DOMString rel;
  readonly attribute DOMTokenList relList;
  attribute DOMString hreflang;
  attribute DOMString type;
};
HTMLAreaElement implements HTMLHyperlinkElementUtils;

The area element represents either a hyperlink with some text and a corresponding area on an image map, or a dead area on an image map.

An area element with a parent node must have a map element ancestor or a template element ancestor.

If the area element has an href attribute, then the area element represents a hyperlink. In this case, the alt attribute must be present. It specifies the text of the hyperlink. Its value must be text that informs the user about the destination of the link.

If the area element has no href attribute, then the area represented by the element cannot be selected, and the alt attribute must be omitted.

In both cases, the shape and coords attributes specify the area.

The shape attribute is an enumerated attribute. The following table lists the keywords defined for this attribute. The states given in the first cell of the rows with keywords give the states to which those keywords map. Some of the keywords are non-conforming, as noted in the last column.

State Keywords Notes
Circle state circle
circ Non-conforming
Default state default
Polygon state poly
polygon Non-conforming
Rectangle state rect
rectangle Non-conforming

The attribute may be omitted. The missing value default is the rectangle state.

The coords attribute must, if specified, contain a valid list of floating-point numbers. This attribute gives the coordinates for the shape described by the shape attribute. The processing for this attribute is described as part of the image map processing model.

In the circle state, area elements must have a coords attribute present, with three integers, the last of which must be non-negative. The first integer must be the distance in CSS pixels from the left edge of the image to the center of the circle, the second integer must be the distance in CSS pixels from the top edge of the image to the center of the circle, and the third integer must be the radius of the circle, again in CSS pixels.

In the default state state, area elements must not have a coords attribute. (The area is the whole image.)

In the polygon state, area elements must have a coords attribute with at least six integers, and the number of integers must be even. Each pair of integers must represent a coordinate given as the distances from the left and the top of the image in CSS pixels respectively, and all the coordinates together must represent the points of the polygon, in order.

In the rectangle state, area elements must have a coords attribute with exactly four integers, the first of which must be less than the third, and the second of which must be less than the fourth. The four points must represent, respectively, the distance from the left edge of the image to the left side of the rectangle, the distance from the top edge to the top side, the distance from the left edge to the right side, and the distance from the top edge to the bottom side, all in CSS pixels.

When user agents allow users to follow hyperlinks or download hyperlinks created using the area element, as described in the next section, the href, target, and download attributes decide how the link is followed. The rel, hreflang, and type attributes may be used to indicate to the user the likely nature of the target resource before the user follows the link.

The target, download, rel, hreflang, and type attributes must be omitted if the href attribute is not present.

The activation behavior of area elements is to run the following steps:

  1. If the area element’s node document is not fully active, then abort these steps.
  2. If the area element has a download attribute and the algorithm is not allowed to show a popup; or, if the user has not indicated a specific browsing context for following the link, and the element’s target attribute is present, and applying the rules for choosing a browsing context given a browsing context name, using the value of the target attribute as the browsing context name, would result in there not being a chosen browsing context, then run these substeps:

    1. If there is an entry settings object, throw an InvalidAccessError exception.
    2. Abort these steps without following the hyperlink.
  3. Otherwise, the user agent must follow the hyperlink or download the hyperlink created by the area element, if any, and as determined by the download attribute and any expressed user preference.

The IDL attributes alt, coords, target, download, rel, hreflang, and type, each must reflect the respective content attributes of the same name.

The IDL attribute shape must reflect the shape content attribute.

The IDL attribute relList must reflect the rel content attribute.


The area element also supports the HTMLHyperlinkElementUtils interface. [URL]

When the element is created, and whenever the element’s href content attribute is set, changed, or removed, the user agent must invoke the element’s HTMLHyperlinkElementUtils interface’s set the input algorithm with the value of the href content attribute, if any, or the empty string otherwise, as the given value.

The element’s HTMLHyperlinkElementUtils interface’s get the base algorithm must simply return the document base URL.

The element’s HTMLHyperlinkElementUtils interface’s query encoding is the document’s character encoding.

When the element’s HTMLHyperlinkElementUtils interface invokes its update steps with a string value, the user agent must set the element’s href content attribute to the string value.

4.7.17. Image maps

4.7.17.1. Authoring

An image map allows geometric areas on an image to be associated with hyperlinks.

An image, in the form of an img element, may be associated with an image map (in the form of a map element) by specifying a usemap attribute on the img element. The usemap attribute, if specified, must be a valid hash-name reference to a 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:

<p>
  Please select a shape:
  <img src="shapes.png" usemap="#shapes"
      alt="Four shapes are available: a red hollow box, a green circle, a blue triangle, and a yellow four-pointed star.">
  <map name="shapes">
  <area shape=rect coords="50,50,100,100"> <!-- the hole in the red box -->
  <area shape=rect coords="25,25,125,125" href="red.html" alt="Red box.">
  <area shape=circle coords="200,75,50" href="green.html" alt="Green circle.">
  <area shape=poly coords="325,25,262,125,388,125" href="blue.html" alt="Blue triangle.">
  <area shape=poly coords="450,25,435,60,400,75,435,90,450,125,465,90,500,75,465,60"
        href="yellow.html" alt="Yellow star.">
  </map>
</p>
4.7.17.2. Processing model

If an img element has a usemap attribute specified, user agents must process it as follows:

  1. Parse the attribute’s value using the rules for parsing a hash-name reference to a map element, with the element’s node document as the context node. This will return either an element (the map) or null.
  2. If that returned null, then abort these steps. The image is not associated with an image map after all.
  3. Otherwise, the user agent must collect all the area elements that are descendants of the map. Let those be the areas.

Having obtained the list of 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 img element represents, then it must use the following steps.

In user agents that do not support images, or that have images disabled, object elements cannot represent images, and thus this section never applies (the fallback content is shown instead). The following steps therefore only apply to img elements.

  1. Remove all the area elements in areas that have no href attribute.
  2. Remove all the area elements in areas that have no alt attribute, or whose alt attribute’s value is the empty string, if there is another area element in areas with the same value in the href attribute and with a non-empty alt attribute.
  3. Each remaining area element in areas represents a hyperlink. Those hyperlinks should all be made available to the user in a manner associated with the text of the img.

    In this context, user agents may represent area and img elements with no specified alt attributes, or whose alt attributes are the empty string or some other non-visible text, in a user-agent-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 area elements in areas, in reverse tree order (so the last specified area element in the map is the bottom-most shape, and the first element in the map, in tree order, is the top-most shape).

Each 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 shape attribute represents.
  2. Use the rules for parsing a list of floating-point numbers to parse the element’s 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 area element’s current state, as per the following table, then the shape is empty; abort these steps.

    State Minimum number of items
    Circle state 3
    Default state 0
    Polygon state 6
    Rectangle state 4
  4. Check for excess items in the coords list as per the entry in the following list corresponding to the shape attribute’s state:

    Circle state
    Drop any items in the list beyond the third.
    Default state
    Drop all items in the list.
    Polygon state
    Drop the last item if there’s an odd number of items.
    Rectangle state
    Drop any items in the list beyond the fourth.
  5. If the shape attribute represents the 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 shape attribute represents the 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 shape attribute represents the circle state, and the third number in the list is less than or equal to zero, then the shape is empty; abort these steps.
  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 shape attribute:
    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 CSS pixels from the left edge of the image and y CSS pixels from the top edge of the image, and whose radius is r pixels.

    Default state

    The shape is a rectangle that exactly covers the entire image.

    Polygon state

    Let xi be the (2i)th entry in coords, and yi be the (2i+1)th entry in coords (the first entry in coords being the one with index 0).

    Let the coordinates be (xi, yi), interpreted in 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. [GRAPHICS]

    Rectangle state

    Let x1 be the first number in coords, y1 be the second number, x2 be the third number, and y2 be the fourth number.

    The shape is a rectangle whose top-left corner is given by the coordinate (x1, y1) and whose bottom right corner is given by the coordinate (x2, y2), those coordinates being interpreted as 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 width and 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 area elements representing hyperlinks to be selected and activated (e.g., using a keyboard).

Because a map element (and its area elements) can be associated with multiple img and object elements, it is possible for an area element to correspond to multiple focusable areas of the document.

Image maps are live; if the DOM is mutated, then the user agent must act as if it had rerun the algorithms for image maps.

4.7.18. MathML

The math element from the MathML namespace falls into the embedded content, phrasing content, flow content, and palpable content categories for the purposes of the content models in this specification.

This specification refers to several specific MathML elements, in particular: annotation-xml, merror, mi, mn, mo, ms, and mtext.

When the MathML annotation-xml element contains elements from the HTML namespace, such elements must all be flow content. [MATHML]

When the MathML token elements (mi, mo, mn, ms, and mtext) are descendants of HTML elements, they may contain phrasing content elements from the HTML namespace. [MATHML]

User agents must handle text other than 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 an mtext element in the MathML namespace. (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 an merror element in the MathML namespace containing some appropriate error message.

To enable authors to use MathML tools that only accept MathML in its XML form, interactive HTML user agents are encouraged to provide a way to export any MathML fragment as an XML namespace-well-formed XML fragment.

The semantics of MathML elements are defined by the MathML specification and other applicable specifications. [MATHML]

Here is an example of the use of MathML in an HTML document:
<!DOCTYPE html>
<html>
  <head>
  <title>The quadratic formula</title>
  </head>
  <body>
  <h1>The quadratic formula</h1>
  <p>
    <math>
    <mi>x</mi>
    <mo>=</mo>
    <mfrac>
      <mrow>
      <mo form="prefix">-</mo> <mi>b</mi>
      <mo>±</mo>
      <msqrt>
        <msup> <mi>b</mi> <mn>2</mn> </msup>
        <mo>-</mo>
        <mn>4</mn> <mo></mo> <mi>a</mi> <mo></mo> <mi>c</mi>
      </msqrt>
      </mrow>
      <mrow>
      <mn>2</mn> <mo></mo> <mi>a</mi>
      </mrow>
    </mfrac>
    </math>
  </p>
  </body>
</html>

4.7.19. SVG

The svg element from the SVG namespace falls into the embedded content, phrasing content, flow content, and palpable content categories for the purposes of the content models in this specification.

To enable authors to use SVG tools that only accept SVG in its XML form, interactive HTML user agents are encouraged to provide a way to export any SVG fragment as an XML namespace-well-formed XML fragment.

When the SVG foreignObject element contains elements from the HTML namespace, such elements must all be flow content. [SVG11]

The content model for title elements in the SVG namespace inside HTML documents is phrasing content. (This further constrains the requirements given in the SVG specification.)

The semantics of SVG elements are defined by the SVG specification and other applicable specifications. [SVG11]

User agent requirements: SVG as implemented today follows neither SVG 1.1 nor SVG Tiny 1.2 precisely, instead implementing subsets of each. Although it is hoped that the in-progress SVG 2 specification is a more realistic target for implementations, until that specification is ready, user agents must implement the SVG 1.1 specification with the following willful violations and additions. [SVG11] [SVGTiny12] [SVG2]

The following features from SVG 1.1 must not be implemented:

  • The tref element
  • The cursor element (use CSS’s cursor property instead)
  • The font-defining elements: font, glyph, missing-glyph, hkern, vkern, font-face, font-face-src, font-face-uri, font-face-format, and font-face-name (use CSS’s @font-face instead)
  • The externalResourcesRequired attribute
  • The enable-background property
  • The contentScriptType and contentStyleType attributes (use the type attribute on the script and style elements instead)

The following features from SVG Tiny 1.2 must be implemented:

  • The non-scaling-stroke value for the vector-effect property
  • The class attribute is allowed on all SVG elements
  • The tabindex attribute is allowed on visible SVG elements
  • The ARIA accessibility attributes are allowed on all SVG elements

4.7.20. Dimension attributes

Author requirements: The width and height attributes on img, iframe, embed, object, video, and, when their type attribute is in the image button state, input elements may be specified to give the dimensions of the visual content of the element (the width and height respectively, relative to the nominal direction of the output medium), in CSS pixels. The attributes, if specified, must have values that are valid non-negative integers.

The specified dimensions given may differ from the dimensions specified in the resource itself, since the resource may have a resolution that differs from the CSS pixel resolution. (On screens, CSS pixels have a resolution of 96ppi, but in general the CSS pixel resolution depends on the reading distance.) If both attributes are specified, then one of the following statements must be true:

  • specified width - 0.5 ≤ specified height * target ratiospecified width + 0.5
  • specified height - 0.5 ≤ specified width / target ratiospecified height + 0.5
  • specified height = specified width = 0

The target ratio is the ratio of the intrinsic width to the intrinsic height in the resource. The specified width and specified height are the values of the width and height attributes respectively.

The two attributes must be omitted if the resource in question does not have both an intrinsic width and an intrinsic height.

If the two attributes are both zero, it indicates that the element is not intended for the user (e.g., it might be a part of a service to count page views).

The dimension attributes are not intended to be used to stretch the image.

User agent requirements: User agents are expected to use these attributes as hints for the rendering.

The width and height IDL attributes on the iframe, embed, object, and video elements must reflect the respective content attributes of the same name.

For iframe, embed, and object the IDL attributes are DOMString; for video the IDL attributes are unsigned long.

The corresponding IDL attributes for img and input elements are defined in those respective elements' sections, as they are slightly more specific to those elements' other behaviors.

Links are a conceptual construct, created by a, area, and link elements, that represent a connection between two resources, one of which is the current Document. There are two kinds of links in HTML:

Links to external resources
These are links to resources that are to be used to augment the current document, generally automatically processed by the user agent.
Hyperlinks
These are links to other resources that are generally exposed to the user by the user agent so that the user can cause the user agent to navigate to those resources, e.g., to visit them in a browser or download them.

For link elements with an href attribute and a rel attribute, links must be created for the keywords of the rel attribute, as defined for those keywords in the link types section.

Similarly, for a and area elements with an href attribute and a rel attribute, links must be created for the keywords of the rel attribute as defined for those keywords in the link types section. Unlike link elements, however, a and area elements with an href attribute that either do not have a rel attribute, or whose rel attribute has no keywords that are defined as specifying hyperlinks, must also create a hyperlink. This implied hyperlink has no special meaning (it has no link type) beyond linking the element’s node document to the resource given by the element’s href attribute.

A hyperlink can have one or more hyperlink annotations that modify the processing semantics of that hyperlink.

The href attribute on a and area elements must have a value that is a valid URL potentially surrounded by spaces.

The href attribute on a and area elements is not required; when those elements do not have href attributes they do not create hyperlinks.

The target attribute, if present, must be a valid browsing context name or keyword. It gives the name of the browsing context that will be used. User agents use this name when following hyperlinks.

When an a or area element’s activation behavior is invoked, the user agent may allow the user to indicate a preference regarding whether the hyperlink is to be used for navigation or whether the resource it specifies is to be downloaded.

In the absence of a user preference, the default should be navigation if the element has no download attribute, and should be to download the specified resource if it does.

Whether determined by the user’s preferences or via the presence or absence of the attribute, if the decision is to use the hyperlink for navigation then the user agent must follow the hyperlink, and if the decision is to use the hyperlink to download a resource, the user agent must download the hyperlink. These terms are defined in subsequent sections below.

The download attribute, if present, indicates that the author intends the hyperlink to be used for downloading a resource. The attribute may have a value; the value, if any, specifies the default file name that the author recommends for use in labeling the resource in a local file system. There are no restrictions on allowed values, but authors are cautioned that most file systems have limitations with regard to what punctuation is supported in file names, and user agents are likely to adjust file names accordingly.

The rel attribute on a and area elements controls what kinds of links the elements create. The attribute’s value must be a set of space-separated tokens. The allowed keywords and their meanings are defined below.

rel's supported tokens are the keywords defined in HTML link types which are allowed on a and area elements, impact the processing model, and are supported by the user agent. The possible supported tokens are noreferrer, and noopener. rel's supported tokens must only include the tokens from this list that the user agent implements the processing model for.

Other specifications may add HTML link types as defined in Other link types. These specifications may require that their link types be included in rel's supported tokens.

The rel attribute has no default value. If the attribute is omitted or if none of the values in the attribute are recognized by the user agent, then the document has no particular relationship with the destination resource other than there being a hyperlink between the two.

The hreflang attribute on a elements that create hyperlinks, if present, gives the language of the linked resource. It is purely advisory. The value must be a valid BCP 47 language tag. [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 MIME type of the linked resource. It is purely advisory. The value must be a valid mime type. User agents must not consider the type attribute authoritative — upon fetching the resource, user agents must not use metadata included in the link to the resource to determine its type.

4.8.3. API for a and area elements

[NoInterfaceObject]
interface HTMLHyperlinkElementUtils {
  stringifier attribute USVString href;
  readonly attribute USVString origin;
  attribute USVString protocol;
  attribute USVString username;
  attribute USVString password;
  attribute USVString host;
  attribute USVString hostname;
  attribute USVString port;
  attribute USVString pathname;
  attribute USVString search;
  attribute USVString hash;
};
hyperlink . toString()
hyperlink . href

Returns the hyperlink’s URL.

Can be set, to change the URL.

hyperlink . origin

Returns the hyperlink’s URL’s origin.

hyperlink . protocol

Returns the hyperlink’s URL’s scheme.

Can be set, to change the URL’s scheme.

hyperlink . username

Returns the hyperlink’s URL’s username.

Can be set, to change the URL’s username.

hyperlink . password

Returns the hyperlink’s URL’s password.

Can be set, to change the URL’s password.

hyperlink . host

Returns the hyperlink’s URL’s host and port (if different from the default port for the scheme).

Can be set, to change the URL’s host and port.

hyperlink . hostname

Returns the hyperlink’s URL’s host.

Can be set, to change the URL’s host.

hyperlink . port

Returns the hyperlink’s URL’s port.

Can be set, to change the URL’s port.

hyperlink . pathname

Returns the hyperlink’s URL’s path.

Can be set, to change the URL’s path.

hyperlink . search

Returns the hyperlink’s URL’s query (includes leading "?" if non-empty).

Can be set, to change the URL’s query (ignores leading "?").

hyperlink . hash

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 HTMLHyperlinkElementUtils mixin has an associated url (null or a URL). It is initially null.

An element implementing the HTMLHyperlinkElementUtils mixin has an associated set the url algorithm, which sets this element’s URL to the resulting URL string of parsing this element’s href content attribute value relative to this element. If parsing was aborted with an error, set this element’s URL to null.

When elements implementing the HTMLHyperlinkElementUtils mixin are created, and whenever those elements have their href content attribute set, changed, or removed, the user agent must set the url.

This is only observable for blob: URLs as parsing them involves the StructuredClone abstract algorithm.

An element implementing the HTMLHyperlinkElementUtils mixin has an associated reinitialise url algorithm, which runs these steps:

  1. If element’s URL is non-null, its scheme is "blob", and its non-relative flag is set, terminate these steps.
  2. Set the url.

To update href, set the element’s href content attribute’s value to the element’s URL, serialized.


The href attribute’s getter must run these steps:

  1. Reinitialise url.
  2. Let url be this element’s URL.
  3. If url is null and this element has no href content attribute, return the empty string.
  4. Otherwise, if url is null, return this element’s href content attribute’s value.
  5. Return url, serialized.

The href attribute’s setter must set this element’s href content attribute’s value to the given value.

The origin attribute’s getter must run these steps:

  1. Reinitialise url.
  2. If this element’s URL is null, return the empty string.
  3. Return the Unicode serialization of this element’s URL’s origin.

It returns the Unicode rather than the ASCII serialization for compatibility with MessageEvent.

The protocol attribute’s getter must run these steps:

  1. Reinitialise url.
  2. If this element’s URL is null, return ":".
  3. Return this element’s URL’s scheme, followed by ":".

The protocol attribute’s setter must run these steps:

  1. Reinitialise url.
  2. If this element’s URL is null, terminate these steps.
  3. Basic URL parse the given value, followed by :", with this element’s URL as url and scheme start state as state override.
  4. Update href.

The username attribute’s getter must run these steps:

  1. Reinitialise url.
  2. If this element’s URL is null, return the empty string.
  3. Return this element’s URL’s username.

The username attribute’s setter must run these steps:

  1. Reinitialise url.
  2. Let url be this element’s URL.
  3. If url or url’s host is null, or url’s non-relative flag is set, terminate these steps.
  4. set the username, given url and the given value.
  5. Update href.

The password attribute’s getter must run these steps:

  1. Reinitialise url.
  2. Let url be this element’s URL.
  3. If url or url’s password is null, return the empty string.
  4. Return url’s password.

The password attribute’s setter must run these steps:

  1. Reinitialise url.
  2. Let url be this element’s URL.
  3. If url or url’s host is null, or url’s non-relative flag is set, terminate these steps.
  4. Set the password, given url and the given value.
  5. Update href.

The host attribute’s getter must run these steps:

  1. Reinitialise url.
  2. Let url be this element’s URL.
  3. If url or url’s host is null, return the empty string.
  4. If url’s port is null, return url’s host, serialized.
  5. Return url’s host, serialized, followed by ":" and url’s port, serialized.

The host attribute’s setter must run these steps:

  1. Reinitialise url.
  2. Let url be this element’s URL.
  3. If url is null or url’s non-relative flag is set, terminate these steps.
  4. Basic URL parse the given value, with url as url and host state as state override.
  5. Update href.

The hostname attribute’s getter must run these steps:

  1. Reinitialise url.
  2. Let url be this element’s URL.
  3. If url or url’s host is null, return the empty string.
  4. Return url’s host, serialized.

The hostname attribute’s setter must run these steps:

  1. Reinitialise url.
  2. Let url be this element’s URL.
  3. If url is null or url’s non-relative flag is set, terminate these steps.
  4. Basic URL parse the given value, with url as url and hostname state as state override.
  5. Update href.

The port attribute’s getter must run these steps:

  1. Reinitialise url.
  2. Let url be this element’s URL.
  3. If url or url’s port is null, return the empty string.
  4. Return url’s port, serialized.

The port attribute’s setter must run these steps:

  1. Reinitialise url.
  2. Let url be this element’s URL.
  3. If url or url’s host is null, url’s non-relative flag is set, or url’s scheme is "file", terminate these steps.
  4. Basic URL parse the given value, with url as url and port state as state override.
  5. Update href.

The pathname attribute’s getter must run these steps:

  1. Reinitialise url.
  2. Let url be this element’s URL.
  3. If url is null, return the empty string.
  4. If url’s non-relative flag is set, return the first string in url’s path.
  5. Return "/", followed by the strings in url’s path (including empty strings), separated from each other by "/".

The pathname attribute’s setter must run these steps:

  1. Reinitialise url.
  2. Let url be this element’s URL.
  3. If url is null or url’s non-relative flag is set, terminate these steps.
  4. Set url’s path to the empty list.
  5. Basic URL parse the given value, with url as url and path start state as state override.
  6. Update href.

The search attribute’s getter must run these steps:

  1. Reinitialise url.
  2. Let url be this element’s URL.
  3. If url is null, or url’s query is either null or the empty string, return the empty string.
  4. Return "?", followed by url’s query.

The search attribute’s setter must run these steps:

  1. Reinitialise url.
  2. Let url be this element’s URL.
  3. If url is null, terminate these steps.
  4. If the given value is the empty string, set url’s query to null.
  5. Otherwise, run these substeps:

    1. Let input be the given value with a single leading "?" removed, if any.
    2. Set url’s query to the empty string.
    3. Basic URL parse input, with url as url and query state as state override, and this element’s node document’s document’s character encoding as encoding override.
  6. Update href.

The hash attribute’s getter must run these steps:

  1. Reinitialise url.
  2. Let url be this element’s URL.
  3. If url is null, or url’s fragment is either null or the empty string, return the empty string.
  4. Return "#", followed by url’s fragment.

The hash attribute’s setter must run these steps:

  1. Reinitialise url.
  2. Let url be this element’s URL.
  3. If url is null or url’s scheme is "javascript", terminate these steps.
  4. If the given value is the empty string, set url’s fragment to null.
  5. Otherwise, run these substeps:

    1. Let input be the given value with a single leading "#" removed, if any.
    2. Set url’s fragment to the empty string.
    3. Basic URL parse input, with url as url and fragment state as state override.
  6. Update href.

When a user follows a hyperlink created by an element subject, optionally with a hyperlink suffix, the user agent must run the following steps:

  1. Let replace be false.
  2. Let source be the browsing context that contains the Document object with which subject in question is associated.
  3. If the user indicated a specific browsing context when following the hyperlink, or if the user agent is configured to follow hyperlinks by navigating a particular browsing context, then let target be that browsing context. If this is a new top-level browsing context (e.g., when the user followed the hyperlink using "Open in New Tab"), then source must be set as the new browsing context’s one permitted sandboxed navigator.

    Otherwise, if subject is an a or area element that has a target attribute, then let target be the browsing context that is chosen by applying the rules for choosing a browsing context given a browsing context name, using the value of the target attribute as the browsing context name. If these rules result in the creation of a new browsing context, set replace to true.

    Otherwise, if target is an a or area element with no target attribute, but the Document contains a base element with a target attribute, then let target be the browsing context that is chosen by applying the rules for choosing a browsing context given a browsing context name, using the value of the target attribute of the first such base element as the browsing context name. If these rules result in the creation of a new browsing context, set replace to true.

    Otherwise, let target be the browsing context that subject itself is in.

  4. Parse the URL given by subject’s href attribute, relative to subject’s node document.
  5. If that is successful, let URL be the resulting URL string.

    Otherwise, if parsing the URL failed, the user agent may report the error to the user in a user-agent-specific manner, may queue a task to navigate the target browsing context to an error page to report the error, or may ignore the error and do nothing. In any case, the user agent must then abort these steps.

  6. If there is a hyperlink suffix, append it to URL.
  7. Queue a task to navigate the target browsing context to URL. If replace is true, the navigation must be performed with replacement enabled. The source browsing context must be source.

The task source for the tasks mentioned above is the DOM manipulation task source.

4.8.5. Downloading resources

In some cases, resources are intended for later use rather than immediate viewing. To indicate that a resource is intended to be downloaded for use later, rather than immediately used, the download attribute can be specified on the a or area element that creates the hyperlink to that resource.

The attribute can furthermore be given a value, to specify the file name that user agents are to use when storing the resource in a file system. This value can be overridden by the Content-Disposition HTTP header’s filename parameters. [RFC6266]

In cross-origin situations, the download attribute has to be combined with the Content-Disposition HTTP header, specifically with the attachment disposition type, to avoid the user being warned of possibly nefarious activity. (This is to protect users from being made to download sensitive personal or confidential information without their full understanding.)


When a user downloads a hyperlink created by an element subject, optionally with a hyperlink suffix, the user agent must run the following steps:

  1. Parse the URL given by subject’s href attribute, relative to subject.
  2. If parsing the URL fails, the user agent may report the error to the user in a user-agent-specific manner, may navigate to an error page to report the error, or may ignore the error and do nothing. In either case, the user agent must abort these steps.
  3. Otherwise, let URL be the resulting URL string.
  4. If there is a hyperlink suffix, append it to URL.
  5. Return to whatever algorithm invoked these steps and continue these steps in parallel.
  6. Fetch URL and handle the resulting resource as a download.

When a user agent is to handle a resource obtained from a fetch as a download, it should provide the user with a way to save the resource for later use, if a resource is successfully obtained; or otherwise should report any problems downloading the file to the user.

If the user agent needs a file name for a resource being handled as a download, it should select one using the following algorithm.

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 void value.
  2. If the resource has a Content-Disposition header, that header specifies the attachment disposition type, and the header includes file name information, then let filename have the value specified by the header, and jump to the step labeled sanitize below. [RFC6266]
  3. Let interface origin be the origin of the Document in which the download or navigate action resulting in the download was initiated, if any.
  4. Let resource origin be the origin of the URL of the resource being downloaded, unless that URL’s scheme component is data, in which case let resource 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 resource origin is the same origin as interface origin, and false otherwise.
  6. If trusted operation is true and the resource has a Content-Disposition header and that header includes file name information, then let filename have the value specified by the header, and jump to the step labeled sanitize below. [RFC6266]
  7. If the download was not initiated from a hyperlink created by an a or area element, or if the element of the hyperlink from which it was initiated did not have a 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 file name.
  8. Let proposed filename have the value of the download attribute of the element of the 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 the resource has a 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. [RFC6266]
  11. No proposed file name: If trusted operation is true, or if the user indicated a preference for having the resource in question downloaded, let filename have a value derived from the URL of the resource in a user-agent-defined manner, and jump to the step labeled sanitize below.
  12. Act in a user-agent-defined manner to safeguard the user from a potentially hostile cross-origin download. If the download is not to be aborted, then let filename be set to the user’s preferred file name or to a file name 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 the resource being downloaded, 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 download attribute was used to trigger the download, or because the resource in question 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 the resource in question comes from quite a different source, and to prevent confusion, any suggested file name 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 file name, 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 file names, or trimming leading and trailing whitespace.

  15. If the platform conventions do not in any way use extensions to determine the types of file on the file system, then return filename as the file name and abort these steps.
  16. Let claimed type be the type given by the resource’s Content-Type metadata, if any is known. Let named type be the type given by filename’s extension, if any is known. For the purposes of this step, a type is a mapping of a MIME type to an 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 file name and abort these steps.
  18. If claimed type and named type are the same type (i.e., the type given by the resource’s Content-Type metadata is consistent with the type given by filename’s extension), then return filename as the file name and abort these steps.
  19. If the claimed type is known, then alter filename to add an 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 extension (e.g., ".txt").

    This last step would make it impossible to download executables, which might not be desirable. As always, implementors are forced to balance security and usability in this matter.

  20. Return filename as the file name.

For the purposes of this algorithm, a file extension consists of any part of the file name that platform conventions dictate will be used for identifying the type of the file. For example, many operating systems use the part of the file name following the last dot (".") in the file name 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 resource itself, its URL, and any download attribute, in deciding where to store the resulting file in the user’s file system.

The following table summarizes the link types that are defined by this specification. This table is non-normative; the actual definitions for the link types are given in the next few sections.

In this section, the term referenced document refers to the resource identified by the element representing the link, and the term current document refers to the resource within which the element representing the link finds itself.

To determine which link types apply to a link, a, or area element, the element’s rel attribute must be split on spaces. The resulting tokens are the link types that apply to that element.

Except where otherwise specified, a keyword must not be specified more than once per rel attribute.

Link types are always ASCII case-insensitive, and must be compared as such.

Thus, rel="next" is the same as rel="NEXT".

Link type Effect on... Brief description
link a and area
alternate hyperlink hyperlink Gives alternate representations of the current document.
author hyperlink hyperlink Gives a link to the author of the current document or article.
bookmark not allowed hyperlink Gives the permalink for the nearest ancestor section.
help hyperlink hyperlink Provides a link to context-sensitive help.
icon External Resource not allowed Imports an icon to represent the current document.
license hyperlink hyperlink Indicates that the main content of the current document is covered by the copyright license described by the referenced document.
next hyperlink hyperlink Indicates that the current document is a part of a series, and that the next document in the series is the referenced document.
nofollow not allowed Annotation Indicates that the current document’s original author or publisher does not endorse the referenced document.
noreferrer not allowed Annotation Requires that the user agent not send an HTTP Referer (sic) header if the user follows the hyperlink.
prev hyperlink hyperlink Indicates that the current document is a part of a series, and that the previous document in the series is the referenced document.
search hyperlink hyperlink Gives a link to a resource that can be used to search through the current document and its related pages.
stylesheet External Resource not allowed Imports a stylesheet.
tag not allowed hyperlink Gives a tag (identified by the given address) that applies to the current document.

Some of the types described below list synonyms for these values. These are to be handled as specified by user agents, but must not be used in documents.

The alternate keyword may be used with link, a, and area elements.

The meaning of this keyword depends on the values of the other attributes.

If the element is a link element and the rel attribute also contains the keyword stylesheet

The alternate keyword modifies the meaning of the stylesheet keyword in the way described for that keyword. The alternate keyword does not create a link of its own.

If the alternate keyword is used with the type attribute set to the value application/rss+xml or the value application/atom+xml

The keyword creates a hyperlink referencing a syndication feed (though not necessarily syndicating exactly the same content as the current page).

The first link or a element in the document (in tree order) with the alternate keyword used with the type attribute set to the value application/rss+xml or the value application/atom+xml must be treated as the default syndication feed for the purposes of feed autodiscovery.

The following link element gives the syndication feed for the current page:
<link rel="alternate" type="application/atom+xml" href="data.xml">

The following extract offers various different syndication feeds:

<p>You can access the planets database using Atom feeds:</p>
<ul>
  <li><a href="recently-visited-planets.xml" rel="alternate" type="application/atom+xml">Recently Visited Planets</a></li>
  <li><a href="known-bad-planets.xml" rel="alternate" type="application/atom+xml">Known Bad Planets</a></li>
  <li><a href="unexplored-planets.xml" rel="alternate" type="application/atom+xml">Unexplored Planets</a></li>
</ul>
Otherwise

The keyword creates a hyperlink referencing an alternate representation of the current document.

The nature of the referenced document is given by the hreflang, and type attributes.

If the alternate keyword is used with the hreflang attribute, and that attribute’s value differs from the root element’s language, it indicates that the referenced document is a translation.

If the alternate keyword is used with the type attribute, it indicates that the referenced document is a reformulation of the current document in the specified format.

The hreflang and type attributes can be combined when specified with the alternate keyword.

For example, the following link is a French translation that uses the PDF format:
<link rel=alternate type=application/pdf hreflang=fr href=manual-fr>

This relationship is transitive — that is, if a document links to two other documents with the link type "alternate", then, in addition to implying that those documents are alternative representations of the first document, it is also implying that those two documents are alternative representations of each other.

The author keyword may be used with link, a, and area elements. This keyword creates a hyperlink.

For a and area elements, the author keyword indicates that the referenced document provides further information about the author of the nearest article element ancestor of the element defining the hyperlink, if there is one, or of the page as a whole, otherwise.

For link elements, the author keyword indicates that the referenced document provides further information about the author for the page as a whole.

The "referenced document" can be, and often is, a mailto: URL giving the e-mail address of the author. [RFC6068]

Synonyms: For historical reasons, user agents must also treat link, a, and area elements that have a rev attribute with the value "made" as having the author keyword specified as a link relationship.

The bookmark keyword may be used with a and area elements. This keyword creates a hyperlink.

The bookmark keyword gives a permalink for the nearest ancestor article element of the linking element in question, or of the section the linking element is most closely associated with, if there are no ancestor article elements.

The following snippet has three permalinks. A user agent could determine which permalink applies to which part of the spec by looking at where the permalinks are given.
...
 <body>
 <h1>Example of permalinks</h1>
 <div id="a">
   <h2>First example</h2>
   <p><a href="a.html" rel="bookmark">This permalink applies to
   only the content from the first H2 to the second H2</a>. The DIV isn’t
   exactly that section, but it roughly corresponds to it.</p>
 </div>
 <h2>Second example</h2>
 <article id="b">
   <p><a href="b.html" rel="bookmark">This permalink applies to
   the outer ARTICLE element</a> (which could be, e.g., a blog post).</p>
   <article id="c">
   <p><a href="c.html" rel="bookmark">This permalink applies to
   the inner ARTICLE element</a> (which could be, e.g., a blog comment).</p>
   </article>
 </article>
 </body>
 ...

The help keyword may be used with link, a, and area elements. This keyword creates a hyperlink.

For a and area elements, the help keyword indicates that the referenced document provides further help information for the parent of the element defining the hyperlink, and its children.

In the following example, the form control has associated context-sensitive help. The user agent could use this information, for example, displaying the referenced document if the user presses the "Help" or "F1" key.
<p><label> Topic: <input name=topic> <a href="help/topic.html" rel="help">(Help)</a></label></p>

For link elements, the help keyword indicates that the referenced document provides help for the page as a whole.

For a and area elements, on some browsers, the help keyword causes the link to use a different cursor.

The icon keyword may be used with link elements. This keyword creates an 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 type, media, and sizes attributes. If there are multiple equally appropriate icons, user agents must use the last one declared in 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 icon keyword. However, for the purposes of determining the type of the resource, user agents must expect the resource to be an image.

The sizes attribute gives the sizes of icons for visual media. Its value, if present, is merely advisory. User agents may use the value to decide which icon(s) to use if multiple icons are available.

If specified, the attribute must have a value that is an unordered set of unique space-separated tokens which are ASCII case-insensitive. Each value must be either an ASCII case-insensitive match for the string "any", or a value that consists of two valid non-negative integers that do not have a leading U+0030 DIGIT ZERO (0) character and that are separated by a single U+0078 LATIN SMALL LETTER X or U+0058 LATIN CAPITAL LETTER X character.

The keywords represent icon sizes in raw pixels (as opposed to CSS pixels).

An icon that is 50 CSS pixels wide intended for displays with a device pixel density of two device pixels per 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 split the attribute’s value on spaces, 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:

  • 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. Abort these steps for that keyword.
  • Let width string be the string before the "x" or "X".
  • Let height string be the string after the "x" or "X".
  • If either width string or height string start with a U+0030 DIGIT ZERO (0) character or contain any characters other than ASCII digits, then this keyword doesn’t represent anything. Abort these steps for that keyword.
  • Apply the rules for parsing non-negative integers to width string to obtain width.
  • Apply the rules for parsing non-negative integers to height string to obtain height.
  • 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 sizes attribute must not represent icon sizes that are not actually available in the linked resource.

In the absence of a link with the icon keyword, for Document objects obtained over HTTP or HTTPS, user agents may instead run these steps in parallel:

  1. Let request be a new request whose URL is the absolute URL obtained by resolving the URL "/favicon.ico" against the document’s address, client is the Document object’s Window object’s environment settings object, type is "image", destination is "subresource", synchronous flag is set, credentials mode is "include", and whose use-URL-credentials flag is set.
  2. Let response be the result of fetching request.
  3. Use response’s unsafe response as an icon as if it had been declared using the icon keyword.
The following snippet shows the top part of an application with several icons.
<!DOCTYPE HTML>
<html>
  <head>
  <title>lsForums — Inbox</title>
  <link rel=icon href=favicon.png sizes="16x16" type="image/png">
  <link rel=icon href=windows.ico sizes="32x32 48x48" type="image/vnd.microsoft.icon">
  <link rel=icon href=mac.icns sizes="128x128 512x512 8192x8192 32768x32768">
  <link rel=icon href=iphone.png sizes="57x57" type="image/png">
  <link rel=icon href=gnome.svg sizes="any" type="image/svg+xml">
  <link rel=stylesheet href=lsforums.css>
  <script src=lsforums.js></script>
  <meta name=application-name content="lsForums">
  </head>
  <body>
  ...

For historical reasons, the icon keyword may be preceded by the keyword "shortcut". If the "shortcut" keyword is present, the rel attribute’s entire value must be an ASCII case-insensitive match for the string "shortcut icon" (with a single U+0020 SPACE character between the tokens and no other space characters).

The license keyword may be used with link, a, and area elements. This keyword creates a hyperlink.

The license keyword indicates that the referenced document provides the copyright license terms under which the main content of the current document is provided.

This specification defines the main content of a document and content that is not deemed to be part of that main content via the main element. The distinction should be made clear to the user.

Consider a photo sharing site. A page on that site might describe and show a photograph, and the page might be marked up as follows:
<!DOCTYPE HTML>
<html>
  <head>
  <title>Exampl Pictures: Kissat</title>
  <link rel="stylesheet" href="/style/default">
  </head>
  <body>
  <h1>Kissat</h1>
  <nav>
    <a href="../">Return to photo index</a>
  </nav>

  <main>
  <figure>
    <img src="/pix/39627052_fd8dcd98b5.jpg">
    <figcaption>Kissat</figcaption>
  </figure>
  <p>One of them has six toes!</p>
  <p><small>This photograph is <a rel="license" href="https://www.opensource.org/licenses/mit-license.php">MIT Licensed</a></small></p>
  </main>
  <footer>
    <a href="/">Home</a> | <a href="../">Photo index</a>
    <p><small>© copyright 2009 Exampl Pictures. All Rights Reserved.</small></p>
  </footer>
  </body>
</html>

In this case the license applies to just the photo (the main content of the document), not the whole document. In particular not the design of the page itself, which is covered by the copyright given at the bottom of the document. This should be made clear in the text referencing the licensing link and could also be made clearer in the styling (e.g., making the license link prominently positioned near the photograph, while having the page copyright in small text at the foot of the page, or adding a border to the main element.)

Synonyms: For historical reasons, user agents must also treat the keyword "copyright" like the license keyword.

The nofollow keyword may be used with a and area elements. This keyword does not create a hyperlink, but annotates any other hyperlinks created by the element (the implied hyperlink, if no other keywords create one).

The nofollow keyword indicates that the link is not endorsed by the original author or publisher of the page, or that the link to the referenced document was included primarily because of a commercial relationship between people affiliated with the two pages.

The noreferrer keyword may be used with a and area elements. This keyword does not create a hyperlink, but annotates any other hyperlinks created by the element (the implied hyperlink, if no other keywords create one).

It indicates that no referrer information is to be leaked when following the link.

If a user agent follows a link defined by an a or area element that has the noreferrer keyword, the user agent must set their request’s referrer to "no-referrer".

This keyword also causes the opener attribute to remain null if the hyperlink creates a new browsing context.

The search keyword may be used with link, a, and area elements. This keyword creates a hyperlink.

The search keyword indicates that the referenced document provides an interface specifically for searching the document and its related resources.

OpenSearch description documents can be used with link elements and the search link type to enable user agents to autodiscover search interfaces. [OPENSEARCH]

The stylesheet keyword may be used with link elements. This keyword creates an external resource link that contributes to the styling processing model.

The specified resource is a resource that describes how to present the document. Exactly how the resource is to be processed depends on the actual type of the resource.

If the alternate keyword is also specified on the link element, then the link is an alternative stylesheet; in this case, the title attribute must be specified on the link element, with a non-empty value.

The default type for resources given by the stylesheet keyword is text/css.

The appropriate times to obtain the resource are:

Quirk: If the document has been set to quirks mode, has the same origin as the URL of the external resource, and the Content-Type metadata of the external resource is not a supported style sheet type, the user agent must instead assume it to be text/css.

Once a resource has been obtained, if its Content-Type metadata is text/css, the user agent must run these steps:

  1. Let element be the link element that created the external resource link.

  2. If element has an associated CSS style sheet, remove the CSS style sheet in question.

  3. If element no longer creates an external resource link that contributes to the styling processing model, or if, since the resource in question was obtained, it has become appropriate to obtain it again (meaning this algorithm is about to be invoked again for a newly obtained resource), then abort these steps.

  4. Create a CSS style sheet with the following properties:

    type

    text/css

    location

    The resulting URL string determined during the obtain algorithm.

    This is before any redirects get applied.

    owner node

    element

    media

    The 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. The CSSOM specification defines what happens when the attribute is dynamically set, changed, or removed.

    title

    The title attribute of element.

    This is similarly a reference to the attribute, rather than a copy of the attribute’s current value.

    alternate flag

    Set if the link is an alternative stylesheet; unset otherwise.

    origin-clean flag

    Set if the resource is CORS-same-origin; unset otherwise.

    parent CSS style sheet

    owner CSS rule

    null

    disabled flag

    Left at its default value.

    CSS rules

    Left uninitialized.

    The CSS environment encoding is the result of running the following steps: [CSS-SYNTAX-3]

    1. If the element has a charset attribute, get an encoding from that attribute’s value. If that succeeds, return the resulting encoding and abort these steps. [ENCODING]

    2. Otherwise, return the document’s character encoding. [DOM]

The tag keyword may be used with a and area elements. This keyword creates a hyperlink.

The tag keyword indicates that the tag that the referenced document represents applies to the current document.

Since it indicates that the tag applies to the current document, it would be inappropriate to use this keyword in the markup of a tag cloud, which lists the popular tags across a set of pages.

This document is about some gems, and so it is tagged with "https://en.wikipedia.org/wiki/Gemstone" to unambiguously categorize it as applying to the "jewel" kind of gems, and not to, say, the towns in the US, the Ruby package format, or the Swiss locomotive class:
<!DOCTYPE HTML>
<html>
  <head>
  <title>My Precious</title>
  </head>
  <body>
  <header><h1>My precious</h1> <p>Summer 2012</p></header>
  <p>Recently I managed to dispose of a red gem that had been
  bothering me. I now have a much nicer blue sapphire.</p>
  <p>The red gem had been found in a bauxite stone while I was digging
  out the office level, but nobody was willing to haul it away. The
  same red gem stayed there for literally years.</p>
  <footer>
    Tags: <a rel=tag href="https://en.wikipedia.org/wiki/Gemstone">Gemstone</a>
  </footer>
  </body>
</html>
In this document, there are two articles. The "tag" link, however, applies to the whole page (and would do so wherever it was placed, including if it was within the article elements).
<!DOCTYPE HTML>
<html>
  <head>
  <title>Gem 4/4</title>
  </head>
  <body>
  <article>
    <h1>801: Steinbock</h1>
    <p>The number 801 Gem 4/4 electro-diesel has an ibex and was rebuilt in 2002.</p>
  </article>
  <article>
    <h1>802: Murmeltier</h1>
    <figure>
    <img src="https://upload.wikimedia.org/wikipedia/commons/b/b0/Trains_de_la_Bernina_en_hiver_2.jpg"
          alt="The 802 was red with pantographs and tall vents on the side.">
    <figcaption>The 802 in the 1980s, above Lago Bianco.</figcaption>
    </figure>
    <p>The number 802 Gem 4/4 electro-diesel has a marmot and was rebuilt in 2003.</p>
  </article>
  <p class="topic"><a rel=tag href="https://en.wikipedia.org/wiki/Rhaetian_Railway_Gem_4/4">Gem 4/4</a></p>
  </body>
</html>

Some documents form part of a sequence of documents.

A sequence of documents is one where each document can have a previous sibling and a next sibling. A document with no previous sibling is the start of its sequence, a document with no next sibling is the end of its sequence.

A document may be part of multiple sequences.

The next keyword may be used with link, a, and area elements. This keyword creates a hyperlink.

The next keyword indicates that the document is part of a sequence, and that the link is leading to the document that is the next logical document in the sequence.

The prev keyword may be used with link, a, and area elements. This keyword creates a hyperlink.

The prev keyword indicates that the document is part of a sequence, and that the link is leading to the document that is the previous logical document in the sequence.

Synonyms: For historical reasons, user agents must also treat the keyword "previous" like the prev keyword.

Extensions to the predefined set of link types may be registered in the microformats wiki existing-rel-values page. [MFREL]

Anyone is free to edit the microformats wiki existing-rel-values page at any time to add a type. Extension types must be specified with the following information:

Keyword

The actual value being defined. The value should not be confusingly similar to any other defined value (e.g., differing only in case).

If the value contains a U+003A COLON character (:), it must also be an absolute URL.

Effect on... link

One of the following:

Not allowed
The keyword must not be specified on link elements.
Hyperlink
The keyword may be specified on a link element; it creates a hyperlink.
External Resource
The keyword may be specified on a link element; it creates an external resource link.
Effect on... a and area

One of the following:

Not allowed
The keyword must not be specified on a and area elements.
Hyperlink
The keyword may be specified on a and area elements; it creates a hyperlink.
External Resource
The keyword may be specified on a and area elements; it creates an external resource link.
Hyperlink Annotation
The keyword may be specified on a and area elements; it annotates other hyperlinks created by the element.
Brief description
A short non-normative description of what the keyword’s meaning is.
Specification
A link to a more detailed description of the keyword’s semantics and requirements. It could be another page on the Wiki, or a link to an external page.
Synonyms
A list of other keyword values that have exactly the same processing requirements. Authors should not use the values defined to be synonyms, they are only intended to allow user agents to support legacy content. Anyone may remove synonyms that are not used in practice; only names that need to be processed as synonyms for compatibility with legacy content are to be registered in this way.
Status

One of the following:

Proposed
The keyword has not received wide peer review and approval. Someone has proposed it and is, or soon will be, using it.
Ratified
The keyword has received wide peer review and approval. It has a specification that unambiguously defines how to handle pages that use the keyword, including when they use it in incorrect ways.
Discontinued
The keyword has received wide peer review and it has been found wanting. Existing pages are using this keyword, but new pages should avoid it. The "brief description" and "specification" entries will give details of what authors should use instead, if anything.

If a keyword is found to be redundant with existing values, it should be removed and listed as a synonym for the existing value.

If a keyword is registered in the "proposed" state for a period of a month or more without being used or specified, then it may be removed from the registry.

If a keyword is added with the "proposed" status and found to be redundant with existing values, it should be removed and listed as a synonym for the existing value. If a keyword is added with the "proposed" status and found to be harmful, then it should be changed to "discontinued" status.

Anyone can change the status at any time, but should only do so in accordance with the definitions above.

Conformance checkers may use the information given on the microformats wiki existing-rel-values page to establish if a value is allowed or not: values defined in this specification or marked as "proposed" or "ratified" must be accepted when used on the elements for which they apply as described in the "Effect on..." field, whereas values marked as "discontinued" or values not containing a U+003A COLON character but not listed in either this specification or on the aforementioned page must be reported as invalid. The remaining values must be accepted as valid if they are absolute URLs containing US-ASCII characters only and rejected otherwise. Conformance checkers may cache this information (e.g., for performance reasons or to avoid the use of unreliable network connectivity).

Note: Even URL-valued link types are compared ASCII-case-insensitively. Validators might choose to warn about characters U+0041 (LATIN CAPITAL LETTER A) through U+005A (LATIN CAPITAL LETTER Z) (inclusive) in the pre-case-folded form of link types that contain a colon.

When an author uses a new type not defined by either this specification or the Wiki page, conformance checkers should offer to add the value to the Wiki, with the details described above, with the "proposed" status.

Types defined as extensions in the microformats wiki existing-rel-values page with the status "proposed" or "ratified" may be used with the rel attribute on link, a, and area elements in accordance to the "Effect on..." field. [MFREL]

4.9. Tabular data

4.9.1. The table element

Categories:
Flow content.
Palpable content.
Contexts in which this element can be used:
Where flow content is expected.
Content model:
In this order: optionally a caption element, followed by zero or more colgroup elements, followed optionally by a thead element, followed by either zero or more tbody elements or one or more tr elements, followed optionally by a tfoot element, optionally intermixed with one or more script-supporting elements.
Tag omission in text/html:
Neither tag is omissible
Content attributes:
Global attributes
border
Allowed ARIA role attribute values:
Any role value.
Allowed ARIA state and property attributes:
Global aria-* attributes
Any aria-* attributes applicable to the allowed roles.
DOM interface:
interface HTMLTableElement : HTMLElement {
  attribute HTMLTableCaptionElement? caption;
  HTMLTableCaptionElement createCaption();
  void deleteCaption();
  attribute HTMLTableSectionElement? tHead;
  HTMLTableSectionElement createTHead();
  void deleteTHead();
  attribute HTMLTableSectionElement? tFoot;
  HTMLTableSectionElement createTFoot();
  void deleteTFoot();
  [SameObject] readonly attribute HTMLCollection tBodies;
  HTMLTableSectionElement createTBody();
  [SameObject] readonly attribute HTMLCollection rows;
  HTMLTableRowElement insertRow(optional long index = -1);
  void deleteRow(long index);
};

The table element represents data with more than one dimension, in the form of a table.

The table element takes part in the 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 table model.

Authors are encouraged to provide information describing how to interpret complex tables. Guidance on how to provide such information is given below.

Tables should not be used as layout aids.

Historically, many Web authors have tables in HTML as a way to control their page layout making it difficult to extract tabular data from such documents.

In particular, users of accessibility tools, like screen readers, are likely to find it very difficult to navigate pages with tables used for layout.

If a table is to be used for layout it must be marked with the attribute role="presentation" for a user agent to properly represent the table to an assistive technology and to properly convey the intent of the author to tools that wish to extract tabular data from the document.

There are a variety of alternatives to using HTML tables for layout, primarily using CSS positioning and the CSS table model. [CSS-2015]

The border content attribute may be specified on a table element to explicitly indicate that the table element is not being used for layout purposes. If specified, the attribute’s value must either be the empty string or the value "1". The attribute is used by certain user agents as an indication that borders should be drawn around cells of the table.


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 layout table.

Authors and implementors are encouraged to consider using some of the 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 role attribute with the value presentation Probably a layout table
The use of the non-conforming border attribute with the non-conforming value 0 Probably a layout table
The use of the non-conforming cellspacing and cellpadding attributes with the value 0 Probably a layout table
The use of caption, thead, or th elements Probably a non-layout table
The use of the headers and scope attributes Probably a non-layout table
The use of the non-conforming 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 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. Implementors are urged to provide feedback elaborating on their experiences with trying to create a layout table detection heuristic.

If a table element has a (non-conforming) 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.


table . caption [ = value ]

Returns the table’s caption element.

Can be set, to replace the caption element.

caption = table . createCaption()

Ensures the table has a caption element, and returns it.

table . deleteCaption()

Ensures the table does not have a caption element.

table . tHead [ = value ]

Returns the table’s thead element.

Can be set, to replace the thead element. If the new value is not a thead element, throws a HierarchyRequestError exception.

thead = table . createTHead()

Ensures the table has a thead element, and returns it.

table . deleteTHead()

Ensures the table does not have a thead element.

table . tFoot [ = value ]

Returns the table’s tfoot element.

Can be set, to replace the tfoot element. If the new value is not a tfoot element, throws a HierarchyRequestError exception.

tfoot = table . createTFoot()

There is only one known native implementation of createTFoot (Firefox/Gecko). Therefore this feature should not be relied upon.

Ensures the table has a tfoot element, and returns it.

table . deleteTFoot()

Ensures the table does not have a tfoot element.

table . tBodies

Returns an HTMLCollection of the tbody elements of the table.

tbody = table . createTBody()

Creates a tbody element, inserts it into the table, and returns it.

table . rows

Returns an HTMLCollection of the tr elements of the table.

tr = table . insertRow( [ index ] )

Creates a tr element, along with a tbody if required, inserts them into the table at the position given by the argument, and returns the tr.

The position is relative to the rows in the table. The index -1, which is the default if the argument is omitted, is equivalent to inserting at the end of the table.

If the given position is less than -1 or greater than the number of rows, throws an IndexSizeError exception.

table . deleteRow(index)

Removes the tr element with the given position in the table.

The position is relative to the rows in the table. The index -1 is equivalent to deleting the last row of the table.

If the given position is less than -1 or greater than the index of the last row, or if there are no rows, throws an IndexSizeError exception.

The caption IDL attribute must return, on getting, the first caption element child of the table element, if any, or null otherwise. On setting, the first caption element child of the table element, if any, must be removed, and the new value, if not null, must be inserted as the first node of the table element.

The createCaption() method must return the first caption element child of the table element, if any; otherwise a new caption element must be created, inserted as the first node of the table element, and then returned.

The deleteCaption() method must remove the first caption element child of the table element, if any.

The tHead IDL attribute must return, on getting, the first thead element child of the table element, if any, or null otherwise. On setting, if the new value is null or a thead element, the first thead element child of the table element, if any, must be removed, and the new value, if not null, must be inserted immediately before the first element in the table element that is neither a caption element nor a 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 thead element, then a HierarchyRequestError DOM exception must be thrown instead.

The createTHead() method must return the first thead element child of the table element, if any; otherwise a new thead element must be created and inserted immediately before the first element in the table element that is neither a caption element nor a 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 thead element child of the table element, if any.

The tFoot IDL attribute must return, on getting, the first tfoot element child of the table element, if any, or null otherwise. On setting, if the new value is null or a tfoot element, the first tfoot element child of the 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 tfoot element, then a HierarchyRequestError DOM exception must be thrown instead.

The createTFoot() method must return the first tfoot element child of the table element, if any; otherwise a new tfoot element must be created and inserted at the end of the table, and then that new element must be returned.

The deleteTFoot() method must remove the first tfoot element child of the table element, if any.

The tBodies attribute must return an HTMLCollection rooted at the table node, whose filter matches only tbody elements that are children of the table element.

The createTBody() method must create a new tbody element, insert it immediately after the last tbody element child in the table element, if any, or at the end of the table element if the table element has no tbody element children, and then must return the new tbody element.

The rows attribute must return an HTMLCollection rooted at the table node, whose filter matches only tr elements that are either children of the table element, or children of thead, tbody, or tfoot elements that are themselves children of the table element. The elements in the collection must be ordered such that those elements whose parent is a thead are included first, in tree order, followed by those elements whose parent is either a table or tbody element, again in tree order, followed finally by those elements whose parent is a tfoot element, still in 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 rows collection:
The method must throw an IndexSizeError exception.
If the rows collection has zero elements in it, and the table has no tbody elements in it:
The method must create a tbody element, then create a tr element, then append the tr element to the tbody element, then append the tbody element to the table element, and finally return the tr element.
If the rows collection has zero elements in it:
The method must create a tr element, append it to the last tbody element in the table, and return the tr element.
If index is -1 or equal to the number of items in rows collection:
The method must create a tr element, and append it to the parent of the last tr element in the rows collection. Then, the newly created tr element must be returned.
Otherwise:
The method must create a tr element, insert it immediately before the indexth tr element in the rows collection, in the same parent, and finally must return the newly created tr element.

When the deleteRow(index) method is called, the user agent must run the following steps:

  1. If index is equal to -1, then index must be set to the number of items in the rows collection, minus one.
  2. Now, if index is less than zero, or greater than or equal to the number of elements in the rows collection, the method must instead throw an IndexSizeError exception, and these steps must be aborted.
  3. Otherwise, the method must remove the indexth element in the 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.
<section>
  <h1>Today’s Sudoku</h1>
  <table>
  <colgroup><col><col><col>
  <colgroup><col><col><col>
  <colgroup><col><col><col>
  <tbody>
    <tr> <td> 1 <td>   <td> 3 <td> 6 <td>   <td> 4 <td> 7 <td>   <td> 9
    <tr> <td>   <td> 2 <td>   <td>   <td> 9 <td>   <td>   <td> 1 <td>
    <tr> <td> 7 <td>   <td>   <td>   <td>   <td>   <td>   <td>   <td> 6
  <tbody>
    <tr> <td> 2 <td>   <td> 4 <td>   <td> 3 <td>   <td> 9 <td>   <td> 8
    <tr> <td>   <td>   <td>   <td>   <td>   <td>   <td>   <td>   <td>
    <tr> <td> 5 <td>   <td>   <td> 9 <td>   <td> 7 <td>   <td>   <td> 1
  <tbody>
    <tr> <td> 6 <td>   <td>   <td>   <td> 5 <td>   <td>   <td>   <td> 2
    <tr> <td>   <td>   <td>   <td>   <td> 7 <td>   <td>   <td>   <td>
    <tr> <td> 9 <td>   <td>   <td> 8 <td>   <td> 2 <td>   <td>   <td> 5
  </table>
</section>
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:

Characteristics with positive and negative sides
Negative Characteristic Positive
Sad Mood Happy
Failing Grade Passing

...could 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
<p id="summary">In the following table, characteristics are
given in the second column, with the negative side in the left column and the positive
side in the right column.</p>
<table aria-describedby="summary">
  <caption>Characteristics with positive and negative sides</caption>
  <thead>
  <tr>
    <th id="n"> Negative
    <th> Characteristic
    <th> Positive
  <tbody>
  <tr>
    <td headers="n r1"> Sad
    <th id="r1"> Mood
    <td> Happy
  <tr>
    <td headers="n r2"> Failing
    <th id="r2"> Grade
    <td> Passing
</table>
    

In the example above the aria-describedby attribute is used to explicitly associate the information with the table for assistive technology users.

Next to the table, in the same figure
<figure aria-labelledby="caption"> 
 <p>Characteristics are given in the second column, with the
  negative side in the left column and the positive side in the right
  column.</p>
  <table>
  <caption id="caption">Characteristics with positive and negative sides</caption>
  <thead>
    <tr>
    <th id="n"> Negative
    <th> Characteristic
    <th> Positive
  <tbody>
    <tr>
    <td headers="n r1"> Sad
    <th id="r1"> Mood
    <td> Happy
    <tr>
    <td headers="n r2"> Failing
    <th id="r2"> Grade
    <td> Passing
  </table>
</figure>
    

The figure in this example has been labeled by the table caption using aria-labelledby.

Authors may also use other techniques, or combinations of the above techniques, as appropriate.

Regardless of the method used to provide additional descriptive information for a table, if a table needs a caption, authors should use a caption element as it is the most robust method for providing an accessible caption for a table.

The best option, of course, rather than writing a description explaining the way the table is laid out, is to adjust the table such that no explanation is needed.

In the case of the table used in the examples above, a simple rearrangement of the table so that the headers are on the top and left sides removes the need for an explanation as well as removing the need for the use of headers attributes:
<table>
  <caption>Characteristics with positive and negative sides</caption>
  <thead>
  <tr>
    <th> Characteristic
    <th> Negative
    <th> Positive
  <tbody>
  <tr>
    <th> Mood
    <td> Sad
    <td> Happy
  <tr>
    <th> Grade
    <td> Failing
    <td> Passing
</table>
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

Categories:
None.
Contexts in which this element can be used:
As the first element child of a table element.
Content model:
Flow content, but with no descendant table elements.
Tag omission in text/html:
Neither tag is omissible
Content attributes:
Global attributes
Allowed ARIA role attribute values:
Any role value.
Allowed ARIA state and property attributes:
Global aria-* attributes
Any aria-* attributes applicable to the allowed roles.
DOM interface:
interface HTMLTableCaptionElement : HTMLElement {};

The caption element represents the title of the table that is its parent, if it has a parent and that is a table element.

The caption element takes part in the table model.

When a table element is the only content in a figure element other than the figcaption, the caption element should be omitted in favor of the figcaption.

A caption can introduce context for a table, making it significantly easier to understand.

Consider, for instance, the following table:
1 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

In the abstract, this table is not clear. However, with a caption giving the table’s number (for reference in the main prose) and explaining its use, it makes more sense:

<caption>
<p>Table 1.
<p>This table shows the total score obtained from rolling two
six-sided dice. The first row represents the value of the first die,
the first column the value of the second die. The total is given in
the cell that corresponds to the values of the two dice.
</caption>

This provides the user with more context:

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

Categories:
None.
Contexts in which this element can be used:
As a child of a table element, after any caption elements and before any thead, tbody, tfoot, and tr elements.
Content model:
If the span attribute is present: Nothing.
If the span attribute is absent: Zero or more col and template elements.
Tag omission in text/html:
A colgroup element’s end tag may be omitted if the colgroup element is not immediately followed by a space character or a comment.
Content attributes:
Global attributes
span - Number of columns spanned by the element
Allowed ARIA role attribute values:
None
Allowed ARIA state and property attributes:
Global aria-* attributes
DOM interface:
interface HTMLTableColElement : HTMLElement {
  attribute unsigned long span;
};

The colgroup element represents a group of one or more columns in the table that is its parent, if it has a parent and that is a table element.

If the colgroup element contains no col elements, then the element may have a span content attribute specified, whose value must be a valid non-negative integer greater than zero.

The colgroup element and its span attribute take part in the table model.

The span IDL attribute must reflect the content attribute of the same name. The value must be limited to only non-negative numbers greater than zero.

4.9.4. The col element

Categories:
None.
Contexts in which this element can be used:
As a child of a colgroup element that doesn’t have a span attribute.
Content model:
Nothing.
Tag omission in text/html:
No end tag.
Content attributes:
Global attributes
span
Allowed ARIA role attribute values:
None
Allowed ARIA state and property attributes:
Global aria-* attributes
DOM interface:
HTMLTableColElement, same as for colgroup elements. This interface defines one member, span.

If a col element has a parent and that is a colgroup element that itself has a parent that is a table element, then the col element represents one or more columns in the column group represented by that colgroup.

The element may have a span content attribute specified, whose value must be a valid non-negative integer greater than zero.

The col element and its span attribute take part in the table model.

The span IDL attribute must reflect the content attribute of the same name. The value must be limited to only non-negative numbers greater than zero.

4.9.5. The tbody element

Categories:
None.
Contexts in which this element can be used:
As a child of a table element, after any caption, colgroup, and thead elements, but only if there are no tr elements that are children of the table element.
Content model:
Zero or more tr and script-supporting elements.
Tag omission in text/html:
A tbody element’s start tag may be omitted if the first thing inside the tbody element is a tr element, and if the element is not immediately preceded by a tbody, thead, or tfoot element whose end tag has been omitted. (It can’t be omitted if the element is empty.). A tbody element’s end tag may be omitted if the tbody element is immediately followed by a tbody or tfoot element, or if there is no more content in the parent element.
Content attributes:
Global attributes
Allowed ARIA role attribute values:
Any role value.
Allowed ARIA state and property attributes:
Global aria-* attributes
Any aria-* attributes applicable to the allowed roles.
DOM interface:
interface HTMLTableSectionElement : HTMLElement {
  [SameObject] readonly attribute HTMLCollection rows;
  HTMLElement insertRow(optional long index = -1);
  void deleteRow(long index);
};

The HTMLTableSectionElement interface is also used for thead and tfoot elements.

The tbody element represents a block of rows that consist of a body of data for the parent table element, if the tbody element has a parent and it is a table.

The tbody element takes part in the table model.

tbody . rows

Returns an HTMLCollection of the tr elements of the table section.

tr = tbody . insertRow( [ index ] )

Creates a tr element, inserts it into the table section at the position given by the argument, and returns the tr.

The position is relative to the rows in the table section. The index -1, which is the default if the argument is omitted, is equivalent to inserting at the end of the table section.

If the given position is less than -1 or greater than the number of rows, throws an IndexSizeError exception.

tbody . deleteRow(index)

Removes the tr element with the given position in the table section.

The position is relative to the rows in the table section. The index -1 is equivalent to deleting the last row of the table section.

If the given position is less than -1 or greater than the index of the last row, or if there are no rows, throws an IndexSizeError exception.

The rows attribute must return an HTMLCollection rooted at the element, whose filter matches only tr elements that are children of the element.

The insertRow(index) method must, when invoked on an element table section, act as follows:

If index is less than -1 or greater than the number of elements in the rows collection, the method must throw an IndexSizeError exception.

If index is -1 or equal to the number of items in the rows collection, the method must create a tr element, append it to the element table section, and return the newly created tr element.

Otherwise, the method must create a tr element, insert it as a child of the table section element, immediately before the indexth tr element in the rows collection, and finally must return the newly created tr element.

The deleteRow(index) method must, when invoked, act as follows:

If index is less than -1 or greater than the number of elements in the rows collection, the method must throw an IndexSizeError exception.

If index is -1, remove the last element in the rows collection from its parent.

Otherwise, remove the indexth element in the rows collection from its parent.

4.9.6. The thead element

Categories:
None.
Contexts in which this element can be used:
As a child of a table element, after any caption, and colgroup elements and before any tbody, tfoot, and tr elements, but only if there are no other thead elements that are children of the table element.
Content model:
Zero or more tr and script-supporting elements.
Tag omission in text/html:
A thead element’s end tag may be omitted if the thead element is immediately followed by a tbody or tfoot element.
Content attributes:
Global attributes
Allowed ARIA role attribute values:
Any role value.
Allowed ARIA state and property attributes:
Global aria-* attributes
Any aria-* attributes applicable to the allowed roles.
DOM interface:
HTMLTableSectionElement, as defined for tbody elements.

The thead element represents the block of rows that consist of the column labels (headers) for the parent table element, if the thead element has a parent and it is a table.

The thead element takes part in the table model.

This example shows a thead element being used. Notice the use of both th and td elements in the thead element: the first row is the headers, and the second row is an explanation of how to fill in the table.
<table>
  <caption> School auction sign-up sheet </caption>
 <thead>
  <tr>
    <th><label for=e1>Name</label>
    <th><label for=e2>Product</label>
    <th><label for=e3>Picture</label>
    <th><label for=e4>Price</label>
  <tr>
    <td>Your name here
    <td>What are you selling?
    <td>Link to a picture
    <td>Your reserve price
 <tbody>
  <tr>
    <td>Ms Danus
    <td>Doughnuts
    <td><img src="https://example.com/mydoughnuts.png" title="Doughnuts from Ms Danus">
    <td>$45
  <tr>
    <td><input id=e1 type=text name=who required form=f>
    <td><input id=e2 type=text name=what required form=f>
    <td><input id=e3 type=url name=pic form=f>
    <td><input id=e4 type=number step=0.01 min=0 value=0 required form=f>
</table>
<form id=f action="/auction.cgi">
  <input type=button name=add value="Submit">
</form>

4.9.7. The tfoot element

Categories:
None.
Contexts in which this element can be used:
As a child of a table element, after any caption, colgroup, thead, tbody, and tr elements, but only if there are no other tfoot elements that are children of the table element.
Content model:
Zero or more tr and script-supporting elements.
Tag omission in text/html:
A tfoot element’s end tag may be omitted if the tfoot element is immediately followed by a tbody element, or if there is no more content in the parent element.
Content attributes:
Global attributes
Allowed ARIA role attribute values:
Any role value.
Allowed ARIA state and property attributes:
Global aria-* attributes
Any aria-* attributes applicable to the allowed roles.
DOM interface:
HTMLTableSectionElement, as defined for tbody elements.

The tfoot element represents the block of rows that consist of the column summaries (footers) for the parent table element, if the tfoot element has a parent and it is a table.

The tfoot element takes part in the table model.

4.9.8. The tr element

Categories:
None.
Contexts in which this element can be used:
As a child of a thead element.
As a child of a tbody element.
As a child of a tfoot element.
As a child of a table element, after any caption, colgroup, and thead elements, but only if there are no tbody elements that are children of the table element.
Content model:
Zero or more td, th, and script-supporting elements.
Tag omission in text/html:
A tr element’s end tag may be omitted if the tr element is immediately followed by another tr element, or if there is no more content in the parent element.
Content attributes:
Global attributes
Allowed ARIA role attribute values:
Any role value.
Allowed ARIA state and property attributes:
Global aria-* attributes
Any aria-* attributes applicable to the allowed roles.
DOM interface:
interface HTMLTableRowElement : HTMLElement {
  readonly attribute long rowIndex;
  readonly attribute long sectionRowIndex;
  [SameObject] readonly attribute HTMLCollection cells;
  HTMLElement insertCell(optional long index = -1);
  void deleteCell(long index);
};

The tr element represents a row of cells in a table.

The tr element takes part in the table model.

tr . rowIndex

Returns the position of the row in the table’s rows list.

Returns -1 if the element isn’t in a table.

tr . sectionRowIndex

Returns the position of the row in the table section’s rows list.

Returns -1 if the element isn’t in a table section.

tr . cells

Returns an HTMLCollection of the td and th elements of the row.

cell = tr . insertCell( [ index ] )

Creates a td element, inserts it into the table row at the position given by the argument, and returns the td.

The position is relative to the cells in the row. The index -1, which is the default if the argument is omitted, is equivalent to inserting at the end of the row.

If the given position is less than -1 or greater than the number of cells, throws an IndexSizeError exception.

tr . deleteCell(index)

Removes the td or th element with the given position in the row.

The position is relative to the cells in the row. The index -1 is equivalent to deleting the last cell of the row.

If the given position is less than -1 or greater than the index of the last cell, or if there are no cells, throws an IndexSizeError exception.

The rowIndex attribute must, if the element has a parent table element, or a parent tbody, thead, or tfoot element and a grandparent table element, return the index of the tr element in that table element’s rows collection. If there is no such table element, then the attribute must return -1.

The sectionRowIndex attribute must, if the element has a parent table, tbody, thead, or tfoot element, return the index of the tr element in the parent element’s rows collection (for tables, that’s the HTMLTableElement.rows collection; for table sections, that’s the HTMLTableRowElement.rows collection). If there is no such parent element, then the attribute must return -1.

The cells attribute must return an HTMLCollection rooted at the tr element, whose filter matches only td and th elements that are children of the tr element.

The insertCell(index) method must act as follows:

If index is less than -1 or greater than the number of elements in the cells collection, the method must throw an IndexSizeError exception.

If index is equal to -1 or equal to the number of items in cells collection, the method must create a td element, append it to the tr element, and return the newly created td element.

Otherwise, the method must create a td element, insert it as a child of the tr element, immediately before the indexth td or th element in the cells collection, and finally must return the newly created td element.

The deleteCell(index) method must act as follows:

If index is less than -1 or greater than the number of elements in the cells collection, the method must throw an IndexSizeError exception.

If index is -1, remove the last element in the cells collection from its parent.

Otherwise, remove the indexth element in the cells collection from its parent.

4.9.9. The td element

Categories:
Sectioning root.
Contexts in which this element can be used:
As a child of a tr element.
Content model:
Flow content.
Tag omission in text/html:
A td element’s end tag may be omitted if the td element is immediately followed by a td or th element, or if there is no more content in the parent element.
Content attributes:
Global attributes
colspan - Number of columns that the cell is to span
rowspan - Number of rows that the cell is to span
headers - The header cells for this cell
Allowed ARIA role attribute values:
Any role value.
Allowed ARIA state and property attributes:
Global aria-* attributes
Any aria-* attributes applicable to the allowed roles.
DOM interface:
interface HTMLTableDataCellElement : HTMLTableCellElement {};

The td element represents a data cell in a table.

The td element and its colspan, rowspan, and headers attributes take part in the 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 table model, or listing the cell’s header cells (as determined by the algorithm for assigning header cells). When a cell’s header cells are being listed, user agents may use the value of abbr attributes on those header cells, if any, instead of the contents of the header cells themselves.

4.9.10. The th element

Categories:
None.
Contexts in which this element can be used:
As a child of a tr element.
Content model:
Flow content, but with no header, footer, sectioning content, or heading content descendants
Tag omission in text/html:
A th element’s end tag may be omitted if the th element is immediately followed by a td or th element, or if there is no more content in the parent element.
Content attributes:
Global attributes
colspan - Number of columns that the cell is to span
rowspan - Number of rows that the cell is to span
headers - The headers for this cell
scope - Specifies which cells the header cell applies to
abbr - Alternative label to use for the header cell when referencing the cell in other contexts
Allowed ARIA role attribute values:
Any role value.
Allowed ARIA state and property attributes:
Global aria-* attributes
Any aria-* attributes applicable to the allowed roles.
DOM interface:
interface HTMLTableHeaderCellElement : HTMLTableCellElement {
  attribute DOMString scope;
  attribute DOMString abbr;
};

The th element represents a header cell in a table.

The th element may have a scope content attribute specified. The scope attribute is an enumerated attribute with five states, four of which have explicit keywords:

The row keyword, which maps to the row state
The row state means the header cell applies to some of the subsequent cells in the same row(s).
The col keyword, which maps to the column state
The column state means the header cell applies to some of the subsequent cells in the same column(s).
The rowgroup keyword, which maps to the row group state
The row group state means the header cell applies to all the remaining cells in the row group. A th element’s scope attribute must not be in the row group state if the element is not anchored in a row group.
The colgroup keyword, which maps to the column group state
The colgroup group state means the header cell applies to all the remaining cells in the column group. A th element’s scope attribute must not be in the column group state if the element is not anchored in a column group.
The auto state
The auto state makes the header cell apply to a set of cells selected based on context.

The scope attribute’s missing value default is the auto state.

The th element may have an abbr content attribute specified. Its value must be an alternative label for the header cell, to be used when referencing the cell in other contexts (e.g., when describing the header cells that apply to a data cell). It is typically an abbreviated form of the full header cell, but can also be an expansion, or merely a different phrasing.

The th element and its colspan, rowspan, headers, and scope attributes take part in the table model.

The scope IDL attribute must reflect the content attribute of the same name, limited to only known values.

The abbr IDL attribute must reflect the content attribute of the same name.

The following example shows how the scope attribute’s rowgroup value affects which data cells a header cell applies to.

Here is a markup fragment showing a table:

The tbody elements in this example identify the range of the row groups.

<table>
    <caption>Measurement of legs and tails in Cats and English speakers</caption>
  <thead>
  <tr> <th> ID <th> Measurement <th> Average <th> Maximum
  <tbody>
  <tr> <td> <th scope=rowgroup> Cats <td> <td>
  <tr> <td> 93 <th scope=row> Legs <td> 3.5 <td> 4
  <tr> <td> 10 <th scope=row> Tails <td> 1 <td> 1
  </tbody>
  <tbody>
  <tr> <td> <th scope=rowgroup> English speakers <td> <td>
  <tr> <td> 32 <th scope=row> Legs <td> 2.67 <td> 4
  <tr> <td> 35 <th scope=row> Tails <td> 0.33 <td> 1
  </tbody>
</table>

This would result in the following table:

Measurement of legs and tails in Cats and English speakers
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 header cells in row 1 ("ID", "Measurement", "Average" and "Maximum") each apply only to the cells in their column.

The header cells with a scope=rowgroup ("Cats" and 'English speakers') apply to all the cells in their row group other than the cells (to their left) in column 1:

The header "Cats" (row 2, column 2) applies to the headers "Legs" (row 3, column 2) and "Tails" (row 4, column 2) and to the data cells in rows 2, 3 and 4 of the "Average" and "Maximum" columns.

The header 'English speakers' (row 5, column 2) applies to the headers "Legs" (row 6, column 2) and "Tails" (row 7, column 2) and to the data cells in rows 5, 6 and 7 of the "Average" and "Maximum" columns.

Each of the "Legs" and "Tails" header cells has a scope=row and therefore apply to the data cells (to the right) in their row, from the "Average" and "Maximum" columns.

Representation of the example table overlayed with arrows indicating which cells each header applies to.

4.9.11. Attributes common to td and th elements

The td and th elements may have a colspan content attribute specified, whose value must be a valid non-negative integer greater than zero.

The td and th elements may also have a rowspan content attribute specified, whose value must be a valid non-negative integer. For this attribute, the value zero means that the cell is to span all the remaining rows in the row group.

These attributes give the number of columns and rows respectively that the cell is to span. These attributes must not be used to overlap cells, as described in the description of the table model.


The td and th element may have a headers content attribute specified. The headers attribute, if specified, must contain a string consisting of an unordered set of unique space-separated tokens that are case-sensitive, each of which must have the value of an id of a th element taking part in the same table as the td or th element (as defined by the table model).

A th element with id id is said to be directly targeted by all td and th elements in the same table that have headers attributes whose values include as one of their tokens the ID id. A th element A is said to be targeted by a th or td element B if either A is directly targeted by B or if there exists an element C that is itself targeted by the element B and A is directly targeted by C.

A th element must not be targeted by itself.

The colspan, rowspan, and headers attributes take part in the table model.


The td and th elements implement interfaces that inherit from the HTMLTableCellElement interface:

interface HTMLTableCellElement : HTMLElement {
  attribute unsigned long colSpan;
  attribute unsigned long rowSpan;
  [PutForwards=value] readonly attribute DOMTokenList headers;
  readonly attribute long cellIndex;
};
cell . cellIndex

Returns the position of the cell in the row’s cells list. This does not necessarily correspond to the x-position of the cell in the table, since earlier cells might cover multiple rows or columns.

Returns -1 if the element isn’t in a row.

The colSpan IDL attribute must reflect the colspan content attribute. Its default value is 1.

The rowSpan IDL attribute must reflect the rowspan content attribute. Its default value is 1.

The headers IDL attribute must reflect the content attribute of the same name.

The cellIndex IDL attribute must, if the element has a parent tr element, return the index of the cell’s element in the parent element’s cells collection. If there is no such parent element, then the attribute must return -1.

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 < xwidth, and the y coordinates are always in the range 0 ≤ y < yheight. If one or both of xwidth and yheight are zero, then the table is empty (has no slots). Tables correspond to table elements.

A cell is a set of slots anchored at a slot (cellx, celly), and with a particular width and height such that the cell covers all the slots with coordinates (x, y) where cellx ≤ x < cellx+width and celly ≤ y < celly+height. Cells can either be data cells or header cells. Data cells correspond to td elements, and header cells correspond to 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=xwidth-1, for a particular value of y. Rows usually correspond to tr elements, though a row group can have some implied rows at the end in some cases involving cells spanning multiple rows.

A column is a complete set of slots from y=0 to y=yheight-1, for a particular value of x. Columns can correspond to col elements. In the absence of col elements, columns are implied.

A row group is a set of rows anchored at a slot (0, groupy) with a particular height such that the row group covers all the slots with coordinates (x, y) where 0 ≤ x < xwidth and groupy ≤ y < groupy+height. Row groups correspond to tbody, thead, and tfoot elements. Not every row is necessarily in a row group.

A column group is a set of columns anchored at a slot (groupx, 0) with a particular width such that the column group covers all the slots with coordinates (x, y) where groupx ≤ x < groupx+width and 0 ≤ y < yheight. Column groups correspond to colgroup elements. Not every column is necessarily in a column group.

Row groups cannot overlap each other. Similarly, column groups cannot overlap each other.

A cell cannot cover slots that are from two or more row groups. It is, however, possible for a cell to be in multiple column groups. All the slots that form part of one cell are part of zero or one row groups and zero or more column groups.

In addition to cells, columns, rows, row groups, and column groups, tables can have a 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 table elements and their descendants. Documents must not have table model errors.

4.9.12.1. Forming a table

User agents must use the following algorithm to determine

  • which elements correspond to which slots in a table associated with a table element,
  • the dimensions of the table (xwidth and yheight), and
  • if there are any table model errors .

    The algorithm selects the first caption encountered and assigns it as the caption for the table, and selects the first thead and processes it. Until there is a thead, tfoot, tbody or tr element, it processes any colgroup elements encountered, and any col children, to create column groups. Finally, from the first thead, tfoot, tbody or tr element encountered as a child of the table it processes those elements, moving the first tfoot encountered to the end of the table respectively.

    1. Let xwidth be zero.

    2. Let yheight be zero.

    3. Let table footer be null.

    4. Let table header be null.

    5. Let the table be the table represented by the table element. The xwidth and yheight variables give the table’s dimensions. The table is initially empty.

    6. If the table element has no children elements, then return the table (which will be empty), and abort these steps.

    7. Associate the first caption element child of the table element with the table. If there are no such children, then it has no associated caption element.

    8. Let the current element be the first element child of the 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.

    9. While the current element is not one of the following elements, advance the current element to the next child of the table:

    10. If the current element is a colgroup, follow these substeps:

      1. Column groups: Process the current element according to the appropriate case below:

        If the current element has any col element children

        Follow these steps:

        1. Let xstart have the value of xwidth.

        2. Let the current column be the first col element child of the colgroup element.

        3. Columns: If the current column col element has a span attribute, then parse its value using the 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 col element has no span attribute, or if trying to parse the attribute’s value resulted in an error or zero, then let span be 1.

        4. Increase xwidth by span.

        5. Let the last span columns in the table correspond to the current column col element.

        6. If current column is not the last col element child of the colgroup element, then let the current column be the next col element child of the colgroup element, and return to the step labeled columns.

        7. Let all the last columns in the table from x=xstart to x=xwidth-1 form a new column group, anchored at the slot (xstart, 0), with width xwidth-xstart, corresponding to the colgroup element.

        If the current element has no col element children
        1. If the colgroup element has a span attribute, then parse its value using the 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 colgroup element has no span attribute, or if trying to parse the attribute’s value resulted in an error or zero, then let span be 1.

        2. Increase xwidth by span.

        3. Let the last span columns in the table form a new column group, anchored at the slot (xwidth-span, 0), with width span, corresponding to the colgroup element.

      2. Advance the current element to the next child of the table.

      3. While the current element is not one of the following elements, advance the current element to the next child of the table:

      4. If the current element is a colgroup element, jump to the step labeled column groups above.

    11. Let ycurrent be zero.

    12. Let the list of downward-growing cells be an empty list.

    13. Rows: While the current element is not one of the following elements, advance the current element to the next child of the table:

      Run the algorithm for processing row groups for the first thead child of the table.

    14. If the current element is a tfoot and the value of table footer is null, then run the following substeps:

      1. let table footer be the current element;

      2. advance the current element to the next child of the table, and

      3. return to the step labeled rows.

    15. If the current element is a thead and the value of table header is null, then run the following substeps:

      1. let table header be the current element;

      2. advance the current element to the next child of the table, and

      3. return to the step labeled rows.

    16. If the current element is a tr then run the algorithm for processing rows, advance the current element to the next child of the table, and return to the step labeled rows.

    17. Run the algorithm for ending a row group.

    18. The current element is either a thead, tfoot, or a tbody.

      Run the algorithm for processing row groups.

    19. Advance the current element to the next child of the table.

    20. Return to the step labeled rows.

    21. End: run the algorithm for processing row groups to process table footer.

    22. If there exists a row or column in the table containing only slots that do not have a cell anchored to them, then this is a table model error.

    23. Return the table.

    The algorithm for processing row groups, which is invoked by the set of steps above for processing thead, tbody, and tfoot elements, is:

    1. Let ystart have the value of yheight.

    2. For each tr element that is a child of the element being processed, in tree order, run the algorithm for processing rows.

    3. If yheight > ystart, then let all the last rows in the table from y=ystart to y=yheight-1 form a new row group, anchored at the slot with coordinate (0, ystart), with height yheight-ystart, corresponding to the element being processed.

    4. Run the 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 ycurrent is less than yheight, follow these steps:

      1. Run the algorithm for growing downward-growing cells.

      2. Increase ycurrent 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 tr elements, is:

    1. If yheight is equal to ycurrent, then increase yheight by

      1. (ycurrent is never greater than yheight.)

    2. Let xcurrent be 0.

    3. Run the algorithm for growing downward-growing cells.

    4. If the tr element being processed has no td or th element children, then increase ycurrent by 1, abort this set of steps, and return to the algorithm above.

    5. Let current cell be the first td or th element child in the tr element being processed.

    6. Cells: While xcurrent is less than xwidth and the slot with coordinate (xcurrent, ycurrent) already has a cell assigned to it, increase xcurrent by 1.

    7. If xcurrent is equal to xwidth, increase xwidth by 1. (xcurrent is never greater than xwidth.)

    8. If the current cell has a colspan attribute, then 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.

    9. If the current cell has a rowspan attribute, then 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.

    10. If rowspan is zero and the table element’s node document is not set to quirks mode, then let cell grows downward be true, and set rowspan to 1. Otherwise, let cell grows downward be false.

    11. If xwidth < xcurrent+colspan, then let xwidth be xcurrent+colspan.

    12. If yheight < ycurrent+rowspan, then let yheight be ycurrent+rowspan.

    13. Let the slots with coordinates (x, y) such that xcurrent ≤ x < xcurrent+colspan and ycurrent ≤ y < ycurrent+rowspan be covered by a new cell c, anchored at (xcurrent, ycurrent), which has width colspan and height rowspan, corresponding to the current cell element.

      If the current cell element is a 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 algorithm for assigning header cells described in the next section.

      If any of the slots involved already had a cell covering them, then this is a table model error. Those slots now have two cells overlapping.

    14. If cell grows downward is true, then add the tuple {c, xcurrent, colspan} to the list of downward-growing cells.

    15. Increase xcurrent by colspan.

    16. If current cell is the last td or th element child in the tr element being processed, then increase ycurrent by 1, abort this set of steps, and return to the algorithm above.

    17. Let current cell be the next td or th element child in the 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, cellx, width} tuple in the list of downward-growing cells, if any, extend the cell cell so that it also covers the slots with coordinates (x, ycurrent), where cellx ≤ x < cellx+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 (principalx, principaly) be the coordinate of the slot to which the principal cell is anchored.

    3. If the principal cell has a headers attribute specified
      1. Take the value of the principal cell’s headers attribute and split it on spaces, letting id list be the list of tokens obtained.

      2. For each token in the id list, if the first element in the Document with an ID equal to the token is a cell in the same table, and that cell is not the principal cell, then add that cell to header list.

      If principal cell does not have a headers attribute specified
      1. Let principalwidth be the width of the principal cell.

      2. Let principalheight be the height of the principal cell.

      3. For each value of y from principaly to principaly+principalheight-1, run the internal algorithm for scanning and assigning header cells, with the principal cell, the header list, the initial coordinate (principalx,y), and the increments Δx=-1 and Δy=0.

      4. For each value of x from principalx to principalx+principalwidth-1, run the internal algorithm for scanning and assigning header cells, with the principal cell, the header list, the initial coordinate (x,principaly), and the increments Δx=0 and Δy=-1.

      5. If the principal cell is anchored in a row group, then add all header cells that are row group headers and are anchored in the same row group with an x-coordinate less than or equal to principalx+principalwidth-1 and a y-coordinate less than or equal to principaly+principalheight-1 to header list.

      6. If the principal cell is anchored in a column group, then add all header cells that are column group headers and are anchored in the same column group with an x-coordinate less than or equal to principalx+principalwidth-1 and a y-coordinate less than or equal to principaly+principalheight-1 to header list.

    4. Remove all the 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 (initialx, initialy), and Δx and Δy increments, is as follows:

    1. Let x equal initialx.

    2. Let y equal initialy.

    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 is 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 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 row header, then let blocked be true.

      5. If blocked is false, then add the current cell to the headers 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 conditions are true:

    • The cell’s scope attribute is in the column state, or
    • The cell’s scope attribute is in the 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 conditions are true:

    • The cell’s scope attribute is in the row state, or
    • The cell’s scope attribute is in the auto state, the cell is not a 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 scope attribute is in the column group state.

    A header cell is said to be a row group header if its scope attribute is in the row group state.

    A cell is said to be an empty cell if it contains no elements and its text content, if any, consists only of White_Space characters.

4.9.13. Examples

This section is non-normative.

The following shows how might one mark up the bottom part of table 45 of the Smithsonian physical tables, Volume 71:

<table>
  <caption>Specification values: <b>Steel</b>, <b>Castings</b>,
  Ann. A.S.T.M. A27-16, Class B;* P max. 0.06; S max. 0.05.</caption>
  <thead>
  <tr>
    <th rowspan=2>Grade.</th>
    <th rowspan=2>Yield Point.</th>
    <th colspan=2>Ultimate tensile strength</th>
    <th rowspan=2>Per cent elong. 50.8mm or 2 in.</th>
    <th rowspan=2>Per cent reduct. area.</th>
  </tr>
  <tr>
    <th>kg/mm<sup>2</sup></th>
    <th>lb/in<sup>2</sup></th>
  </tr>
  </thead>
  <tbody>
  <tr>
    <td>Hard</td>
    <td>0.45 ultimate</td>
    <td>56.2</td>
    <td>80,000</td>
    <td>15</td>
    <td>20</td>
  </tr>
  <tr>
    <td>Medium</td>
    <td>0.45 ultimate</td>
    <td>49.2</td>
    <td>70,000</td>
    <td>18</td>
    <td>25</td>
  </tr>
  <tr>
    <td>Soft</td>
    <td>0.45 ultimate</td>
    <td>42.2</td>
    <td>60,000</td>
    <td>22</td>
    <td>30</td>
  </tr>
  </tbody>
</table>

This table could look like this:

Specification values: Steel, Castings, Ann. A.S.T.M. A27-16, Class B;* P max. 0.06; S max. 0.05.
Grade. Yield Point. Ultimate tensile strength 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

The following shows how one might mark up the gross margin table on page 46 of Apple, Inc’s 10-K filing for fiscal year 2008:

<table>
  <thead>
  <tr>
    <th>
    <th>2008
    <th>2007
    <th>2006
  <tbody>
  <tr>
    <th>Net sales
    <td>$ 32,479
    <td>$ 24,006
    <td>$ 19,315
  <tr>
    <th>Cost of sales
    <td>  21,334
    <td>  15,852
    <td>  13,717
  <tbody>
  <tr>
    <th>Gross margin
    <td>$ 11,145
    <td>$  8,154
    <td>$  5,598
  <tfoot>
  <tr>
    <th>Gross margin percentage
    <td>34.3%
    <td>34.0%
    <td>29.0%
</table>

This table could look like this:

2008 2007 2006
Net sales $ 32,479 $ 24,006 $ 19,315
Cost of sales 21,334 15,852 13,717
Gross margin $ 11,145 $ 8,154 $ 5,598
Gross margin percentage 34.3% 34.0% 29.0%

The following shows how one might mark up the operating expenses table from lower on the same page of that document:

<table>
  <colgroup> <col>
  <colgroup> <col> <col> <col>
  <thead>
  <tr> <th> <th>2008 <th>2007 <th>2006
  <tbody>
  <tr> <th scope=rowgroup> Research and development
        <td> $ 1,109 <td> $ 782 <td> $ 712
  <tr> <th scope=row> Percentage of net sales
        <td> 3.4% <td> 3.3% <td> 3.7%
  <tbody>
  <tr> <th scope=rowgroup> Selling, general, and administrative
        <td> $ 3,761 <td> $ 2,963 <td> $ 2,433
  <tr> <th scope=row> Percentage of net sales
        <td> 11.6% <td> 12.3% <td> 12.6%
</table>

This table could look like this:

2008 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

4.10.1. Introduction

This section is non-normative.

A form is a component of a Web page that has form controls, such as text fields, buttons, checkboxes, range controls, or color pickers. A user can interact with such a form, providing data that can then be sent to the server for further processing (e.g., returning the results of a search or calculation). No client-side scripting is needed in many cases, though an API is available so that scripts can augment the user experience or use forms for purposes other than submitting data to a server.

Writing a form consists of several steps, which can be performed in any order: 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 form element, inside which are placed the controls. Most controls are represented by the input element, which by default provides a one-line text field. To label a control, the label element is used; the label text and the control itself go inside the label element. Each area within a form is typically represented using a div element. Putting this together, here is how one might ask for the customer’s name:

<form>
  <div><label>Customer name: <input></label></div>
</form>

To let the user select the size of the pizza, we can use a set of radio buttons. Radio buttons also use the input element, this time with a type attribute with the value radio. To make the radio buttons work as a group, they are given a common name using the name attribute. To group a batch of controls together, such as, in this case, the radio buttons, one can use the fieldset element. The title of such a group of controls is given by the first element in the fieldset, which has to be a legend element.

<form>
  <div><label>Customer name: <input></label></div>
  <fieldset>
  <legend> Pizza Size </legend>
  <div><label> <input type=radio name=size> Small </label></div>
  <div><label> <input type=radio name=size> Medium </label></div>
  <div><label> <input type=radio name=size> Large </label></div>
  </fieldset>
</form>

Changes from the previous step are highlighted.

To pick toppings, we can use checkboxes. These use the input element with a type attribute with the value checkbox:

<form>
  <div><label>Customer name: <input></label></div>
  <fieldset>
  <legend> Pizza Size </legend>
  <div><label> <input type=radio name=size> Small </label></div>
  <div><label> <input type=radio name=size> Medium </label></div>
  <div><label> <input type=radio name=size> Large </label></div>
  </fieldset>
  <fieldset>
  <legend> Pizza Toppings </legend>
  <div><label> <input type=checkbox> Bacon </label></div>
  <div><label> <input type=checkbox> Extra Cheese </label></div>
  <div><label> <input type=checkbox> Onion </label></div>
  <div><label> <input type=checkbox> Mushroom </label></div>
  </fieldset>
</form>

The pizzeria for which this form is being written is always making mistakes, so it needs a way to contact the customer. For this purpose, we can use form controls specifically for telephone numbers (input elements with their type attribute set to tel) and e-mail addresses (input elements with their type attribute set to email):

<form>
  <div><label>Customer name: <input></label></div>
  <div><label>Telephone: <input type=tel></label></div>
  <div><label>E-mail address: <input type=email></label></div>
  <fieldset>
  <legend> Pizza Size </legend>
  <div><label> <input type=radio name=size> Small </label></div>
  <div><label> <input type=radio name=size> Medium </label></div>
  <div><label> <input type=radio name=size> Large </label></div>
  </fieldset>
  <fieldset>
  <legend> Pizza Toppings </legend>
  <div><label> <input type=checkbox> Bacon </label></div>
  <div><label> <input type=checkbox> Extra Cheese </label></div>
  <div><label> <input type=checkbox> Onion </label></div>
  <div><label> <input type=checkbox> Mushroom </label></div>
  </fieldset>
</form>

We can use an input element with its type attribute set to time to ask for a delivery time. Many of these form controls have attributes to control exactly what values can be specified; in this case, three attributes of particular interest are min, max, and step. These set the minimum time, the maximum time, and the interval between allowed values (in seconds). This pizzeria only delivers between 11am and 9pm, and doesn’t promise anything better than 15 minute increments, which we can mark up as follows:

<form>
  <div><label>Customer name: <input></label></div>
  <div><label>Telephone: <input type=tel></label></div>
  <div><label>E-mail address: <input type=email></label></div>
  <fieldset>
  <legend> Pizza Size </legend>
  <div><label> <input type=radio name=size> Small </label></div>
  <div><label> <input type=radio name=size> Medium </label></div>
  <div><label> <input type=radio name=size> Large </label></div>
  </fieldset>
  <fieldset>
  <legend> Pizza Toppings </legend>
  <div><label> <input type=checkbox> Bacon </label></div>
  <div><label> <input type=checkbox> Extra Cheese </label></div>
  <div><label> <input type=checkbox> Onion </label></div>
  <div><label> <input type=checkbox> Mushroom </label></div>
  </fieldset>
  <div><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900"></label></div>
</form>

The textarea element can be used to provide a free-form text field. In this instance, we are going to use it to provide a space for the customer to give delivery instructions:

<form>
  <div><label>Customer name: <input></label></div>
  <div><label>Telephone: <input type=tel></label></div>
  <div><label>E-mail address: <input type=email></label></div>
  <fieldset>
  <legend> Pizza Size </legend>
  <div><label> <input type=radio name=size> Small </label></div>
  <div><label> <input type=radio name=size> Medium </label></div>
  <div><label> <input type=radio name=size> Large </label></div>
  </fieldset>
  <fieldset>
  <legend> Pizza Toppings </legend>
  <div><label> <input type=checkbox> Bacon </label></div>
  <div><label> <input type=checkbox> Extra Cheese </label></div>
  <div><label> <input type=checkbox> Onion </label></div>
  <div><label> <input type=checkbox> Mushroom </label></div>
  </fieldset>
  <div><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900"></label></div>
  <div><label>Delivery instructions: <textarea></textarea></label></div>
</form>

Finally, to make the form submittable we use the button element:

<form>
  <div><label>Customer name: <input></label></div>
  <div><label>Telephone: <input type=tel></label></div>
  <div><label>E-mail address: <input type=email></label></div>
  <fieldset>
  <legend> Pizza Size </legend>
  <div><label> <input type=radio name=size> Small </label></div>
  <div><label> <input type=radio name=size> Medium </label></div>
  <div><label> <input type=radio name=size> Large </label></div>
  </fieldset>
  <fieldset>
  <legend> Pizza Toppings </legend>
  <div><label> <input type=checkbox> Bacon </label></div>
  <div><label> <input type=checkbox> Extra Cheese </label></div>
  <div><label> <input type=checkbox> Onion </label></div>
  <div><label> <input type=checkbox> Mushroom </label></div>
  </fieldset>
  <div><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900"></label></div>
  <div><label>Delivery instructions: <textarea></textarea></label></div>
  <div><button>Submit order</button></div>
</form>
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 application/x-www-form-urlencoded format, expecting the following parameters sent in an HTTP POST body:

custname

Customer’s name

custtel

Customer’s telephone number

custemail

Customer’s e-mail address

size

The pizza size, either small, medium, or large

topping

A topping, specified once for each selected topping, with the allowed values being bacon, cheese, onion, and mushroom

delivery

The requested delivery time

comments

The delivery instructions

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 method attribute is specified on the form element. This doesn’t specify how the form data is encoded, though; to specify that, you use the enctype attribute. You also have to specify the URL of the service that will handle the submitted data, using the action attribute.

For each form control you want submitted, you then have to give a name that will be used to refer to the data in the submission. We already specified the name for the group of radio buttons; the same attribute (name) also specifies the submission name. Radio buttons can be distinguished from each other in the submission by giving them different values, using the value attribute.

Multiple controls can have the same name; for example, here we give all the checkboxes the same name, and the server distinguishes which checkbox was checked by seeing which values are submitted with that name — like the radio buttons, they are also given unique values with the value attribute.

Given the settings in the previous section, this all becomes:

<form method="post"
      enctype="application/x-www-form-urlencoded"
      action="https://pizza.example.com/order.cgi">
  <p><label>Customer name: <input name="custname"></label></p>
  <p><label>Telephone: <input type=tel name="custtel"></label></p>
  <p><label>E-mail address: <input type=email name="custemail"></label></p>
  <fieldset>
  <legend> Pizza Size </legend>
  <p><label> <input type=radio name=size value="small"> Small </label></p>
  <p><label> <input type=radio name=size value="medium"> Medium </label></p>
  <p><label> <input type=radio name=size value="large"> Large </label></p>
  </fieldset>
  <fieldset>
  <legend> Pizza Toppings </legend>
  <p><label> <input type=checkbox name="topping" value="bacon"> Bacon </label></p>
  <p><label> <input type=checkbox name="topping" value="cheese"> Extra Cheese </label></p>
  <p><label> <input type=checkbox name="topping" value="onion"> Onion </label></p>
  <p><label> <input type=checkbox name="topping" value="mushroom"> Mushroom </label></p>
  </fieldset>
  <p><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900" name="delivery"></label></p>
  <p><label>Delivery instructions: <textarea name="comments"></textarea></label></p>
  <p><button>Submit order</button></p>
</form>

There is no particular significance to the way some of the attributes have their values quoted and others don’t. The HTML syntax allows a variety of equally valid ways to specify attributes, as discussed in §8 The HTML syntax.

For example, if the customer entered "Denise Lawrence" as their name, "555-321-8642" as their telephone number, did not specify an e-mail address, asked for a medium-sized pizza, selected the Extra Cheese and Mushroom toppings, entered a delivery time of 7pm, and left the delivery instructions text field blank, the user agent would submit the following to the online Web service:

custname=Denise+Lawrence&custtel=555-321-8642&custemail=&size=medium&topping=cheese&topping=mushroom&delivery=19%3A00&comments=
4.10.1.4. Client-side form validation

This section is non-normative.

Forms can be annotated in such a way that the user agent will check the user’s input before the form is submitted. The server still has to verify the input is valid (since hostile users can easily bypass the form validation), but it allows the user to avoid the wait incurred by having the server be the sole checker of the user’s input.

The simplest annotation is the required attribute, which can be specified on input elements to indicate that the form is not to be submitted until a value is given. By adding this attribute to the customer name, pizza size, and delivery time fields, we allow the user agent to notify the user when the user submits the form without filling in those fields:

<form method="post"
      enctype="application/x-www-form-urlencoded"
      action="https://pizza.example.com/order.cgi">
  <p><label>Customer name: <input name="custname" required></label></p>
  <p><label>Telephone: <input type=tel name="custtel"></label></p>
  <p><label>E-mail address: <input type=email name="custemail"></label></p>
  <fieldset>
  <legend> Pizza Size </legend>
  <p><label> <input type=radio name=size required value="small"> Small </label></p>
  <p><label> <input type=radio name=size required value="medium"> Medium </label></p>
  <p><label> <input type=radio name=size required value="large"> Large </label></p>
  </fieldset>
  <fieldset>
  <legend> Pizza Toppings </legend>
  <p><label> <input type=checkbox name="topping" value="bacon"> Bacon </label></p>
  <p><label> <input type=checkbox name="topping" value="cheese"> Extra Cheese </label></p>
  <p><label> <input type=checkbox name="topping" value="onion"> Onion </label></p>
  <p><label> <input type=checkbox name="topping" value="mushroom"> Mushroom </label></p>
  </fieldset>
  <p><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900" name="delivery" required></label></p>
  <p><label>Delivery instructions: <textarea name="comments"></textarea></label></p>
  <p><button>Submit order</button></p>
</form>

It is also possible to limit the length of the input, using the maxlength attribute. By adding this to the textarea element, we can limit users to 1000 characters, preventing them from writing huge essays to the busy delivery drivers instead of staying focused and to the point:

<form method="post"
      enctype="application/x-www-form-urlencoded"
      action="https://pizza.example.com/order.cgi">
  <p><label>Customer name: <input name="custname" required></label></p>
  <p><label>Telephone: <input type=tel name="custtel"></label></p>
  <p><label>E-mail address: <input type=email name="custemail"></label></p>
  <fieldset>
  <legend> Pizza Size </legend>
  <p><label> <input type=radio name=size required value="small"> Small </label></p>
  <p><label> <input type=radio name=size required value="medium"> Medium </label></p>
  <p><label> <input type=radio name=size required value="large"> Large </label></p>
  </fieldset>
  <fieldset>
  <legend> Pizza Toppings </legend>
  <p><label> <input type=checkbox name="topping" value="bacon"> Bacon </label></p>
  <p><label> <input type=checkbox name="topping" value="cheese"> Extra Cheese </label></p>
  <p><label> <input type=checkbox name="topping" value="onion"> Onion </label></p>
  <p><label> <input type=checkbox name="topping" value="mushroom"> Mushroom </label></p>
  </fieldset>
  <p><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900" name="delivery" required></label></p>
  <p><label>Delivery instructions: <textarea name="comments" maxlength=1000></textarea></label></p>
  <p><button>Submit order</button></p>
</form>

When a form is submitted, invalid events are fired at each form control that is invalid, and then at the form element itself. This can be useful for displaying a summary of the problems with the form, since typically the browser itself will only report one problem at a time.

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 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:

<form method="post"
      enctype="application/x-www-form-urlencoded"
      action="https://pizza.example.com/order.cgi">
  <p><label>Customer name: <input name="custname" required autocomplete="shipping name"></label></p>
  <p><label>Telephone: <input type=tel name="custtel" autocomplete="shipping tel"></label></p>
  <p><label>E-mail address: <input type=email name="custemail" autocomplete="shipping email"></label></p>
  <fieldset>
  <legend> Pizza Size </legend>
  <p><label> <input type=radio name=size required value="small"> Small </label></p>
  <p><label> <input type=radio name=size required value="medium"> Medium </label></p>
  <p><label> <input type=radio name=size required value="large"> Large </label></p>
  </fieldset>
  <fieldset>
  <legend> Pizza Toppings </legend>
  <p><label> <input type=checkbox name="topping" value="bacon"> Bacon </label></p>
  <p><label> <input type=checkbox name="topping" value="cheese"> Extra Cheese </label></p>
  <p><label> <input type=checkbox name="topping" value="onion"> Onion </label></p>
  <p><label> <input type=checkbox name="topping" value="mushroom"> Mushroom </label></p>
  </fieldset>
  <p><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900" name="delivery" required></label></p>
  <p><label>Delivery instructions: <textarea name="comments" maxlength=1000></textarea></label></p>
  <p><button>Submit order</button></p>
</form>
4.10.1.6. Improving the user experience on mobile devices

This section is non-normative.

Some devices, in particular those with on-screen keyboards and those in locales with languages with many characters (e.g., Japanese), can provide the user with multiple input modalities. For example, when typing in a credit card number the user may wish to only see keys for digits 0-9, while when typing in their name they may wish to see a form field that by default capitalizes each word.

Using the inputmode attribute we can select appropriate input modalities:

<form method="post"
      enctype="application/x-www-form-urlencoded"
      action="https://pizza.example.com/order.cgi">
  <p><label>Customer name: <input name="custname" required autocomplete="shipping name" inputmode="latin-name"></label></p>
  <p><label>Telephone: <input type=tel name="custtel" autocomplete="shipping tel"></label></p>
  <p><label>E-mail address: <input type=email name="custemail" autocomplete="shipping email"></label></p>
  <fieldset>
  <legend> Pizza Size </legend>
  <p><label> <input type=radio name=size required value="small"> Small </label></p>
  <p><label> <input type=radio name=size required value="medium"> Medium </label></p>
  <p><label> <input type=radio name=size required value="large"> Large </label></p>
  </fieldset>
  <fieldset>
  <legend> Pizza Toppings </legend>
  <p><label> <input type=checkbox name="topping" value="bacon"> Bacon </label></p>
  <p><label> <input type=checkbox name="topping" value="cheese"> Extra Cheese </label></p>
  <p><label> <input type=checkbox name="topping" value="onion"> Onion </label></p>
  <p><label> <input type=checkbox name="topping" value="mushroom"> Mushroom </label></p>
  </fieldset>
  <p><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900" name="delivery" required></label></p>
  <p><label>Delivery instructions: <textarea name="comments" maxlength=1000 inputmode="latin-prose"></textarea></label></p>
  <p><button>Submit order</button></p>
</form>
4.10.1.7. The difference between the field type, the autofill field name, and the input modality

This section is non-normative.

The type, autocomplete, and inputmode attributes can seem confusingly similar. For instance, in all three cases, the string "email" is a valid value. This section attempts to illustrate the difference between the three attributes and provides advice suggesting how to use them.

The type attribute on input elements decides what kind of control the user agent will use to expose the field. Choosing between different values of this attribute is the same choice as choosing whether to use an input element, a textarea element, a select element, a keygen element, etc.

The autocomplete attribute, in contrast, describes what the value that the user will enter actually represents. Choosing between different values of this attribute is the same choice as choosing what the label for the element will be.

First, consider telephone numbers. If a page is asking for a telephone number from the user, the right form control to use is <input type=tel>. However, which autocomplete value to use depends on which phone number the page is asking for, whether they expect a telephone number in the international format or just the local format, and so forth.

For example, a page that forms part of a checkout process on an e-commerce site for a customer buying a gift to be shipped to a friend might need both the buyer’s telephone number (in case of payment issues) and the friend’s telephone number (in case of delivery issues). If the site expects international phone numbers (with the country code prefix), this could thus look like this:

<p><label>Your phone number: <input type=tel name=custtel autocomplete="billing tel"></label>
<p><label>Recipient’s phone number: <input type=tel name=shiptel autocomplete="shipping tel"></label>
<p>Please enter complete phone numbers including the country code prefix, as in "+1 555 123 4567".

But if the site only supports British customers and recipients, it might instead look like this (notice the use of tel-national rather than tel):

<p><label>Your phone number: <input type=tel name=custtel autocomplete="billing tel-national"></label>
<p><label>Recipient’s phone number: <input type=tel name=shiptel autocomplete="shipping tel-national"></label>
<p>Please enter complete UK phone numbers, as in "(01632) 960 123".

Now, consider a person’s preferred languages. The right autocomplete value is language. However, there could be a number of different form controls used for the purpose: a free text field (<input type=text>), a drop-down list (<select>), radio buttons (<input type=radio>), etc. It only depends on what kind of interface is desired.

The inputmode decides what kind of input modality (e.g., keyboard) to use, when the control is a free-form text field.

Consider names. If a page just wants one name from the user, then the relevant control is <input type=text>. If the page is asking for the user’s full name, then the relevant autocomplete value is name. But if the user is Japanese, and the page is asking for the user’s Japanese name and the user’s romanized name, then it would be helpful to the user if the first field defaulted to a Japanese input modality, while the second defaulted to a Latin input modality (ideally with automatic capitalization of each word). This is where the inputmode attribute can help:

<p><label>Japanese name: <input name="j" type="text" autocomplete="section-jp name" inputmode="kana"></label>
<label>Romanized name: <input name="e" type="text" autocomplete="section-en name" inputmode="latin-name"></label>

In this example, the "section-*" keywords in the autocomplete attributes' values tell the user agent that the two fields expect different names. Without them, the user agent could automatically fill the second field with the value given in the first field when the user gave a value to the first field.

The "-jp" and "-en" parts of the keywords are opaque to the user agent; the user agent cannot guess, from those, that the two names are expected to be in Japanese and English respectively.

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 use the 24-hour clock, and 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日".

The same applies to the way numbers are written in different places. For example, in some locales, such as US English, "1,234" usually means "one thousand two hundred and thirty-four", while "1.234" means "one and two hundred and thirty-four thousandths", or "one point two three four", while in many other locales the meanings are exactly reversed.

The format used "on the wire", i.e., in HTML markup and as the values for form submissions, is intended to be computer-readable and consistent irrespective of the user’s locale, to allow scripts in pages and on servers to process times, dates, and numbers in a consistent manner with minimal work.

In HTML markup and form submission dates and times are always written in a locale-neutral format derived from the ISO-8601 standard. For example, dates are generally in a format such as 2016-06-19.

Likewise, in markup and form submission numbers are always written without grouping separators, and a FULL STOP character "." @@ as a decimal separator.

The time, date, or number may be translated to the user’s preferred presentation (based on expressed preferences or on the locale of the page itself), before being displayed to the user. Similarly, user agents may allow a user to input a time, date, or number using their preferred format, then 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 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 flow content, phrasing content, and interactive content.

A number of the elements are form-associated elements, which means they can have a form owner.

The form-associated elements fall into several subcategories:

Listed elements

Denotes elements that are listed in the form.elements and fieldset.elements APIs.

Submittable elements

Denotes elements that can be used for constructing the form data set when a form element is submitted.

Some submittable elements can be, depending on their attributes, buttons. The prose below defines when an element is a button. Some buttons are specifically submit buttons.

Resettable elements

Denotes elements that can be affected when a form element is reset.

Reassociateable elements

Denotes elements that have a form content attribute, and a matching form IDL attribute, that allow authors to specify an explicit form owner.

Some elements, not all of them form-associated, are categorized as labelable elements. These are elements that can be associated with a label element.

The following table is non-normative and summarizes the above categories of form elements:

form-associated listed submittable resettable reassociateable labelable
can have a form owner listed in the form.elements and fieldset.elements APIs can be used for constructing the form data set when a form element is submitted can be affected when a form element is reset have a form attribute (allows authors to specify an explicit form owner) can be associated with a label element
input yes yes yes yes yes yes (except "hidden")
button yes yes yes no yes yes
select yes yes yes yes yes yes
textarea yes yes yes yes yes yes
fieldset yes yes no no yes no
output yes yes no yes yes yes
object yes yes yes no yes no
meter no no no no no yes
progress no no no no no yes
label yes no no no no no
img yes no no no no no

4.10.3. The form element

Categories:
Flow content.
Palpable content.
Contexts in which this element can be used:
Where flow content is expected.
Content model:
Flow content, but with no form element descendants.
Tag omission in text/html:
Neither tag is omissible.
Content attributes:
Global attributes
accept-charset - Character encodings to use for §4.10.22 Form submission
action - URL to use for §4.10.22 Form submission
autocomplete - Default setting for autofill feature for controls in the form
enctype - Form data set encoding type to use for §4.10.22 Form submission
method - HTTP method to use for §4.10.22 Form submission
name - Name of form to use in the document.forms API
novalidate - Bypass form control validation for §4.10.22 Form submission
target - browsing context for §4.10.22 Form submission
Allowed ARIA role attribute values:
Any role value.
Allowed ARIA state and property attributes:
Global aria-* attributes
Any aria-* attributes applicable to the allowed roles.
DOM interface:
[OverrideBuiltins]
interface HTMLFormElement : HTMLElement {
  attribute DOMString acceptCharset;
  attribute DOMString action;
  attribute DOMString autocomplete;
  attribute DOMString enctype;
  attribute DOMString encoding;
  attribute DOMString method;
  attribute DOMString name;
  attribute boolean noValidate;
  attribute DOMString target;

  [SameObject] readonly attribute HTMLFormControlsCollection elements;
  readonly attribute unsigned long length;
  getter Element (unsigned long index);
  getter (RadioNodeList or Element) (DOMString name);

  void submit();
  void reset();
  boolean checkValidity();
  boolean reportValidity();
};

The form element represents a collection of form-associated elements, some of which can represent editable values that can be submitted to a server for processing.

The accept-charset content attribute gives the character encodings that are to be used for the submission. If specified, the value must be an ordered set of unique space-separated tokens that are ASCII case-insensitive, and each token must be an ASCII case-insensitive match for one of the labels of an ASCII-compatible encoding. [ENCODING]

The name content attribute represents the form's name within the forms collection. The value must not be the empty string, and the value must be unique amongst the form elements in the forms collection that it is in, if any.

The autocomplete content attribute is an enumerated attribute. The attribute has two states. The on keyword maps to the on state, and the off keyword maps to the off state. The attribute may also be omitted. The missing value default is the on state. The off state indicates that by default, form controls in the form will have their autofill field name set to "off"; the on state indicates that by default, form controls in the form will have their autofill field name set to "on".

The action, enctype, method, enctype, novalidate, and target attributes are attributes for form submission.

form . elements

Returns an HTMLFormControlsCollection of the form controls in the form (excluding image buttons for historical reasons).

form . length

Returns the number of form controls in the form (excluding image buttons for historical reasons).

form[index]

Returns the indexth element in the form (excluding image buttons for historical reasons).

form[name]

Returns the form control (or, if there are several, a RadioNodeList of the form controls) in the form with the given ID or name (excluding image buttons for historical reasons); or, if there are none, returns the img element with the given ID.

Once an element has been referenced using a particular name, that name will continue being available as a way to reference that element in this method, even if the element’s actual ID or name changes, for as long as the element remains in the Document.

If there are multiple matching items, then a RadioNodeList object containing all those elements is returned.

form . submit()

Submits the form.

form . reset()

Resets the form.

form . checkValidity()

Returns true if the form’s controls are all valid; otherwise, returns false.

form . reportValidity()

Returns true if the form’s controls are all valid; otherwise, returns false and informs the user.

The autocomplete IDL attribute must reflect the content attribute of the same name, limited to only known values.

The name IDL attribute must reflect the content attribute of the same name.

The acceptCharset IDL attribute must reflect the accept-charset content attribute.


The elements IDL attribute must return an HTMLFormControlsCollection rooted at the form element’s home subtree’s root element, whose filter matches listed elements whose form owner is the form element, with the exception of input elements whose type attribute is in the image button state, which must, for historical reasons, be excluded from this particular collection.

The length IDL attribute must return the number of nodes represented by the elements collection.

The supported property indices at any instant are the indices supported by the object returned by the elements attribute at that instant.

When a form element is indexed for indexed property retrieval, the user agent must return the value returned by the item method on the elements collection, when invoked with the given index as its argument.


Each 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 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 listed element candidate whose form owner is the form element, with the exception of any input elements whose type attribute is in the image button state, run these substeps:

    1. If candidate has an id attribute, add an entry to sourced names with that id attribute’s value as the string, candidate as the element, and id as the source.
    2. If candidate has a name attribute, add an entry to sourced names with that name attribute’s value as the string, candidate as the element, and name as the source.
  3. For each img element candidate whose form owner is the form element, run these substeps:

    1. If candidate has an id attribute, add an entry to sourced names with that id attribute’s value as the string, candidate as the element, and id as the source.
    2. If candidate has a name attribute, add an entry to sourced names with that name attribute’s value as the string, candidate as the element, and name as the source.
  4. For each entry past entry in the 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 past names map as the age.

  5. Sort sourced names by 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.

The properties exposed in this way must be unenumerable.

When a form element is indexed for named property retrieval, the user agent must run the following steps:

  1. Let candidates be a live RadioNodeList object containing all the listed elements whose form owner is the form element that have either an id attribute or a name attribute equal to name, with the exception of input elements whose type attribute is in the Image Button state, in tree order.
  2. If candidates is empty, let candidates be a live RadioNodeList object containing all the img elements that are descendants of the form element and that have either an id attribute or a name attribute equal to name, in tree order.
  3. If candidates is empty, name is the name of one of the entries in the form element’s past names map: return the object associated with name in that map.
  4. If candidates contains more than one node, return candidates and abort these steps.
  5. Otherwise, candidates contains exactly one node. Add a mapping from name to the node in candidates in the form element’s 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 form element’s past names map changes form owner, then its entries must be removed from that map.


The submit() method, when invoked, must submit the form element from the form element itself, with the submitted from submit() method flag set.

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

  1. If the form element is marked as locked for reset, then abort these steps.
  2. Mark the form element as locked for reset.
  3. Reset the form element.
  4. Unmark the form element as locked for reset.

If the checkValidity() method is invoked, the user agent must statically validate the constraints of the 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 interactively validate the constraints of the 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:
<form action="https://www.google.com/search" method="get">
  <label>Google: <input type="search" name="q"></label> <input type="submit" value="Search...">
</form>
<form action="https://www.bing.com/search" method="get">
  <label>Bing: <input type="search" name="q"></label> <input type="submit" value="Search...">
</form>

4.10.4. The label element

Categories:
Flow content.
Phrasing content.
Interactive content.
Form-associated element.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Phrasing content, but with no descendant labelable elements unless it is the element’s labeled control, and no descendant label elements.
Tag omission in text/html:
Neither tag is omissable
Content attributes:
Global attributes
for - Associate the label with form control
Allowed ARIA role attribute values:
None
Allowed ARIA state and property attributes:
Global aria-* attributes
DOM interface:
interface HTMLLabelElement : HTMLElement {
  readonly attribute HTMLFormElement? form;
  attribute DOMString htmlFor;
  readonly attribute HTMLElement? control;
};

The label element represents a caption in a user interface. The caption can be associated with a specific form control, known as the label element’s labeled control, either using the for attribute, or by putting the form control inside the label element itself.

Except where otherwise specified by the following rules, a label element has no labeled control.

The for attribute may be specified to indicate a form control with which the caption is to be associated. If the attribute is specified, the attribute’s value must be the ID of a labelable element in the same Document as the label element. If the attribute is specified and there is an element in the Document whose ID is equal to the value of the for attribute, and the first such element is a labelable element, then that element is the label element’s labeled control.

The following example shows the use of a for attribute, to associate labels which do not contain the element they label.

<form>
  <table>
    <caption>Example of using <label:gt;'s for attribute with <label></caption>
    <tr>
      <th><label for="name">Customer name: </label></th>
      <td><input name="name" id="name"></td>
    </tr>
  </table>
</form>

Note that the id attribute is required to associate the for attribute, while the name attribute is required so the value of the input will be submitted as part of the form.

If the for attribute is not specified, but the label element has a labelable element descendant, then the first such descendant in tree order is the label element’s labeled control.

The label element’s activation behavior should match the platform’s label behavior. Similarly, any additional presentation hints should match the platform’s label presentation.

On many platforms activating a checkbox label checks the checkbox, while activating a text input’s label focuses the input. Clicking the label "Lost" in the following snippet could trigger the user agent to run synthetic click activation steps on the checkbox, as if the element itself had been triggered by the user, while clicking the label "Where?" would queue a task that runs the focusing steps for the element to the text input:
<label><input type="checkbox" name="lost"> Lost</label><br> <label>Where? <input type="text" name="where"></label>

If a label element has interactive content other than its labeled control, the activation behavior of the label element for events targeted at those interactive content descendants and any descendants of those must be to do nothing.

In the following example, clicking on the link does not toggle the checkbox, even if the platform normally toggles a checkbox when clicking on a label. Instead, clicking the link triggers the normal activation behavior of following the link.

<!-- bad example - link inside label reduces checkbox activation area -->
<label><input type=checkbox name=tac>I agree to <a href="tandc.html">the terms and conditions</a></label>


The ability to click or press a label to trigger an event on a control provides usability and accessibility benefits by increasing the hit area of a control, making it easier for a user to operate. These benefits may be lost or reduced, if the label element contains an element with its own activation behavior, such as a link:

<!-- bad example - all label text inside the link reduces activation area to checkbox only -->
<label><input type=checkbox name=tac><a href="tandc.html">I agree to the terms and conditions</a></label>

The usability and accessibility benefits can be maintained by placing such elements outside the label element:

  <!-- good example - link outside label means checkbox activation area includes the checkbox and all the label text -->
  <label><input type=checkbox name=tac>I agree to the terms and conditions</label>
(read <a href="tandc.html">Terms and Conditions</a>)

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.
<p><label>Full name: <input name=fn> <small>Format: First Last</small></label></p>
<p><label>Age: <input name=age type=number min=0></label></p>
<p><label>Post code: <input name=pc> <small>Format: AB12 3CD</small></label></p>
label . control

Returns the form control that is associated with this element.

The htmlFor IDL attribute must reflect the for content attribute.

The control IDL attribute must return the label element’s labeled control, if any, or null if there isn’t one.


control . labels

Returns a NodeList of all the label elements that the form control is associated with.

Labelable elements have a NodeList object associated with them that represents the list of label elements, in tree order, whose labeled control is the element in question. The labels IDL attribute of labelable elements, on getting, must return that NodeList object.

4.10.5. The input element

Categories:
Flow content.
Phrasing content.
If the type attribute is not in the Hidden state: interactive content.
If the type attribute is not in the Hidden state: listed, labelable, submittable, resettable, and reassociateable form-associated element.
If the type attribute is in the Hidden state: listed, submittable, resettable, and reassociateable form-associated element.
If the type attribute is not in the Hidden state: Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Nothing.
Tag omission in text/html:
No end tag
Content attributes:
Global attributes
accept - Hint for expected file type in file upload controls
alt - Replacement text for use when images are not available
autocomplete - Hint for form autofill feature
autofocus - Automatically focus the form control when the page is loaded
checked - Whether the command or control is checked
dirname - Name of form field to use for sending the element’s directionality in §4.10.22 Form submission
disabled - Whether the form control is disabled
form - Associates the control with a form element
formaction - URL to use for §4.10.22 Form submission
formenctype - Form data set encoding type to use for §4.10.22 Form submission
formmethod - HTTP method to use for §4.10.22 Form submission
formnovalidate - Bypass form control validation for §4.10.22 Form submission
formtarget - browsing context for §4.10.22 Form submission
height - Vertical dimension
inputmode - Hint for selecting an input modality
list - List of autocomplete options
max - Maximum value
maxlength - Maximum length of value
min - Minimum value
minlength - Minimum length of value
multiple - Whether to allow multiple values
name - Name of form control to use for §4.10.22 Form submission and in the form.elements API
pattern - Pattern to be matched by the form control’s value
placeholder - User-visible label to be placed within the form control
readonly - Whether to allow the value to be edited by the user
required - Whether the control is required for §4.10.22 Form submission
size - Size of the control
src - Address of the resource
step - Granularity to be matched by the form control’s value
type - Type of form control
value - Value of the form control
width - Horizontal dimension
Also, the title attribute has special semantics on this element when used in conjunction with the pattern attribute.
Allowed ARIA role attribute values:
Depends upon state of the type attribute.
Allowed ARIA state and property attributes:
Global aria-* attributes
Any aria-* attributes applicable to the allowed roles.
DOM interface:
interface HTMLInputElement : HTMLElement {
  attribute DOMString accept;
  attribute DOMString alt;
  attribute DOMString autocomplete;
  attribute boolean autofocus;
  attribute boolean defaultChecked;
  attribute boolean checked;
  attribute DOMString dirName;
  attribute boolean disabled;
  readonly attribute HTMLFormElement? form;
  readonly attribute FileList? files;
  attribute DOMString formAction;
  attribute DOMString formEnctype;
  attribute DOMString formMethod;
  attribute boolean formNoValidate;
  attribute DOMString formTarget;
  attribute unsigned long height;
  attribute boolean indeterminate;
  attribute DOMString inputMode;
  readonly attribute HTMLElement? list;
  attribute DOMString max;
  attribute long maxLength;
  attribute DOMString min;
  attribute long minLength;
  attribute boolean multiple;
  attribute DOMString name;
  attribute DOMString pattern;
  attribute DOMString placeholder;
  attribute boolean readOnly;
  attribute boolean required;
  attribute unsigned long size;
  attribute DOMString src;
  attribute DOMString step;
  attribute DOMString type;
  attribute DOMString defaultValue;
  [TreatNullAs=EmptyString] attribute DOMString value;
  attribute object? valueAsDate;
  attribute unrestricted double valueAsNumber;
  attribute unsigned long width;

  void stepUp(optional long n = 1);
  void stepDown(optional long n = 1);

  readonly attribute boolean willValidate;
  readonly attribute ValidityState validity;
  readonly attribute DOMString validationMessage;
  boolean checkValidity();
  boolean reportValidity();
  void setCustomValidity(DOMString error);

  [SameObject] readonly attribute NodeList labels;

  void select();
  attribute unsigned long selectionStart;
  attribute unsigned long selectionEnd;
  attribute DOMString selectionDirection;
  void setRangeText(DOMString replacement);
  void setRangeText(DOMString replacement, unsigned long start, unsigned long end, optional SelectionMode selectionMode = "preserve");
  void setSelectionRange(unsigned long start, unsigned long end, optional DOMString direction);
};

The input element represents a typed data field, usually with a form control to allow the user to edit the data.

The type attribute controls the data type of the element. It is an enumerated attribute. The data type is used to select the control to use for the input. Some data types allow either a text field or combo box control to be used, based on the absence or presence of a list attribute on the element. The following table lists the keywords and states for the attribute — the keywords in the left column map to the state, data type and control(s) in the cells on the same row.

Keyword State Data type Control type
hidden Hidden An arbitrary string n/a
text Text Text with no line breaks A text field or combo box
search Search Text with no line breaks Search field or combo box
tel Telephone Text with no line breaks A text field or combo box
url URL An absolute URL A text field or combo box
email E-mail An e-mail address or list of e-mail addresses A text field or combo box
password Password Text with no line breaks (sensitive information) A text field that obscures data entry
date Date A date (year, month, day) with no time zone A date control
month Month A date consisting of a year and a month with no time zone A month control
week Week A date consisting of a week-year number and a week number with no time zone A week control
time Time A time (hour, minute, seconds, fractional seconds) with no time zone A time control
datetime-local Local Date and Time A local date and time (year, month, day, hour, minute, second, fractional seconds) with no time-zone offset information A local date and time control
number Number A numerical value A text field or combo box or spinner control
range Range A numerical value, with the extra semantic that the exact value is not important A slider control or similar
color Color An sRGB color with 8-bit red, green, and blue components A color well
checkbox Checkbox A set of zero or more values from a predefined list A checkbox
radio Radio Button An enumerated value A radio button
file File Upload Zero or more files each with a MIME type and optionally a file name A label and a button
submit submit button An enumerated value, with the extra semantic that it must be the last value selected and initiates form submission A button
image 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 reset button n/a A button
button Button n/a A button

The missing value default is the Text state.

Which of the accept, alt, autocomplete, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, inputmode, list, max, maxlength, min, minlength, multiple, pattern, placeholder, readonly, required, size, src, step, and width content attributes, the checked, files, valueAsDate, valueAsNumber, and list IDL attributes, the select() method, the selectionStart, selectionEnd, and selectionDirection, IDL attributes, the setRangeText() and setSelectionRange() methods, the stepUp() and stepDown() methods, and the input and change events apply to an input element depends on the state of its type attribute. The subsections that define each type also clearly define in normative "bookkeeping" sections which of these feature apply, and which do not apply, to each type. The behavior of these features depends on whether they apply or not, as defined in their various sections (q.v. for Content attributes, for APIs, for events).

The following table is non-normative and summarizes which of those content attributes, IDL attributes, methods, and events apply to each state:

Hidden Text, Search URL, Telephone E-mail Password Date, Month, Week, Time, Local Date and Time Number Range Color Checkbox, Radio Button File Upload submit button image button reset button, Button
Content attributes
accept · · · · · · · · · · Yes · · ·
alt · · · · · · · · · · · · Yes ·
autocomplete · Yes Yes Yes Yes Yes Yes Yes Yes · · · · ·
checked · · · · · · · · · Yes · · · ·
dirname · Yes · · · · · · · · · · · ·
formaction · · · · · · · · · · · Yes Yes ·
formenctype · · · · · · · · · · · Yes Yes ·
formmethod · · · · · · · · · · · Yes Yes ·
formnovalidate · · · · · · · · · · · Yes Yes ·
formtarget · · · · · · · · · · · Yes Yes ·
height · · · · · · · · · · · · Yes ·
inputmode · Yes · · Yes · · · · · · · · ·
list · Yes Yes Yes · Yes Yes Yes Yes · · · · ·
max · · · · · Yes Yes Yes · · · · · ·
maxlength · Yes Yes Yes Yes · · · · · · · · ·
min · · · · · Yes Yes Yes · · · · · ·
minlength · Yes Yes Yes Yes · · · · · · · · ·
multiple · · · Yes · · · · · · Yes · · ·
pattern · Yes Yes Yes Yes · · · · · · · · ·
placeholder · Yes Yes Yes Yes · Yes · · · · · · ·
readonly · Yes Yes Yes Yes Yes Yes · · · · · · ·
required · Yes Yes Yes Yes Yes Yes · · Yes Yes · · ·
size · Yes Yes Yes Yes · · · · · · · · ·
src · · · · · · · · · · · · Yes ·
step · · · · · Yes Yes Yes · · · · · ·
width · · · · · · · · · · · · Yes ·
IDL attributes and methods
checked · · · · · · · · · Yes · · · ·
files · · · · · · · · · · Yes · · ·
value default value value value value value value value value default/on filename default default default
valueAsDate · · · · · Yes · · · · · · · ·
valueAsNumber · · · · · Yes Yes Yes · · · · · ·
list · Yes Yes Yes · Yes Yes Yes Yes · · · · ·
select() · Yes Yes† Yes Yes† Yes† Yes† · Yes† · Yes† · · ·
selectionStart · Yes Yes · Yes · · · · · · · · ·
selectionEnd · Yes Yes · Yes · · · · · · · · ·
selectionDirection · Yes Yes · Yes · · · · · · · · ·
setRangeText() · Yes Yes · Yes · · · · · · · · ·
setSelectionRange() · Yes Yes · Yes · · · · · · · · ·
stepDown() · · · · · Yes Yes Yes · · · · · ·
stepUp() · · · · · Yes Yes Yes · · · · · ·
Events
input event · Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes · · ·
change event · Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes · · ·

† If the control has no text field, the select() method results in a no-op, with no "InvalidStateError" DOMException.

Some states of the type attribute define a value sanitization algorithm.

Each input element has a value, which is exposed by the 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 max, min, step, valueAsDate, valueAsNumber, stepDown(), and stepUp().

Each input element has a boolean dirty value flag. The dirty value 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 value. (It is also set to true when the value is programmatically changed, as described in the definition of the value IDL attribute.)

The value content attribute gives the default value of the input element. When the value content attribute is added, set, or removed, if the control’s dirty value flag is false, the user agent must set the value of the element to the value of the value content attribute, if there is one, or the empty string otherwise, and then run the current value sanitization algorithm, if one is defined.

Each input element has a checkedness, which is exposed by the checked IDL attribute.

Each input element has a boolean dirty checkedness flag. When it is true, the element is said to have a dirty checkedness. The 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 checkedness.

The checked content attribute is a boolean attribute that gives the default checkedness of the input element. When the checked content attribute is added, if the control does not have dirty checkedness, the user agent must set the checkedness of the element to true; when the checked content attribute is removed, if the control does not have dirty checkedness, the user agent must set the checkedness of the element to false.

The reset algorithm for input elements is to set the dirty value flag and dirty checkedness flag back to false, set the value of the element to the value of the value content attribute, if there is one, or the empty string otherwise, set the checkedness of the element to true if the element has a checked content attribute and false if it does not, empty the list of selected files, and then invoke the value sanitization algorithm, if the type attribute’s current state defines one.

Each input element can be mutable. Except where otherwise specified, an input element is always mutable. Similarly, except where otherwise specified, the user agent should not allow the user to modify the element’s value or checkedness.

When an input element is disabled, it is not mutable.

The readonly attribute can also in some cases (e.g., for the Date state, but not the Checkbox state) stop an input element from being mutable.

The cloning steps for input elements must propagate the value, dirty value flag, checkedness, and dirty checkedness flag from the node being cloned to the copy.


When an input element is first created, the element’s rendering and behavior must be set to the rendering and behavior defined for the type attribute’s state, and the value sanitization algorithm, if one is defined for the type attribute’s state, must be invoked.

When an input element’s type attribute changes state, the user agent must run the following steps:

  1. If the previous state of the element’s type attribute put the value IDL attribute in the value mode, and the element’s value is not the empty string, and the new state of the element’s type attribute puts the value IDL attribute in either the default mode or the default/on mode, then set the element’s value content attribute to the element’s value.
  2. Otherwise, if the previous state of the element’s type attribute put the value IDL attribute in any mode other than the value mode, and the new state of the element’s type attribute puts the value IDL attribute in the value mode, then set the value of the element to the value of the value content attribute, if there is one, or the empty string otherwise, and then set the control’s dirty value flag to false.
  3. Otherwise, if the previous state of the element’s type attribute put the value IDL attribute in any mode other than the filename mode, and the new state of the element’s type attribute puts the value IDL attribute in the filename mode, then set the 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 Radio Button state uses this, in particular.)
  6. Invoke the value sanitization algorithm, if one is defined for the type attribute’s new state.

The name attribute represents the element’s name. The dirname attribute controls how the element’s directionality is submitted. The disabled attribute is used to make the control non-interactive and to prevent its value from being submitted. The form attribute is used to explicitly associate the input element with its form owner. The autofocus attribute controls focus. The inputmode attribute controls the user interface’s input modality for the control. The autocomplete attribute controls how the user agent provides autofill behavior.

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 checkbox controls.

The accept, alt, max, min, multiple, pattern, placeholder, required, size, src, and step IDL attributes must reflect the respective content attributes of the same name. The dirName IDL attribute must reflect the dirname content attribute. The readOnly IDL attribute must reflect the readonly content attribute. The defaultChecked IDL attribute must reflect the checked content attribute. The defaultValue IDL attribute must reflect the value content attribute.

The type IDL attribute must reflect the respective content attribute of the same name, limited to only known values. The inputMode IDL attribute must reflect the inputmode content attribute, limited to only known values. The maxLength IDL attribute must reflect the maxlength content attribute, limited to only non-negative numbers. The minLength IDL attribute must reflect the minlength content attribute, limited to only non-negative numbers.

The IDL attributes width and height must return the rendered width and height of the image, in CSS pixels, if an image is being rendered, and is being rendered to a visual medium; or else the intrinsic width and height of the image, in CSS pixels, if an image is available but not being rendered to a visual medium; or else 0, if no image is available. When the input element’s type attribute is not in the image button state, then no image is available. [CSS-2015]

On setting, they must act as if they reflected the respective content attributes of the same name.

The willValidate, validity, and validationMessage IDL attributes, and the checkValidity(), reportValidity(), and setCustomValidity() methods, are part of the constraint validation API. The labels IDL attribute provides a list of the element’s labels. The select(), selectionStart, selectionEnd, selectionDirection, setRangeText(), and setSelectionRange() methods and IDL attributes expose the element’s text selection. The autofocus, disabled, form, and name IDL attributes are part of the element’s forms API.

4.10.5.1. States of the type attribute
4.10.5.1.1. Hidden state (type=hidden)

When an input element’s type attribute is in the Hidden state, the rules in this section apply.

The input element represents a value that is not intended to be examined or manipulated by the user.

Constraint validation: If an input element’s type attribute is in the Hidden state, it is barred from constraint validation.

If the name attribute is present and has a value that is a case-sensitive match for the string "_charset_", then the element’s value attribute must be omitted.

The value IDL attribute applies to this element and is in mode default.

The following content attributes must not be specified and do not apply to the element: accept, alt, autocomplete, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, inputmode, list, max, maxlength, min, minlength, multiple, pattern, placeholder, readonly, required, size, src, step, and width.

The following IDL attributes and methods do not apply to the element: checked, files, list, selectionStart, selectionEnd, selectionDirection, valueAsDate, and valueAsNumber IDL attributes; select(), setRangeText(), setSelectionRange(), stepDown(), and stepUp() methods.

The input and change events do not apply.

4.10.5.1.2. Text (type=text) state and Search state (type=search)

When an input element’s type attribute is in the Text state or the Search state, the rules in this section apply.

The input element represents a one line plain text edit control for the element’s value.

The difference between the Text state and the Search state is primarily stylistic: on platforms where search fields are distinguished from regular text fields, the Search state might result in an appearance consistent with the platform’s search fields rather than appearing like a regular text field.

If the element is mutable, its 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 value.

If the element is 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 dir attribute to "ltr" if the user selected a left-to-right writing direction, and "rtl" if the user selected a right-to-left writing direction.
  2. Queue a task to fire a simple event that bubbles named input at the input element.

The value attribute, if specified, must have a value that contains no U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters.

The following common input element content attributes, IDL attributes, and methods apply to the element: autocomplete, dirname, inputmode, list, maxlength, minlength, pattern, placeholder, readonly, required, and size content attributes; list, selectionStart, selectionEnd, selectionDirection, and value IDL attributes; select(), setRangeText(), and setSelectionRange() methods.

The value IDL attribute is in mode value.

The input and change events apply.

The following content attributes must not be specified and do not apply to the element: accept, alt, checked, formaction, formenctype, formmethod, formnovalidate, formtarget, height, max, min, multiple, src, step, and width.

The following IDL attributes and methods do not apply to the element: checked, files, valueAsDate, and valueAsNumber IDL attributes; stepDown() and stepUp() methods.

4.10.5.1.3. Telephone state (type=tel)

When an input element’s type attribute is in the Telephone state, the rules in this section apply.

The input element represents a control for editing a telephone number given in the element’s value.

If the element is mutable, its value should be editable by the user. User agents may change the spacing and, with care, the punctuation of 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 value.

The value attribute, if specified, must have a value that contains no U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters.

Unlike the URL and E-mail types, the Telephone type does not enforce a particular syntax. This is intentional; in practice, telephone number fields tend to be free-form fields, because there are a wide variety of valid phone numbers. Systems that need to enforce a particular format are encouraged to use the pattern attribute or the setCustomValidity() method to hook into the client-side validation mechanism.

The following common input element content attributes, IDL attributes, and methods apply to the element: autocomplete, list, maxlength, minlength, pattern, placeholder, readonly, required, and size content attributes; list, selectionStart, selectionEnd, selectionDirection, and value IDL attributes; select(), setRangeText(), and setSelectionRange() methods.

The value IDL attribute is in mode value.

The input and change events apply.

The following content attributes must not be specified and do not apply to the element: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, inputmode, max, min, multiple, src, step, and width.

The following IDL attributes and methods do not apply to the element: checked, files, valueAsDate, and valueAsNumber IDL attributes; stepDown() and stepUp() methods.

4.10.5.1.4. URL state (type=url)

When an input element’s type attribute is in the URL state, the rules in this section apply.

The input element represents a control for editing a single absolute URL given in the element’s value.

If the element is mutable, the user agent should allow the user to change the URL represented by its value. User agents may allow the user to set the value to a string that is not a valid absolute URL, but may also or instead automatically escape characters entered by the user so that the value is always a valid 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 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 value.

The value attribute, if specified and not empty, must have a value that is a valid URL potentially surrounded by spaces that is also an absolute URL.

The value sanitization algorithm is as follows: Strip line breaks from the value, then strip leading and trailing whitespace from the value.

Constraint validation: While the value of the element is neither the empty string nor a valid absolute URL, the element is suffering from a type mismatch.

The following common input element content attributes, IDL attributes, and methods apply to the element: autocomplete, list, maxlength, minlength, pattern, placeholder, readonly, required, and size content attributes; list, selectionStart, selectionEnd, selectionDirection, and value IDL attributes; select(), setRangeText(), and setSelectionRange() methods.

The value IDL attribute is in mode value.

The input and change events apply.

The following content attributes must not be specified and do not apply to the element: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, inputmode, max, min, multiple, src, step, and width.

The following IDL attributes and methods do not apply to the element: checked, files, valueAsDate, and valueAsNumber IDL attributes; stepDown() and stepUp() methods.

If a document contained the following markup:
<input type="url" name="location" list="urls">
<datalist id="urls">
  <option label="MIME: Format of Internet Message Bodies" value="https://tools.ietf.org/html/rfc2045">
  <option label="HTML 4.01 Specification" value="https://www.w3.org/TR/html4/">
  <option label="Form Controls" value="https://www.w3.org/TR/xforms/slice8.html#ui-commonelems-hint">
  <option label="Scalable Vector Graphics (SVG) 1.1 Specification" value="https://www.w3.org/TR/SVG/">
  <option label="Feature Sets - SVG 1.1 - 20030114" value="https://www.w3.org/TR/SVG/feature.html">
  <option label="The Single UNIX Specification, Version 3" value="https://www.unix-systems.org/version3/">
</datalist>

...and the user had typed "www.w3", and the user agent had also found that the user had visited https://www.w3.org/Consortium/#membership and https://www.w3.org/TR/XForms/ in the recent past, then the rendering might look like this:

A text box with an icon on the left followed by the text "www.w3" 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 scroll bar 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 user agent-defined manner (maybe by how frequently the user refers to those URLs). Note how the user agent 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 user agent has no titles to provide for those values.

4.10.5.1.5. E-mail state (type=email)

When an input element’s type attribute is in the E-mail state, the rules in this section apply.

How the E-mail state operates depends on whether the multiple attribute is specified or not.

When the multiple attribute is not specified on the element

The input element represents a control for editing an e-mail address given in the element’s value.

If the element is mutable, the user agent should allow the user to change the e-mail address represented by its value. User agents may allow the user to set the value to a string that is not a valid e-mail address. The user agent should act in a manner consistent with expecting the user to provide a single e-mail address. User agents should allow the user to set the 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 value. User agents may transform the value for display and editing; in particular, user agents should convert punycode in the domain labels of the 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 suffering from bad input.

The value attribute, if specified and not empty, must have a value that is a single valid e-mail address.

The value sanitization algorithm is as follows: Strip line breaks from the value, then strip leading and trailing whitespace from the value.

Constraint validation: While the value of the element is neither the empty string nor a single valid e-mail address, the element is suffering from a type mismatch.

When the multiple attribute is specified on the element

The input element represents a control for adding, removing, and editing the e-mail addresses given in the element’s values.

If the element is mutable, the user agent should allow the user to add, remove, and edit the e-mail addresses represented by its values. User agents may allow the user to set any individual value in the list of values to a string that is not a valid e-mail 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 values. User agents may transform the values for display and editing; in particular, user agents should convert punycode in the domain labels of the 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 suffering from bad input.

Whenever the user changes the element’s values, the user agent must run the following steps:

  1. Let latest values be a copy of the element’s values.
  2. Strip leading and trailing whitespace from each value in latest values.
  3. Let the element’s 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 value attribute, if specified, must have a value that is a valid e-mail address list.

The value sanitization algorithm is as follows:

  1. Split on commas the element’s value, strip leading and trailing whitespace from each resulting token, if any, and let the element’s values be the (possibly empty) resulting list of (possibly empty) tokens, maintaining the original order.
  2. Let the element’s value be the result of concatenating the element’s values, separating each value from the next by a single U+002C COMMA character (,), maintaining the list’s order.

Constraint validation: While the value of the element is not a valid e-mail address list, the element is suffering from a type mismatch.

When the multiple attribute is set or removed, the user agent must run the value sanitization algorithm.

A valid e-mail address is a string that matches the email production of the following ABNF, the character set for which is Unicode. This ABNF implements the extensions described in RFC 1123. [ABNF] [RFC5322] [RFC1034] [RFC1123]

email         = 1*( atext / "." ) "@" label *( "." label )
label         = let-dig [ [ ldh-str ] let-dig ]  ; limited to a length of 63 characters by RFC 1034 section 3.5
atext         = < as defined in RFC 5322 section 3.2.3 >
let-dig       = < as defined in RFC 1034 section 3.5 >
ldh-str       = < as defined in RFC 1034 section 3.5 >

This requirement is a willful violation of RFC 5322, which defines a syntax for e-mail addresses that is simultaneously too strict (before the "@" character), too vague (after the "@" character), and too lax (allowing comments, whitespace characters, and quoted strings in manners unfamiliar to most users) to be of practical use here.

The following JavaScript- and Perl-compatible regular expression is an implementation of the above definition.

/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/

A valid e-mail address list is a set of comma-separated tokens, where each token is itself a valid e-mail address. To obtain the list of tokens from a valid e-mail address list, an implementation must split the string on commas.

The following common input element content attributes, IDL attributes, and methods apply to the element: autocomplete, list, maxlength, minlength, multiple, pattern, placeholder, readonly, required, and size content attributes; list and value IDL attributes; select() method.

The value IDL attribute is in mode value.

The input and change events apply.

The following content attributes must not be specified and do not apply to the element: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, inputmode, max, min, src, step, and width.

The following IDL attributes and methods do not apply to the element: checked, files, selectionStart, selectionEnd, selectionDirection, valueAsDate, and valueAsNumber IDL attributes; select(), setRangeText(), setSelectionRange(), stepDown() and stepUp() methods.

4.10.5.1.6. Password state (type=password)

When an input element’s type attribute is in the Password state, the rules in this section apply.

The input element represents a one line plain text edit control for the element’s value. The user agent should obscure the value so that people other than the user cannot see it.

If the element is mutable, its 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 value.

The value attribute, if specified, must have a value that contains no U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters.

The following common input element content attributes, IDL attributes, and methods apply to the element: autocomplete, inputmode, maxlength, minlength, pattern, placeholder, readonly, required, and size content attributes; selectionStart, selectionEnd, selectionDirection, and value IDL attributes; select(), setRangeText(), and setSelectionRange() methods.

The value IDL attribute is in mode value.

The input and change events apply.

The following content attributes must not be specified and do not apply to the element: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, list, max, min, multiple, src, step, and width.

The following IDL attributes and methods do not apply to the element: checked, files, list, valueAsDate, and valueAsNumber IDL attributes; stepDown() and stepUp() methods.

4.10.5.1.7. Date state (type=date)

When an input element’s type attribute is in the Date state, the rules in this section apply.

The input element represents a control for setting the element’s value to a string representing a specific date.

date values represent a "floating" time and do not include time zone information. Care is needed when converting values of this type to or from date data types in JavaScript and other programming languages. In many cases, an implicit time-of-day and time zone are used to create a global ("incremental") time (an integer value that represents the offset from some arbitrary epoch time). Processing or conversion of these values, particularly across time zones, can change the value of the date itself. [TIMEZONE]

If the element is mutable, the user agent should allow the user to change the date represented by its value, as obtained by parsing a date from it. User agents must not allow the user to set the value to a non-empty string that is not a valid date string. If the user agent provides a user interface for selecting a date, then the value must be set to a valid date string representing the user’s selection. User agents should allow the user to set the value to the empty string.

Constraint validation: While the user interface describes input that the user agent cannot convert to a valid date string, the control is suffering from bad input.

See §4.10.1.8 Date, time, and number formats for a discussion of the difference between the input format and submission format for date, time, and number form controls, and the implementation notes regarding localization of form controls.

The value attribute, if specified and not empty, must have a value that is a valid date string.

The value sanitization algorithm is as follows: If the value of the element is not a valid date string, then set it to the empty string instead.

The min attribute, if specified, must have a value that is a valid date string. The max attribute, if specified, must have a value that is a valid date string.

The step attribute is expressed in days. The step scale factor is 86,400,000 (which converts the days to milliseconds, which is the base unit of comparison for the conversion algorithms below). The default step is 1 day.

When the element is suffering from a step mismatch, the user agent may round the element’s value to the nearest date for which the element would not suffer from a step mismatch.

The algorithm to convert a string to a number, given a string input, is as follows: If 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 date, ignoring leap seconds.

The algorithm to convert a number to a string, given a number input, is as follows: Return a valid date string that represents the 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 algorithm to convert a string to a Date object, given a string input, is as follows: If parsing a date from input results in an error, then return an error; otherwise, return a new Date object representing midnight UTC on the morning of the parsed date.

The algorithm to convert a Date object to a string, given a Date object input, is as follows: Return a valid date string that represents the date current at the time represented by input in the UTC time zone.

The following common input element content attributes, IDL attributes, and methods apply to the element: autocomplete, list, max, min, readonly, required, and step content attributes; list, value, valueAsDate, and valueAsNumber IDL attributes; select(), stepDown(), and stepUp() methods.

The value IDL attribute is in mode value.

The input and change events apply.

The following content attributes must not be specified and do not apply to the element: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, inputmode, maxlength, minlength, multiple, pattern, placeholder, size, src, and width.

The following IDL attributes and methods do not apply to the element: checked, selectionStart, selectionEnd, and selectionDirection IDL attributes; setRangeText(), and setSelectionRange() methods.

4.10.5.1.8. Month state (type=month)

When an input element’s type attribute is in the Month state, the rules in this section apply.

The input element represents a control for setting the element’s value to a string representing a specific month.

If the element is mutable, the user agent should allow the user to change the month represented by its value, as obtained by parsing a month from it. User agents must not allow the user to set the value to a non-empty string that is not a valid month string. If the user agent provides a user interface for selecting a month, then the value must be set to a valid month string representing the user’s selection. User agents should allow the user to set the value to the empty string.

Constraint validation: While the user interface describes input that the user agent cannot convert to a valid month string, the control is suffering from bad input.

See §4.10.1.8 Date, time, and number formats for a discussion of the difference between the input format and submission format for date, time, and number form controls, and the implementation notes regarding localization of form controls.

The value attribute, if specified and not empty, must have a value that is a valid month string.

The value sanitization algorithm is as follows: If the value of the element is not a valid month string, then set it to the empty string instead.

The min attribute, if specified, must have a value that is a valid month string. The max attribute, if specified, must have a value that is a valid month string.

The step attribute is expressed in months. The step scale factor is 1 (units of whole months are the base unit of comparison for the conversion algorithms below). The default step is 1 month.

When the element is suffering from a step mismatch, the user agent may round the element’s value to the nearest month for which the element would not suffer from a step mismatch.

The algorithm to convert a string to a number, given a string input, is as follows: If 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 month.

The algorithm to convert a number to a string, given a number input, is as follows: Return a valid month string that represents the month that has input months between it and January 1970.

The algorithm to convert a string to a Date object, given a string input, is as follows: If parsing a month from input results in an error, then return an error; otherwise, return a new Date object representing midnight UTC on the morning of the first day of the parsed month.

The algorithm to convert a Date object to a string, given a Date object input, is as follows: Return a valid month string that represents the month current at the time represented by input in the UTC time zone.

The following common input element content attributes, IDL attributes, and methods apply to the element: autocomplete, list, max, min, readonly, required, and step content attributes; list, value, valueAsDate, and valueAsNumber IDL attributes; select(), stepDown(), and stepUp() methods.

The value IDL attribute is in mode value.

The input and change events apply.

The following content attributes must not be specified and do not apply to the element: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, inputmode, maxlength, minlength, multiple, pattern, placeholder, size, src, and width.

The following IDL attributes and methods do not apply to the element: checked, files, selectionStart, selectionEnd, and selectionDirection IDL attributes; setRangeText(), and setSelectionRange() methods.

4.10.5.1.9. Week state (type=week)

When an input element’s type attribute is in the Week state, the rules in this section apply.

The input element represents a control for setting the element’s value to a string representing a specific week beginning on a Monday, at midnight UTC.

If the element is mutable, the user agent should allow the user to change the week represented by its value, as obtained by parsing a week from it. User agents must not allow the user to set the value to a non-empty string that is not a valid week string. If the user agent provides a user interface for selecting a week, then the value must be set to a valid week string representing the user’s selection. User agents should allow the user to set the value to the empty string.

Constraint validation: While the user interface describes input that the user agent cannot convert to a valid week string, the control is suffering from bad input.

See §4.10.1.8 Date, time, and number formats for a discussion of the difference between the input format and submission format for date, time, and number form controls, and the implementation notes regarding localization of form controls.

The value attribute, if specified and not empty, must have a value that is a valid week string.

The value sanitization algorithm is as follows: If the value of the element is not a valid week string, then set it to the empty string instead.

The min attribute, if specified, must have a value that is a valid week string. The max attribute, if specified, must have a value that is a valid week string.

The step attribute is expressed in weeks. The step scale factor is 604,800,000 (which converts the weeks to milliseconds, which is the base unit of comparison for the conversion algorithms below). The default step is 1 week. The default step base is -259,200,000 (the start of week 1970-W01 which is the Monday 3 days before 1970-01-01).

When the element is suffering from a step mismatch, the user agent may round the element’s value to the nearest week for which the element would not suffer from a step mismatch.

The algorithm to convert a string to a number, given a string input, is as follows: If 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 week, ignoring leap seconds.

The algorithm to convert a number to a string, given a number input, is as follows: Return a valid week string that represents the 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 algorithm to convert a string to a Date object, given a string input, is as follows: If parsing a week from input results in an error, then return an error; otherwise, return a new Date object representing midnight UTC on the morning of the Monday of the parsed week.

The algorithm to convert a Date object to a string, given a Date object input, is as follows: Return a valid week string that represents the week current at the time represented by input in the UTC time zone.

The following common input element content attributes, IDL attributes, and methods apply to the element: autocomplete, list, max, min, readonly, required, and step content attributes; list, value, valueAsDate, and valueAsNumber IDL attributes; select(), stepDown(), and stepUp() methods.

The value IDL attribute is in mode value.

The input and change events apply.

The following content attributes must not be specified and do not apply to the element: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, inputmode, maxlength, minlength, multiple, pattern, placeholder, size, src, and width.

The following IDL attributes and methods do not apply to the element: checked, files, selectionStart, selectionEnd, and selectionDirection IDL attributes; setRangeText(), and setSelectionRange() methods.

4.10.5.1.10. Time state (type=time)

When an input element’s type attribute is in the Time state, the rules in this section apply.

The input element represents a control for setting the element’s value to a string representing a specific time.

If the element is mutable, the user agent should allow the user to change the time represented by its value, as obtained by parsing a time from it. User agents must not allow the user to set the value to a non-empty string that is not a valid time string. If the user agent provides a user interface for selecting a time, then the value must be set to a valid time string representing the user’s selection. User agents should allow the user to set the value to the empty string.

Constraint validation: While the user interface describes input that the user agent cannot convert to a valid time string, the control is suffering from bad input.

See §4.10.1.8 Date, time, and number formats for a discussion of the difference between the input format and submission format for date, time, and number form controls, and the implementation notes regarding localization of form controls.

The value attribute, if specified and not empty, must have a value that is a valid time string.

The value sanitization algorithm is as follows: If the value of the element is not a valid time string, then set it to the empty string instead.

The form control has a periodic domain.

The min attribute, if specified, must have a value that is a valid time string. The max attribute, if specified, must have a value that is a valid time string.

The step attribute is expressed in seconds. The step scale factor is 1000 (which converts the seconds to milliseconds, which is the base unit of comparison for the conversion algorithms below). The default step is 60 seconds.

When the element is suffering from a step mismatch, the user agent may round the element’s value to the nearest time for which the element would not suffer from a step mismatch.

The algorithm to convert a string to a number, given a string input, is as follows: If 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 time on a day with no time changes.

The algorithm to convert a number to a string, given a number input, is as follows: Return a valid time string that represents the time that is input milliseconds after midnight on a day with no time changes.

The algorithm to convert a string to a Date object, given a string input, is as follows: If parsing a time from input results in an error, then return an error; otherwise, return a new Date object representing the parsed time in UTC on 1970-01-01.

The algorithm to convert a Date object to a string, given a Date object input, is as follows: Return a valid time string that represents the UTC time component that is represented by input.

The following common input element content attributes, IDL attributes, and methods apply to the element: autocomplete, list, max, min, readonly, required, and step content attributes; list, value, valueAsDate, and valueAsNumber IDL attributes; select(), stepDown(), and stepUp() methods.

The value IDL attribute is in mode value.

The input and change events apply.

The following content attributes must not be specified and do not apply to the element: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, inputmode, maxlength, minlength, multiple, pattern, placeholder, size, src, and width.

The following IDL attributes and methods do not apply to the element: checked, files, selectionStart, selectionEnd, and selectionDirection IDL attributes; setRangeText(), and setSelectionRange() methods.

4.10.5.1.11. Local Date and Time state (type=datetime-local)

When an input element’s type attribute is in the Local Date and Time state, the rules in this section apply.

The input element represents a control for setting the element’s value to a string representing a local date and time, with no time-zone offset information.

If the element is mutable and the user agent provides a user interface for selecting a local date and time, then the value must be set to a valid normalized global date and time string representing the user’s selection. User agents should allow the user to set the value to the empty string.

Constraint validation: While the user interface describes input that the user agent cannot convert to a valid normalized global date and time string, the control is suffering from bad input.

See §4.10.1.8 Date, time, and number formats for a discussion of the difference between the input format and submission format for date, time, and number form controls, and the implementation notes regarding localization of form controls.

The value attribute, if specified and not empty, must have a value that is a valid floating date and time string.

The value sanitization algorithm is as follows: If the value of the element is a valid floating date and time string, then set it to a valid normalized floating date and time string representing the same date and time; otherwise, set it to the empty string instead.

The min attribute, if specified, must have a value that is a valid floating date and time string. The max attribute, if specified, must have a value that is a valid floating date and time string.

The step attribute is expressed in seconds. The step scale factor is 1000 (which converts the seconds to milliseconds, which is the base unit of comparison for the conversion algorithms below). The default step is 60 seconds.

When the element is suffering from a step mismatch, the user agent may round the element’s value to the nearest floating date and time for which the element would not suffer from a step mismatch.

The algorithm to convert a string to a number, given a string input, is as follows: If 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 floating date and time, ignoring leap seconds.

The algorithm to convert a number to a string, given a number input, is as follows: Return a valid normalized floating 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").

The following common input element content attributes, IDL attributes, and methods apply to the element: autocomplete, list, max, min, readonly, required, and step content attributes; list, value, and valueAsNumber IDL attributes; select(), stepDown(), and stepUp() methods.

The value IDL attribute is in mode value.

The input and change events apply.

The following content attributes must not be specified and do not apply to the element: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, inputmode, maxlength, minlength, multiple, pattern, placeholder, size, src, and width.

The following IDL attributes and methods do not apply to the element: checked, files, selectionStart, selectionEnd, selectionDirection, and valueAsDate IDL attributes; setRangeText(), and setSelectionRange() methods.

The following example shows part of a flight booking application. The application uses an input element with its type attribute set to datetime-local, and it then interprets the given date and time in the time zone of the selected airport.
<fieldset>
  <legend>Destination</legend>
  <p><label>Airport: <input type=text name=to list=airports></label></p>
  <p><label>Departure time: <input type=datetime-local name=totime step=3600></label></p>
</fieldset>
<datalist id=airports>
  <option value=ATL label="Atlanta">
  <option value=MEM label="Memphis">
  <option value=LHR label="London Heathrow">
  <option value=LAX label="Los Angeles">
  <option value=FRA label="Frankfurt">
</datalist>
4.10.5.1.12. Number state (type=number)

When an input element’s type attribute is in the Number state, the rules in this section apply.

The input element represents a control for setting the element’s value to a string representing a number.

If the element is mutable, the user agent should allow the user to change the number represented by its value, as obtained from applying the rules for parsing floating-point number values to it. User agents must not allow the user to set the value to a non-empty string that is not a valid floating-point number. If the user agent provides a user interface for selecting a number, then the value must be set to the best representation of the number representing the user’s selection as a floating-point number. User agents should allow the user to set the value to the empty string.

Constraint validation: While the user interface describes input that the user agent cannot convert to a valid floating-point number, the control is 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 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.

See §4.10.1.8 Date, time, and number formats for a discussion of the difference between the input format and submission format for date, time, and number form controls, and the implementation notes regarding localization of form controls.

The value attribute, if specified and not empty, must have a value that is a valid floating-point number.

The value sanitization algorithm is as follows: If the value of the element is not a valid floating-point number, then set it to the empty string instead.

The min attribute, if specified, must have a value that is a valid floating-point number. The max attribute, if specified, must have a value that is a valid floating-point number.

The step scale factor is 1. The default step is 1 (allowing only integers to be selected by the user, unless the step base has a non-integer value).

When the element is suffering from a step mismatch, the user agent may round the element’s value to the nearest number for which the element would not suffer from a step mismatch. If there are two such numbers, user agents are encouraged to pick the one nearest positive infinity.

The algorithm to convert a string to a number, given a string input, is as follows: If applying the rules for parsing floating-point number values to input results in an error, then return an error; otherwise, return the resulting number.

The algorithm to convert a number to a string, given a number input, is as follows: Return a valid floating-point number that represents input.

The following common input element content attributes, IDL attributes, and methods apply to the element: autocomplete, list, max, min, placeholder, readonly, required, and step content attributes; list, value, and valueAsNumber IDL attributes; select(), stepDown(), and stepUp() methods.

The value IDL attribute is in mode value.

The input and change events apply.

The following content attributes must not be specified and do not apply to the element: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, inputmode, maxlength, minlength, multiple, pattern, size, src, and width.

The following IDL attributes and methods do not apply to the element: checked, files, selectionStart, selectionEnd, selectionDirection, and valueAsDate IDL attributes; setRangeText(), and setSelectionRange() methods.

Here is an example of using a numeric input control:
<label>How much do you want to charge? $<input type=number min=0 step=0.01 name=price></label>

As described above, a user agent might support numeric input in the user’s local format, converting it to the format required for submission as described above. This might include handling grouping separators (as in "872,000,000,000") and various decimal separators (such as "3,99" vs "3.99") or using local digits (such as those in Arabic, Devanagari, Persian, and Thai).

The type=number state is not appropriate for input that happens to only consist of numbers but isn’t strictly speaking a number. For example, it would be inappropriate for credit card numbers or US postal codes. A simple way of determining whether to use type=number is to consider whether it would make sense for the input control to have a spinbox interface (e.g., with "up" and "down" arrows). Getting a credit card number wrong by 1 in the last digit isn’t a minor mistake, it’s as wrong as getting every digit incorrect. So it would not make sense for the user to select a credit card number using "up" and "down" buttons. When a spinbox interface is not appropriate, type=text is probably the right choice (possibly with a pattern attribute).

4.10.5.1.13. Range state (type=range)

When an input element’s type attribute is in the Range state, the rules in this section apply.

The input element represents a control for setting the element’s value to a string representing a number, but with the caveat that the exact value is not important, letting user agents provide a simpler interface than they do for the Number state.

If the element is mutable, the user agent should allow the user to change the number represented by its value, as obtained from applying the rules for parsing floating-point number values to it. User agents must not allow the user to set the value to a string that is not a valid floating-point number. If the user agent provides a user interface for selecting a number, then the value must be set to a 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 value to the empty string.

Constraint validation: While the user interface describes input that the user agent cannot convert to a valid floating-point number, the control is suffering from bad input.

The value attribute, if specified, must have a value that is a valid floating-point number.

The value sanitization algorithm is as follows: If the value of the element is not a valid floating-point number, then set it to the best representation, as a floating-point number, of the default value.

The default value is the minimum plus half the difference between the minimum and the maximum, unless the maximum is less than the minimum, in which case the default value is the minimum.

When the element is suffering from an underflow, the user agent must set the element’s value to the best representation, as a floating-point number, of the minimum.

When the element is suffering from an overflow, if the maximum is not less than the minimum, the user agent must set the element’s value to a valid floating-point number that represents the maximum.

When the element is suffering from a step mismatch, the user agent must round the element’s value to the nearest number for which the element would not suffer from a step mismatch, and which is greater than or equal to the minimum, and, if the maximum is not less than the minimum, which is less than or equal to the 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 <input type="range" min=0 max=100 step=20 value=50> results in a range control whose initial value is 60.

Here is an example of a range control using an autocomplete list with the list attribute. This could be useful if there are values along the full range of the control that are especially important, such as preconfigured light levels or typical speed limits in a range control used as a speed control. The following markup fragment:
<input type="range" min="-100" max="100" value="0" step="10" name="power" list="powers">
<datalist id="powers">
  <option value="0">
  <option value="-30">
  <option value="30">
 <option value="++50">
</datalist>

...with the following style sheet applied:

input { height: 75px; width: 49px; background: #D5CCBB; color: black; }

...might render as:

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 user agent determined the orientation of the control from the ratio of the style-sheet-specified height and width properties. The colors were similarly derived from the style sheet. The tick marks, however, were derived from the markup. In particular, the step attribute has not affected the placement of tick marks, the user agent deciding to only use the author-specified completion values and then adding longer tick marks at the extremes.

Note also how the invalid value ++50 was completely ignored.

For another example, consider the following markup fragment:
<input name=x type=range min=100 max=700 step=9.09090909 value=509.090909>

A user agent could display in a variety of ways, for instance:

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:
<input type="range" name="a" list="a-values">
<datalist id="a-values">
<option value="10" label="Low">
<option value="90" label="High">
</datalist>

With styles that make the control draw vertically, it might look as follows:

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 min attribute, if specified, must have a value that is a valid floating-point number. The default minimum is 0. The max attribute, if specified, must have a value that is a valid floating-point number. The default maximum is 100.

The step scale factor is 1. The default step is 1 (allowing only integers, unless the min attribute has a non-integer value).

The algorithm to convert a string to a number, given a string input, is as follows: If applying the rules for parsing floating-point number values to input results in an error, then return an error; otherwise, return the resulting number.

The algorithm to convert a number to a string, given a number input, is as follows: Return the best representation, as a floating-point number, of input.

The following common input element content attributes, IDL attributes, and methods apply to the element: autocomplete, list, max, min, and step content attributes; list, value, and valueAsNumber IDL attributes; stepDown() and stepUp() methods.

The value IDL attribute is in mode value.

The input and change events apply.

The following content attributes must not be specified and do not apply to the element: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, inputmode, maxlength, minlength, multiple, pattern, placeholder, readonly, required, size, src, and width.

The following IDL attributes and methods do not apply to the element: checked, files, selectionStart, selectionEnd, selectionDirection, and valueAsDate IDL attributes; select(), setRangeText(), and setSelectionRange() methods.

4.10.5.1.14. Color state (type=color)

When an input element’s type attribute is in the Color state, the rules in this section apply.

The input element represents a color well control, for setting the element’s value to a string representing a simple color.

In this state, there is always a color picked, and there is no way to set the value to the empty string.

If the element is mutable, the user agent should allow the user to change the color represented by its value, as obtained from applying the rules for parsing simple color values to it. User agents must not allow the user to set the value to a string that is not a valid lowercase simple color. If the user agent provides a user interface for selecting a color, then the value must be set to the result of using the rules for serializing simple color values to the user’s selection. User agents must not allow the user to set the value to the empty string.

Constraint validation: While the user interface describes input that the user agent cannot convert to a valid lowercase simple color, the control is suffering from bad input.

The value attribute, if specified and not empty, must have a value that is a valid simple color.

The value sanitization algorithm is as follows: If the value of the element is a valid simple color, then set it to the value of the element converted to ASCII lowercase; otherwise, set it to the string "#000000".

The following common input element content attributes and IDL attributes apply to the element: autocomplete and list content attributes; list and value IDL attributes; select() method.

The value IDL attribute is in mode value.

The input and change events apply.

The following content attributes must not be specified and do not apply to the element: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, inputmode, max, maxlength, min, minlength, multiple, pattern, placeholder, readonly, required, size, src, step, and width.

The following IDL attributes and methods do not apply to the element: checked, files, selectionStart, selectionEnd, selectionDirection, valueAsDate, and valueAsNumber IDL attributes; setRangeText(), setSelectionRange(), stepDown(), and stepUp() methods.

4.10.5.1.15. Checkbox state (type=checkbox)

When an input element’s type attribute is in the Checkbox state, the rules in this section apply.

The input element represents a two-state control that represents the element’s checkedness state. If the element’s checkedness state is true, the control represents a positive selection, and if it is false, a negative selection. If the element’s indeterminate IDL attribute is set to true, then the control’s selection should be obscured as if the control was in a third, indeterminate, state.

The control is never a true tri-state control, even if the element’s indeterminate IDL attribute is set to true. The indeterminate IDL attribute only gives the appearance of a third state.

If the element is mutable, then: The pre-click activation steps consist of setting the element’s checkedness to its opposite value (i.e., true if it is false, false if it is true), and of setting the element’s indeterminate IDL attribute to false. The canceled activation steps consist of setting the checkedness and the element’s indeterminate IDL attribute back to the values they had before the pre-click activation steps were run. The activation behavior is to fire a simple event that bubbles named input at the element and then fire a simple event that bubbles named change at the element.

If the element is not mutable, it has no activation behavior.

Constraint validation: If the element is required and its checkedness is false, then the element is suffering from being missing.

input . indeterminate [ = value ]

When set, overrides the rendering of checkbox controls so that the current value is not visible.

The following common input element content attributes and IDL attributes apply to the element: checked, and required content attributes; checked and value IDL attributes.

The value IDL attribute is in mode default/on.

The input and change events apply.

The following content attributes must not be specified and do not apply to the element: accept, alt, autocomplete, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, inputmode, list, max, maxlength, min, minlength, multiple, pattern, placeholder, readonly, size, src, step, and width.

The following IDL attributes and methods do not apply to the element: files, list, selectionStart, selectionEnd, selectionDirection, valueAsDate, and valueAsNumber IDL attributes; select(), setRangeText(), setSelectionRange(), stepDown(), and stepUp() methods.

4.10.5.1.16. Radio Button state (type=radio)

When an input element’s type attribute is in the Radio Button state, the rules in this section apply.

The input element represents a control that, when used in conjunction with other input elements, forms a radio button group in which only one control can have its checkedness state set to true. If the element’s checkedness state is true, the control represents the selected control in the group, and if it is false, it indicates a control in the group that is not selected.

The radio button group that contains an input element a also contains all the other input elements b that fulfill all of the following conditions:

A document must not contain an input element whose radio button group contains only that element.

When any of the following phenomena occur, if the element’s checkedness state is true after the occurrence, the checkedness state of all the other elements in the same radio button group must be set to false:

If the element R is mutable, then: The pre-click activation steps for R consist of getting a reference to the element in R’s radio button group that has its checkedness set to true, if any, and then setting R’s checkedness to true. The canceled activation steps for R consist of checking if the element to which a reference was obtained in the pre-click activation steps, if any, is still in what is now R’s radio button group, if it still has one, and if so, setting that element’s checkedness to true; or else, if there was no such element, or that element is no longer in R’s radio button group, or if R no longer has a radio button group, setting R’s checkedness to false. The activation behavior for R is to fire a simple event that bubbles named input at R and then fire a simple event that bubbles named change at R.

If the element is not mutable, it has no activation behavior.

Constraint validation: If an element in the radio button group is required, and all of the input elements in the radio button group have a checkedness that is false, then the element is suffering from being missing.

If none of the radio buttons in a radio button group are checked when they are inserted into the document, then they will all be initially unchecked in the interface, until such time as one of them is checked (either by the user or by script).

The following common input element content attributes and IDL attributes apply to the element: checked and required content attributes; checked and value IDL attributes.

The value IDL attribute is in mode default/on.

The input and change events apply.

The following content attributes must not be specified and do not apply to the element: accept, alt, autocomplete, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, inputmode, list, max, maxlength, min, minlength, multiple, pattern, placeholder, readonly, size, src, step, and width.

The following IDL attributes and methods do not apply to the element: files, list, selectionStart, selectionEnd, selectionDirection, valueAsDate, and valueAsNumber IDL attributes; select(), setRangeText(), setSelectionRange(), stepDown(), and stepUp() methods.

4.10.5.1.17. File Upload state (type=file)

When an input element’s type attribute is in the File Upload state, the rules in this section apply.

The input element represents a list of selected files, each file consisting of a file name, a file type, and a file body (the contents of the file).

File names must not contain 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 File Upload state, are those parts of file names that are separated by U+005C REVERSE SOLIDUS character (\) characters.

Unless the multiple attribute is set, there must be no more than one file in the list of selected files.

If the element is mutable, then the element’s activation behavior is to run the following steps:

  1. If the algorithm is not allowed to show a popup, then abort these steps without doing anything else.
  2. Return, but continue running these steps in parallel.
  3. Optionally, wait until any prior execution of this algorithm has terminated.
  4. Display a prompt to the user requesting that the user specify some files. If the multiple attribute is not set, 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.
  5. Wait for the user to have made their selection.
  6. Queue a task to first update the element’s selected files so that it represents the user’s selection, then fire a simple event that bubbles named input at the input element, and finally fire a simple event that bubbles named change at the input element.

If the element is 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 queue a task to first update the element’s selected files so that it represents the user’s new selection, then fire a simple event that bubbles named input at the input element, and finally fire a simple event that bubbles named change at the input element.

If the element is not mutable, it has no activation behavior and the user agent must not allow the user to change the element’s selection.

Constraint validation: If the element is required and the list of selected files is empty, then the element is suffering from being missing.


The accept attribute may be specified to provide user agents with a hint of what file types will be accepted.

If specified, the attribute must consist of a set of comma-separated tokens, each of which must be an ASCII case-insensitive match for one of the following:

The string "audio/*"
Indicates that sound files are accepted.
The string "video/*"
Indicates that video files are accepted.
The string "image/*"
Indicates that image files are accepted.
A valid MIME type with no parameters
Indicates that files of the specified type are accepted.
A string whose first character is a U+002E FULL STOP character (.)
Indicates that files with the specified file extension are accepted.

The tokens must not be ASCII case-insensitive matches for any of the other tokens (i.e., duplicates are not allowed). To obtain the list of tokens from the attribute, the user agent must 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:
<input type="file" accept=".doc,.docx,.xml,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document">

On platforms that only use file extensions to describe file types, the extensions listed here can be used to filter the allowed documents, while the MIME types can be used with the system’s type registration table (mapping MIME types to extensions used by the system), if any, to determine any other extensions to allow. Similarly, on a system that does not have file names or extensions but labels documents with MIME types internally, the MIME types can be used to pick the allowed files, while the extensions can be used if the system has an extension registration table that maps known extensions to MIME types used by the system.

Extensions tend to be ambiguous (e.g., there are an untold number of formats that use the ".dat" extension, and users can typically quite easily rename their files to have a ".doc" extension even if they are not Microsoft Word documents), and MIME types tend to be unreliable (e.g., many formats have no formally registered types, and many formats are in practice labeled using a number of different MIME types). Authors are reminded that, as usual, data received from a client should be treated with caution, as it may not be in an expected format even if the user is not hostile and the user agent fully obeyed the accept attribute’s requirements.

For historical reasons, the value IDL attribute prefixes the file name with the string "C:\fakepath\". Some legacy user agents actually included the full path (which was a security vulnerability). As a result of this, obtaining the file name from the value IDL attribute in a backwards-compatible way is non-trivial. The following function extracts the file name in a suitably compatible manner:
function extractFilename(path) {
  if (path.substr(0, 12) == "C:\\fakepath\\")
    return path.substr(12); // modern browser
  var x;
  x = path.lastIndexOf('/');
  if (x >= 0) // Unix-based path
    return path.substr(x+1);
  x = path.lastIndexOf('\\');
  if (x >= 0) // Windows-based path
    return path.substr(x+1);
  return path; // just the file name
}

This can be used as follows:

<p><input type=file name=image onchange="updateFilename(this.value)"></p>
<p>The name of the file you picked is: <span id="filename">(none)</span></p>
<script>
  function updateFilename(path) {
    var name = extractFilename(path);
    document.getElementById('filename').textContent = name;
  }
</script>

The following common input element content attributes and IDL attributes apply to the element: accept, multiple, and required content attributes; files and value IDL attributes; select() method.

The value IDL attribute is in mode filename.

The input and change events apply.

The following content attributes must not be specified and do not apply to the element: alt, autocomplete, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, inputmode, list, max, maxlength, min, minlength, pattern, placeholder, readonly, size, src, step, and width.

The element’s value attribute must be omitted.

The following IDL attributes and methods do not apply to the element: checked, list, selectionStart, selectionEnd, selectionDirection, valueAsDate, and valueAsNumber IDL attributes; setRangeText(), setSelectionRange(), stepDown(), and stepUp() methods.

4.10.5.1.18. Submit Button state (type=submit)

When an input element’s type attribute is in the submit button state, the rules in this section apply.

The input element represents a button that, when activated, submits the form. If the element has a value attribute, the button’s label must be the value of that attribute; otherwise, it must be an implementation-defined string that means "Submit" or some such. The element is a button, specifically a submit button. (This is a fingerprinting vector.)

Since the default label is 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.

If the element is mutable, then the element’s activation behavior is as follows: if the element has a form owner, and the element’s node document is fully active, submit the form owner from the input element; otherwise, do nothing.

If the element is not mutable, it has no activation behavior.

The formaction, formenctype, formmethod, formnovalidate, and formtarget attributes are attributes for form submission.

The formnovalidate attribute can be used to make submit buttons that do not trigger the constraint validation.

The following common input element content attributes and IDL attributes apply to the element: formaction, formenctype, formmethod, formnovalidate, and formtarget content attributes; value IDL attribute.

The value IDL attribute is in mode default.

The following content attributes must not be specified and do not apply to the element: accept, alt, autocomplete, checked, dirname, height, inputmode, list, max, maxlength, min, minlength, multiple, pattern, placeholder, readonly, required, size, src, step, and width.

The following IDL attributes and methods do not apply to the element: checked, files, list, selectionStart, selectionEnd, selectionDirection, valueAsDate, and valueAsNumber IDL attributes; select(), setRangeText(), setSelectionRange(), stepDown(), and stepUp() methods.

The input and change events do not apply.

4.10.5.1.19. Image Button state (type=image)

When an input element’s type attribute is in the image button state, the rules in this section apply.

The input element represents either an image from which a user can select a coordinate and submit the form, or alternatively a button from which the user can submit the form. The element is a button, specifically a submit button.

The coordinate is sent to the server during form submission by sending two entries for the element, derived from the name of the control but with ".x" and ".y" appended to the name with the x and y components of the coordinate respectively.


The image is given by the src attribute. The src attribute must be present, and must contain a valid non-empty URL potentially surrounded by spaces referencing a non-interactive, optionally animated, image resource that is neither paged nor scripted.

When any of the these events occur

  • the input element’s type attribute is first set to the Image Button state (possibly when the element is first created), and the src attribute is present
  • the input element’s type attribute is changed back to the Image Button state, and the src attribute is present, and its value has changed since the last time the type attribute was in the Image Button state
  • the input element’s type attribute is in the Image Button state, and the 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 src attribute’s value is the empty string, the user agent must parse the value of the src attribute value, relative to the element’s node document, and if that is successful, run these substeps:

  1. Let request be a new request whose URL is the resulting URL string, client is the element’s node document’s Window object’s environment settings object, type is "image", destination is "subresource", omit-Origin-header flag is set, credentials mode is "include", and whose use-URL-credentials flag is set.
  2. Fetch request.

Fetching the image must delay the load event of the element’s node document until the task that is queued by the 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 task that is queued by the networking task source while the image is being fetched must update the presentation of the image appropriately.

The user agent should apply the image sniffing rules to determine the type of the image, with the image’s 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 associated Content-Type headers.

User agents must not support non-image resources with the 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.

The task that is queued by the networking task source once the resource has been fetched, must, if the download was successful and the image is available, queue a task to fire a simple event named load at the input element; and 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, queue a task to fire a simple event named error on the input element.


The alt attribute provides the textual label for the button for users and user agents who cannot use the image. The alt attribute must be present, and must contain a non-empty string giving the label that would be appropriate for an equivalent button if the image was unavailable.

The input element supports dimension attributes.


If the src attribute is set, and the image is available and the user agent is configured to display that image, then: The element represents a control for selecting a coordinate from the image specified by the src attribute; if the element is mutable, the user agent should allow the user to select this coordinate, and the element’s activation behavior is as follows: if the element has a form owner, and the element’s node document is fully active, take the user’s selected coordinate, and submit the input element’s form owner from the input element. If the user activates the control without explicitly selecting a coordinate, then the coordinate (0,0) must be assumed.

Otherwise, the element represents a submit button whose label is given by the value of the alt attribute; if the element is mutable, then the element’s activation behavior is as follows: if the element has a form owner, and the element’s node document is fully active, set the selected coordinate to (0,0), and submit the input element’s form owner from the input element.

In either case, if the element is mutable but has no form owner or the element’s node document is not fully active, then its activation behavior must be to do nothing. If the element is not mutable, it has no activation behavior.

The selected coordinate must consist of an x-component and a y-component. The coordinates represent the position relative to the edge of the 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 valid integer representing a number x in the range -(borderleft+paddingleft) ≤ xwidth+borderright+paddingright, where width is the rendered width of the image, borderleft is the width of the border on the left of the image, paddingleft is the width of the padding on the left of the image, borderright is the width of the border on the right of the image, and paddingright is the width of the padding on the right of the image, with all dimensions given in CSS pixels.

The y-component must be a valid integer representing a number y in the range -(bordertop+paddingtop) ≤ yheight+borderbottom+paddingbottom, where height is the rendered height of the image, bordertop is the width of the border above the image, paddingtop is the width of the padding above the image, borderbottom is the width of the border below the image, and paddingbottom is the width of the padding below the image, with all dimensions given in CSS pixels.

Where a border or padding is missing, its width is zero CSS pixels.


The formaction, formenctype, formmethod, formnovalidate, and formtarget attributes are attributes for form submission.

image . width [ = value ]
image . height [ = value ]

These attributes return the actual rendered dimensions of the image, or zero if the dimensions are not known.

They can be set, to change the corresponding content attributes.

The following common input element content attributes and IDL attributes apply to the element: alt, formaction, formenctype, formmethod, formnovalidate, formtarget, height, src, and width content attributes; value IDL attribute.

The value IDL attribute is in mode default.

The following content attributes must not be specified and do not apply to the element: accept, autocomplete, checked, dirname, inputmode, list, max, maxlength, min, minlength, multiple, pattern, placeholder, readonly, required, size, and step.

The element’s value attribute must be omitted.

The following IDL attributes and methods do not apply to the element: checked, files, list, selectionStart, selectionEnd, selectionDirection, valueAsDate, and valueAsNumber IDL attributes; select(), setRangeText(), setSelectionRange(), stepDown(), and stepUp() methods.

The input and change events do not apply.

Many aspects of this state’s behavior are similar to the behavior of the img element. Readers are encouraged to read that section, where many of the same requirements are described in more detail.

Take the following form:
<form action="process.cgi">
  <input type=image src=map.png name=where alt="Show location list">
</form>

If the user clicked on the image at coordinate (127,40) then the URL used to submit the form would be "process.cgi?where.x=127&where.y=40".

(In this example, it’s assumed that for users who don’t see the map, and who instead just see a button labeled "Show location list", clicking the button will cause the server to show a list of locations to pick from instead of the map.)

4.10.5.1.20. Reset Button state (type=reset)

When an input element’s type attribute is in the Reset Button state, the rules in this section apply.

The input element represents a button that, when activated, resets the form. If the element has a value attribute, the button’s label must be the value of that attribute; otherwise, it must be an implementation-defined string that means "Reset" or some such. The element is a button. (This is a fingerprinting vector.)

Since the default label is 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.

If the element is mutable, then the element’s activation behavior, if the element has a form owner and the element’s node document is fully active, is to reset the form owner; otherwise, it is to do nothing.

If the element is not mutable, it has no activation behavior.

Constraint validation: The element is barred from constraint validation.

The value IDL attribute applies to this element and is in mode default.

The following content attributes must not be specified and do not apply to the element: accept, alt, autocomplete, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, inputmode, list, max, maxlength, min, minlength, multiple, pattern, placeholder, readonly, required, size, src, step, and width.

The following IDL attributes and methods do not apply to the element: checked, files, list, selectionStart, selectionEnd, selectionDirection, valueAsDate, and valueAsNumber IDL attributes; select(), setRangeText(), setSelectionRange(), stepDown(), and stepUp() methods.

The input and change events do not apply.

4.10.5.1.21. Button state (type=button)

When an input element’s type attribute is in the Button state, the rules in this section apply.

The input element represents a button with no default behavior. A label for the button must be provided in the value attribute, though it may be the empty string. If the element has a value attribute, the button’s label must be the value of that attribute; otherwise, it must be the empty string. The element is a button.

If the element is mutable, the element’s activation behavior is to do nothing.

If the element is not mutable, it has no activation behavior.

Constraint validation: The element is barred from constraint validation.

The value IDL attribute applies to this element and is in mode default.

The following content attributes must not be specified and do not apply to the element: accept, alt, autocomplete, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, inputmode, list, max, maxlength, min, minlength, multiple, pattern, placeholder, readonly, required, size, src, step, and width.

The following IDL attributes and methods do not apply to the element: checked, files, list, selectionStart, selectionEnd, selectionDirection, valueAsDate, and valueAsNumber IDL attributes; select(), setRangeText(), setSelectionRange(), stepDown(), and stepUp() methods.

The input and change events do not apply.

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 input element’s 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 input element attributes

These attributes only apply to an input element if its type attribute is in a state whose definition declares that the attribute applies. When an attribute doesn’t apply to an input element, user agents must ignore the attribute, regardless of the requirements and definitions below.

4.10.5.3.1. The maxlength and minlength attributes

The maxlength attribute, when it applies, is a form control maxlength attribute controlled by the input element’s dirty value flag.

The minlength attribute, when it applies, is a form control minlength attribute controlled by the input element’s dirty value flag.

If the input element has a maximum allowed value length, then the code-unit length of the value of the element’s value attribute must be equal to or less than the element’s maximum allowed value length.

The following extract shows how a messaging client’s text entry could be arbitrarily restricted to a fixed number of characters, thus forcing any conversation through this medium to be terse and discouraging intelligent discourse.
<label>What are you doing? <input name=status maxlength=140></label>
Here, a password is given a minimum length:
<p><label>Username: <input name=u required></label>
<p><label>Password: <input name=p required minlength=12></label>
4.10.5.3.2. The size attribute

The size attribute gives the number of characters that, in a visual rendering, the user agent is to allow the user to see while editing the element’s value.

The size attribute, if specified, must have a value that is a valid non-negative integer greater than zero.

If the attribute is present, then its value must be parsed using the 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 size IDL attribute is limited to only non-negative numbers greater than zero and has a default value of 20.

4.10.5.3.3. The readonly attribute

The readonly attribute is a boolean attribute that controls whether or not the user can edit the form control. When specified, the element is not mutable.

Constraint validation: If the readonly attribute is specified on an input element, the element is barred from constraint validation.

The difference between disabled and readonly is that read-only controls are still focusable, so the user can still select the text and interact with it, whereas disabled controls are entirely non-interactive. (For this reason, only text controls can be made read-only: it wouldn’t make sense for checkboxes or buttons, for instances.)

In the following example, the existing product identifiers cannot be modified, but they are still displayed as part of the form, for consistency with the row representing a new product (where the identifier is not yet filled in).
<form action="products.cgi" method="post" enctype="multipart/form-data">
  <table>
  <tr> <th> Product ID <th> Product name <th> Price <th> Action
  <tr>
    <td> <input readonly="readonly" name="1.pid" value="H412">
    <td> <input required="required" name="1.pname" value="Floor lamp Ulke">
    <td> $<input required="required" type="number" min="0" step="0.01" name="1.pprice" value="49.99">
    <td> <button formnovalidate="formnovalidate" name="action" value="delete:1">Delete</button>
  <tr>
    <td> <input readonly="readonly" name="2.pid" value="FG28">
    <td> <input required="required" name="2.pname" value="Table lamp Ulke">
    <td> $<input required="required" type="number" min="0" step="0.01" name="2.pprice" value="24.99">
    <td> <button formnovalidate="formnovalidate" name="action" value="delete:2">Delete</button>
  <tr>
    <td> <input required="required" name="3.pid" value="" pattern="[A-Z0-9]+">
    <td> <input required="required" name="3.pname" value="">
    <td> $<input required="required" type="number" min="0" step="0.01" name="3.pprice" value="">
    <td> <button formnovalidate="formnovalidate" name="action" value="delete:3">Delete</button>
  </table>
  <p> <button formnovalidate="formnovalidate" name="action" value="add">Add</button> </p>
  <p> <button name="action" value="update">Save</button> </p>
</form>
4.10.5.3.4. The required attribute

The required attribute is a boolean attribute. When specified, the element is required.

Constraint validation: If the element is required, and its value IDL attribute applies and is in the mode value, and the element is mutable, and the element’s value is the empty string, then the element is suffering from being missing.

The following form has two required fields, one for an e-mail address and one for a password. It also has a third field that is only considered valid if the user types the same password in the password field and this third field.
<h1>Create new account</h1>
<form action="/newaccount" method=post
      oninput="up2.setCustomValidity(up2.value != up.value ? 'Passwords do not match.' : '')">
  <p>
  <label for="username">E-mail address:</label>
  <input id="username" type=email required name=un>
  <p>
  <label for="password1">Password:</label>
  <input id="password1" type=password required name=up>
  <p>
  <label for="password2">Confirm password:</label>
  <input id="password2" type=password name=up2>
  <p>
  <input type=submit value="Create account">
</form>
For radio buttons, the required attribute is satisfied if any of the radio buttons in the group is selected. Thus, in the following example, any of the radio buttons can be checked, not just the one marked as required:
<fieldset>
  <legend>Did the movie pass the Bechdel test?</legend>
  <p><label><input type="radio" name="bechdel" value="no-characters"> No, there are not even two female characters in the movie. </label>
  <p><label><input type="radio" name="bechdel" value="no-names"> No, the female characters never talk to each other. </label>
  <p><label><input type="radio" name="bechdel" value="no-topic"> No, when female characters talk to each other it’s always about a male character. </label>
  <p><label><input type="radio" name="bechdel" value="yes" required> Yes. </label>
  <p><label><input type="radio" name="bechdel" value="unknown"> I don’t know. </label>
</fieldset>

To avoid confusion as to whether a radio button group is required or not, authors are encouraged to specify the attribute on all the radio buttons in a group. Indeed, in general, authors are encouraged to avoid having radio button groups that do not have any initially checked controls in the first place, as this is a state that the user cannot return to, and is therefore generally considered a poor user interface.

4.10.5.3.5. The multiple attribute

The multiple attribute is a boolean attribute that indicates whether the user is to be allowed to specify more than one value.

The following extract shows how an e-mail client’s "Cc" field could accept multiple e-mail addresses.
<label>Cc: <input type=email multiple name=cc></label>

If the user had, amongst many friends in their user contacts database, two friends "Arthur Dent" (with address "art@example.net") and "Adam Josh" (with address "adamjosh@example.net"), then, after the user has typed "a", the user agent might suggest these two e-mail addresses to the user.

Form control group containing 'Send', 'Save now' and 'Discard' buttons, a 'To:' combo box with an 'a' displayed in the text box and 2 list items below.

The page could also link in the user’s contacts database from the site:

<label>Cc: <input type=email multiple name=cc list=contacts></label>
...
<datalist id="contacts">
  <option value="hedral@damowmow.com">
  <option value="pillar@example.com">
  <option value="astrophy@cute.example">
  <option value="astronomy@science.example.org">
</datalist>

Suppose the user had entered "bob@example.net" into this text field, and then started typing a second e-mail address starting with "a". The user agent might show both the two friends mentioned earlier, as well as the "astrophy" and "astronomy" values given in the datalist element.

Form control group containing 'send',
    'save now' and 'discard' buttons and a 'To:' combo box with 'bob@example.net,a' displayed in the text box and 4 list items below.

The following extract shows how an e-mail client’s "Attachments" field could accept multiple files for upload.
<label>Attachments: <input type=file multiple name=att></label>
4.10.5.3.6. The pattern attribute

The pattern attribute specifies a regular expression against which the control’s value, or, when the multiple attribute applies and is set, the control’s values, are to be checked.

If specified, the attribute’s value must match the JavaScript Pattern production. [ECMA-262]

If an input element has a pattern attribute specified, and the attribute’s value, when compiled as a JavaScript regular expression with only the "u" flag specified, compiles successfully, then the resulting regular expression is the element’s compiled pattern regular expression. If the element has no such attribute, or if the value doesn’t compile successfully, then the element has no compiled pattern regular expression. [ECMA-262]

If the value doesn’t compile successfully, user agents are encouraged to log this fact in a developer console, to aid debugging.

Constraint validation: If the element’s value is not the empty string, and either the element’s multiple attribute is not specified or it does not apply to the input element given its type attribute’s current state, and the element has a compiled pattern regular expression but that regular expression does not match the entirety of the element’s value, then the element is suffering from a pattern mismatch.

Constraint validation: If the element’s value is not the empty string, and the element’s multiple attribute is specified and applies to the input element, and the element has a compiled pattern regular expression but that regular expression does not match the entirety of each of the element’s values, then the element is suffering from a pattern mismatch.

The compiled pattern regular expression, when matched against a string, must have its start anchored to the start of the string and its end anchored to the end of the string.

This implies that the regular expression language used for this attribute is the same as that used in JavaScript, except that the pattern attribute is matched against the entire value, not just any subset (somewhat as if it implied a ^(?: at the start of the pattern and a )$ at the end).

When an input element has a pattern attribute specified, authors should provide a description of the pattern in text near the control. Authors may also include a title attribute to give a description of the pattern. User agents may use the contents of this attribute, if it is present, when informing the user that the pattern is not matched, or at any other suitable time, such as in a tooltip or read out by assistive technology when the control gains focus.

Relying on the title attribute for the visual display of text content 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).

For example, the following snippet:
<label> Part number:
  <input pattern="[0-9][A-Z]{3}" name="part"
        title="A part number is a digit followed by three uppercase letters."/>
</label>

...could cause the user agent 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 pattern attribute, the title attribute, if used, must describe the pattern. Additional information could also be included, so long as it assists the user in filling in the control. Otherwise, assistive technology would be impaired.

For instance, if the title attribute contained the caption of the control, assistive technology could end up saying something like The text you have entered does not match the required pattern. Birthday, which is not useful.

user agents may still show the title in non-error situations (for example, as a tooltip when hovering over the control), so authors should be careful not to word titles as if an error has necessarily occurred.

4.10.5.3.7. The min and max attributes

Some form controls can have explicit constraints applied limiting the allowed range of values that the user can provide. Normally, such a range would be linear and continuous. A form control can have a periodic domain, however, in which case the form control’s broadest possible range is finite, and authors can specify explicit ranges within it that span the boundaries.

Specifically, the broadest range of a type=time control is midnight to midnight (24 hours), and authors can set both continuous linear ranges (such as 9pm to 11pm) and discontinuous ranges spanning midnight (such as 11pm to 1am).

The min and max attributes indicate the allowed range of values for the element.

Their syntax is defined by the section that defines the type attribute’s current state.

If the element has a min attribute, and the result of applying the algorithm to convert a string to a number to the value of the min attribute is a number, then that number is the element’s minimum; otherwise, if the type attribute’s current state defines a default minimum, then that is the minimum; otherwise, the element has no minimum.

The min attribute also defines the step base.

If the element has a max attribute, and the result of applying the algorithm to convert a string to a number to the value of the max attribute is a number, then that number is the element’s maximum; otherwise, if the type attribute’s current state defines a default maximum, then that is the maximum; otherwise, the element has no maximum.

If the element does not have a periodic domain, the max attribute’s value (the maximum) must not be less than the min attribute’s value (its minimum).

If an element that does not have a periodic domain has a maximum that is less than its minimum, then so long as the element has a value, it will either be suffering from an underflow or suffering from an overflow.

An element has a reversed range if it has a periodic domain and its maximum is less than its minimum.

An element has range limitations if it has a defined minimum or a defined maximum.

How these range limitations apply depends on whether the element has a multiple attribute.

If the element does not have a multiple attribute specified or if the multiple attribute does not apply

Constraint validation: When the element has a minimum and does not have a reversed range, and the result of applying the algorithm to convert a string to a number to the string given by the element’s value is a number, and the number obtained from that algorithm is less than the minimum, the element is suffering from an underflow.

Constraint validation: When the element has a maximum and does not have a reversed range, and the result of applying the algorithm to convert a string to a number to the string given by the element’s value is a number, and the number obtained from that algorithm is more than the maximum, the element is suffering from an overflow.

Constraint validation: When an element has a reversed range, and the result of applying the algorithm to convert a string to a number to the string given by the element’s value is a number, and the number obtained from that algorithm is more than the maximum and less than the minimum, the element is simultaneously suffering from an underflow and suffering from an overflow.

If the element does have a multiple attribute specified and the multiple attribute does apply

Constraint validation: When the element has a minimum, and the result of applying the algorithm to convert a string to a number to any of the strings in the element’s values is a number that is less than the minimum, the element is suffering from an underflow.

Constraint validation: When the element has a maximum, and the result of applying the algorithm to convert a string to a number to any of the strings in the element’s values is a number that is more than the maximum, the element is suffering from an overflow.

The following date control limits input to dates that are before the 1980s:
<input name=bday type=date max="1979-12-31">
The following number control limits input to whole numbers greater than zero:
<input name=quantity required="" type="number" min="1" value="1">
The following time control limits input to those minutes that occur between 9pm and 6am, defaulting to midnight:
<input name="sleepStart" type=time min="21:00" max="06:00" step="60" value="00:00">
4.10.5.3.8. The step attribute

The step attribute indicates the granularity that is expected (and required) of the value or values, by limiting the allowed values. The section that defines the 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 step attribute, if specified, must either have a value that is a valid floating-point number that parses to a number that is greater than zero, or must have a value that is an ASCII case-insensitive match for the string "any".

The attribute provides the allowed value step for the element, as follows:

  1. If the step attribute is absent, then the allowed value step is the default step multiplied by the step scale factor.

  2. Otherwise, if the attribute’s value is an ASCII case-insensitive match for the string "any", then there is no allowed value step.

  3. Otherwise, let step value be the result of running the rules for parsing floating-point number values, when they are applied to the step attribute’s value.

  4. If the previous step returned an error, or step value is zero, or a number less than zero, then the allowed value step is the default step multiplied by the step scale factor.

  5. If the element’s type attribute is in the Date, Month, Week, or Time state, then round step value to the nearest whole number using the "round to nearest + round half up" technique, unless the value is less-than one, in which case let step value be 1.

  6. The allowed value step is step value multiplied by the step scale factor.

The step base is the value returned by the following algorithm:

  1. If the element has a min content attribute, and the result of applying the algorithm to convert a string to a number to the value of the min content attribute is not an error, then return that result and abort these steps.

  2. If the element has a value content attribute, and the result of applying the algorithm to convert a string to a number to the value of the value content attribute is not an error, then return that result and abort these steps.

  3. If a default step base is defined for this element given its type attribute’s state, then return it and abort these steps.

  4. Return zero.

How these range limitations apply depends on whether the element has a multiple attribute.

If the element does not have a multiple attribute specified or if the multiple attribute does not apply

Constraint validation: When the element has an allowed value step, and the result of applying the algorithm to convert a string to a number to the string given by the value is a number, and that number is not step aligned, the element is suffering from a step mismatch.

If the element does have a multiple attribute specified and the multiple attribute does apply

Constraint validation: When the element has an allowed value step, and the result of applying the algorithm to convert a string to a number to any of the strings in the values is a number that is not step aligned, the element is suffering from a step mismatch.

The following range control only accepts values in the range 0..1, and allows 256 steps in that range:
<input name=opacity type=range min=0 max=1 step=0.00392156863>
The following control allows any time in the day to be selected, with any accuracy (e.g., thousandth-of-a-second accuracy or more):
<input name=favtime type=time step=any>

Normally, time controls are limited to an accuracy of one minute.

4.10.5.3.9. The list attribute

The list attribute is used to identify an element that lists predefined options suggested to the user.

If present, its value must be the ID of a datalist element in the same document.

The suggestions source element is the first element in the document in tree order to have an ID equal to the value of the list attribute, if that element is a datalist element. If there is no list attribute, or if there is no element with that ID, or if the first element with that ID is not a datalist element, then there is no suggestions source element.

If there is a suggestions source element, then, when the user agent is allowing the user to edit the input element’s value, the user agent should offer the suggestions represented by the suggestions source element to the user in a manner suitable for the type of control used. The user agent may use the suggestion’s label to identify the suggestion if appropriate.

User agents are encouraged to filter the suggestions represented by the 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.

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 multiple attribute specified or if the multiple attribute does not apply

When the user selects a suggestion, the input element’s value must be set to the selected suggestion’s value, as if the user had written that value themself.

If the element’s type attribute is in the Range state and the element has a multiple attribute specified

When the user selects a suggestion, the user agent must identify which value in the element’s values the user intended to update, and must then update the element’s values so that the relevant value is changed to the value given by the selected suggestion’s value, as if the user had themself set it to that value.

If the element’s type attribute is in the E-mail state and the element has a multiple attribute specified

When the user selects a suggestion, the user agent must either add a new entry to the input element’s values, whose value is the selected suggestion’s value, or change an existing entry in the input element’s values to have the value given by the selected suggestion’s 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 a user-agent-defined manner.


If the list attribute does not apply, there is no suggestions source element.

This URL field offers some suggestions.
<label>Homepage: <input name=hp type=url list=hpurls></label>
<datalist id=hpurls>
  <option value="https://www.google.com/" label="Google">
  <option value="https://www.reddit.com/" label="Reddit">
</datalist>

Other URLs from the user’s history might show also; this is up to the user agent.

This example demonstrates how to design a form that uses the autocompletion list feature while still degrading usefully in legacy user agents.

If the autocompletion list is merely an aid, and is not important to the content, then simply using a datalist element with children option elements is enough. To prevent the values from being rendered in legacy user agents, they need to be placed inside the value attribute instead of inline.

<p>
  <label>
  Enter a breed:
  <input type="text" name="breed" list="breeds">
  <datalist id="breeds">
    <option value="Abyssinian">
    <option value="Alpaca">
    <!-- ... -->
  </datalist>
  </label>
</p>

However, if the values need to be shown in legacy user agents, then fallback content can be placed inside the datalist element, as follows:

<p>
  <label>
  Enter a breed:
  <input type="text" name="breed" list="breeds">
  </label>
  <datalist id="breeds">
  <label>
    or select one from the list:
    <select name="breed">
    <option value=""> (none selected)
    <option>Abyssinian
    <option>Alpaca
    <!-- ... -->
    </select>
  </label>
  </datalist>
</p>

The fallback content will only be shown in user agents that don’t support datalist. The options, on the other hand, will be detected by all user agents, even though they are not children of the datalist element.

Note that if an option element used in a datalist is selected, it will be selected by default by legacy user agents (because it affects the select), but it will not have any effect on the input element in user agents that support datalist.

4.10.5.3.10. The placeholder attribute

The placeholder attribute represents a short hint (a word or short phrase) intended to aid the user with data entry when the control has no value. A hint could be a sample value or a brief description of the expected format. The attribute, if specified, must have a value that contains no U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters.

The placeholder attribute should not be used as a replacement for a label. For a longer hint or other advisory text, place the text next to the control.

Use of the placeholder attribute as a replacement for a label can reduce the accessibility and usability of the control for a range of users including older users and users with cognitive, mobility, fine motor skill or vision impairments. While the hint given by the control’s label is shown at all times, the short hint given in the placeholder attribute is only shown before the user enters a value. Furthermore, placeholder text may be mistaken for a pre-filled value, and as commonly implemented the default color of the placeholder text provides insufficient contrast and the lack of a separate visible label reduces the size of the hit region available for setting focus on the control.

User agents should present this hint to the user, after having stripped line breaks from it, when the element’s value is the empty string, especially if the control is not focused.

If a user agent normally doesn’t show this hint to the user when the control is focused, then the user agent should nonetheless show the hint for the control if it was focused as a result of the 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 placeholder attribute:
<fieldset>
  <legend>Mail Account</legend>
  <p><label>Name: <input type="text" name="fullname" placeholder="John Ratzenberger"></label></p>
  <p><label>Address: <input type="email" name="address" placeholder="john@example.net"></label></p>
  <p><label>Password: <input type="password" name="password"></label></p>
  <p><label>Description: <input type="text" name="desc" placeholder="My Email Account"></label></p>
</fieldset>
In situations where the control’s content has one directionality but the placeholder needs to have a different directionality, Unicode’s bidirectional-algorithm formatting characters can be used in the attribute value:
<input name=t1 type=tel placeholder="&#x202B; رقم الهاتف 1 &#x202E;">
<input name=t2 type=tel placeholder="&#x202B; رقم الهاتف 2 &#x202E;">

For slightly more clarity, here’s the same example using numeric character references instead of inline Arabic:

<input name=t1 type=tel placeholder="&#x202B;&#1585;&#1602;&#1605; &#1575;&#1604;&#1607;&#1575;&#1578;&#1601; 1&#x202E;">
<input name=t2 type=tel placeholder="&#x202B;&#1585;&#1602;&#1605; &#1575;&#1604;&#1607;&#1575;&#1578;&#1601; 2&#x202E;">
4.10.5.4. Common input element APIs
input . value [ = value ]
Returns the current value of the form control.

Can be set, to change the value.

Throws an "InvalidStateError" DOMException if it is set to any value other than the empty string when the control is a file upload control.

input . checked [ = value ]
Returns the current checkedness of the form control.

Can be set, to change the checkedness.

input . files
Returns a FileList object listing the selected files of the form control.

Returns null if the control isn’t a file control.

input . valueAsDate [ = value ]
Returns a Date object representing the form control’s value, if applicable; otherwise, returns null.

Can be set, to change the value.

Throws an "InvalidStateError" DOMException if the control isn’t date- or time-based.

input . valueAsNumber [ = value ]
Returns a number representing the form control’s value, if applicable; otherwise, returns NaN.

Can be set, to change the value. Setting this to NaN will set the underlying value to the empty string.

Throws an "InvalidStateError" DOMException if the control is neither date- or time-based nor numeric.

input . stepUp( [ n ] )
input . stepDown( [ n ] )
Changes the form control’s value by the value given in the step attribute, multiplied by n. The default value for n is 1.

Throws "InvalidStateError" DOMException if the control is neither date- or time-based nor numeric, or if the step attribute’s value is "any".

input . list
Returns the datalist element indicated by the list attribute.

The value IDL attribute allows scripts to manipulate the value of an input element. The attribute is in one of the following modes, which define its behavior:

value

On getting, it must return the current value of the element. On setting, it must set the element’s value to the new value, set the element’s dirty value flag to true, invoke the value sanitization algorithm, if the element’s type attribute’s current state defines one, and then, if the element has a text entry cursor position, should move the text entry cursor position to the end of the text field, unselecting any selected text and resetting the selection direction to none.

default

On getting, if the element has a value attribute, it must return that attribute’s value; otherwise, it must return the empty string. On setting, it must set the element’s value attribute to the new value.

default/on

On getting, if the element has a value attribute, it must return that attribute’s value; otherwise, it must return the string "on". On setting, it must set the element’s value attribute to the new value.

filename

On getting, it must return the string "C:\fakepath\" followed by the name of the first file in the list of selected files, if any, or the empty string if the list is empty. On setting, if the new value is the empty string, it must empty the list of selected files; otherwise, it must throw an "InvalidStateError" DOMException.

This "fakepath" requirement is a sad accident of history. See the example in the File Upload state section for more information.

Since path components are not permitted in file names in the list of selected files, the "\fakepath\" cannot be mistaken for a path component.


The checked IDL attribute allows scripts to manipulate the checkedness of an input element. On getting, it must return the current checkedness of the element; and on setting, it must set the element’s checkedness to the new value and set the element’s dirty checkedness flag to true.


The files IDL attribute allows scripts to access the element’s selected files. On getting, if the IDL attribute applies, it must return a FileList object that represents the current selected files. The same object must be returned until the list of selected files changes. If the IDL attribute does not apply, then it must instead return null. [FILEAPI]


The valueAsDate IDL attribute represents the value of the element, interpreted as a date.

On getting, if the valueAsDate attribute does not apply, as defined for the input element’s type attribute’s current state, then return null. Otherwise, run the algorithm to convert a string to a Date object defined for that state to the element’s value; if the algorithm returned a Date object, then return it, otherwise, return null.

On setting, if the valueAsDate attribute does not apply, as defined for the input element’s type attribute’s current state, then throw an InvalidStateError exception; otherwise, if the new value is not null and not a Date object throw a TypeError exception; otherwise if the new value is null or a Date object representing the NaN time value, then set the value of the element to the empty string; otherwise, run the algorithm to convert a Date object to a string, as defined for that state, on the new value, and set the value of the element to the resulting string.


The valueAsNumber IDL attribute represents the value of the element, interpreted as a number.

On getting, if the valueAsNumber attribute does not apply, as defined for the input element’s type attribute’s current state, then return a Not-a-Number (NaN) value. Otherwise, if the valueAsDate attribute applies, run the algorithm to convert a string to a Date object defined for that state to the element’s value; if the algorithm returned a Date object, then return the time value of the object (the number of milliseconds from midnight UTC the morning of 1970-01-01 to the time represented by the Date object), otherwise, return a Not-a-Number (NaN) value. Otherwise, run the algorithm to convert a string to a number defined for that state to the element’s 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 TypeError exception. Otherwise, if the valueAsNumber attribute does not apply, as defined for the input element’s type attribute’s current state, then throw an InvalidStateError exception. Otherwise, if the new value is a Not-a-Number (NaN) value, then set the value of the element to the empty string. Otherwise, if the valueAsDate attribute applies, run the algorithm to convert a Date object to a string defined for that state, passing it a Date object whose time value is the new value, and set the value of the element to the resulting string. Otherwise, run the algorithm to convert a number to a string, as defined for that state, on the new value, and set the 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 stepDown() and stepUp() methods do not apply, as defined for the input element’s type attribute’s current state, then throw an "InvalidStateError" DOMException, and abort these steps.

  2. If the element has no allowed value step, then throw an "InvalidStateError" DOMException, and abort these steps.

  3. If the element has a minimum and a maximum and the minimum is greater than the maximum, then abort these steps.

  4. If the element has a minimum and a maximum and there is no step aligned value greater than or equal to the element’s minimum and less than or equal to the element’s maximum, then abort these steps.

  5. If applying the algorithm to convert a string to a number to the string given by the element’s 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 is not step aligned, then:

    1. If the method invoked was the stepDown() method, then step-align value with negative preference. Otherwise step-align value with positive preference. In either case, let value be the result.

      This ensures that the value first snaps to a step-aligned value when it doesn’t start step-aligned. For example, starting with the following input with value of 3:
      <input type="number" value="3" min="1" max="10" step="2.6">
      

      Invoking the stepUp() method will snap the value to 3.6; subsequent invocations will increment the value by 2.6 (e.g., 6.2, then 8.8). Likewise, the following input element in the Week state will also step-align in similar fashion, though in this state, the step value is rounded to 3, per the derivation of the allowed value step.

      <input type="week" value="2016-W20" min="2016-W01" max="2017-W01" step="2.6">
      

      Invoking stepUp() will result in a value of "2016-W22" because the nearest step-aligned value from the step base of "2016-W01" (the min value) with 3 week steps that is greater than the value of "2016-W20" is "2016-W22" (i.e.: W01, W04, W07, W10, W13, W16, W19, W22).

    Otherwise (value is step aligned), run the following substeps:

    1. Let n be the argument.

    2. Let delta be the allowed value step multiplied by n.

    3. If the method invoked was the stepDown() method, negate delta.

    4. Let value be the result of adding delta to value.

  8. If the element has a minimum, and value is less than that minimum, then set value to the step-aligned minimum value with positive preference.

  9. If the element has a maximum, and value is greater than that maximum, then set value to the step-aligned maximum value with negative preference.

  10. If either the method invoked was the stepDown() method and value is greater than valueBeforeStepping, or the method invoked was the stepUp() method and value is less than valueBeforeStepping, then abort these steps.

    This ensures that invoking the stepUp() method on the input element in the following example does not change the value of that element:
    <input type=number value=1 max=0>
    
  11. Let value as string be the result of running the algorithm to convert a number to a string, as defined for the input element’s type attribute’s current state, on value.

  12. Set the value of the element to value as string.

To determine if a value v is step aligned do the following:

This algorithm checks to see if a value falls along an input element’s defined step intervals, with the interval’s origin at the step base value. It is used to determine if the element’s value is suffering from a step mismatch and for various checks in the stepUp() and stepDown() methods.

  1. Subtract the step base from v and let the result be relative distance.

  2. If dividing the relative distance by the allowed value step results in a value with a remainder then v is not step aligned. Otherwise it is step aligned.

To step-align a value v with either negative preference or positive preference, do the following:

negative preference selects a step-aligned value that is less than or equal to v, while positive preference step-aligns with a value greater than or equal to v.

  1. Subtract the step base from v and let the result be relative distance.

  2. Let step interval count be the result of integer dividing (or divide and throw out any remainder) relative distance by the allowed value step.

  3. Let candidate be the step interval count multiplied by the allowed value step.

  4. If this algorithm was invoked with negative preference and the value of v is less than candidate, then decrement candidate by the allowed value step.

    Otherwise, if this algorithm was invoked with positive preference and the value of v is greater than candidate, then increment candidate by the allowed value step.

  5. The step-aligned value is candidate. Return candidate.


The list IDL attribute must return the current suggestions source element, if any, or null otherwise.

4.10.5.5. Common event behaviors

When the input and change events apply (which is the case for all input controls other than buttons and those with the type attribute in the Hidden state), the events are fired to indicate that the user has interacted with the control. The input event fires whenever the user has modified the data of the control. The change event fires when the value is committed, if that makes sense for the control, or else when the control loses focus. In all cases, the input event comes before the corresponding change event (if any).

When an input element has a defined activation behavior, the rules for dispatching these events, if they apply, are given in the section above that defines the type attribute’s state. (This is the case for all input controls with the type attribute in the Checkbox state, the Radio Button state, or the File Upload state.)

For input elements without a defined activation behavior, but to which these events apply, and for which the user interface involves both interactive manipulation and an explicit commit action, then when the user changes the element’s value, the user agent must queue a task to fire a simple event that bubbles named input at the input element, and any time the user commits the change, the user agent must queue a task to fire a simple event that bubbles named change at the input element.

An example of a user interface involving both interactive manipulation and a commit action would be a Range controls that use a slider, when manipulated using a pointing device. While the user is dragging the control’s knob, input events would fire whenever the position changed, whereas the change event would only fire when the user let go of the knob, committing to a specific value.

For input elements without a defined activation behavior, but to which these events 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 value, the user agent must queue a task to first fire a simple event that bubbles named input at the input element, and then fire a simple event that bubbles named change at the input element.

An example of a user interface with a commit action would be a Color control that consists of a single button that brings up a color wheel: if the 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 Date control that allows both text-based user input and user selection from a drop-down calendar: while text input does 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.

The Range control is also an example of a user interface that has a commit action when used with a pointing device (rather than a keyboard): during the time that the pointing device starts manipulating the slider until the time that the slider is released, no commit action is taken (though input events are fired as the value is changed). Only after the slider is release is the commit action taken.

For input elements without a defined activation behavior, but to which these events apply, any time the user causes the element’s value to change without an explicit commit action, the user agent must queue a task to fire a simple event that bubbles named input at the input element. The corresponding change event, if any, will be fired when the control loses focus.

Examples of a user changing the element’s value would include the user typing into a text field, pasting a new value into the field, or undoing an edit in that field. Some user interactions do not cause changes to the value, e.g., hitting the "delete" key in an empty text field, or replacing some text in the field with text from the clipboard that happens to be exactly the same text.

A Range control in the form of a slider that the user has focused and is interacting with using a keyboard would be another example of the user changing the element’s value without a commit step.

In the case of tasks that just fire an input event, user agents may wait for a suitable break in the user’s interaction before 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 input element’s value on behalf of the user (e.g., as part of a form prefilling feature), the user agent must queue a task to first update the value accordingly, then fire a simple event that bubbles named input at the input element, then fire a simple event that bubbles named change at the input element.

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.)

The task source for these tasks is the user interaction task source.

4.10.6. The button element

Categories:
Flow content.
Phrasing content.
Interactive content.
listed, labelable, submittable, and reassociateable form-associated element.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Phrasing content, but there must be no interactive content descendant.
Tag omission in text/html:
Neither tag is omissible
Content attributes:
Global attributes
autofocus - Automatically focus the form control when the page is loaded
disabled - Whether the form control is disabled
form - Associates the control with a form element
formaction - URL to use for §4.10.22 Form submission
formenctype - Form data set encoding type to use for §4.10.22 Form submission
formmethod - HTTP method to use for §4.10.22 Form submission
formnovalidate - Bypass form control validation for §4.10.22 Form submission
formtarget - browsing context for §4.10.22 Form submission
menu - Specifies the element’s designated pop-up menu
name - Name of form control to use for §4.10.22 Form submission and in the form.elements API
type - Type of button
value - Value to be used for §4.10.22 Form submission
Allowed ARIA role attribute values:
button (default - do not set), link, menuitem, menuitemcheckbox, menuitemradio or radio.
Allowed ARIA state and property attributes:
Global aria-* attributes
Any aria-* attributes applicable to the allowed roles.
DOM interface:
interface HTMLButtonElement : HTMLElement {
  attribute boolean autofocus;
  attribute boolean disabled;
  readonly attribute HTMLFormElement? form;
  attribute DOMString formAction;
  attribute DOMString formEnctype;
  attribute DOMString formMethod;
  attribute boolean formNoValidate;
  attribute DOMString formTarget;
  attribute DOMString name;
  attribute DOMString type;
  attribute DOMString value;
  attribute HTMLMenuElement? menu;

  readonly attribute boolean willValidate;
  readonly attribute ValidityState validity;
  readonly attribute DOMString validationMessage;
  boolean checkValidity();
  boolean reportValidity();
  void setCustomValidity(DOMString error);

  [SameObject] readonly attribute NodeList labels;
};

The button element represents a button labeled by its contents.

The element is a button.

The type attribute controls the behavior of the button when it is activated. It is an enumerated attribute. The following table lists the keywords and states for the attribute — the keywords in the left column map to the states in the cell in the second column on the same row as the keyword.

Keyword State Brief description
submit submit button Submits the form.
reset reset button Resets the form.
button Button Does nothing.
menu Menu Shows a menu.

The missing value default is the submit button state.

If the type attribute is in the submit button state, the element is specifically a submit button.

Constraint validation: If the type attribute is in the reset button state, the Button state, or the Menu state, the element is barred from constrain validation.

When a button element is not disabled, its activation behavior element is to run the steps defined in the following list for the current state of the element’s type attribute:

submit button
If the element has a form owner and the element’s node document is fully active, the element must submit the form owner from the button element.
reset button
If the element has a form owner and the element’s node document is fully active, the element must reset the form owner.
Button
Do nothing.
Menu

The element must follow these steps:

  1. If the button is not being rendered, abort these steps.
  2. If the button element’s node document is not fully active, abort these steps.
  3. Let menu be the element’s designated pop-up menu, if any. If there isn’t one, then abort these steps.
  4. Fire a trusted event with the name show at menu, using the RelatedEvent interface, with the relatedTarget attribute initialized to the button element. The event must be cancelable.
  5. If the event is not canceled, then build and show the menu for menu, with the button element as the subject.

The form attribute is used to explicitly associate the button element with its form owner. The name attribute represents the element’s name. The disabled attribute is used to make the control non-interactive and to prevent its value from being submitted. The autofocus attribute controls focus. The formaction, formenctype, formmethod, formnovalidate, and formtarget attributes are attributes for form submission.

The formnovalidate attribute can be used to make submit buttons that do not trigger the constraint validation.

The formaction, formenctype, formmethod, formnovalidate, and formtarget must not be specified if the element’s type attribute is not in the submit button state.

The value attribute gives the element’s value for the purposes of form submission. The element’s value is the value of the element’s value attribute, if there is one, or the empty string otherwise.

A button (and its value) is only included in the form submission if the button itself was used to initiate the form submission.


If the element’s type attribute is in the Menu state, the menu attribute must be specified to give the element’s menu. The value must be the ID of a menu element in the same home subtree whose type attribute is in the popup menu state. The attribute must not be specified if the element’s type attribute is not in the Menu state.

A button element’s designated pop-up menu is the first element in the button's home subtree whose ID is that given by the button element’s menu attribute, if there is such an element and its type attribute is in the popup menu state; otherwise, the element has no designated pop-up menu.


The value and menu IDL attributes must reflect the content attributes of the same name.

The type IDL attribute must reflect the content attribute of the same name, limited to only known values.

The willValidate, validity, and validationMessage IDL attributes, and the checkValidity(), reportValidity(), and setCustomValidity() methods, are part of the constraint validation API. The labels IDL attribute provides a list of the element’s labels. The autofocus, disabled, form, and 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:
<button type=button
        onclick="alert('This 15-20 minute piece was composed by George Gershwin.')">
  Show hint
</button>

4.10.7. The select element

Categories:
Flow content.
Phrasing content.
Interactive content.
listed, labelable, submittable, resettable, and reassociateable form-associated element.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Zero or more option, optgroup, and script-supporting elements.
Tag omission in text/html:
Neither tag is omissible
Content attributes:
Global attributes
autofocus - Automatically focus the form control when the page is loaded
disabled - Whether the form control is disabled
form - Associates the control with a form element
multiple - Whether to allow multiple values
name - Name of form control to use for §4.10.22 Form submission and in the form.elements API
required - Whether the control is required for §4.10.22 Form submission
size - Size of the control
Allowed ARIA role attribute values:
listbox (default - do not set) or menu.
Allowed ARIA state and property attributes:
Global aria-* attributes
Any aria-* attributes applicable to the allowed roles.
DOM interface:
interface HTMLSelectElement : HTMLElement {
  attribute DOMString autocomplete;
  attribute boolean autofocus;
  attribute boolean disabled;
  readonly attribute HTMLFormElement? form;
  attribute boolean multiple;
  attribute DOMString name;
  attribute boolean required;
  attribute unsigned long size;

  readonly attribute DOMString type;

  [SameObject] readonly attribute HTMLOptionsCollection options;
  attribute unsigned long length;
  getter Element? item(unsigned long index);
  HTMLOptionElement? namedItem(DOMString name);
  void add((HTMLOptionElement or HTMLOptGroupElement) element, optional (HTMLElement or long)? before = null);
  void remove(); // ChildNode overload
  void remove(long index);
  setter void (unsigned long index, HTMLOptionElement? option);

  [SameObject] readonly attribute HTMLCollection selectedOptions;
  attribute long selectedIndex;
  attribute DOMString value;

  readonly attribute boolean willValidate;
  readonly attribute ValidityState validity;
  readonly attribute DOMString validationMessage;
  boolean checkValidity();
  boolean reportValidity();
  void setCustomValidity(DOMString error);

  [SameObject] readonly attribute NodeList labels;
};

The select element represents a control for selecting amongst a set of options.

The multiple attribute is a boolean attribute. If the attribute is present, then the select element represents a control for selecting zero or more options from the list of options. If the attribute is absent, then the select element represents a control for selecting a single option from the list of options.

The size attribute gives the number of options to show to the user. The size attribute, if specified, must have a value that is a valid non-negative integer greater than zero.

The display size of a select element is the result of applying the rules for parsing non-negative integers to the value of element’s 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 size attribute is absent, then the element’s display size is 4 if the element’s multiple content attribute is present, and 1 otherwise.

The list of options for a select element consists of all the option element children of the select element, and all the option element children of all the optgroup element children of the select element, in tree order.

The required attribute is a boolean attribute. When specified, the user will be required to select a value before submitting the form.

If a select element has a required attribute specified, does not have a multiple attribute specified, and has a display size of 1; and if the value of the first option element in the select element’s list of options (if any) is the empty string, and that option element’s parent node is the select element (and not an optgroup element), then that option is the select element’s placeholder label option.

If a select element has a required attribute specified, does not have a multiple attribute specified, and has a display size of 1, then the select element must have a placeholder label option.

In practice, the requirement stated in the paragraph above can only apply when a select element does not have a sizes attribute with a value greater than 1.

Constraint validation: If the element has its required attribute specified, and either none of the option elements in the select element’s list of options have their selectedness set to true, or the only option element in the select element’s list of options with its selectedness set to true is the placeholder label option, then the element is suffering from being missing.

If the multiple attribute is absent, and the element is not disabled, then the user agent should allow the user to pick an option element in its list of options that is itself not disabled. Upon this option element being picked (either through a click, or through unfocusing the element after changing its value, or through a menu command, or through any other mechanism), and before the relevant user interaction event is queued (e.g., before the click event), the user agent must set the selectedness of the picked option element to true, set its dirtiness to true, and then send select update notifications.

If the multiple attribute is absent, whenever an option element in the select element’s list of options has its selectedness set to true, and whenever an option element with its selectedness set to true is added to the select element’s list of options, the user agent must set the selectedness of all the other option elements in its list of options to false.

If the multiple attribute is absent and the element’s display size is greater than 1, then the user agent should also allow the user to request that the option whose 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 click event), the user agent must set the selectedness of that option element to false, set its dirtiness to true, and then send select update notifications.

If nodes are inserted or nodes are removed causing the list of options to gain or lose one or more option elements, or if an option element in the list of options asks for a reset, then, if the select element’s multiple attribute is absent, the user agent must run the first applicable set of steps from the following list:

If the select element’s display size is 1, and no option elements in the select element’s list of options have their selectedness set to true
Set the selectedness of the first option element in the list of options in tree order that is not disabled, if any, to true.
If two or more option elements in the select element’s list of options have their selectedness set to true
Set the selectedness of all but the last option element with its selectedness set to true in the list of options in tree order to false.

If the multiple attribute is present, and the element is not disabled, then the user agent should allow the user to toggle the selectedness of the option elements in its list of options that are themselves not disabled. Upon such an element being toggled (either through a click, or through a menu command, or any other mechanism), and before the relevant user interaction event is queued (e.g., before a related click event), the selectedness of the option element must be changed (from true to false or false to true), the dirtiness of the element must be set to true, and the user agent must send select update notifications.

When the user agent is to send select update notifications, queue a task to first fire a simple event that bubbles named input at the select element, and then fire a simple event that bubbles named change at the select element, using the user interaction task source as the task source. If the JavaScript execution context stack was not empty when the user agent was to send select update notifications, then the resulting input and change events must not be trusted.

The reset algorithm for select elements is to go through all the option elements in the element’s list of options, set their selectedness to true if the option element has a selected attribute, and false otherwise, set their dirtiness to false, and then have the option elements ask for a reset.

The form attribute is used to explicitly associate the select element with its form owner. The name attribute represents the element’s name. The disabled attribute is used to make the control non-interactive and to prevent its value from being submitted. The autofocus attribute controls focus. The autocomplete attribute controls how the user agent provides autofill behavior.

A select element that is not disabled is mutable.

select . type

Returns "select-multiple" if the element has a multiple attribute, and "select-one" otherwise.

select . options

Returns an HTMLOptionsCollection of the list of options.

select . length [ = value ]

Returns the number of elements in the list of options.

When set to a smaller number, truncates the number of option elements in the select.

When set to a greater number, adds new blank option elements to the select.

element = select . item(index)
select[index]

Returns the item with index index from the list of options. The items are sorted in tree order.

element = select . namedItem(name)

Returns the first item with ID or name name from the list of options.

Returns null if no element with that ID could be found.

select . add(element [, before ] )

Inserts element before the node given by before.

The before argument can be a number, in which case element is inserted before the item with that number, or an element from the list of options, in which case element is inserted before that element.

If before is omitted, null, or a number out of range, then element will be added at the end of the list.

This method will throw a HierarchyRequestError exception if element is an ancestor of the element into which it is to be inserted.

select . selectedOptions

Returns an HTMLCollection of the list of options that are selected.

select . selectedIndex [ = value ]

Returns the index of the first selected item, if any, or -1 if there is no selected item.

Can be set, to change the selection.

select . value [ = value ]

Returns the value of the first selected item, if any, or the empty string if there is no selected item.

Can be set, to change the selection.

The type IDL attribute, on getting, must return the string "select-one" if the multiple attribute is absent, and the string "select-multiple" if the multiple attribute is present.

The options IDL attribute must return an HTMLOptionsCollection rooted at the select node, whose filter matches the elements in the list of options.

The options collection is also mirrored on the HTMLSelectElement object. The supported property indices at any instant are the indices supported by the object returned by the options attribute at that instant.

The length IDL attribute must return the number of nodes represented by the options collection. On setting, it must act like the attribute of the same name on the options collection.

The item(index) method must return the value returned by the method of the same name on the options collection, when invoked with the same argument.

The namedItem(name) method must return the value returned by the method of the same name on the options collection, when invoked with the same argument.

When the user agent is to set the value of a new indexed property for a given property index index to a new value value, it must instead set the value of a new indexed property with the given property index index to the new value value on the options collection.

Similarly, the add() method must act like its namesake method on that same options collection.

The remove() method must act like its namesake method on that same options collection when it has arguments, and like its namesake method on the ChildNode interface implemented by the HTMLSelectElement ancestor interface Element when it has no arguments.

The selectedOptions IDL attribute must return an HTMLCollection rooted at the select node, whose filter matches the elements in the list of options that have their selectedness set to true.

The selectedIndex IDL attribute, on getting, must return the index of the first option element in the list of options in tree order that has its selectedness set to true, if any. If there isn’t one, then it must return -1.

On setting, the selectedIndex attribute must set the selectedness of all the option elements in the list of options to false, and then the option element in the list of options whose index is the given new value, if any, must have its selectedness set to true and its dirtiness set to true.

This can result in no element having a selectedness set to true even in the case of the select element having no multiple attribute and a display size of 1.

The value IDL attribute, on getting, must return the value of the first option element in the list of options in tree order that has its selectedness set to true, if any. If there isn’t one, then it must return the empty string.

On setting, the value attribute must set the selectedness of all the option elements in the list of options to false, and then the first option element in the list of options, in tree order, whose value is equal to the given new value, if any, must have its selectedness set to true and its dirtiness set to true.

This can result in no element having a selectedness set to true even in the case of the select element having no multiple attribute and a display size of 1.

The multiple, required, and size IDL attributes must reflect the respective content attributes of the same name. The size IDL attribute has a default value of zero.

For historical reasons, the default value of the size IDL attribute does not return the actual size used, which, in the absence of the size content attribute, is either 1 or 4 depending on the presence of the multiple attribute.

The willValidate, validity, and validationMessage IDL attributes, and the checkValidity(), reportValidity(), and setCustomValidity() methods, are part of the constraint validation API. The labels IDL attribute provides a list of the element’s labels. The autofocus, disabled, form, and name IDL attributes are part of the element’s forms API.

The following example shows how a select element can be used to offer the user with a set of options from which the user can select a single option. The default option is preselected.
<p>
  <label for="unittype">Select unit type:</label>
  <select id="unittype" name="unittype">
  <option value="1"> Miner </option>
  <option value="2"> Puffer </option>
  <option value="3" selected> Snipey </option>
  <option value="4"> Max </option>
  <option value="5"> Firebot </option>
  </select>
</p>

When there is no default option, a value that provides instructions or a hint (placeholder option) can be used instead:

<select name="unittype" required>
  <option value=""> Select unit type </option>
  <option value="1"> Miner </option>
  <option value="2"> Puffer </option>
  <option value="3"> Snipey </option>
  <option value="4"> Max </option>
  <option value="5"> Firebot </option>
</select>
Here, the user is offered a set of options from which he can select any number. By default, all five options are selected.
<p>
  <label for="allowedunits">Select unit types to enable on this map:</label>
  <select id="allowedunits" name="allowedunits" multiple>
  <option value="1" selected> Miner </option>
  <option value="2" selected> Puffer </option>
  <option value="3" selected> Snipey </option>
  <option value="4" selected> Max </option>
  <option value="5" selected> Firebot </option>
  </select>
</p>
Sometimes, a user has to select one or more items. This example shows such an interface.
<p>Select the songs from that you would like on your Act II Mix Tape:</p>
<select multiple required name="act2">
  <option value="s1">It Sucks to Be Me (Reprize)
  <option value="s2">There is Life Outside Your Apartment
  <option value="s3">The More You Ruv Someone
  <option value="s4">Schadenfreude
  <option value="s5">I Wish I Could Go Back to College
  <option value="s6">The Money Song
  <option value="s7">School for Monsters
  <option value="s8">The Money Song (Reprize)
  <option value="s9">There’s a Fine, Fine Line (Reprize)
  <option value="s10">What Do You Do With a B.A. in English? (Reprize)
  <option value="s11">For Now
</select>

4.10.8. The datalist element

Categories:
Flow content.
Phrasing content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Either: phrasing content.
Or: Zero or more option and script-supporting elements.
Tag omission in text/html:
Neither tag is omissible
Content attributes:
Global attributes
Allowed ARIA role attribute values:
listbox (default - do not set).
Allowed ARIA state and property attributes:
Global aria-* attributes
Any aria-* attributes applicable to the allowed roles.
DOM interface:
interface HTMLDataListElement : HTMLElement {
  [SameObject] readonly attribute HTMLCollection options;
};

The datalist element represents a set of option elements that represent predefined options for other controls. In the rendering, the datalist element represents nothing and it, along with its children, should be hidden.

The datalist element can be used in two ways. In the simplest case, the datalist element has just option element children.

<label>
  Sex:
  <input name=sex list=sexes>
  <datalist id=sexes>
  <option value="Female">
  <option value="Male">
  </datalist>
</label>

In the more elaborate case, the datalist element can be given contents that are to be displayed for down-level clients that don’t support datalist. In this case, the option elements are provided inside a select element inside the datalist element.

<label>
  Sex:
  <input name=sex list=sexes>
</label>
<datalist id=sexes>
  <label>
  or select from the list:
  <select name=sex>
    <option value="">
    <option>Female
    <option>Male
  </select>
  </label>
</datalist>

The datalist element is hooked up to an input element using the list attribute on the input element.

Each option element that is a descendant of the datalist element, that is not disabled, and whose value is a string that isn’t the empty string, represents a suggestion. Each suggestion has a value and a label.

datalist . options
Returns an HTMLCollection of the option elements of the datalist element.

The options IDL attribute must return an HTMLCollection rooted at the datalist node, whose filter matches option elements.

Constraint validation: If an element has a datalist element ancestor, it is barred from constraint validation.

4.10.9. The optgroup element

Categories:
None.
Contexts in which this element can be used:
As a child of a select element.
Content model:
Zero or more option and script-supporting elements.
Tag omission in text/html:
An optgroup element’s end tag may be omitted if the optgroup element is immediately followed by another optgroup element, or if there is no more content in the parent element.
Content attributes:
Global attributes
disabled - Whether the form control is disabled
label - User-visible label
Allowed ARIA role attribute values:
None
Allowed ARIA state and property attributes:
Global aria-* attributes
DOM interface:
interface HTMLOptGroupElement : HTMLElement {
  attribute boolean disabled;
  attribute DOMString label;
};

The optgroup element represents a group of option elements with a common label.

The element’s group of option elements consists of the option elements that are children of the optgroup element.

When showing option elements in select elements, user agents should show the option elements of such groups as being related to each other and separate from other option elements.

The disabled content attribute is a boolean attribute and can be used to disable a group of option elements together.

The label content 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 option elements in a select element.

The disabled and label IDL attributes must reflect the respective content attributes of the same name.

There is no way to select an optgroup element. Only option elements can be selected. An optgroup element merely provides a label for a group of option elements.

The following snippet shows how a set of lessons from three courses could be offered in a select drop-down widget:
<form action="courseselector.dll" method="get">
  <p>Which course would you like to watch today?
  <p><label>Course:
  <select name="c">
    <optgroup label="8.01 Physics I: Classical Mechanics">
    <option value="8.01.1">Lecture 01: Powers of Ten
    <option value="8.01.2">Lecture 02: 1D Kinematics
    <option value="8.01.3">Lecture 03: Vectors
    <optgroup label="8.02 Electricity and Magnestism">
    <option value="8.02.1">Lecture 01: What holds our world together?
    <option value="8.02.2">Lecture 02: Electric Field
    <option value="8.02.3">Lecture 03: Electric Flux
    <optgroup label="8.03 Physics III: Vibrations and Waves">
    <option value="8.03.1">Lecture 01: Periodic Phenomenon
    <option value="8.03.2">Lecture 02: Beats
    <option value="8.03.3">Lecture 03: Forced Oscillations with Damping
  </select>
  </label>
  <p><input type=submit value="▶ Play">
</form>

4.10.10. The option element

Categories:
None.
Contexts in which this element can be used:
As a child of a select element.
As a child of a datalist element.
As a child of an optgroup element.
Content model:
If the element has a label attribute and a value attribute: Nothing.
If the element has a label attribute but no value attribute: Text.
If the element has no label attribute: Text.
Tag omission in text/html:
An option element’s end tag may be omitted if the option element is immediately followed by another option element, or if it is immediately followed by an optgroup element, or if there is no more content in the parent element.
Content attributes:
Global attributes
disabled - Whether the form control is disabled
label - User-visible label
selected - Whether the option is selected by default
value - Value to be used for §4.10.22 Form submission
Allowed ARIA role attribute values:
option (default - do not set), menuitem, menuitemradio or separator.
Allowed ARIA state and property attributes:
Global aria-* attributes
Any aria-* attributes applicable to the allowed roles.
DOM interface:
[NamedConstructor=Option(optional DOMString text = "", optional DOMString value, optional boolean defaultSelected = false, optional boolean selected = false)]
interface HTMLOptionElement : HTMLElement {
  attribute boolean disabled;
  readonly attribute HTMLFormElement? form;
  attribute DOMString label;
  attribute boolean defaultSelected;
  attribute boolean selected;
  attribute DOMString value;

  attribute DOMString text;
  readonly attribute long index;
};

The option element represents an option in a select element or as part of a list of suggestions in a datalist element.

In certain circumstances described in the definition of the select element, an option element can be a select element’s placeholder label option. A placeholder label option does not represent an actual option, but instead represents a label for the select control.

The disabled content attribute is a boolean attribute. An option element is disabled if its disabled attribute is present or if it is a child of an optgroup element whose disabled attribute is present.

An option element that is disabled must prevent any click events that are queued on the user interaction task source from being dispatched on the element.

The label content attribute provides a label for the element. The label of an option element is the value of the label content attribute, if there is one and its value is not the empty string, or, otherwise, the value of the element’s text IDL attribute if its value is not the empty string.

The label content attribute, if specified, must not be empty.

The value content attribute provides a value for element. The value of an option element is the value of the value content attribute, if there is one, or, if there is not, the value of the element’s text IDL attribute (which may be the empty string).

The selected content attribute is a boolean attribute. It represents the default selectedness of the element.

The dirtiness of an option element is a boolean state, initially false. It controls whether adding or removing the selected content attribute has any effect.

The selectedness of an option element is a boolean state, initially false. Except where otherwise specified, when the element is created, its selectedness must be set to true if the element has a selected attribute. Whenever an option element’s selected attribute is added, if its dirtiness is false, its selectedness must be set to true. Whenever an option element’s selected attribute is removed, if its dirtiness is false, its selectedness must be set to false.

The Option() constructor, when called with three or fewer arguments, overrides the initial state of the selectedness state to always be false even if the third argument is true (implying that a selected attribute is to be set). The fourth argument can be used to explicitly set the initial selectedness state when using the constructor.

A select element whose multiple attribute is not specified must not have more than one descendant option element with its selected attribute set.

An option element’s index is the number of option elements that are in the same list of options but that come before it in tree order. If the option element is not in a list of options, then the option element’s index is zero.

option . selected
Returns true if the element is selected, and false otherwise.

Can be set, to override the current state of the element.

option . index
Returns the index of the element in its select element’s options list.
option . form
Returns the element’s form element, if any, or null otherwise.
option . text
Same as textContent, except that spaces are collapsed and script elements are skipped.
option = new Option()( [ text [, value [, defaultSelected [, selected ] ] ] ] )
Returns a new option element.

The text argument sets the contents of the element.

The value argument sets the value attribute.

The defaultSelected argument sets the selected attribute.

The selected argument sets whether or not the element is selected. If it is omitted, even if the defaultSelected argument is true, the element is not selected.

The disabled IDL attribute must reflect the content attribute of the same name. The defaultSelected IDL attribute must reflect the selected content attribute.

The label IDL attribute, on getting, if there is a label content attribute, must return that attribute’s value; otherwise, it must return the element’s label. On setting, the element’s label content attribute must be set to the new value.

The value IDL attribute, on getting, must return the element’s value. On setting, the element’s value content attribute must be set to the new value.

The selected IDL attribute, on getting, must return true if the element’s selectedness is true, and false otherwise. On setting, it must set the element’s selectedness to the new value, set its dirtiness to true, and then cause the element to ask for a reset.

The index IDL attribute must return the element’s index.

The text IDL attribute, on getting, must return the result of stripping and collapsing whitespace from the concatenation of data of all the Text node descendants of the option element, in tree order, excluding any that are descendants of descendants of the option element that are themselves script elements in the HTML namespace or script elements in the SVG namespace.

On setting, the text attribute must act as if the textContent IDL attribute on the element had been set to the new value.

The form IDL attribute’s behavior depends on whether the option element is in a select element or not. If the option has a select element as its parent, or has an optgroup element as its parent and that optgroup element has a select element as its parent, then the form IDL attribute must return the same value as the form IDL attribute on that select element. Otherwise, it must return null.

A constructor is provided for creating HTMLOptionElement objects (in addition to the factory methods from DOM such as createElement()): Option(text, value, defaultSelected, selected). When invoked as a constructor, it must return a new HTMLOptionElement object (a new option element). If the first argument is not the empty string, the new object must have as its only child a Text node whose data is the value of that argument. Otherwise, it must have no children. If the value argument is present, the new object must have a value attribute set with the value of the argument as its value. If the defaultSelected argument is true, the new object must have a selected attribute set with no value. If the selected argument is true, the new object must have its selectedness set to true; otherwise the selectedness must be set to false, even if the defaultSelected argument is true. The element’s node document must be the active document of the browsing context of the Window object on which the interface object of the invoked constructor is found.

4.10.11. The textarea element

Categories:
Flow content.
Phrasing content.
Interactive content.
listed, labelable, submittable, resettable, and reassociateable form-associated element.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Text.
Tag omission in text/html:
Neither tag is omissible
Content attributes:
Global attributes
autocomplete - Hint for form autofill feature
autofocus - Automatically focus the form control when the page is loaded
cols - Maximum number of characters per line
dirname - Name of form field to use for sending the element’s directionality in §4.10.22 Form submission
disabled - Whether the form control is disabled
form - Associates the control with a form element
inputmode - Hint for selecting an input modality
maxlength - Maximum length of value
minlength - Minimum length of value
name - Name of form control to use for §4.10.22 Form submission and in the form.elements API
placeholder - User-visible label to be placed within the form control
readonly - Whether to allow the value to be edited by the user
required - Whether the control is required for §4.10.22 Form submission
rows - Number of lines to show
wrap - How the value of the form control is to be wrapped for §4.10.22 Form submission
Allowed ARIA role attribute values:
textbox (default - do not set).
Allowed ARIA state and property attributes:
Global aria-* attributes
Any aria-* attributes applicable to the allowed roles.
DOM interface:
interface HTMLTextAreaElement : HTMLElement {
  attribute DOMString autocomplete;
  attribute boolean autofocus;
  attribute unsigned long cols;
  attribute DOMString dirName;
  attribute boolean disabled;
  readonly attribute HTMLFormElement? form;
  attribute DOMString inputMode;
  attribute long maxLength;
  attribute long minLength;
  attribute DOMString name;
  attribute DOMString placeholder;
  attribute boolean readOnly;
  attribute boolean required;
  attribute unsigned long rows;
  attribute DOMString wrap;

  readonly attribute DOMString type;
  attribute DOMString defaultValue;
  [TreatNullAs=EmptyString] attribute DOMString value;
  readonly attribute unsigned long textLength;

  readonly attribute boolean willValidate;
  readonly attribute ValidityState validity;
  readonly attribute DOMString validationMessage;
  boolean checkValidity();
  boolean reportValidity();
  void setCustomValidity(DOMString error);

  [SameObject] readonly attribute NodeList labels;

  void select();
  attribute unsigned long selectionStart;
  attribute unsigned long selectionEnd;
  attribute DOMString selectionDirection;
  void setRangeText(DOMString replacement);
  void setRangeText(DOMString replacement, unsigned long start, unsigned long end, optional SelectionMode selectionMode = "preserve");
  void setSelectionRange(unsigned long start, unsigned long end, optional DOMString direction);
};

The textarea element 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 raw value of a textarea control must be initially the empty string.

This element has rendering requirements involving the bidirectional algorithm.

The readonly attribute is a boolean attribute used to control whether the text can be edited by the user or not.

In this example, a text field is marked read-only because it represents a read-only file:
Filename: <code>/etc/bash.bashrc</code>
<textarea name="buffer" readonly>
# System-wide .bashrc file for interactive bash(1) shells.

# To enable the settings / commands in this file for login shells as well,
# this file has to be sourced in /etc/profile.

# If not running interactively, don’t do anything
[ -z "$PS1" ] &amp;&amp; return

...</textarea>

Constraint validation: If the readonly attribute is specified on a textarea element, the element is barred from constraint validation.

A textarea element is mutable if it is neither disabled nor has a readonly attribute specified.

When a textarea is mutable, its 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 raw value to change, the user agent must queue a task to fire a simple event that bubbles named input at the textarea element. 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 textarea element has a dirty value flag, which must be initially set to false, and must be set to true whenever the user interacts with the control in a way that changes the raw value.

When the textarea element’s textContent IDL attribute changes value, if the element’s dirty value flag is false, then the element’s raw value must be set to the value of the element’s textContent IDL attribute.

The reset algorithm for textarea elements is to set the element’s raw value to the value of the element’s textContent IDL attribute.

When a textarea element is popped off the stack of open elements of an HTML parser or XML parser, then the user agent must invoke the element’s reset algorithm.

If the element is 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 dir attribute to "ltr" if the user selected a left-to-right writing direction, and "rtl" if the user selected a right-to-left writing direction.
  2. Queue a task to fire a simple event that bubbles named input at the textarea element.

The cols attribute specifies the expected maximum number of characters per line. If the cols attribute is specified, its value must be a valid non-negative integer greater than zero. If applying the 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 textarea element’s 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 rows attribute is specified, its value must be a valid non-negative integer greater than zero. If applying the 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 character height.

The wrap attribute is an enumerated attribute with two keywords and states: the soft keyword which maps to the Soft state, and the hard keyword which maps to the Hard state. The missing value default is the Soft state.

The Soft state indicates that the text in the textarea is not to be wrapped when it is submitted (though it can still be wrapped in the rendering).

The Hard state indicates that the text in the textarea is to have newlines added by the user agent so that the text is wrapped when it is submitted.

If the element’s wrap attribute is in the Hard state, the cols attribute must be specified.

For historical reasons, the element’s value is normalized in three different ways for three different purposes. The raw value is the value as it was originally set. It is not normalized. The API value is the value used in the value IDL attribute. It is normalized so that line breaks use U+000A LINE FEED (LF) characters. Finally, there is the value, as used in form submission and other processing models in this specification. It is normalized so that line breaks use U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character pairs, and in addition, if necessary given the element’s wrap attribute, additional line breaks are inserted to wrap the text at the given width.

The element’s API value is defined to be the element’s raw value with the following transformation applied:

  1. Replace every U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character pair from the raw value with a single U+000A LINE FEED (LF) character.
  2. Replace every remaining U+000D CARRIAGE RETURN character from the raw value with a single U+000A LINE FEED (LF) character.

The element’s value is defined to be the element’s raw value with the textarea wrapping transformation applied. The textarea wrapping transformation is the following algorithm, as applied to a string:

  1. Replace every occurrence of a U+000D CARRIAGE RETURN (CR) character not followed by a U+000A LINE FEED (LF) character, and every occurrence of a U+000A LINE FEED (LF) character not preceded by a U+000D CARRIAGE RETURN (CR) character, by a two-character string consisting of a U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character pair.
  2. If the element’s wrap attribute is in the Hard state, insert U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character pairs into the string using a user agent-defined algorithm so that each line has no more than 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+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character pairs.

The maxlength attribute is a form control maxlength attribute controlled by the textarea element’s dirty value flag.

If the textarea element has a maximum allowed value length, then the element’s children must be such that the code-unit length of the value of the element’s textContent IDL attribute with the textarea wrapping transformation applied is equal to or less than the element’s maximum allowed value length.

The minlength attribute is a form control minlength attribute controlled by the textarea element’s dirty value flag.

The required attribute is a boolean attribute. When specified, the user will be required to enter a value before submitting the form.

Constraint validation: If the element has its required attribute specified, and the element is mutable, and the element’s value is the empty string, then the element is 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 placeholder attribute should not be used as a replacement for a label. For a longer hint or other advisory text, place the text next to the control.

Use of the placeholder attribute as a replacement for a label can reduce the accessibility and usability of the control for a range of users including older users and users with cognitive, mobility, fine motor skill or vision impairments. While the hint given by the control’s label is shown at all times, the short hint given in the placeholder attribute is only shown before the user enters a value. Furthermore, placeholder text may be mistaken for a pre-filled value, and as commonly implemented the default color of the placeholder text provides insufficient contrast and the lack of a separate visible label reduces the size of the hit region available for setting focus on the control.

User agents should present this hint to the user when the element’s value is the empty string and the control is not 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.

The name attribute represents the element’s name. The dirname attribute controls how the element’s directionality is submitted. The disabled attribute is used to make the control non-interactive and to prevent its value from being submitted. The form attribute is used to explicitly associate the textarea element with its form owner. The autofocus attribute controls focus. The inputmode attribute controls the user interface’s input modality for the control. The autocomplete attribute controls how the user agent provides autofill behavior.

textarea . type

Returns the string "textarea".

textarea . value

Returns the current value of the element.

Can be set, to change the value.

The cols, placeholder, required, rows, and wrap attributes must reflect the respective content attributes of the same name. The cols and rows attributes are limited to only non-negative numbers greater than zero. The cols attribute’s default value is 20. The rows attribute’s default value is 2. The dirName IDL attribute must reflect the dirname content attribute. The inputMode IDL attribute must reflect the inputmode content attribute, limited to only known values. The maxLength IDL attribute must reflect the maxlength content attribute, limited to only non-negative numbers. The minLength IDL attribute must reflect the minlength content attribute, limited to only non-negative numbers. The readOnly IDL attribute must reflect the readonly content attribute.

The type IDL attribute must return the value "textarea".

The defaultValue IDL attribute must act like the element’s textContent IDL attribute.

The value attribute must, on getting, return the element’s API value; on setting, it must set the element’s raw value to the new value, set the element’s dirty value flag to true, and should then move the text entry cursor position to the end of the text field, unselecting any selected text and resetting the selection direction to none.

The textLength IDL attribute must return the code-unit length of the element’s API value.

The willValidate, validity, and validationMessage IDL attributes, and the checkValidity(), reportValidity(), and setCustomValidity() methods, are part of the constraint validation API. The labels IDL attribute provides a list of the element’s labels. The select(), selectionStart, selectionEnd, selectionDirection, setRangeText(), and setSelectionRange() methods and IDL attributes expose the element’s text selection. The autofocus, disabled, form, and name IDL attributes are part of the element’s forms API.

Here is an example of a textarea being used for unrestricted free-form text input in a form:
<p>If you have any comments, please let us know: <textarea cols=80 name=comments></textarea></p>

To specify a maximum length for the comments, one can use the maxlength attribute:

<p>If you have any short comments, please let us know: <textarea cols=80 name=comments maxlength=200></textarea></p>

To give a default value, text can be included inside the element:

<p>If you have any comments, please let us know: <textarea cols=80 name=comments>You rock!</textarea></p>

You can also give a minimum length. Here, a letter needs to be filled out by the user; a template (which is shorter than the minimum length) is provided, but is insufficient to submit the form:

<textarea required minlength="500">Dear Madam Speaker,

Regarding your letter dated ...

...

Yours Sincerely,

...</textarea>

A placeholder can be given as well, to suggest the basic form to the user, without providing an explicit template:

<textarea placeholder="Dear Francine,

They closed the parks this week, so we won’t be able to
meet your there. Should we just have dinner?

Love,
Daddy"></textarea>

To have the browser submit the directionality of the element along with the value, the dirname attribute can be specified:

<p>If you have any comments, please let us know (you may use either English or Hebrew for your comments):
<textarea cols=80 name=comments dirname=comments.dir></textarea></p>

4.10.12. The keygen element

Categories:
Flow content.
Phrasing content.
Interactive content.
listed, labelable, submittable, resettable, and reassociateable form-associated element.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Nothing.
Tag omission in text/html:
No end tag.
Content attributes:
Global attributes
autofocus - Automatically focus the form control when the page is loaded
challenge - String to package with the generated and signed public key
disabled - Whether the form control is disabled
form - Associates the control with a form element
keytype - The type of cryptographic key to generate
name - Name of form control to use for §4.10.22 Form submission and in the form.elements API
Allowed ARIA role attribute values:
None
Allowed ARIA state and property attributes:
Global aria-* attributes
DOM interface:
interface HTMLKeygenElement : HTMLElement {
  attribute boolean autofocus;
  attribute DOMString challenge;
  attribute boolean disabled;
  readonly attribute HTMLFormElement? form;
  attribute DOMString keytype;
  attribute DOMString name;

  readonly attribute DOMString type;

  readonly attribute boolean willValidate;
  readonly attribute ValidityState validity;
  readonly attribute DOMString validationMessage;
  boolean checkValidity();
  boolean reportValidity();
  void setCustomValidity(DOMString error);

  [SameObject] readonly attribute NodeList labels;
};

This feature is in the process of being removed from the Web platform. (This is a long process that takes many years.) Using the keygen element at this time is highly discouraged.

The keygen element represents a key pair generator control. When the control’s form is submitted, the private key is stored in the local keystore, and the public key is packaged and sent to the server.

The challenge attribute may be specified. Its value will be packaged with the submitted key.

The keytype attribute is an enumerated attribute. The following table lists the keywords and states for the attribute — the keywords in the left column map to the states listed in the cell in the second column on the same row as the keyword. User agents are not required to support these values, and must only recognize values whose corresponding algorithms they support.

Keyword State
rsa RSA

The invalid value default state is the unknown state. The missing value default state is the RSA state, if it is supported, or the unknown state otherwise.

This specification does not specify what key types user agents are to support — it is possible for a user agent to not support any key types at all.

The user agent may expose a user interface for each keygen element to allow the user to configure settings of the element’s key pair generator, e.g., the key length.

The reset algorithm for keygen elements is to set these various configuration settings back to their defaults.

The element’s value is the string returned from the following algorithm:

  1. Use the appropriate step from the following list:

    If the keytype attribute is in the RSA state

    Generate an RSA key pair using the settings given by the user, if appropriate, using the md5WithRSAEncryption RSA signature algorithm (the signature algorithm with MD5 and the RSA encryption algorithm) referenced in section 2.2.1 ("RSA Signature Algorithm") of RFC 3279, and defined in RFC 3447. [RFC3279] [RFC3447]

    Otherwise, the keytype attribute is in the unknown state

    The given key type is not supported. Return the empty string and abort this algorithm.

    Let private key be the generated private key.

    Let public key be the generated public key.

    Let signature algorithm be the selected signature algorithm.

  2. If the element has a challenge attribute, then let challenge be that attribute’s value. Otherwise, let challenge be the empty string.

  3. Let algorithm be an ASN.1 AlgorithmIdentifier structure as defined by RFC 5280, with the algorithm field giving the ASN.1 OID used to identify signature algorithm, using the OIDs defined in section 2.2 ("Signature Algorithms") of RFC 3279, and the parameters field set up as required by RFC 3279 for AlgorithmIdentifier structures for that algorithm. [X690] [RFC5280] [RFC3279]

  4. Let spki be an ASN.1 SubjectPublicKeyInfo structure as defined by RFC 5280, with the algorithm field set to the algorithm structure from the previous step, and the subjectPublicKey field set to the BIT STRING value resulting from ASN.1 DER encoding the public key. [X690] [RFC5280]

  5. Let publicKeyAndChallenge be an ASN.1 PublicKeyAndChallenge structure as defined below, with the spki field set to the spki structure from the previous step, and the challenge field set to the string challenge obtained earlier. [X690]

  6. Let signature be the BIT STRING value resulting from ASN.1 DER encoding the signature generated by applying the signature algorithm to the byte string obtained by ASN.1 DER encoding the publicKeyAndChallenge structure, using private key as the signing key. [X690]

  7. Let signedPublicKeyAndChallenge be an ASN.1 SignedPublicKeyAndChallenge structure as defined below, with the publicKeyAndChallenge field set to the publicKeyAndChallenge structure, the signatureAlgorithm field set to the algorithm structure, and the signature field set to the BIT STRING signature from the previous step. [X690]

  8. Return the result of base64 encoding the result of ASN.1 DER encoding the signedPublicKeyAndChallenge structure. [RFC4648] [X690]

The data objects used by the above algorithm are defined as follows. These definitions use the same "ASN.1-like" syntax defined by RFC 5280. [RFC5280]

PublicKeyAndChallenge ::= SEQUENCE {
  spki SubjectPublicKeyInfo,
  challenge IA5STRING
}

SignedPublicKeyAndChallenge ::= SEQUENCE {
  publicKeyAndChallenge PublicKeyAndChallenge,
  signatureAlgorithm AlgorithmIdentifier,
  signature BIT STRING
}

Constraint validation: The keygen element is barred from constraint validation.

The form attribute is used to explicitly associate the keygen element with its form owner. The name attribute represents the element’s name. The disabled attribute is used to make the control non-interactive and to prevent its value from being submitted. The autofocus attribute controls focus.

keygen . type

Returns the string "keygen".

The challenge IDL attribute must reflect the content attribute of the same name.

The keytype IDL attribute must reflect the content attribute of the same name, limited to only known values.

The type IDL attribute must return the value "keygen".

The willValidate, validity, and validationMessage IDL attributes, and the checkValidity(), reportValidity(), and setCustomValidity() methods, are part of the constraint validation API. The labels IDL attribute provides a list of the element’s labels. The autofocus, disabled, form, and name IDL attributes are part of the element’s forms API.

This specification does not specify how the private key generated is to be used. It is expected that after receiving the SignedPublicKeyAndChallenge (SPKAC) structure, the server will generate a client certificate and offer it back to the user for download; this certificate, once downloaded and stored in the key store along with the private key, can then be used to authenticate to services that use TLS and certificate authentication. For more information, see e.g., this MDN article.

To generate a key pair, add the private key to the user’s key store, and submit the public key to the server, markup such as the following can be used:
<form action="processkey.cgi" method="post" enctype="multipart/form-data">
  <p><keygen name="key"></p>
  <p><input type=submit value="Submit key..."></p>
</form>

The server will then receive a form submission with a packaged RSA public key as the value of "key". This can then be used for various purposes, such as generating a client certificate, as mentioned above.

4.10.13. The output element

Categories:
Flow content.
Phrasing content.
listed, labelable, resettable, and reassociateable form-associated element.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Phrasing content.
Tag omission in text/html:
Neither tag is omissible
Content attributes:
Global attributes
for - Specifies controls from which the output was calculated
form - Associates the control with a form element
name - Name of form control to use for §4.10.22 Form submission and in the form.elements API
Allowed ARIA role attribute values:
status (default - do not set), Any role value.
Allowed ARIA state and property attributes:
Global aria-* attributes
Any aria-* attributes applicable to the allowed roles.
DOM interface:
interface HTMLOutputElement : HTMLElement {
  [SameObject, PutForwards=value] readonly attribute DOMTokenList htmlFor;
  readonly attribute HTMLFormElement? form;
  attribute DOMString name;

  readonly attribute DOMString type;
  attribute DOMString defaultValue;
  attribute DOMString value;

  readonly attribute boolean willValidate;
  readonly attribute ValidityState validity;
  readonly attribute DOMString validationMessage;
  boolean checkValidity();
  boolean reportValidity();
  void setCustomValidity(DOMString error);

  [SameObject] readonly attribute NodeList labels;
};

The output element represents the result of a calculation performed by the application, or the result of a user action.

This element can be contrasted with the samp element, which is the appropriate element for quoting the output of other programs run previously.

The for content attribute allows an explicit relationship to be made between the result of a calculation and the elements that represent the values that went into the calculation or that otherwise influenced the calculation. The for attribute, if specified, must contain a string consisting of an unordered set of unique space-separated tokens that are case-sensitive, each of which must have the value of an ID of an element in the same Document.

The form attribute is used to explicitly associate the output element with its form owner. The name attribute represents the element’s name. The output element is associated with a form so that it can be easily 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 value mode flag which is either value or default. Initially, the value mode flag must be set to default.

The element also has a default value. Initially, the default value must be the empty string.

When the value mode flag is in mode default, the contents of the element represent both the value of the element and its default value. When the value mode flag is in mode value, the contents of the element represent the value of the element only, and the default value is only accessible using the defaultValue IDL attribute.

Whenever the element’s descendants are changed in any way, if the value mode flag is in mode default, the element’s default value must be set to the value of the element’s textContent IDL attribute.

The reset algorithm for output elements is to set the element’s value mode flag to default and then to set the element’s textContent IDL attribute to the value of the element’s default value (thus replacing the element’s child nodes).

output . value [ = value ]

Returns the element’s current value.

Can be set, to change the value.

output . defaultValue [ = value ]

Returns the element’s current default value.

Can be set, to change the default value.

output . type

Returns the string "output".

The value IDL attribute must act like the element’s textContent IDL attribute, except that on setting, in addition, before the child nodes are changed, the element’s value mode flag must be set to value.

The defaultValue IDL attribute, on getting, must return the element’s default value. On setting, the attribute must set the element’s default value, and, if the element’s value mode flag is in the mode default, set the element’s textContent IDL attribute as well.

The type attribute must return the string "output".

The htmlFor IDL attribute must reflect the for content attribute.

The willValidate, validity, and validationMessage IDL attributes, and the checkValidity(), reportValidity(), and setCustomValidity() methods, are part of the constraint validation API. The labels IDL attribute provides a list of the element’s labels. The form and name IDL attributes are part of the element’s forms API.

A simple calculator could use output for its display of calculated results:
<form onsubmit="return false" oninput="o.value = a.valueAsNumber + b.valueAsNumber">
  <input name=a type=number step=any> +
  <input name=b type=number step=any> =
  <output name=o for="a b"></output>
</form>
In this example, an output element is used to report the results of a calculation performed by a remote server, as they come in:
<output id="result"></output>
<script>
  var primeSource = new WebSocket('ws://primes.example.net/');
  primeSource.onmessage = function (event) {
    document.getElementById('result').value = event.data;
  }
</script>

4.10.14. The progress element

Categories:
Flow content.
Phrasing content.
Labelable element.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Phrasing content, but there must be no progress element descendants.
Tag omission in text/html:
Neither tag is omissible
Content attributes:
Global attributes
value - Current value of the element
max - Upper bound of range
Allowed ARIA role attribute values:
progressbar (default - do not set).
Allowed ARIA state and property attributes:
Global aria-* attributes
Any aria-* attributes applicable to the allowed roles.
DOM interface:
interface HTMLProgressElement : HTMLElement {
  attribute double value;
  attribute double max;
  readonly attribute double position;
  [SameObject] readonly attribute NodeList labels;
};

The progress element represents the completion progress of a task. The progress is either indeterminate, indicating that progress is being made but that it is not clear how much more work remains to be done before the task is complete (e.g., because the task is waiting for a remote host to respond), or the progress is a number in the range zero to a maximum, giving the fraction of work that has so far been completed.

There are two attributes that determine the current task completion represented by the element. The value content attribute specifies how much of the task has been completed, and the max content attribute specifies how much work the task requires in total. The units are arbitrary and not specified.

To make a determinate progress bar, add a value attribute with the current progress (either a number from 0.0 to 1.0, or, if the max attribute is specified, a number from 0 to the value of the max attribute). To make an indeterminate progress bar, remove the value attribute.

Authors are encouraged to also include the current value and the maximum value inline as text inside the element, so that the progress is made available to users of legacy user agents.

Here is a snippet of a Web application that shows the progress of some automated task:
<section>
  <h2>Task Progress</h2>
  <p>Progress: <progress id="p" max=100><span>0</span>%</progress></p>
  <script>
  var progressBar = document.getElementById('p');
  function updateProgress(newValue) {
    progressBar.value = newValue;
    progressBar.getElementsByTagName('span')[0].textContent = newValue;
  }
  </script>
</section>

(The updateProgress() method in this example would be called by some other code on the page to update the actual progress bar as the task progressed.)

The value and max attributes, when present, must have values that are valid floating-point numbers. The value attribute, if present, must have a value equal to or greater than zero, and less than or equal to the value of the max attribute, if present, or 1.0, otherwise. The max attribute, if present, must have a value greater than zero.

The progress element is the wrong element to use for something that is just a gauge, as opposed to task progress. For instance, indicating disk space usage using progress would be inappropriate. Instead, the meter element is available for such use cases.

User agent requirements: If the 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 max attribute, the user agent must parse the max attribute’s value according to the 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 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 maximum value of the progress bar is 1.0.

If the progress bar is a determinate progress bar, user agents must parse the value attribute’s value according to the rules for parsing floating-point number values. If this does not result in an error, and if the parsed value is less than the maximum value and greater than zero, then the current value of the progress bar is that parsed value. Otherwise, if the parsed value was greater than or equal to the maximum value, then the current value of the progress bar is the maximum value of the progress bar. Otherwise, if parsing the value attribute’s value resulted in an error, or a number less than or equal to zero, then the current value of the progress bar is zero.

user agent requirements for showing the progress bar: When representing a progress element to the user, the user agent should indicate whether it is a determinate or indeterminate progress bar, and in the former case, should indicate the relative position of the current value relative to the maximum value.

progress . position

For a determinate progress bar (one with known current and maximum values), returns the result of dividing the current value by the maximum value.

For an indeterminate progress bar, returns -1.

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 current value by the 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 current value. On setting, the given value must be converted to the best representation of the number as a floating-point number and then the value content attribute must be set to that string.

Setting the 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 reflect the content attribute of the same name, limited to numbers greater than zero. The default value for max is 1.0.

The labels IDL attribute provides a list of the element’s labels.

4.10.15. The meter element

Categories:
Flow content.
Phrasing content.
Labelable element.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Phrasing content, but there must be no meter element descendants.
Tag omission in text/html:
Neither tag is omissible
Content attributes:
Global attributes
value - Current value of the element
min - Lower bound of range
max - Upper bound of range
low - High limit of low range
high - Low limit of high range
optimum - Optimum value in gauge
Allowed ARIA role attribute values:
None
Allowed ARIA state and property attributes:
Global aria-* attributes
DOM interface:
interface HTMLMeterElement : HTMLElement {
  attribute double value;
  attribute double min;
  attribute double max;
  attribute double low;
  attribute double high;
  attribute double optimum;
  [SameObject] readonly attribute NodeList labels;
};

The meter element represents a scalar measurement within a known range, or a fractional value; for example disk usage, the relevance of a query result, or the fraction of a voting population to have selected a particular candidate.

This is also known as a gauge.

The meter element should not be used to indicate progress (as in a progress bar). For that role, HTML provides a separate progress element.

The meter element also does not represent a scalar value of arbitrary range — for example, it would be wrong to use this to report a weight, or height, unless there is a known maximum value.

There are six attributes that determine the semantics of the gauge represented by the element.

The min attribute specifies the lower bound of the range, and the max attribute specifies the upper bound. The value attribute specifies the value to have the gauge indicate as the "measured" value.

The other three attributes can be used to segment the gauge’s range into "low", "medium", and "high" parts, and to indicate which part of the gauge is the "optimum" part. The low attribute specifies the range that is considered to be the "low" part, and the high attribute specifies the range that is considered to be the "high" part. The optimum attribute gives the position that is "optimum"; if that is higher than the "high" value then this indicates that the higher the value, the better; if it’s lower than the "low" mark then it indicates that lower values are better, and naturally if it is in between then it indicates that neither high nor low values are good.

Authoring requirements: The value attribute must be specified. The value, min, low, high, max, and optimum attributes, when present, must have values that are valid floating-point numbers.

In addition, the attributes' values are further constrained:

Let value be the value attribute’s number.

If the min attribute is specified, then let minimum be that attribute’s value; otherwise, let it be zero.

If the max attribute is specified, then let maximum be that attribute’s value; otherwise, let it be 1.0.

The following inequalities must hold, as applicable:

  • minimumvaluemaximum
  • minimumlowmaximum (if low is specified)
  • minimumhighmaximum (if high is specified)
  • minimumoptimummaximum (if optimum is specified)
  • lowhigh (if both low and high are specified)

If no minimum or maximum is specified, then the range is assumed to be 0..1, and the value thus has to be within that range.

Authors are encouraged to include a textual representation of the gauge’s state in the element’s contents, for users of user agents that do not support the meter element.

When used with microdata, the meter element’s value attribute provides the element’s machine-readable value.

The following examples show three gauges that would all be three-quarters full:
Storage space usage: <meter value=6 max=8>6 blocks used (out of 8 total)</meter>
Voter turnout: <meter value=0.75><img alt="75%" src="graph75.png"></meter>
Tickets sold: <meter min="0" max="100" value="75"></meter>

The following example is incorrect use of the element, because it doesn’t give a range (and since the default maximum is 1, both of the gauges would end up looking maxed out):

<p>The grapefruit pie had a radius of <meter value=12>12cm</meter>and a height of <meter value=2>2cm</meter>.</p> <!-- BAD! -->

Instead, one would either not include the meter element, or use the meter element with a defined range to give the dimensions in context compared to other pies:

<p>The grapefruit pie had a radius of 12cm and a height of
2cm.</p>
<dl>
  <dt>Radius: <dd> <meter min=0 max=20 value=12>12cm</meter>
  <dt>Height: <dd> <meter min=0 max=10 value=2>2cm</meter>
</dl>

There is no explicit way to specify units in the meter element, but the units may be specified in the title attribute in free-form text.

The example above could be extended to mention the units:
<dl>
  <dt>Radius: <dd> <meter min=0 max=20 value=12 title="centimeters">12cm</meter>
  <dt>Height: <dd> <meter min=0 max=10 value=2 title="centimeters">2cm</meter>
</dl>

User agent requirements: User agents must parse the min, max, value, low, high, and optimum attributes using the 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 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 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 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 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 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 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

user agent 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.

user agent requirements for showing the gauge: When representing a meter element to the user, the user agent 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.

User agents may combine the value of the title attribute and the other attributes to provide context-sensitive help or inline text detailing the actual values.

For example, the following snippet:
<meter min=0 max=60 value=23.2 title=seconds></meter>

...might cause the user agent to display a gauge with a tooltip saying "Value: 23.2 out of 60." on one line and "seconds" on a second line.

The value IDL attribute, on getting, must return the actual value. On setting, the given value must be converted to the best representation of the number as a floating-point number and then the value content attribute must be set to that string.

The min IDL attribute, on getting, must return the minimum value. On setting, the given value must be converted to the best representation of the number as a floating-point number and then the min content attribute must be set to that string.

The max IDL attribute, on getting, must return the maximum value. On setting, the given value must be converted to the best representation of the number as a floating-point number and then the max content attribute must be set to that string.

The low IDL attribute, on getting, must return the low boundary. On setting, the given value must be converted to the best representation of the number as a floating-point number and then the low content attribute must be set to that string.

The high IDL attribute, on getting, must return the high boundary. On setting, the given value must be converted to the best representation of the number as a floating-point number and then the high content attribute must be set to that string.

The optimum IDL attribute, on getting, must return the optimum value. On setting, the given value must be converted to the best representation of the number as a floating-point number and then the optimum content attribute must be set to that string.

The labels IDL attribute provides a list of the element’s labels.

The following example shows how a gauge could fall back to localized or pretty-printed text.
<p>Disk usage: <meter min=0 value=170261928 max=233257824>170 261 928 bytes used
out of 233 257 824 bytes available</meter></p>

4.10.16. The fieldset element

Categories:
Flow content.
Sectioning root.
listed and reassociateable form-associated element.
Palpable content.
Contexts in which this element can be used:
Where flow content is expected.
Content model:
Optionally a legend element, followed by flow content.
Tag omission in text/html:
Neither tag is omissible
Content attributes:
Global attributes
disabled - Whether the form control is disabled
form - Associates the control with a form element
name - Name of form control to use for §4.10.22 Form submission and in the form.elements API
Allowed ARIA role attribute values:
group (default - do not set) or presentation.
Allowed ARIA state and property attributes:
Global aria-* attributes
Any aria-* attributes applicable to the allowed roles.
DOM interface:
interface HTMLFieldSetElement : HTMLElement {
  attribute boolean disabled;
  readonly attribute HTMLFormElement? form;
  attribute DOMString name;

  readonly attribute DOMString type;

  [SameObject] readonly attribute HTMLCollection elements;

  readonly attribute boolean willValidate;
  [SameObject] readonly attribute ValidityState validity;
  readonly attribute DOMString validationMessage;
  boolean checkValidity();
  boolean reportValidity();
  void setCustomValidity(DOMString error);
};

The fieldset element represents a set of form controls optionally grouped under a common name.

The name of the group is given by the first legend element that is a child of the fieldset element, if any. The remainder of the descendants form the group.

The disabled attribute, when specified, causes all the form control descendants of the fieldset element, excluding those that are descendants of the fieldset element’s first legend element child, if any, to be disabled.

A fieldset element is a disabled fieldset if it matches any of the following conditions:

  • Its disabled attribute is specified
  • It is a descendant of another fieldset element whose disabled attribute is specified, and is not a descendant of that fieldset element’s first legend element child, if any.

The form attribute is used to explicitly associate the fieldset element with its form owner. The name attribute represents the element’s name.

fieldset . type

Returns the string "fieldset".

fieldset . elements

Returns an HTMLCollection of the form controls in the element.

The disabled IDL attribute must reflect the content attribute of the same name.

The type IDL attribute must return the string "fieldset".

The elements IDL attribute must return an HTMLCollection rooted at the fieldset element, whose filter matches listed elements.

The willValidate, validity, and validationMessage attributes, and the checkValidity(), reportValidity(), and setCustomValidity() methods, are part of the constraint validation API. The form and name IDL attributes are part of the element’s forms API.

This example shows a fieldset element being used to group a set of related controls:
<fieldset>
  <legend>Display</legend>
  <p><label><input type=radio name=c value=0 checked> Black on White</label>
  <p><label><input type=radio name=c value=1> White on Black</label>
  <p><label><input type=checkbox name=g> Use grayscale</label>
  <p><label>Enhance contrast <input type=range name=e list=contrast min=0 max=100 value=0 step=1></label>
  <datalist id=contrast>
  <option label=Normal value=0>
  <option label=Maximum value=100>
  </datalist>
</fieldset>
The following snippet shows a fieldset with a checkbox in the legend that controls whether or not the fieldset is enabled. The contents of the fieldset consist of two required text fields and an optional year/month control.
<fieldset name="clubfields" disabled>
  <legend> <label>
  <input type=checkbox name=club onchange="form.clubfields.disabled = !checked">
  Use Club Card
  </label> </legend>
  <p><label>Name on card: <input name=clubname required></label></p>
  <p><label>Card number: <input name=clubnum required pattern="[-0-9]+"></label></p>
  <p><label>Expiry date: <input name=clubexp type=month></label></p>
</fieldset>
You can also nest fieldset elements. Here is an example expanding on the previous one that does so:
<fieldset name="clubfields" disabled>
  <legend> <label>
  <input type=checkbox name=club onchange="form.clubfields.disabled = !checked">
  Use Club Card
  </label> </legend>
  <p><label>Name on card: <input name=clubname required></label></p>
  <fieldset name="numfields">
  <legend> <label>
    <input type=radio checked name=clubtype onchange="form.numfields.disabled = !checked">
    My card has numbers on it
  </label> </legend>
  <p><label>Card number: <input name=clubnum required pattern="[-0-9]+"></label></p>
  </fieldset>
  <fieldset name="letfields" disabled>
  <legend> <label>
    <input type=radio name=clubtype onchange="form.letfields.disabled = !checked">
    My card has letters on it
  </label> </legend>
  <p><label>Card code: <input name=clublet required pattern="[A-Za-z]+"></label></p>
  </fieldset>
</fieldset>

In this example, if the outer "Use Club Card" checkbox is not checked, everything inside the outer fieldset, including the two radio buttons in the legends of the two nested fieldsets, will be disabled. However, if the checkbox is checked, then the radio buttons will both be enabled and will let you select which of the two inner fieldsets is to be enabled.

4.10.17. The legend element

Categories:
None.
Contexts in which this element can be used:
As the first child of a fieldset element.
Content model:
Phrasing content.
Tag omission in text/html:
Neither tag is omissible
Content attributes:
Global attributes
Allowed ARIA role attribute values:
Any role value.
Allowed ARIA state and property attributes:
Global aria-* attributes
Any aria-* attributes applicable to the allowed roles.
DOM interface:
interface HTMLLegendElement : HTMLElement {
  readonly attribute HTMLFormElement? form;
};

The legend element represents a caption for the rest of the contents of the legend element’s parent fieldset element, if any.

legend . form

Returns the element’s form element, if any, or null otherwise.

The form IDL attribute’s behavior depends on whether the legend element is in a fieldset element or not. If the legend has a fieldset element as its parent, then the form IDL attribute must return the same value as the form IDL attribute on that fieldset element. Otherwise, it must return null.

4.10.18. Form control infrastructure

4.10.18.1. A form control value

Most form controls have a value and a checkedness. (The latter is only used by input elements.) These are used to describe how the user interacts with the control.

A control’s 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 a numeric field that expects digits, the user’s input would be the string "three" but the control’s value would remain unchanged. Or, if a user enters the email address "  awesome@example.com" (with leading whitespace) into 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 value of "awesome@example.com" (without the leading whitespace).

To define the behavior of constraint validation in the face of the input element’s multiple attribute, input elements can also have separately defined values.

The select element does not have a value; the selectedness of its option elements is what is used instead.

4.10.18.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 value or checkedness of a form control, or whether or not a control can be automatically prefilled.

4.10.18.3. Association of controls and forms

A form-associated element can have a relationship with a form element, which is called the element’s form owner. If a form-associated element is not associated with a form element, its form owner is said to be null.

A form-associated element is, by default, associated with its nearest ancestor form element (as described below), but, if it is reassociateable, may have a form attribute specified to override this.

This feature allows authors to work around the lack of support for nested form elements.

If a reassociateable form-associated element has a form attribute specified, then that attribute’s value must be the ID of a form element in the element’s owner Document.

The rules in this section are complicated by the fact that although conforming documents will never contain nested form elements, it is quite possible (e.g., using a script that performs DOM manipulation) to generate documents that have such nested elements. They are also complicated by rules in the HTML parser that, for historical reasons, can result in a form-associated element being associated with a form element that is not its ancestor.

When a form-associated element is created, its form owner must be initialized to null (no owner).

When a form-associated element is to be associated with a form, its form owner must be set to that form.

When a form-associated element or one of its ancestors is inserted into a Document, then the user agent must reset the form owner of that form-associated element. The HTML parser overrides this requirement when inserting form controls.

When an element changes its parent node resulting in a form-associated element and its form owner (if any) no longer being in the same home subtree, then the user agent must reset the form owner of that form-associated element.

When a reassociateable form-associated element’s form attribute is set, changed, or removed, then the user agent must reset the form owner of that element.

When a reassociateable form-associated element has a form attribute and the ID of any of the elements in the Document changes, then the user agent must reset the form owner of that form-associated element.

When a reassociateable form-associated element has a form attribute and an element with an ID is inserted into or removed from the Document, then the user agent must reset the form owner of that form-associated element.

When the user agent is to reset the form owner of a form-associated element, it must run the following steps:

  1. If the element’s form owner is not null, and either the element is not reassociateable or its form content attribute is not present, and the element’s form owner is its nearest form element ancestor after the change to the ancestor chain, then do nothing, and abort these steps.
  2. Let the element’s form owner be null.
  3. If the element is reassociateable, has a form content attribute, and is itself in a Document, then run these substeps:

    1. If the first element in the Document to have an ID that is case-sensitively equal to the element’s form content attribute’s value is a form element, then associate the form-associated element with that form element.
    2. Abort the "reset the form owner" steps.
  4. Otherwise, if the form-associated element in question has an ancestor form element, then associate the form-associated element with the nearest such ancestor form element.
  5. Otherwise, the element is left unassociated.
In the following non-conforming snippet:
...  <form id="a">
  <div id="b"></div>
  </form>
  <script>
  document.getElementById('b').innerHTML =
      '<table><tr><td><form id="c"><input id="d"></table>' +
      '<input id="e">';
  </script>
...

The form owner of "d" would be the inner nested form "c", while the form owner of "e" would be the outer form "a".

This happens as follows: First, the "e" node gets associated with "c" in the HTML parser. Then, the 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 form elements.

element . form
Returns the element’s form owner.

Returns null if there isn’t one.

Reassociateable form-associated elements have a form IDL attribute, which, on getting, must return the element’s form owner, or null if there isn’t one.

4.10.19. Attributes common to form controls

4.10.19.1. Naming form controls: the name attribute

The name content attribute gives the name of the form control, as used in §4.10.22 Form submission and in the form element’s elements object. If the attribute is specified, its value must not be the empty string.

Any non-empty value for name is allowed, but the name "_charset_" is special:

_charset_

This value, if used as the name of a Hidden control with no value attribute, is automatically given a value during submission consisting of the submission character encoding.

The name IDL attribute must reflect the name content attribute.

4.10.19.2. Submitting element directionality: the dirname attribute

The dirname attribute on a form control element enables the submission of the directionality of the element, and gives the name of the field that contains this value during §4.10.22 Form submission. If such an attribute is specified, its value must not be the empty string.

In this example, a form contains a text field and a submission button:
<form action="addcomment.cgi" method=post>
  <p><label>Comment: <input type=text name="comment" dirname="comment.dir" required></label></p>
  <p><button name="mode" type=submit value="add">Post Comment</button></p>
</form>

When the user submits the form, the user agent includes three fields, one called "comment", one called "comment.dir", and one called "mode"; so if the user types "Hello", the submission body might be something like:

comment=Hello&comment.dir=ltr&mode=add

If the user manually switches to a right-to-left writing direction and enters "مرحبا", the submission body might be something like:

comment=%D9%85%D8%B1%D8%AD%D8%A8%D8%A7&comment.dir=rtl&mode=add
4.10.19.3. Limiting user input length: the maxlength attribute

A form control maxlength attribute, controlled by a dirty value flag, declares a limit on the number of characters a user can input.

If an element has its form control maxlength attribute specified, the attribute’s value must be a valid non-negative integer. If the attribute is specified and applying the rules for parsing non-negative integers to its value results in a number, then that number is the element’s maximum allowed value length. If the attribute is omitted or parsing its value results in an error, then there is no maximum allowed value length.

Constraint validation: If an element has a maximum allowed value length, its dirty value flag is true, its value was last changed by a user edit (as opposed to a change made by a script), and the code-unit length of the element’s value is greater than the element’s maximum allowed value length, then the element is suffering from being too long.

User agents may prevent the user from causing the element’s value to be set to a value whose code-unit length is greater than the element’s maximum allowed value length.

In the case of textarea elements, this is the value, not the raw value, so the textarea wrapping transformation is applied before the maximum allowed value length is checked.

4.10.19.4. Setting minimum input length requirements: the minlength attribute

A form control minlength attribute, controlled by a dirty value flag, declares a lower bound on the number of characters a user can input.

The minlength attribute does not imply the required attribute. If the form control has no required attribute, then the value can still be omitted; the minlength attribute only kicks in once the user has entered a value at all. If the empty string is not allowed, then the required attribute also needs to be set.

If an element has its form control minlength attribute specified, the attribute’s value must be a valid non-negative integer. If the attribute is specified and applying the rules for parsing non-negative integers to its value results in a number, then that number is the element’s minimum allowed value length. If the attribute is omitted or parsing its value results in an error, then there is no minimum allowed value length.

If an element has both a maximum allowed value length and a minimum allowed value length, the minimum allowed value length must be smaller than or equal to the maximum allowed value length.

Constraint validation: If an element has a minimum allowed value length, its dirty value flag is true, its value was last changed by a user edit (as opposed to a change made by a script), its value is not the empty string, and the code-unit length of the element’s value is less than the element’s minimum allowed value length, then the element is suffering from being too short.

In this example, there are four text fields. The first is required, and has to be at least 5 characters long. The other three are optional, but if the user fills one in, the user has to enter at least 10 characters.
<form action="/events/menu.cgi" method="post">
  <p><label>Name of Event: <input required minlength=5 maxlength=50 name=event></label></p>
  <p><label>Describe what you would like for breakfast, if anything:
    <textarea name="breakfast" minlength="10"></textarea></label></p>
  <p><label>Describe what you would like for lunch, if anything:
    <textarea name="lunch" minlength="10"></textarea></label></p>
  <p><label>Describe what you would like for dinner, if anything:
    <textarea name="dinner" minlength="10"></textarea></label></p>
  <p><input type=submit value="Submit Request"></p>
</form>
4.10.19.5. Enabling and disabling form controls: the disabled attribute

The disabled content attribute is a boolean attribute.

A form control is disabled if any of the following conditions are met:

  1. The element is a button, input, select, or textarea element, and the disabled attribute is specified on this element (regardless of its value).
  2. The element is a descendant of a fieldset element whose disabled attribute is specified, and is not a descendant of that fieldset element’s first legend element child, if any.

A form control that is disabled must prevent any click events that are queued on the user interaction task source from being dispatched on the element.

Constraint validation: If an element is disabled, it is barred from constraint validation.

The disabled IDL attribute must reflect the disabled content attribute.

4.10.19.6. Form submission

Attributes for form submission can be specified both on form elements and on submit buttons (elements that represent buttons that submit forms, e.g., an input element whose type attribute is in the submit button state).

The attributes for form submission that may be specified on form elements are action, enctype, method, novalidate, and target.

The corresponding attributes for form submission that may be specified on submit buttons are formaction, formenctype, formmethod, formnovalidate, and formtarget. When omitted, they default to the values given on the corresponding attributes on the form element.


The action and formaction content attributes, if specified, must have a value that is a valid non-empty URL potentially surrounded by spaces.

The action of an element is the value of the element’s formaction attribute, if the element is a submit button and has such an attribute, or the value of its form owner’s action attribute, if it has one, or else the empty string.


The method and formmethod content attributes are enumerated attributes with the following keywords and states:

  • The keyword get, mapping to the state GET, indicating the HTTP GET method.
  • The keyword post, mapping to the state POST, indicating the HTTP POST method.

The invalid value default for these attributes is the GET state. The missing value default for the method attribute is also the GET state. (There is no missing value default for the formmethod attribute.)

The method of an element is one of those states. If the element is a submit button and has a formmethod attribute, then the element’s method is that attribute’s state; otherwise, it is the form owner’s method attribute’s state.

Here the method attribute is used to explicitly specify the default value, "get", so that the search query is submitted in the URL:
<form method="get" action="/search.cgi">
  <p><label>Search terms: <input type=search name=q></label></p>
  <p><input type=submit></p>
</form>
On the other hand, here the method attribute is used to specify the value "post", so that the user’s message is submitted in the HTTP request’s body:
<form method="post" action="/post-message.cgi">
  <p><label>Message: <input type=text name=m></label></p>
  <p><input type=submit value="Submit message"></p>
</form>

The enctype and formenctype content attributes are enumerated attributes with the following keywords and states:

  • The "application/x-www-form-urlencoded" keyword and corresponding state.
  • The "multipart/form-data" keyword and corresponding state.
  • The "text/plain" keyword and corresponding state.

The invalid value default for these attributes is the application/x-www-form-urlencoded state. The missing value default for the enctype attribute is also the application/x-www-form-urlencoded state. (There is no missing value default for the formenctype attribute.)

The enctype of an element is one of those three states. If the element is a submit button and has a formenctype attribute, then the element’s enctype is that attribute’s state; otherwise, it is the form owner’s enctype attribute’s state.


The target and formtarget content attributes, if specified, must have values that are valid browsing context names or keywords.

The target of an element is the value of the element’s formtarget attribute, if the element is a submit button and has such an attribute; or the value of its form owner’s target attribute, if it has such an attribute; or, if the Document contains a base element with a target attribute, then the value of the target attribute of the first such base element; or, if there is no such element, the empty string.


The novalidate and formnovalidate content attributes are boolean attributes. If present, they indicate that the form is not to be validated during submission.

The no-validate state of an element is true if the element is a submit button and the element’s formnovalidate attribute is present, or if the element’s form owner’s novalidate attribute is present, and false otherwise.

This attribute is useful to include "save" buttons on forms that have validation constraints, to allow users to save their progress even though they haven’t fully entered the data in the form. The following example shows a simple form that has two required fields. There are three buttons: one to submit the form, which requires both fields to be filled in; one to save the form so that the user can come back and fill it in later; and one to cancel the form altogether.
<form action="editor.cgi" method="post">
  <p><label>Name: <input required name=fn></label></p>
  <p><label>Essay: <textarea required name=essay></textarea></label></p>
  <p><input type=submit name=submit value="Submit essay"></p>
  <p><input type=submit formnovalidate name=save value="Save essay"></p>
  <p><input type=submit formnovalidate name=cancel value="Cancel"></p>
</form>

The action IDL attribute must 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 document’s address must be returned instead.

The target IDL attribute must reflect the content attribute of the same name.

The method and enctype IDL attributes must reflect the respective content attributes of the same name, limited to only known values.

The encoding IDL attribute must reflect the enctype content attribute, limited to only known values.

The noValidate IDL attribute must reflect the novalidate content attribute.

The formAction IDL attribute must reflect the formaction content attribute, except that on getting, when the content attribute is missing or its value is the empty string, the document’s address must be returned instead.

The formEnctype IDL attribute must reflect the formenctype content attribute, limited to only known values.

The formMethod IDL attribute must reflect the formmethod content attribute, limited to only known values.

The formNoValidate IDL attribute must reflect the formnovalidate content attribute.

The formTarget IDL attribute must reflect the formtarget content attribute.

4.10.19.6.1. Autofocusing a form control: the autofocus attribute

The autofocus content attribute allows the author to indicate that a control is to be focused as soon as the page is loaded, allowing the user to just start typing without having to manually focus the main control.

The autofocus attribute is a boolean attribute.

An element’s nearest ancestor autofocus scoping root element is the element itself if it is the element’s root element.

There must not be two elements with the same nearest ancestor autofocus scoping root element that both have the autofocus attribute specified.

When an element with the autofocus attribute specified is inserted into a document, user agents should run the following steps:

  1. Let target be the element’s node document.
  2. If target has no browsing context, abort these steps.
  3. If target’s browsing context has no top-level browsing context (e.g., it is a nested browsing context with no parent browsing context), abort these steps.
  4. If target’s active sandboxing flag set has the sandboxed automatic features browsing context flag, abort these steps.
  5. If target’s origin is not the same as the origin of the node document of the currently focused element in target’s top-level browsing context, abort these steps.
  6. If target’s origin is not the same as the origin of the active document of target’s top-level browsing context, abort these steps.
  7. If the user agent has already reached the last step of this list of steps in response to an element being inserted into a Document whose top-level browsing context’s active document is the same as target’s top-level browsing context’s active document, abort these steps.
  8. If the user has indicated (for example, by starting to type in a form control) that he does not wish focus to be changed, then optionally abort these steps.
  9. Queue a task that runs the focusing steps for the element. User agents may also change the scrolling position of the document, or perform some other action that brings the element to the user’s attention. The task source for this task is the user interaction task source.

Focusing the control does not imply that the user agent must focus the browser window if it has lost focus.

The autofocus IDL attribute must reflect the content attribute of the same name.

In the following snippet, the text control would be focused when the document was loaded.
<input maxlength="256" name="q" value="" autofocus>
<input type="submit" value="Search">
4.10.19.7. Input modalities: the inputmode attribute

The inputmode content attribute is an enumerated attribute that specifies what kind of input mechanism would be most helpful for users entering content into the form control.

User agents must recognize all the keywords and corresponding states given below, but need not support all of the corresponding states. If a keyword’s state is not supported, the user agent must act as if the keyword instead mapped to the given state’s fallback state, as defined below. This fallback behavior is transitive.

For example, if a user agent with a QWERTY keyboard layout does not support text prediction and automatic capitalization, then it could treat the latin-prose keyword in the same way as the verbatim keyword, following the chain Latin ProseLatin TextLatin Verbatim.

The possible keywords and states for the attributes are listed in the following table. The keywords are listed in the first column. Each maps to the state given in the cell in the second column of that keyword’s row, and that state has the fallback state given in the cell in the third column of that row.

Keyword State Fallback state Description
verbatim Latin Verbatim Default Alphanumeric Latin-script input of non-prose content, e.g., usernames, passwords, product codes.
latin Latin Text Latin Verbatim Latin-script input in the user’s preferred language(s), with some typing aids enabled (e.g., text prediction). Intended for human-to-computer communications, e.g., free-form text search fields.
latin-name Latin Name Latin Text Latin-script input in the user’s preferred language(s), with typing aids intended for entering human names enabled (e.g., text prediction from the user’s contact list and automatic capitalization at every word). Intended for situations such as customer name fields.
latin-prose Latin Prose Latin Text Latin-script input in the user’s preferred language(s), with aggressive typing aids intended for human-to-human communications enabled (e.g., text prediction and automatic capitalization at the start of sentences). Intended for situations such as e-mails and instant messaging.
full-width-latin Full-width Latin Latin Prose Latin-script input in the user’s secondary language(s), using full-width characters, with aggressive typing aids intended for human-to-human communications enabled (e.g., text prediction and automatic capitalization at the start of sentences). Intended for latin text embedded inside CJK text.
kana Kana Default Kana or romaji input, typically hiragana input, using full-width characters, with support for converting to kanji. Intended for Japanese text input.
kana-name Kana Name Kana Kana or romaji input, typically hiragana input, using full-width characters, with support for converting to kanji, and with typing aids intended for entering human names enabled (e.g., text prediction from the user’s contact list). Intended for situations such as customer name fields.
katakana Katakana Kana Katakana input, using full-width characters, with support for converting to kanji. Intended for Japanese text input.
numeric Numeric Default Numeric input, including keys for the digits 0 to 9, the user’s preferred thousands separator character, and the character for indicating negative numbers. Intended for numeric codes, e.g., credit card numbers. (For numbers, prefer "<input type=number>".)
tel Telephone Numeric Telephone number input, including keys for the digits 0 to 9, the "#" character, and the "*" character. In some locales, this can also include alphabetic mnemonic labels (e.g., in the US, the key labeled "2" is historically also labeled with the letters A, B, and C). Rarely necessary; use "<input type=tel>" instead.
email E-mail Default Text input in the user’s locale, with keys for aiding in the input of e-mail addresses, such as that for the "@" character and the "." character. Rarely necessary; use "<input type=email>" instead.
url URL Default Text input in the user’s locale, with keys for aiding in the input of Web addresses, such as that for the "/" and "." characters and for quick input of strings commonly found in domain names such as "www." or ".co.uk". Rarely necessary; use "<input type=url>" instead.

The last three keywords listed above are only provided for completeness, and are rarely necessary, as dedicated input controls exist for their usual use cases (as described in the table above).

User agents must all support the Default input mode state, which corresponds to the user agent’s default input modality. This specification does not define how the user agent’s default modality is to operate. The missing value default is the Default input mode state.

User agents should use the input modality corresponding to the state of the inputmode attribute when exposing a user interface for editing the value of a form control to which the attribute applies. An input modality corresponding to a state is one designed to fit the description of the state in the table above. This value can change dynamically; user agents should update their interface as the attribute changes state, unless that would go against the user’s wishes.

4.10.19.8. Autofill
4.10.19.8.1. Autofilling form controls: the autocomplete attribute

User agents sometimes have features for helping users fill forms in, for example prefilling the user’s address based on earlier user input. The autocomplete content attribute can be used to hint to the user agent how to, or indeed whether to, provide such a feature.

There are two ways this attribute is used. When wearing the autofill expectation mantle, the autocomplete attribute describes what input is expected from users. When wearing the autofill anchor mantle, the autocomplete attribute describes the meaning of the given value.

On an input element whose type attribute is in the Hidden state, the autocomplete attribute wears the autofill anchor mantle. In all other cases, it wears the autofill expectation mantle.

When wearing the autofill expectation mantle, the autocomplete attribute, if specified, must have a value that is an ordered set of space-separated tokens consisting of either a single token that is an ASCII case-insensitive match for the string "off", or a single token that is an ASCII case-insensitive match for the string "on", or autofill detail tokens.

When wearing the autofill anchor mantle, the autocomplete attribute, if specified, must have a value that is an ordered set of space-separated tokens consisting of just autofill detail tokens (i.e., the "on" and "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 ASCII case-insensitive match for the string "section-", meaning that the field belongs to the named group.

    For example, if there are two shipping addresses in the form, then they could be marked up as:
    <fieldset>
      <legend>Ship the blue gift to...</legend>
      <p> <label> Address:     <input name=ba autocomplete="section-blue shipping street-address"> </label>
      <p> <label> City:        <input name=bc autocomplete="section-blue shipping address-level2"> </label>
      <p> <label> Postal Code: <input name=bp autocomplete="section-blue shipping postal-code"> </label>
    </fieldset>
    <fieldset>
      <legend>Ship the red gift to...</legend>
      <p> <label> Address:     <input name=ra autocomplete="section-red shipping street-address"> </label>
      <p> <label> City:        <input name=rc autocomplete="section-red shipping address-level2"> </label>
      <p> <label> Postal Code: <input name=rp autocomplete="section-red shipping postal-code"> </label>
    </fieldset>
    
  2. Optionally, a token that is an ASCII case-insensitive match for one of the following strings:

    • "shipping", meaning the field is part of the shipping address or contact information
    • "billing", meaning the field is part of the billing address or contact information
  3. Either of the following two options:

    • A token that is an ASCII case-insensitive match for one of the following autofill field names, excluding those that are inappropriate for the control:

      • "name"
      • "honorific-prefix"
      • "given-name"
      • "additional-name"
      • "family-name"
      • "honorific-suffix"
      • "nickname"
      • "username"
      • "new-password"
      • "current-password"
      • "organization-title"
      • "organization"
      • "street-address"
      • "address-line1"
      • "address-line2"
      • "address-line3"
      • "address-level4"
      • "address-level3"
      • "address-level2"
      • "address-level1"
      • "country"
      • "country-name"
      • "postal-code"
      • "cc-name"
      • "cc-given-name"
      • "cc-additional-name"
      • "cc-family-name"
      • "cc-number"
      • "cc-exp"
      • "cc-exp-month"
      • "cc-exp-year"
      • "cc-csc"
      • "cc-type"
      • "transaction-currency"
      • "transaction-amount"
      • "language"
      • "bday"
      • "bday-day"
      • "bday-month"
      • "bday-year"
      • "sex"
      • "url"
      • "photo"

      (See the table below for descriptions of these values.)

    • The following, in the given order:

      1. Optionally, a token that is an ASCII case-insensitive match for one of the following strings:

        • "home", meaning the field is for contacting someone at their residence
        • "work", meaning the field is for contacting someone at their workplace
        • "mobile", meaning the field is for contacting someone regardless of location
        • "fax", meaning the field describes a fax machine’s contact details
        • "pager", meaning the field describes a pager’s or beeper’s contact details
      2. A token that is an ASCII case-insensitive match for one of the following autofill field names, excluding those that are inappropriate for the control:

        • "tel"
        • "tel-country-code"
        • "tel-national"
        • "tel-area-code"
        • "tel-local"
        • "tel-local-prefix"
        • "tel-local-suffix"
        • "tel-extension"
        • "email"
        • "impp"

        (See the table below for descriptions of these values.)

As noted earlier, the meaning of the attribute and its keywords depends on the mantle that the attribute is wearing.

When wearing the 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 user agent to prefill the value for him; or that the document provides its own autocomplete mechanism and does not want the user agent to provide autocompletion values.

The "on" keyword indicates that the user agent is allowed to provide the user with autocompletion values, but does not provide any further information about what kind of data the user might be expected to enter. User agents would have to use heuristics to decide what autocompletion values to suggest.

The autofill 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 autocomplete attribute is omitted, the default value corresponding to the state of the element’s form owner’s autocomplete attribute is used instead (either "on" or "off"). If there is no form owner, then the value "on" is used.

When wearing the autofill anchor mantle...

The 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.
<form method=post action="step2.cgi">
  <input type=hidden autocomplete=transaction-currency value="CHF">
  <input type=hidden autocomplete=transaction-amount value="15.00">
  <p><label>Credit card number: <input type=text inputmode=numeric autocomplete=cc-number></label>
  <p><label>Expiry Date: <input type=month autocomplete=cc-exp></label>
  <p><input type=submit value="Continue...">
</form>

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 ("cc-exp"), or as two fields, one giving the month ("cc-exp-month") and one the year ("cc-exp-year"). In such cases, the names of the broader fields cover multiple rows, in which the narrower fields are defined.

Generally, authors are encouraged to use the broader fields rather than the narrower fields, as the narrower fields tend to expose Western biases. For example, while it is common in some Western cultures to have a given name and a family name, in that order (and thus often referred to as a first name and a surname), many cultures put the family name first and the given name second, and many others simply have one name (a mononym). Having a single field is therefore more flexible.

Some fields are only appropriate for certain form controls. An autofill field name is inappropriate for a control if the control does not belong to the group listed for that autofill field in the fifth column of the first row describing that 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 Text
"honorific-prefix" Prefix or title (e.g., "Mr.", "Ms.", "Dr.", "Mlle") Free-form text, no newlines Sir Text
"given-name" Given name (in some Western cultures, also known as the first name) Free-form text, no newlines Timothy 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 Text
"family-name" Family name (in some Western cultures, also known as the last name or surname) Free-form text, no newlines Berners-Lee Text
"honorific-suffix" Suffix (e.g., "Jr.", "B.Sc.", "MBASW", "II") Free-form text, no newlines OM, KBE, FRS, FREng, FRSA Text
"nickname" Nickname, screen name, handle: a typically short name used instead of the full name Free-form text, no newlines Tim Text
"organization-title" Job title (e.g., "Software Engineer", "Senior Vice President", "Deputy Managing Director") Free-form text, no newlines Professor Text
"username" A username Free-form text, no newlines timbl Text
"new-password" A new password (e.g., when creating an account or changing a password) Free-form text, no newlines GUMFXbadyrS3 Password
"current-password" The current password for the account identified by the username field (e.g., when logging in) Free-form text, no newlines qwerty 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 Text
"street-address" Street address (multiple lines, newlines preserved) Free-form text 32 Vassar Street
MIT Room 32-G524
Multiline
"address-line1" Street address (one line per field) Free-form text, no newlines 32 Vassar Street Text
"address-line2" Free-form text, no newlines MIT Room 32-G524 Text
"address-line3" Free-form text, no newlines Text
"address-level4" The most fine-grained administrative level, in addresses with four administrative levels Free-form text, no newlines Text
"address-level3" The third administrative level, in addresses with three or more administrative levels Free-form text, no newlines Text
"address-level2" The 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 Text
"address-level1" The broadest 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 Text
"country" Country code Valid ISO 3166-1-alpha-2 country code [ISO3166] US Text
"country-name" Country name Free-form text, no newlines; derived from country in some cases US Text
"postal-code" Postal code, post code, ZIP code, CEDEX code (if CEDEX, append "CEDEX", and the dissement, if relevant, to the address-level2 field) Free-form text, no newlines 02139 Text
"cc-name" Full name as given on the payment instrument Free-form text, no newlines Tim Berners-Lee 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 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 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 Text
"cc-number" Code identifying the payment instrument (e.g., the credit card number) ASCII digits 4114360123456785 Text
"cc-exp" Expiration date of the payment instrument Valid month string 2014-12 Month
"cc-exp-month" Month component of the expiration date of the payment instrument valid integer in the range 1..12 12 Numeric
"cc-exp-year" Year component of the expiration date of the payment instrument valid integer greater than zero 2014 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) ASCII digits 419 Text
"cc-type" Type of payment instrument Free-form text, no newlines Visa Text
"transaction-currency" The currency that the user would prefer the transaction to use ISO 4217 currency code [ISO4217] GBP Text
"transaction-amount" The amount that the user would like for the transaction (e.g., when entering a bid or sale price) Valid floating-point number 401.00 Numeric
"language" Preferred language Valid BCP 47 language tag [BCP47] en Text
"bday" Birthday Valid date string 1955-06-08 Date
"bday-day" Day component of birthday valid integer in the range 1..31 8 Numeric
"bday-month" Month component of birthday valid integer in the range 1..12 6 Numeric
"bday-year" Year component of birthday valid integer greater than zero 1955 Numeric
"sex" Gender identity (e.g., Female, Fa’afafine) Free-form text, no newlines Male 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 Valid URL https://www.w3.org/People/Berners-Lee/ URL
"photo" Photograph, icon, or other image corresponding to the company, person, address, or contact information in the other fields associated with this field Valid URL https://www.w3.org/Press/Stock/Berners-Lee/2001-europaeum-eighth.jpg URL
"tel" Full telephone number, including country code ASCII digits and U+0020 SPACE characters, prefixed by a U+002B PLUS SIGN character (+) +1 617 253 5702 Tel
"tel-country-code" Country code component of the telephone number ASCII digits prefixed by a U+002B PLUS SIGN character (+) +1 Text
"tel-national" Telephone number without the county code component, with a country-internal prefix applied if applicable ASCII digits and U+0020 SPACE characters 617 253 5702 Text
"tel-area-code" Area code component of the telephone number, with a country-internal prefix applied if applicable ASCII digits 617 Text
"tel-local" Telephone number without the country code and area code components ASCII digits 2535702 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 ASCII digits 253 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 ASCII digits 5702 Text
"tel-extension" Telephone number internal extension code ASCII digits 1000 Text
"email" E-mail address Valid e-mail address timbl@w3.org E-mail
"impp" URL representing an instant messaging protocol endpoint (for example, "aim:goim?screenname=example" or "xmpp:fred@example.net") Valid URL irc://example.org/timbl,isuser URL

The groups correspond to controls as follows:

Text
input elements with a type attribute in the Hidden state
input elements with a type attribute in the Text state
input elements with a type attribute in the Search state
textarea elements
select elements
Multiline
input elements with a type attribute in the Hidden state
textarea elements
select elements
Password
input elements with a type attribute in the Hidden state
input elements with a type attribute in the Text state
input elements with a type attribute in the Search state
input elements with a type attribute in the Password state
textarea elements
select elements
URL
input elements with a type attribute in the Hidden state
input elements with a type attribute in the Text state
input elements with a type attribute in the Search state
input elements with a type attribute in the URL state
textarea elements
select elements
E-mail
input elements with a type attribute in the Hidden state
input elements with a type attribute in the Text state
input elements with a type attribute in the Search state
input elements with a type attribute in the E-mail state
textarea elements
select elements
Tel
input elements with a type attribute in the Hidden state
input elements with a type attribute in the Text state
input elements with a type attribute in the Search state
input elements with a type attribute in the Telephone state
textarea elements
select elements
Numeric
input elements with a type attribute in the Hidden state
input elements with a type attribute in the Text state
input elements with a type attribute in the Search state
input elements with a type attribute in the Number state
textarea elements
select elements
Month
input elements with a type attribute in the Hidden state
input elements with a type attribute in the Text state
input elements with a type attribute in the Search state
input elements with a type attribute in the Month state
textarea elements
select elements
Date
input elements with a type attribute in the Hidden state
input elements with a type attribute in the Text state
input elements with a type attribute in the Search state
input elements with a type attribute in the Date state
textarea elements
select elements

Address levels: The "address-level1" – "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 "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.19.8.2. Processing model

Each input element to which the autocomplete attribute applies, each select element, and each textarea element, has an autofill hint set, an autofill scope, an autofill field name, and an IDL-exposed autofill value.

The autofill field name specifies the specific kind of data expected in the field, e.g., "street-address" or "cc-exp".

The autofill hint set identifies what address or contact information type the user agent is to look at, e.g., "shipping fax" or "billing".

The autofill scope identifies the group of fields that are to be filled with the information from the same source, and consists of the 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 autocomplete attribute, then jump to the step labeled default.
  2. Let tokens be the result of splitting the attribute’s value on spaces.
  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. If the indexth token in tokens is not an ASCII case-insensitive match for one of the tokens given in the first column of the following table, or if the number of tokens in tokens is greater than the maximum number given in the cell in the second column of that token’s row, then jump to the step labeled default. Otherwise, let field be the string given in the cell of the first column of the matching row, and let category be the value of the cell in the third column of that same row.

    Token Maximum number of tokens Category
    "off" 1 Off
    "on" 1 Automatic
    "name" 3 Normal
    "honorific-prefix" 3 Normal
    "given-name" 3 Normal
    "additional-name" 3 Normal
    "family-name" 3 Normal
    "honorific-suffix" 3 Normal
    "nickname" 3 Normal
    "organization-title" 3 Normal
    "username" 3 Normal
    "new-password" 3 Normal
    "current-password" 3 Normal
    "organization" 3 Normal
    "street-address" 3 Normal
    "address-line1" 3 Normal
    "address-line2" 3 Normal
    "address-line3" 3 Normal
    "address-level4" 3 Normal
    "address-level3" 3 Normal
    "address-level2" 3 Normal
    "address-level1" 3 Normal
    "country" 3 Normal
    "country-name" 3 Normal
    "postal-code" 3 Normal
    "cc-name" 3 Normal
    "cc-given-name" 3 Normal
    "cc-additional-name" 3 Normal
    "cc-family-name" 3 Normal
    "cc-number" 3 Normal
    "cc-exp" 3 Normal
    "cc-exp-month" 3 Normal
    "cc-exp-year" 3 Normal
    "cc-csc" 3 Normal
    "cc-type" 3 Normal
    "transaction-currency" 3 Normal
    "transaction-amount" 3 Normal
    "language" 3 Normal
    "bday" 3 Normal
    "bday-day" 3 Normal
    "bday-month" 3 Normal
    "bday-year" 3 Normal
    "sex" 3 Normal
    "url" 3 Normal
    "photo" 3 Normal
    "tel" 4 Contact
    "tel-country-code" 4 Contact
    "tel-national" 4 Contact
    "tel-area-code" 4 Contact
    "tel-local" 4 Contact
    "tel-local-prefix" 4 Contact
    "tel-local-suffix" 4 Contact
    "tel-extension" 4 Contact
    "email" 4 Contact
    "impp" 4 Contact
  6. If category is Off or Automatic but the element’s autocomplete attribute is wearing the autofill anchor mantle, then jump to the step labeled default.
  7. If category is Off, let the element’s autofill field name be the string "off", let its autofill hint set be empty, and let its IDL-exposed autofill value be the string "off". Then, abort these steps.
  8. If category is Automatic, let the element’s autofill field name be the string "on", let its autofill hint set be empty, and let its IDL-exposed autofill value be the string "on". Then, abort these steps.
  9. Let scope tokens be an empty list.
  10. Let hint tokens be an empty set.
  11. Let IDL value have the same value as field.
  12. If the indexth token in tokens is the first entry, then skip to the step labeled done.
  13. Decrement index by one.
  14. If category is Contact and the indexth token in tokens is an ASCII case-insensitive match for one of the strings in the following list, then run the substeps that follow:

    • "home"
    • "work"
    • "mobile"
    • "fax"
    • "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 (which at this point will always be field).
    5. If the indexth entry in tokens is the first entry, then skip to the step labeled done.
    6. Decrement index by one.
  15. If the indexth token in tokens is an ASCII case-insensitive match for one of the strings in the following list, then run the substeps that follow:

    • "shipping"
    • "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 (which at this point will either be field or the concatenation of contact, a space, and field).
    5. If the indexth entry in tokens is the first entry, then skip to the step labeled done.
    6. Decrement index by one.
  16. If the indexth entry in tokens is not the first entry, then jump to the step labeled default.
  17. If the first eight characters of the indexth token in tokens are not an ASCII case-insensitive match for the string "section-", then jump to the step labeled default.
  18. Let section be the indexth token in tokens, converted to ASCII lowercase.
  19. Insert section at the start of scope tokens.
  20. Let IDL value be the concatenation of section, a U+0020 SPACE character, and the previous value of IDL value.
  21. Done: Let the element’s autofill hint set be hint tokens.
  22. Let the element’s autofill scope be scope tokens.
  23. Let the element’s autofill field name be field.
  24. Let the element’s IDL-exposed autofill value be IDL value.
  25. Abort these steps.
  26. Default: Let the element’s IDL-exposed autofill value be the empty string, and its autofill hint set and autofill scope be empty.
  27. If the element’s autocomplete attribute is wearing the autofill anchor mantle, then let the element’s autofill field name be the empty string and abort these steps.
  28. Let form be the element’s form owner, if any, or null otherwise.
  29. If form is not null and form’s autocomplete attribute is in the off state, then let the element’s autofill field name be "off".

    Otherwise, let the element’s autofill field name be "on".


For the purposes of autofill, a control’s data depends on the kind of control:

An input element with its type attribute in the E-mail state and with the multiple attribute specified
The element’s values.
Any other input element
A textarea element
The element’s value.
A select element with its multiple attribute specified
The option elements in the select element’s list of options that have their selectedness set to true.
Any other select element
The option element in the select element’s list of options that has its selectedness set to true.

How to process the autofill hint set, autofill scope, and autofill field name depends on the mantle that the autocomplete attribute is wearing.

When wearing the autofill expectation mantle...

When an element’s autofill field name is "off", the user agent should not remember the control’s data, and should not offer past values to the user.

In addition, when an element’s autofill field name is "off", values are reset when traversing the history.

Banks frequently do not want user agents to prefill login information:
<p><label>Account: <input type="text" name="ac" autocomplete="off"></label></p>
<p><label>PIN: <input type="password" name="pin" autocomplete="off"></label></p>

When an element’s autofill field name is not "off", the user agent may store the control’s data, and may offer previously stored values to the user.

For example, suppose a user visits a page with this control:
<select name="country">
  <option>Afghanistan
  <option>Albania
  <option>Algeria
  <option>Andorra
  <option>Angola
  <option>Antigua and Barbuda
  <option>Argentina
  <option>Armenia
  <!-- ... -->
  <option>Yemen
  <option>Zambia
  <option>Zimbabwe
</select>

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 autofill field name is "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 name value, the position of the element in the document’s DOM, what other fields exist in the form, and so forth.

When the autofill field name is one of the names of the 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 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 "shipping" keyword, and another address into fields that used the "billing" keyword, then in subsequent forms only the first address would be suggested for form controls whose autofill hint set contains the keyword "shipping". Both addresses might be suggested, however, for address-related form controls whose autofill hint set does not contain either keyword.

When wearing the autofill anchor mantle...

When the autofill field name is not the empty string, then the user agent must act as if the user had specified the control’s data for the given autofill hint set, autofill scope, and autofill field name combination.

When the user agent autofills form controls, elements with the same form owner and the same autofill scope must use data relating to the same person, address, payment instrument, and contact details. When a user agent autofills "country" and "country-name" fields with the same form owner and autofill scope, and the user agent has a value for the country" field(s), then the "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 autofill field name, form owner and 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 "cc-exp" field and a "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 autofill anchor mantle also. Consider the following markup snippet:
<form>
  <input type=hidden autocomplete="nickname" value="TreePlate">
  <input type=text autocomplete="nickname">
</form>

The only value that a conforming user agent could suggest in the text field is "TreePlate", the value given by the hidden input element.

The "section-*" tokens in the 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 control’s data, and must be done at a time where the element is mutable (e.g., just after the element has been inserted into the document, or when the user agent stops parsing). User agents must only prefill controls using values that the user could have entered.

For example, if a select element only has option elements with values "Steve" and "Rebecca", "Jay", and "Bob", and has an autofill field name "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 select element to the value "Evan", since the user could not have done so themselves.

A user agent prefilling a form control’s value must not cause that control to suffer from a type mismatch, suffer from being too long, suffer from being too short, suffer from an underflow, suffer from an overflow, suffer from a step mismatch, or suffer from a pattern mismatch. 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:
<input name=middle-initial maxlength=1 autocomplete="additional-name">

...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:
<input name=b type=month autocomplete="bday">
2012-07 The day is dropped since the Month state only accepts a month/year combination.
<select name=c autocomplete="bday">
  <option>Jan
  <option>Feb
  ...
  <option>Jul
  <option>Aug
  ...
</select>
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.
<input name=a type=number min=1 max=12 autocomplete="bday-month">
7 User agent converts "July" to a month number in the range 1..12, like the field.
<input name=a type=number min=0 max=11 autocomplete="bday-month">
6 User agent converts "July" to a month number in the range 0..11, like the field.
<input name=a type=number min=1 max=11 autocomplete="bday-month">
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 autofill field name, e.g., to change it from "off" to "on" to allow values to be remembered and prefilled despite the page author’s objections, or to always "off", never remembering values.

More specifically, user agents may in particular consider replacing the autofill field name of form controls that match the description given in the first column of the following table, when their autofill field name is either "on" or "off", with the value given in the second cell of that row. If this table is used, the replacements must be done in tree order, since all but the first row references the 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 listed elements that share the same form owner.

Form control New autofill field name

an input element whose type attribute is in the Text state that is followed by an input element whose type attribute is in the Password state

"username"

an input element whose type attribute is in the Password state that is preceded by an input element whose autofill field name is "username"

"current-password"

an input element whose type attribute is in the Password state that is preceded by an input element whose autofill field name is "current-password"

"new-password"

an input element whose type attribute is in the Password state that is preceded by an input element whose autofill field name is "new-password"

"new-password"

The autocomplete IDL attribute must reflect the content attribute of the same name.

4.10.20. APIs for text field selections

The input and textarea elements define the following members in their DOM interfaces for handling their selection: select(), selectionStart, selectionEnd, selectionDirection, setRangeText(replacement), setSelectionRange(start, end)

The setRangeText() method uses the following enumeration:

enum SelectionMode {
  "select",
  "start",
  "end",
  "preserve" // default
};

These methods and attributes expose and control the selection of input and textarea text fields.

element . select()

Selects everything in the text field.

element . selectionStart [ = value ]

Returns the offset to the start of the selection.

Can be set, to change the start of the selection.

element . selectionEnd [ = value ]

Returns the offset to the end of the selection.

Can be set, to change the end of the selection.

element . selectionDirection [ = value ]

Returns the current direction of the selection.

Can be set, to change the direction of the selection.

The possible values are "forward", "backward", and "none".

element . setSelectionRange(start, end [, direction] )

Changes the selection to cover the given substring in the given direction. If the direction is omitted, it will be reset to be the platform default (none or forward).

element . setRangeText(replacement [, start, end [, selectionMode ] ] )

Replaces a range of text with the new text. If the start and end arguments are not provided, the range is assumed to be the selection.

The final argument determines how the selection should be set after the text has been replaced. The possible values are:

"select"

Selects the newly inserted text.

"start"

Moves the selection to just before the inserted text.

"end"

Moves the selection to just after the selected text.

"preserve"

Attempts to preserve the selection. This is the default.

For input elements, calling these methods while they don’t apply, and getting or setting these attributes while they don’t apply, must throw an InvalidStateError exception. Otherwise, they must act as described below.

For input elements, these methods and attributes must operate on the element’s value. For textarea elements, these methods and attributes must operate on the element’s raw value.

Where possible, user interface features for changing the text selection in input and textarea elements must be implemented in terms of the DOM API described in this section, so that, e.g., all the same events fire.

The selections of input and textarea elements have a direction, which is either forward, backward, or none. This direction is set when the user manipulates the selection. The exact meaning of the selection direction depends on the platform.

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 backwards 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.

The select() method must cause the contents of the text field to be fully selected, with the selection direction being none, if the platform support selections with the direction none, or otherwise forward. The user agent must then queue a task to fire a simple event that bubbles named select at the element, using the user interaction task source as the task source.

In the case of input elements, if the control has no text field, then the method must do nothing.

For instance, in a user agent where <input type=color> is rendered as a color well with a picker, as opposed to a text field accepting a hexadecimal color code, there would be no text field, and thus nothing to select, and thus calls to the method are ignored.

The selectionStart attribute must, on getting, return the offset (in logical order) to the character that immediately follows the start of the selection. If there is no selection, then it must return the offset (in logical order) to the character that immediately follows the text entry cursor.

On setting, it must act as if the setSelectionRange() method had been called, with the new value as the first argument; the current value of the selectionEnd attribute as the second argument, unless the current value of the selectionEnd is less than the new value, in which case the second argument must also be the new value; and the current value of the selectionDirection as the third argument.

The selectionEnd attribute must, on getting, return the offset (in logical order) to the character that immediately follows the end of the selection. If there is no selection, then it must return the offset (in logical order) to the character that immediately follows the text entry cursor.

On setting, it must act as if the setSelectionRange() method had been called, with the current value of the selectionStart attribute as the first argument, the new value as the second argument, and the current value of the selectionDirection as the third argument.

The selectionDirection attribute must, on getting, return the string corresponding to the current selection direction: if the direction is forward, "forward"; if the direction is backward, "backward"; and otherwise, "none".

On setting, it must act as if the setSelectionRange() method had been called, with the current value of the selectionStart IDL attribute as the first argument, the current value of the selectionEnd IDL attribute as the second argument, and the new value as the third argument.

The setSelectionRange(start, end, direction) method must set the selection of the text field to the sequence of characters starting with the character at the startth position (in logical order) and ending with the character at the (end-1)th position. Arguments greater than the length of the value of the text field must be treated as pointing at the end of the text field. 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 user agents where there is no concept of an empty selection, this must set the cursor to be just before the character with offset end. The direction of the selection must be set to backward if direction is a case-sensitive match for the string "backward", forward if direction is a case-sensitive match for the string "forward" or if the platform does not support selections with the direction none, and none otherwise (including if the argument is omitted). The user agent must then queue a task to fire a simple event that bubbles named select at the element, using the user interaction task source as the task source.

The setRangeText(replacement, start, end, selectMode) method must run the following steps:

  1. If the method has only one argument, then let start and end have the values of the selectionStart IDL attribute and the selectionEnd IDL attribute respectively.

    Otherwise, let start, end have the values of the second and third arguments respectively.

  2. If start is greater than end, then throw an IndexSizeError exception and abort these steps.
  3. If start is greater than the length of the value of the text field, then set it to the length of the value of the text field.
  4. If end is greater than the length of the value of the text field, then set it to the length of the value of the text field.
  5. Let selection start be the current value of the selectionStart IDL attribute.
  6. Let selection end be the current value of the selectionEnd IDL attribute.
  7. If start is less than end, delete the sequence of characters starting with the character at the startth position (in logical order) and ending with the character at the (end-1)th position.
  8. Insert the value of the first argument into the text of the value of the text field, immediately before the startth character.
  9. Let new length be the length of the value of the first argument.
  10. Let new end be the sum of start and new length.
  11. 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" (the default)
    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.)

  12. Set the selection of the text field to the sequence of characters starting with the character at the selection startth position (in logical order) and ending with the character at the (selection end-1)th position. In user agents where there is no concept of an empty selection, this must set the cursor to be just before the character with offset end. The direction of the selection must be set to forward if the platform does not support selections with the direction none, and none otherwise.

  13. Queue a task to fire a simple event that bubbles named select at the element, using the user interaction task source as the task source.

All elements to which this API applies have either a selection or a text entry cursor position at all times (even for elements that are not being rendered). User agents should follow platform conventions to determine their initial state.

Characters with no visible rendering, such as U+200D ZERO WIDTH JOINER, still count as characters. Thus, for instance, the selection can include just an invisible character, and the text insertion cursor can be placed to one side or another of such a character.

To obtain the currently selected text, the following JavaScript suffices:
var selectionText = control.value.substring(control.selectionStart, control.selectionEnd);

...where control is the input or textarea element.

To add some text at the start of a text control, while maintaining the text selection, the three attributes must be preserved:
var oldStart = control.selectionStart;
var oldEnd = control.selectionEnd;
var oldDirection = control.selectionDirection;
var prefix = "https://";
control.value = prefix + control.value;
control.setSelectionRange(oldStart + prefix.length, oldEnd + prefix.length, oldDirection);

...where control is the input or textarea element.

4.10.21. Constraints

4.10.21.1. Definitions

A submittable element is a candidate for constraint validation except when a condition has barred the element from constraint validation. (For example, an element is barred from constraint validation if it is an object element.)

An element can have a custom validity error message defined. Initially, an element must have its custom validity error message set to the empty string. When its value is not the empty string, the element is suffering from a custom error. It can be set using the setCustomValidity() method. The user agent should use the 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 value but has a required attribute (input required, textarea required); or, in the case of an element in a radio button group, any of the other elements in the group has a required attribute; or, for select elements, none of the option elements have their selectedness set (select required).

Suffering from a type mismatch

When a control that allows arbitrary user input has a value that is not in the correct syntax (E-mail, URL).

Suffering from a pattern mismatch

When a control has a value that doesn’t satisfy the pattern attribute.

Suffering from being too long

When a control has a value that is too long for the form control maxlength attribute (input maxlength, textarea maxlength).

Suffering from being too short

When a control has a value that is too short for the form control minlength attribute (input minlength, textarea minlength).

Suffering from an underflow

When a control has a value that is not the empty string and is too low for the min attribute.

Suffering from an overflow

When a control has a value that is not the empty string and is too high for the max attribute.

Suffering from a step mismatch

When a control has a value that doesn’t fit the rules given by the step attribute.

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.

Suffering from a custom error

When a control’s custom validity error message (as set by the element’s setCustomValidity() method) is not the empty string.

An element can still suffer from these states even when the element is 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 validity states.

4.10.21.2. Constraint validation

When the user agent is required to statically validate the constraints of 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 submittable elements whose form owner is form, in tree order.
  2. Let invalid controls be an initially empty list of elements.
  3. For each element field in controls, in tree order, run the following substeps:

    1. If field is not a candidate for constraint validation, then move on to the next element.
    2. Otherwise, if field 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 and abort these steps.
  5. Let unhandled invalid controls be an initially empty list of elements.
  6. For each element field in invalid controls, if any, in tree order, run the following substeps:

    1. Fire a simple event named invalid that is cancelable at field.
    2. If the event was not canceled, 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 form element form, then the user agent must run the following steps:

  1. 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 and abort these steps.
  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 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. 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 group are marked as required, only one error need be reported). If one of the controls is not being rendered (e.g., it has the hidden attribute set) then user agents may report a script error.
  4. Return a negative result.
4.10.21.3. The constraint validation API
element . willValidate

Returns true if the element will be validated when the form is submitted; false otherwise.

element . {{HTMLInputElement/setCustomValidity(message)}}

Sets a custom error, so that the element would fail to validate. The given message is the message to be shown to the user when reporting the problem to the user.

If the argument is the empty string, clears the custom error.

element . validity . valueMissing

Returns true if the element has no value but is a required field; false otherwise.

element . validity . typeMismatch

Returns true if the element’s value is not in the correct syntax; false otherwise.

element . validity . patternMismatch

Returns true if the element’s value doesn’t match the provided pattern; false otherwise.

element . validity . tooLong

Returns true if the element’s value is longer than the provided maximum length; false otherwise.

element . validity . tooShort

Returns true if the element’s value, if it is not the empty string, is shorter than the provided minimum length; false otherwise.

element . validity . rangeUnderflow

Returns true if the element’s value is lower than the provided minimum; false otherwise.

element . validity . rangeOverflow

Returns true if the element’s value is higher than the provided maximum; false otherwise.

element . validity . stepMismatch

Returns true if the element’s value doesn’t fit the rules given by the step attribute; false otherwise.

element . validity . badInput

Returns true if the user has provided input in the user interface that the user agent is unable to convert to a value; false otherwise.

element . validity . customError

Returns true if the element has a custom error; false otherwise.

element . validity . valid

Returns true if the element’s value has no validity problems; false otherwise.

valid = element . checkValidity()

Returns true if the element’s value has no validity problems; false otherwise. Fires an invalid event at the element in the latter case.

valid = element . reportValidity()

Returns true if the element’s value has no validity problems; otherwise, returns false, fires an invalid event at the element, and (if the event isn’t canceled) reports the problem to the user.

element . validationMessage

Returns the error message that would be shown to the user if the element was to be checked for validity.

The willValidate IDL attribute must return true if an element is a candidate for constraint validation, and false otherwise (i.e., false if any conditions are barring it from constraint validation).

The setCustomValidity(message), when invoked, must set the custom validity error message to the value of the given message argument.

In the following example, a script checks the value of a form control each time it is edited, and whenever it is not a valid value, uses the setCustomValidity() method to set an appropriate message.
<label>Feeling: <input name=f type="text" oninput="check(this)"></label>
<script>
  function check(input) {
    if (input.value == "good" ||
        input.value == "fine" ||
        input.value == "tired") {
      input.setCustomValidity('"' + input.value + '" is not a feeling.');
   } else {
      // input is fine -- reset the error message
      input.setCustomValidity('');
    }
  }
</script>

The validity IDL attribute must return a ValidityState object that represents the validity states of the element. This object is live.

interface ValidityState {
  readonly attribute boolean valueMissing;
  readonly attribute boolean typeMismatch;
  readonly attribute boolean patternMismatch;
  readonly attribute boolean tooLong;
  readonly attribute boolean tooShort;
  readonly attribute boolean rangeUnderflow;
  readonly attribute boolean rangeOverflow;
  readonly attribute boolean stepMismatch;
  readonly attribute boolean badInput;
  readonly attribute boolean customError;
  readonly attribute boolean valid;
};

A 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, of type boolean, readonly

The control is suffering from being missing.

typeMismatch, of type boolean, readonly

The control is suffering from a type mismatch.

patternMismatch, of type boolean, readonly

The control is suffering from a pattern mismatch.

tooLong, of type boolean, readonly

The control is suffering from being too long.

tooShort, of type boolean, readonly

The control is suffering from being too short.

rangeUnderflow, of type boolean, readonly

The control is suffering from an underflow.

rangeOverflow, of type boolean, readonly

The control is suffering from an overflow.

stepMismatch, of type boolean, readonly

The control is suffering from a step mismatch.

badInput, of type boolean, readonly

The control is suffering from bad input.

customError, of type boolean, readonly

The control is suffering from a custom error.

valid, of type boolean, readonly

None of the other conditions are true.

When the checkValidity() method is invoked, if the element is a candidate for constraint validation and does not satisfy its constraints, the user agent must fire a simple event named invalid that is cancelable (but in this case has no default action) at the element and return false. Otherwise, it must only return true without doing anything else.

When the reportValidity() method is invoked, if the element is a candidate for constraint validation and does not satisfy its constraints, the user agent must: fire a simple event named invalid that is cancelable at the element, and if that event is not canceled, report the problems with the constraints of that element to the user; then, return false. Otherwise, it must only return true without doing anything else. When reporting the problem with the constraints to the user, the user agent may run the 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. User agents may report more than one constraint violation, if the element suffers from multiple problems at once. If the element is not being rendered, then the user agent may, instead of notifying the user, report a script error.

The validationMessage attribute must return the empty string if the element is not a candidate for constraint validation or if it is one but it satisfies its constraints; otherwise, it must 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 the attribute must 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 candidate for constraint validation and is suffering from a custom error, then the custom validity error message should be present in the return value.

4.10.21.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.22. Form submission

4.10.22.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 enctype, and then sent to the destination specified by the action using the given method.

For example, take the following form:

<form action="/find.cgi" method=get>
  <input type=text name=t>
  <input type=search name=q>
  <input type=submit>
</form>

If the user types in "cats" in the first field and "fur" in the second, and then hits the submit button, then the user agent will load /find.cgi?t=cats&q=fur.

On the other hand, consider this form:

<form action="/find.cgi" method=post enctype="multipart/form-data">
  <input type=text name=t>
  <input type=search name=q>
  <input type=submit>
</form>

Given the same user input, the result on submission is quite different: the user agent instead does an HTTP POST to the given URL, with as the entity body something like the following text:

------kYFrd4jNJEgCervEContent-Disposition: form-data; name="t"

cats
------kYFrd4jNJEgCervE
Content-Disposition: form-data; name="q"

fur
------kYFrd4jNJEgCervE--
4.10.22.2. Implicit submission

A form element’s default button is the first submit button in tree order whose form owner is that 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 field is focused implicitly submits the form), then doing so for a form whose default button has a defined activation behavior must cause the user agent to run synthetic click activation steps on that default button.

Consequently, if the default button is disabled, the form is not submitted when such an implicit submission mechanism is used. (A button has no activation behavior when disabled.)

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 submit button, then the implicit submission mechanism must do nothing if the form has more than one field that blocks implicit submission, and must submit the form element from the form element itself otherwise.

For the purpose of the previous paragraph, an element is a field that blocks implicit submission of a form element if it is an input element whose form owner is that form element and whose type attribute is in one of the following states: Text, Search, URL, Telephone, E-mail, Password, Date, Month, Week, Time, Number

4.10.22.3. Form submission algorithm

When a form element form is submitted from an element submitter (typically a button), optionally with a submitted from submit() method flag set, the user agent must run the following steps:

  1. Let form document be the form’s node document.
  2. If form document has no associated browsing context or its active sandboxing flag set has its sandboxed forms browsing context flag set, then abort these steps without doing anything.
  3. Let form browsing context be the browsing context of form document.
  4. If the submitted from submit() method flag is not set, and the submitter element’s no-validate state is false, then interactively validate the constraints of form and examine the result: if the result is negative (the constraint validation concluded that there were invalid fields and probably informed the user of this) then fire a simple event named invalid at the form element and then abort these steps.
  5. If the submitted from submit() method flag is not set, then fire a simple event that bubbles and is cancelable named submit, at form. If the event’s default action is prevented (i.e., if the event is canceled) then abort these steps. Otherwise, continue (effectively the default action is to perform the submission).
  6. Let form data set be the result of constructing the form data set for form in the context of submitter.
  7. Let action be the submitter element’s action.
  8. If action is the empty string, let action be the document’s address of the form document.

  9. Parse the URL action, relative to the submitter element’s node document. If this fails, abort these steps.
  10. Let action be the resulting URL string.
  11. Let action components be the resulting URL record.
  12. Let scheme be the scheme of the resulting URL record.
  13. Let enctype be the submitter element’s enctype.
  14. Let method be the submitter element’s method.
  15. Let target be the submitter element’s target.
  16. If the user indicated a specific browsing context to use when submitting the form, then let target browsing context be that browsing context. Otherwise, apply the rules for choosing a browsing context given a browsing context name using target as the name and form browsing context as the context in which the algorithm is executed, and let target browsing context be the resulting browsing context.
  17. If target browsing context was created in the previous step, or, alternatively, if the form document has not yet completely loaded and the submitted from submit() method flag is set, then let replace be true. Otherwise, let it be false.
  18. Otherwise, select the appropriate row in the table below based on the value of scheme as given by the first cell of each row. Then, select the appropriate cell on that row based on the value of method as given in the first cell of each column. Then, jump to the steps named in that cell and defined below the table.

    GET POST
    http Mutate action URL Submit as entity body
    https Mutate action URL Submit as entity body
    ftp Get action URL Get action URL
    javascript Get action URL Get action URL
    data Get action URL Post to data:
    mailto Mail with headers 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 form element has a planned navigation, which is either null or a task; when the form is first created, its planned navigation must be set to null. In the behaviors described below, when the user agent is required to plan to navigate to a particular resource destination, it must run the following steps:

    1. If the form has a non-null planned navigation, remove it from its task queue.
    2. Let the form's planned navigation be a new task that consists of running the following steps:

      1. Let the form's planned navigation be null.
      2. Navigate target browsing context to destination. If replace is true, then target browsing context must be navigated with replacement enabled.

      For the purposes of this task, target browsing context and replace are the variables that were set up when the overall form submission algorithm was run, with their values as they stood when this planned navigation was queued.

    3. Queue a task that is the form's new planned navigation.

      The task source for this task is the DOM manipulation task source.

    The behaviors are as follows:

    Mutate action URL

    Let query be the result of encoding the form data set using the application/x-www-form-urlencoded encoding algorithm, interpreted as a US-ASCII string.

    Set parsed action’s query component to query.

    Let destination be a new URL formed by applying the URL serializer algorithm to parsed action.

    Plan to navigate to destination.

    Submit as entity body

    Let entity body be the result of encoding the form data set using the appropriate form encoding algorithm.

    Let MIME type be determined as follows:

    If enctype is application/x-www-form-urlencoded

    Let MIME type be "application/x-www-form-urlencoded".

    If enctype is multipart/form-data

    Let MIME type be the concatenation of the string "multipart/form-data;", a U+0020 SPACE character, the string "boundary=", and the multipart/form-data boundary string generated by the multipart/form-data encoding algorithm.

    If enctype is text/plain

    Let MIME type be "text/plain".

    Otherwise, plan to navigate to a new request whose URL is action, method is method, header list consists of Content-Type/MIME type, and body is entity body.

    Get action URL

    Plan to navigate to action.

    The form data set is discarded.

    Post to data:

    Let data be the result of encoding the form data set using the appropriate form encoding algorithm.

    If action contains the string "%%%%" (four U+0025 PERCENT SIGN characters), then percent encode all bytes in data that, if interpreted as US-ASCII, are not characters in the URL default encode set, and then, treating the result as a US-ASCII string, UTF-8 percent encode all the U+0025 PERCENT SIGN characters in the resulting string and replace the first occurrence of "%%%%" in action with the resulting doubly-escaped string. [URL]

    Otherwise, if action contains the string "%%" (two U+0025 PERCENT SIGN characters in a row, but not four), then UTF-8 percent encode all characters in data that, if interpreted as US-ASCII, are not characters in the URL default encode set, and then, treating the result as a US-ASCII string, replace the first occurrence of "%%" in action with the resulting escaped string. [URL]

    Plan to navigate to the potentially modified action (which will be a data: URL).

    Mail with headers

    Let headers be the resulting encoding the form data set using the application/x-www-form-urlencoded encoding algorithm, interpreted as a US-ASCII string.

    Replace occurrences of U+002B PLUS SIGN characters (+) in headers with the string "%20".

    Let destination consist of all the characters from the first character in action to the character immediately before the first U+003F QUESTION MARK character (?), if any, or the end of the string if there are none.

    Append a single U+003F QUESTION MARK character (?) to destination.

    Append headers to destination.

    Plan to navigate to destination.

    Mail as body

    Let body be the resulting of encoding the form data set using the appropriate form encoding algorithm and then percent encoding all the bytes in the resulting byte string that, when interpreted as US-ASCII, are not characters in the URL default encode set. [URL]

    Let destination have the same value as action.

    If destination does not contain a U+003F QUESTION MARK character (?), append a single U+003F QUESTION MARK character (?) to destination. Otherwise, append a single U+0026 AMPERSAND character (&).

    Append the string "body=" to destination.

    Append body, interpreted as a US-ASCII string, to destination.

    Plan to navigate to destination.

    The appropriate form encoding algorithm is determined as follows:

    If enctype is application/x-www-form-urlencoded

    Use the application/x-www-form-urlencoded encoding algorithm.

    If enctype is multipart/form-data

    Use the multipart/form-data encoding algorithm.

    If enctype is text/plain

    Use the text/plain encoding algorithm.

4.10.22.4. Constructing the form data set

The algorithm to construct the form data set for a form form optionally in the context of a submitter submitter is as follows. If not specified otherwise, submitter is null.

  1. Let controls be a list of all the submittable elements whose form owner is form, in tree order.
  2. Let the form data set be a list of name-value-type tuples, initially empty.
  3. Loop: For each element field in controls, in tree order, run the following substeps:

    1. If any of the following conditions are met, then skip these substeps for this element:

      • The field element has a datalist element ancestor.
      • The field element is disabled.
      • The field element is a button but it is not submitter.
      • The field element is an input element whose type attribute is in the Checkbox state and whose checkedness is false.
      • The field element is an input element whose type attribute is in the Radio Button state and whose checkedness is false.
      • The field element is not an input element whose type attribute is in the image button state, and either the field element does not have a name attribute specified, or its name attribute’s value is the empty string.
      • The field element is an object element that is not using a plugin.

      Otherwise, process field as follows:

    2. Let type be the value of the type IDL attribute of field.
    3. If the field element is an input element whose type attribute is in the image button state, then run these further nested substeps:

      1. If the field element has a name attribute specified and its value is not the empty string, let name be that value followed by a single U+002E FULL STOP character (.). Otherwise, let name be the empty string.
      2. Let namex be the string consisting of the concatenation of name and a single U+0078 LATIN SMALL LETTER X character (x).
      3. Let namey be the string consisting of the concatenation of name and a single U+0079 LATIN SMALL LETTER Y character (y).
      4. The field element is submitter, and before this algorithm was invoked the user indicated a coordinate. Let x be the x-component of the coordinate selected by the user, and let y be the y-component of the coordinate selected by the user.
      5. Append an entry to the form data set with the name namex, the value x, and the type type.
      6. Append an entry to the form data set with the name namey and the value y, and the type type.
      7. Skip the remaining substeps for this element: if there are any more elements in controls, return to the top of the loop step, otherwise, jump to the end step below.
    4. Let name be the value of the field element’s name attribute.
    5. If the field element is a select element, then for each option element in the select element’s list of options whose selectedness is true and that is not disabled, append an entry to the form data set with the name as the name, the value of the option element as the value, and type as the type.
    6. Otherwise, if the field element is an input element whose type attribute is in the Checkbox state or the Radio Button state, then run these further nested substeps:

      1. If the field element has a value attribute specified, then let value be the value of that attribute; otherwise, let value be the string "on".
      2. Append an entry to the form data set with name as the name, value as the value, and type as the type.
    7. Otherwise, if the field element is an input element whose type attribute is in the File Upload state, then for each file selected in the input element, append an entry to the form data set with the name as the name, the file (consisting of the name, the type, and the body) as the value, and type as the type. If there are no selected files, then append an entry to the form data set with the name as the name, the empty string as the value, and application/octet-stream as the type.
    8. Otherwise, if the field element is an object element: try to obtain a form submission value from the plugin, and if that is successful, append an entry to the form data set with name as the name, the returned form submission value as the value, and the string "object" as the type.
    9. Otherwise, append an entry to the form data set with name as the name, the value of the field element as the value, and type as the type.
    10. If the element has a dirname attribute, and that attribute’s value is not the empty string, then run these substeps:

      1. Let dirname be the value of the element’s dirname attribute.
      2. Let dir be the string "ltr" if the directionality of the element is 'ltr', and "rtl" otherwise (i.e., when the directionality of the element is 'rtl').
      3. Append an entry to the form data set with dirname as the name, dir as the value, and the string "direction" as the type.

      An element can only have a dirname attribute if it is a textarea element or an input element whose type attribute is in either the Text state or the Search state.

  4. End: For the name of each entry in the form data set, and for the value of each entry in the form data set whose type is not "file" or "textarea", replace every occurrence of a U+000D CARRIAGE RETURN (CR) character not followed by a U+000A LINE FEED (LF) character, and every occurrence of a U+000A LINE FEED (LF) character not preceded by a U+000D CARRIAGE RETURN (CR) character, by a two-character string consisting of a U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character pair.

    In the case of the value of textarea elements, this newline normalization is already performed during the conversion of the control’s raw value into the control’s value (which also performs any necessary line wrapping). In the case of input elements type attributes in the File Upload state, the value is not normalized.

  5. Return the form data set.
4.10.22.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 document’s character encoding.

  2. If the form element has an accept-charset attribute, set encoding to the return value of running these substeps:

    1. Let input be the value of the form element’s accept-charset attribute.

    2. Let candidate encoding labels be the result of splitting input on spaces.

    3. Let candidate encodings be an empty list of character encodings.

    4. For each token in candidate encoding labels in turn (in the order in which they were found in input), get an encoding for the token and, if this does not result in failure, append the encoding to candidate encodings.

    5. If candidate encodings is empty, return UTF-8.

    6. Return the first encoding in candidate encodings.

  3. Return the result of getting an output encoding from encoding.

4.10.22.6. URL-encoded form data

See the WHATWG URL standard for details on application/x-www-form-urlencoded. [URL]

The application/x-www-form-urlencoded encoding algorithm is as follows:

  1. Let encoding be the result of picking an encoding for the form.

  2. Let serialized be the result of running the application/x-www-form-urlencoded serializer given form data set and encoding.

  3. Return the result of encoding serialized.

4.10.22.7. Multipart form data

The multipart/form-data encoding algorithm is as follows:

  1. Let result be the empty string.
  2. If the algorithm was invoked with an explicit character encoding, let the selected character encoding be that encoding. (This algorithm is used by other specifications, which provide an explicit character encoding to avoid the dependency on the form element described in the next paragraph.)

    Otherwise, if the form element has an accept-charset attribute, let the selected character encoding be the result of picking an encoding for the form.

    Otherwise, if the form element has no accept-charset attribute, but the document’s character encoding is an ASCII-compatible encoding, then that is the selected character encoding.

    Otherwise, let the selected character encoding be UTF-8.

  3. Let charset be the name of the selected character encoding.
  4. For each entry in the form data set, perform these substeps:

    1. If the entry’s name is "_charset_" and its type is "hidden", replace its value with charset.
    2. For each character in the entry’s name and value that cannot be expressed using the selected character encoding, replace the character by a string consisting of a U+0026 AMPERSAND character (&), a U+0023 NUMBER SIGN character (#), one or more ASCII digits representing the Unicode code point of the character in base ten, and finally a U+003B SEMICOLON character (;).
  5. Encode the (now mutated) form data set using the rules described by RFC 7578, Returning Values from Forms: multipart/form-data, and return the resulting byte stream. [RFC7578]

    Each entry in the form data set is a field, the name of the entry is the field name and the value of the entry is the field value.

    The order of parts must be the same as the order of fields in the form data set. Multiple entries with the same name must be treated as distinct fields.

    The parts of the generated multipart/form-data resource that correspond to non-file fields must not have a Content-Type header specified. Their names and values must be encoded using the character encoding selected above.

    File names included in the generated multipart/form-data resource (as part of file fields) must use the character encoding selected above, though the precise name may be approximated if necessary (e.g., newlines could be removed from file names, quotes could be changed to "%22", and characters not expressible in the selected character encoding could be replaced by other characters).

    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 multipart/form-data payloads, see RFC 7578. [RFC7578]

4.10.22.8. Plain text form data

The text/plain encoding algorithm is as follows:

  1. Let result be the empty string.
  2. Let encoding be the result of picking an encoding for the form.
  3. Let charset be the name of encoding.
  4. If the entry’s name is "_charset_" and its type is "hidden", replace its value with charset.
  5. If the entry’s type is "file", replace its value with the file’s name only.
  6. For each entry in the form data set, perform these substeps:

    1. Append the entry’s name to result.
    2. Append a single U+003D EQUALS SIGN character (=) to result.
    3. Append the entry’s value to result.
    4. Append a U+000D CARRIAGE RETURN (CR) U+000A LINE FEED (LF) character pair to result.
  7. Return the result of encoding result using encoding.

Payloads using the text/plain format are intended to be human readable. They are not reliably interpretable by computer, as the format is ambiguous (for example, there is no way to distinguish a literal newline in a value from the newline at the end of the value).

4.10.23. Resetting a form

When a form element form is reset, the user agent must fire a simple event named reset, that bubbles and is cancelable, at form, and then, if that event is not canceled, must invoke the reset algorithm of each resettable element whose form owner is form.

When the reset algorithm is invoked by the reset() method, the reset event fired by the reset algorithm must not be trusted.

Each 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 input events to fire).

4.11. Interactive elements

4.11.1. The details element

Categories:
Flow content.
Sectioning root.
Interactive content.
Palpable content.
Contexts in which this element can be used:
Where flow content is expected.
Content model:
One summary element followed by flow content.
Tag omission in text/html:
Neither tag is omissible
Content attributes:
Global attributes
open - Whether the details are visible
Allowed ARIA role attribute values:
Any role that supports aria-expanded.
Allowed ARIA state and property attributes:
Global aria-* attributes
Any aria-* attributes applicable to the allowed roles.
DOM interface:
interface HTMLDetailsElement : HTMLElement {
  attribute boolean open;
};

The details element represents a disclosure widget from which the user can obtain additional information or controls.

The details element is not appropriate for footnotes. Please see §4.13.5 Footnotes for details on how to mark up footnotes.

The first summary element child of the element, if any, represents the summary or legend of the details. If there is no child summary element, the user agent should provide its own legend (e.g., "Details").

The rest of the element’s contents represents the additional information or controls.

The open content attribute is a boolean attribute. If present, it indicates that both the summary and the additional information is to be shown to the user. If the attribute is absent, only the summary is to be shown.

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 set the open attribute on the element to the value open. To honor a request for the information to be hidden, the user agent must remove the open attribute from the element.

Whenever the open attribute is added to or removed from a details element, the user agent must queue a task that runs the following steps, which are known as the details notification task steps, for this details element:

  1. If another task has been queued to run the details notification task steps for this details element, then abort these steps.

    When the open attribute is toggled several times in succession, these steps essentially get coalesced so that only one event is fired.

  2. Fire a simple event named toggle at the details element.

The task source for this task must be the DOM manipulation task source.

The open IDL attribute must reflect the open content attribute.

The following example shows the details element being used to hide technical details in a progress report.
<section class="progress window">
  <h1>Copying "Really Achieving Your Childhood Dreams"</h1>
  <details>
  <summary>Copying... <progress max="375505392" value="97543282"></progress> 25%</summary>
  <dl>
    <dt>Transfer rate:</dt> <dd>452KB/s</dd>
    <dt>Local filename:</dt> <dd>/home/rpausch/raycd.m4v</dd>
    <dt>Remote filename:</dt> <dd>/var/www/lectures/raycd.m4v</dd>
    <dt>Duration:</dt> <dd>01:16:27</dd>
    <dt>Color profile:</dt> <dd>SD (6-1-6)</dd>
    <dt>Dimensions:</dt> <dd>320×240</dd>
  </dl>
  </details>
</section>
The following shows how a details element can be used to hide some controls by default:
<details>
  <summary><label for=fn>Name & Extension:</label></summary>
  <p><input type=text id=fn name=fn value="Pillar Magazine.pdf">
  <p><label><input type=checkbox name=ext checked> Hide extension</label>
</details>

One could use this in conjunction with other details in a list to allow the user to collapse a set of fields down to a small set of headings, with the ability to open each one.

In these examples, the summary really just summarizes what the controls can change, and not the actual values, which is less than ideal.

Because the open attribute is added and removed automatically as the user interacts with the control, it can be used in CSS to style the element differently based on its state. Here, a stylesheet is used to animate the color of the summary when the element is opened or closed:
<style>
  details > summary { transition: color 1s; color: black; }
  details[open] > summary { color: red; }
</style>
<details>
  <summary>Automated Status: Operational</summary>
  <p>Velocity: 12m/s</p>
  <p>Direction: North</p>
</details>

4.11.2. The summary element

Categories:
None.
Contexts in which this element can be used:
As the first child of a details element.
Content model:
Either: phrasing content.
Or: one element of heading content.
Tag omission in text/html:
Neither tag is omissible
Content attributes:
Global attributes
Allowed ARIA role attribute values:
button.
Allowed ARIA state and property attributes:
Global aria-* attributes
Any aria-* attributes applicable to the allowed roles.
DOM interface:
Uses HTMLElement.

The summary element represents a summary, caption, or legend for the rest of the contents of the summary element’s parent details element, if any.

4.11.3. The menu element

Categories:
Flow content.
Contexts in which this element can be used:
Where flow content is expected.
If the element’s type attribute is in the popup menu state: as the child of a menu element whose type attribute is in the popup menu state.
Content model:
If the element’s type attribute is in the popup menu state: in any order, zero or more menuitem elements, zero or more hr elements, zero or more menu elements whose type attributes are in the popup menu state, and zero or more script-supporting elements.
Tag omission in text/html:
Neither tag is omissible
Content attributes:
Global attributes
type - Type of menu
label - User-visible label
Allowed ARIA role attribute values:
menu (default - do not set), directory, list, listbox, menubar, tablist, tabpanel or tree.
Allowed ARIA state and property attributes:
Global aria-* attributes
Any aria-* attributes applicable to the allowed roles.
DOM interface:
interface HTMLMenuElement : HTMLElement {
  attribute DOMString type;
  attribute DOMString label;
};

The menu element represents a group of commands.

The type attribute is an enumerated attribute indicating the kind of menu being declared. The attribute has 1 state. The "context" keyword maps to the popup menu state, in which the element is declaring a context menu. The attribute may also be omitted. The missing value default is the popup menu state.

If a menu element’s type attribute is in the popup menu state, then the element represents the commands of a popup menu, and the user can only examine and interact with the commands if that popup menu is activated through some other element via the contextmenu attribute.

The label attribute gives the label of the menu. It is used by user agents to display nested menus in the UI: a context menu containing another menu would use the nested menu’s label attribute for the submenu’s menu label. The label attribute must only be specified on menu elements whose parent element is a menu element whose type attribute is in the popup menu state.


A menu is a currently relevant menu element if it is the child of a currently relevant menu element, or if it is the designated pop-up menu of a button element that is not inert, does not have a hidden attribute, and is not the descendant of an element with a hidden attribute.


A menu construct consists of an ordered list of zero or more menu item constructs, which can be any of:

  • Commands, which can be marked as default commands (menuitem)
  • Separators (hr)
  • Other menu constructs, each with an associated submenu label, which allows the list to be nested (menu)

To build and show a menu for a particular menu element source and with a particular element subject as a subject, the user agent must run the following steps:

  1. Let pop-up menu be the menu construct created by the build a menu construct algorithm when passed the source element.
  2. Display pop-up menu to the user, and let the algorithm that invoked this one continue.

    If the user selects a menu item construct that corresponds to an element that still represents a command when the user selects it, then the user agent must invoke that command’s Action. If the command’s Action is defined as firing a click event, either directly or via the run synthetic click activation steps algorithm, then the relatedTarget attribute of that click event must be initialized to subject.

    Pop-up menus must not, while being shown, reflect changes in the DOM. The menu is constructed from the DOM before being shown, and is then immutable.

To build a menu construct for an element source, the user agent must run the following steps, which return a menu construct:

  1. Let generated menu be an empty menu construct.
  2. Run the menu item generator steps for the menu element using generated menu as the output.

    The menu item generator steps for a menu element using a specific menu construct output as output are as follows: For each child node of the menu in tree order, run the appropriate steps from the following list:

    If the child is a menuitem element that defines a command
    Append the command to output, respecting the command’s facets. If the menuitem element has a default attribute, mark the command as being a default command.
    If the child is an hr element
    Append a separator to output.
    If the child is a menu element with no label attribute
    Append a separator to output, then run the menu item generator steps for this child menu element, using output as the output, then append another separator to output.
    If the child is a menu element with a label attribute
    Let submenu be the result of running the build a menu construct steps for the child menu element. Then, append submenu to output, using the value of the child menu element’s label attribute as the submenu label.
    Otherwise
    Ignore the child node.
  3. Remove from output any menu construct whose submenu label is the empty string.
  4. Remove from output any menu item construct representing a command whose Label is the empty string.
  5. Collapse all sequences of two or more adjacent separators in output to a single separator.
  6. If the first menu item construct in output is a separator, then remove it.
  7. If the last menu item construct in output is a separator, then remove it.
  8. Return output.

The type IDL attribute must reflect the content attribute of the same name, limited to only known values.

The label IDL attribute must reflect the content attribute of the same name.

4.11.4. The menuitem element

Categories:
None.
Contexts in which this element can be used:
As a child of a menu element whose type attribute is in the popup menu state.
Content model:
Nothing.
Tag omission in text/html:
No end tag.
Content attributes:
Global attributes
type - Type of command
label - User-visible label
icon - Icon for the command
disabled Whether the command or control is disabled
checked Whether the command or control is checked
radiogroup Name of group of commands to treat as a radio button group
default - Mark the command as being a default command
Also, the title attribute has special semantics on this element.
Allowed ARIA role attribute values:
menuitem (default - do not set).
Allowed ARIA state and property attributes:
Global aria-* attributes
Any aria-* attributes applicable to the allowed roles.
DOM interface:
interface HTMLMenuItemElement : HTMLElement {
  attribute DOMString type;
  attribute DOMString label;
  attribute DOMString icon;
  attribute boolean disabled;
  attribute boolean checked;
  attribute DOMString radiogroup;
  attribute boolean default;
};

The menuitem element represents a command that the user can invoke from a popup menu(a context menu).

A menuitem element that uses one or more of the type, label, icon, disabled, checked, and radiogroup attributes defines a new command.


The type attribute indicates the kind of command: either a normal command with an associated action, or a state or option that can be toggled, or a selection of one item from a list of items.

The attribute is an enumerated attribute with three keywords and states. The "command" keyword maps to the Command state, the "checkbox" keyword maps to the Checkbox state, and the "radio" keyword maps to the Radio state. The missing value default is the Command state.

The Command state
The element represents a normal command with an associated action.
The Checkbox state
The element represents a state or option that can be toggled.
The Radio state
The element represents a selection of one item from a list of items.

The label attribute gives the name of the command, as shown to the user. If the attribute is specified, it must have a value that is not the empty string.

The icon attribute gives a picture that represents the command. If the attribute is specified, the attribute’s value must contain a valid non-empty URL potentially surrounded by spaces. To obtain the absolute URL of the icon when the attribute’s value is not the empty string, the attribute’s value must be resolved relative to the element. When the attribute is absent, or its value is the empty string, or parsing its value fails, there is no icon.

The disabled attribute is a boolean attribute that, if present, indicates that the command is not available in the current state.

The distinction between disabled and hidden is subtle. A command would be disabled if, in the same context, it could be enabled if only certain aspects of the situation were changed. A command would be marked as hidden if, in that situation, the command will never be enabled. For example, in the context menu for a water faucet, the command "open" might be disabled if the faucet is already open, but the command "eat" would be marked hidden since the faucet could never be eaten.

The checked attribute is a boolean attribute that, if present, indicates that the command is selected. The attribute must be omitted unless the type attribute is in either the Checkbox state or the Radio state.

The radiogroup attribute gives the name of the group of commands that will be toggled when the command itself is toggled, for commands whose type attribute has the value "radio". The scope of the name is the child list of the parent element. The attribute must be omitted unless the type attribute is in the Radio state. When specified, the attribute’s value must be a non-empty string.


The title attribute gives a hint describing the command, which might be shown to the user to help him.

The default attribute indicates, if present, that the command is the one that would have been invoked if the user had directly activated the menu’s subject instead of using the menu. The default attribute is a boolean attribute.


The type IDL attribute must reflect the content attribute of the same name, limited to only known values.

The label, icon, disabled, checked, and radiogroup, and default IDL attributes must reflect the respective content attributes of the same name.


If the element’s Disabled State is false (enabled) then the element’s activation behavior depends on the element’s type attribute, as follows:

If the type attribute is in the Checkbox state
If the element has a checked attribute, the user agent must remove that attribute. Otherwise, the user agent must add a checked attribute, with the literal value "checked".
If the type attribute is in the Radio state
If the element has a parent, then the user agent must walk the list of child nodes of that parent element, and for each node that is a menuitem element, if that element has a radiogroup attribute whose value exactly matches the current element’s (treating missing radiogroup attributes as if they were the empty string), and has a checked attribute, must remove that attribute.

Then, the element’s checked attribute must be set to the literal value "checked".

Otherwise
The element’s activation behavior is to do nothing.

Firing a synthetic click event at the element does not cause any of the actions described above to happen.

If the element’s Disabled State is true (disabled) then the element has no activation behavior.

The menuitem element is not rendered except as part of a popup menu.

4.11.5. Context menus

4.11.5.1. Declaring a context menu

The contextmenu attribute gives the element’s context menu. The value must be the ID of a menu element in the same home subtree whose type attribute is in the popup menu state.

The contextmenu attribute is "at risk". If testing during the Candidate Recommendation phase does not identify at least two interoperable implementations in current shipping browsers of the contextmenu attribute it will be removed from the HTML 5.1 Specification.

When a user right-clicks on an element with a contextmenu attribute, the user agent will first fire a contextmenu event at the element, and then, if that event is not canceled, a show event at the menu element.

Here is an example of a context menu for an input control:
<form name="npc">
  <label>Character name: <input name=char type=text contextmenu=namemenu required></label>
  <menu type=context id=namemenu>
  <menuitem label="Pick random name" onclick="document.forms.npc.elements.char.value = getRandomName()">
  <menuitem label="Prefill other fields based on name" onclick="prefillFields(document.forms.npc.elements.char.value)">
  </menu>
</form>

This adds two items to the control’s context menu, one called "Pick random name", and one called "Prefill other fields based on name". They invoke scripts that are not shown in the example above.

4.11.5.2. Processing model

Each element has an assigned context menu, which can be null. If an element A has a contextmenu attribute, and there is an element with the ID given by A’s contextmenu attribute’s value in A’s home subtree, and the first such element in tree order is a menu element whose type attribute is in the popup menu state, then A’s assigned context menu is that element. Otherwise, if A has a parent element, then A’s assigned context menu is the assigned context menu of its parent element. Otherwise, A’s assigned context menu is null.

When an element’s context menu is requested (e.g., by the user right-clicking the element, or pressing a context menu key), the user agent must apply the appropriate rules from the following list:

If the user requested a context menu using a pointing device
The user agent must fire a trusted event with the name contextmenu, that bubbles and is cancelable, and that uses the MouseEvent interface, at the element for which the menu was requested. The context information of the event must be initialized to the same values as the last MouseEvent user interaction event that was fired as part of the gesture that was interpreted as a request for the context menu.
Otherwise
The user agent must fire a synthetic mouse event named contextmenu that bubbles and is cancelable at the element for which the menu was requested.

Typically, therefore, the firing of the contextmenu event will be the default action of a mouseup or keyup event. The exact sequence of events is user agent-dependent, as it will vary based on platform conventions.

The default action of the contextmenu event depends on whether or not the element for which the menu was requested has a non-null assigned context menu when the event dispatch has completed, as follows.

If the assigned context menu of the element for which the menu was requested is null, the default action must be for the user agent to show its default context menu, if it has one.

Otherwise, let subject be the element for which the menu was requested, and let menu be the assigned context menu of target immediately after the contextmenu event’s dispatch has completed. The user agent must fire a trusted event with the name show at menu, using the RelatedEvent interface, with the relatedTarget attribute initialized to subject. The event must be cancelable.

If this event (the show event) is not canceled, then the user agent must build and show the menu for menu with subject as the subject.

The user agent may also provide access to its default context menu, if any, with the context menu shown. For example, it could merge the menu items from the two menus together, or provide the page’s context menu as a submenu of the default menu. In general, user agents are encouraged to de-emphasize their own contextual menu items, so as to give the author’s context menu the appearance of legitimacy — to allow documents to feel like "applications" rather than "mere Web pages".

User agents may provide means for bypassing the context menu processing model, ensuring that the user can always access the user agent’s default context menus. For example, the user agent could handle right-clicks that have the Shift key depressed in such a way that it does not fire the contextmenu event and instead always shows the default context menu.


The contextMenu IDL attribute must reflect the contextmenu content attribute.

In this example, an image of cats is given a context menu with four possible commands:
<img src="cats.jpeg" alt="Cats" contextmenu=catsmenu>
<menu type="context" id="catsmenu">
  <menuitem label="Pet the kittens" onclick="kittens.pet()">
  <menuitem label="Cuddle with the kittens" onclick="kittens.cuddle()">
  <menu label="Feed the kittens">
  <menuitem label="Fish" onclick="kittens.feed(fish)">
  <menuitem label="Chicken" onclick="kittens.feed(chicken)">
  </menu>
</menu>

When a user of a mouse-operated visual Web browser right-clicks on the image, the browser might pop up a context menu like this:

A context menu, shown over a picture of cats, with four lines: the first two offering the menu items described in the markup above ('Pet the kittens' and 'Cuddle with the kittens'), the third giving a submenu labeled 'Feed the kittens', and the fourth, after a horizontal splitter, consisting of only a downwards-pointing disclosure triangle.

When the user clicks the disclosure triangle, such a user agent would expand the context menu in place, to show the browser’s own commands:

This would result in the same basic interface, but with a longer menu; the disclosure triangle having been replaced by items such as 'View Image', 'Copy Image', 'Copy Image Location', and so forth.

4.11.5.3. The RelatedEvent interfaces
[Constructor(DOMString type, optional RelatedEventInit eventInitDict)]
interface RelatedEvent : Event {
  readonly attribute EventTarget? relatedTarget;
};

dictionary RelatedEventInit : EventInit {
  EventTarget? relatedTarget;
};
event . relatedTarget

Returns the other event target involved in this event. For example, when a show event fires on a menu element, the other event target involved in the event would be the element for which the menu is being shown.

The relatedTarget attribute must return the value it was initialized to. When the object is created, this attribute must be initialized to null. It represents the other event target that is related to the event.

4.11.6. Commands

4.11.6.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 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 URL to which to navigate, or a form submission.

User agents may expose the commands that match the following criteria:

User agents are encouraged to do this especially for commands that have Access Keys, as a way to advertise those keys to the user.

For example, such commands could be listed in the user agent’s menu bar.

4.11.6.2. Using the a element to define a command

An a element with an href attribute defines a command.

The Label of the command is the string given by the element’s textContent IDL attribute.

The Access Key of the command is the element’s assigned access key, if any.

The Hidden State of the command is true (hidden) if the element has a hidden attribute, and false otherwise.

The Disabled State facet of the command is true if the element or one of its ancestors is inert, and false otherwise.

The Action of the command, if the element has a defined activation behavior, is to run synthetic click activation steps on the element. Otherwise, it is just to fire a click event at the element.

4.11.6.3. Using the button element to define a command

A button element always defines a command.

The Label, Access Key, Hidden State, and Action facets of the command are determined as for a elements (see the previous section).

The Disabled State of the command is true if the element or one of its ancestors is inert, or if the element’s disabled state is set, and false otherwise.

4.11.6.4. Using the input element to define a command

An input element whose type attribute is in one of the submit button, reset button, Image Button, Button, Radio Button, or Checkbox states defines a command.

The Label of the command is determined as follows:

  • If the type attribute is in one of the submit button, reset button, Image Button, or Button states, then the Label is the string given by the value attribute, if any, and a user agent-dependent, locale-dependent value that the user agent uses to label the button itself if the attribute is absent.
  • Otherwise, if the element is a labeled control, then the Label is the string given by the textContent of the first label element in tree order whose labeled control is the element in question. (In DOM terms, this is the string given by element.labels[0].textContent.)
  • Otherwise, if the value attribute is present, then the Label is the value of that attribute.
  • Otherwise, the Label is the empty string.

The Access Key of the command is the element’s assigned access key, if any.

The Hidden State of the command is true (hidden) if the element has a hidden attribute, and false otherwise.

The Disabled State of the command is true if the element or one of its ancestors is inert, or if the element’s disabled state is set, and false otherwise.

The Action of the command, if the element has a defined activation behavior, is to run synthetic click activation steps on the element. Otherwise, it is just to fire a click event at the element.

4.11.6.5. Using the option element to define a command

An option element with an ancestor select element and either no value attribute or a value attribute that is not the empty string defines a command.

The Label of the command is the value of the option element’s label attribute, if there is one, or else the value of option element’s textContent IDL attribute, with leading and trailing whitespace stripped, and with any sequences of two or more space characters replaced by a single U+0020 SPACE character.

The Access Key of the command is the element’s assigned access key, if any.

The Hidden State of the command is true (hidden) if the element has a hidden attribute, and false otherwise.

The Disabled State of the command is true if the element is disabled, or if its nearest ancestor select element is disabled, or if it or one of its ancestors is inert, and false otherwise.

If the option’s nearest ancestor select element has a multiple attribute, the Action of the command is to pick the option element. Otherwise, the Action is to toggle the option element.

4.11.6.6. Using the menuitem element to define a command

A menuitem element always defines a command.

The Label of the command is the value of the element’s label attribute, if there is one, or the empty string if it doesn’t.

The Access Key of the command is the element’s assigned access key, if any.

The Hidden State of the command is true (hidden) if the element has a hidden attribute, and false otherwise.

The Disabled State of the command is true if the element or one of its ancestors is inert, or if the element has a disabled attribute, and false otherwise.

The Action of the command, if the element has a defined activation behavior, is to run synthetic click activation steps on the element. Otherwise, it is just to fire a click event at the element.

4.11.6.7. Using the accesskey attribute on a label element to define a command

A label element that has an assigned access key and a labeled control and whose labeled control defines a command, itself defines a command.

The Label of the command is the string given by the element’s textContent IDL attribute.

The Access Key of the command is the element’s assigned access key.

The Hidden State, Disabled State, and Action facets of the command are the same as the respective facets of the element’s labeled control.

4.11.6.8. Using the accesskey attribute on a legend element to define a command

A legend element that has an assigned access key and is a child of a fieldset element that has a descendant that is not a descendant of the legend element and is neither a label element nor a legend element but that defines a command, itself defines a command.

The Label of the command is the string given by the element’s textContent IDL attribute.

The Access Key of the command is the element’s assigned access key.

The Hidden State, Disabled State, and Action facets of the command are the same as the respective facets of the first element in tree order that is a descendant of the parent of the legend element that defines a command but is not a descendant of the legend element and is neither a label nor a legend element.

4.11.6.9. Using the accesskey attribute to define a command on other elements

An element that has an assigned access key defines a command.

If one of the earlier sections that define elements that define commands define that this element defines a command, then that section applies to this element, and this section does not. Otherwise, this section applies to that element.

The Label of the command depends on the element. If the element is a labeled control, the textContent of the first label element in tree order whose labeled control is the element in question is the Label (in DOM terms, this is the string given by element.labels[0].textContent). Otherwise, the Label is the textContent of the element itself.

The Access Key of the command is the element’s assigned access key.

The Hidden State of the command is true (hidden) if the element has a hidden attribute, and false otherwise.

The Disabled State of the command is true if the element or one of its ancestors is inert, and false otherwise.

The Action of the command is to run the following steps:

  1. Run the focusing steps for the element.
  2. If the element has a defined activation behavior, run synthetic click activation steps on the element.
  3. Otherwise, if the element does not have a defined activation behavior, fire a click event at the element.

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 script to show or hide a section to show more details, the details element could be used.

Authors are also encouraged to make their applications degrade gracefully in the absence of scripting support.

For example, if an author provides a link in a table header to dynamically resort the table, the link could also be made to function without scripts by requesting the sorted table from the server.

4.12.1. The script element

Categories:
Metadata content.
Flow content.
Phrasing content.
Script-supporting element.
Contexts in which this element can be used:
Where metadata content is expected.
Where phrasing content is expected.
Where script-supporting elements are expected.
Content model:
If there is no src attribute, depends on the value of the type attribute, but must match script content restrictions.
If there is a src attribute, the element must be either empty or contain only script documentation that also matches script content restrictions.
Tag omission in text/html:
Neither tag is omissible
Content attributes:
Global attributes
src - Address of the resource
type - Type of embedded resource
charset - Character encoding of the external script resource
async - Execute script in parallel
defer - Defer script execution
crossorigin - How the element handles crossorigin requests
nonce - Cryptographic nonce used in Content Security Policy checks [CSP3]
Allowed ARIA role attribute values:
None
Allowed ARIA state and property attributes:
Global aria-* attributes
DOM interface:
interface HTMLScriptElement : HTMLElement {
  attribute DOMString src;
  attribute DOMString type;
  attribute DOMString charset;
  attribute boolean async;
  attribute boolean defer;
  attribute DOMString? crossOrigin;
  attribute DOMString text;
  attribute DOMString nonce;
};

The script element allows authors to include dynamic script and data blocks in their documents. The element does not represent content for the user.

The type attribute allows customization of the type of script represented:

The requirement that data blocks must be denoted using a valid MIME type is in place to avoid potential future collisions. If this specification ever adds additional types of script, they will be triggered by setting the type attribute to something which is not a MIME type. By using a valid MIME type now, you ensure that your data block will not ever be reinterpreted as a different script type, even in future user agents.

Classic scripts may either be embedded inline or may be imported from an external file using the src attribute, which if specified gives the URL of the external script resource to use. If src is specified, it must be a valid non-empty URL potentially surrounded by spaces. The contents of inline script elements, or the external script resource, must conform with the requirements of the JavaScript specification’s Script production for classic scripts. [ECMA-262]

When used to include data blocks, the data must be embedded inline, the format of the data must be given using the type attribute, and the contents of the script element must conform to the requirements defined for the format used. The src, charset, async, defer, crossorigin, and nonce attributes must not be specified.

The charset attribute gives the character encoding of the external script resource. The attribute must not be specified if the src attribute is not present, or if the script is not a classic script. If the attribute is set, its value must be an ASCII case-insensitive match for one of the labels of an encoding, and must specify the same encoding as the charset parameter of the Content-Type metadata of the external file, if any. [ENCODING]

The async and defer attributes are boolean attributes that indicate how the script should be executed. Classic scripts may specify defer or async.

There are several possible modes that can be selected using these attributes, and depending on the script’s type.

For classic scripts, if the async attribute is present, then the classic script will be fetched in parallel to parsing and evaluated as soon as it is available (potentially before parsing completes). If the async attribute is not present but the defer attribute is present, then the classic script will be fetched 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.

This is all summarized in the following schematic diagram:

With <script>, parsing is interrupted by fetching and execution. With <script defer>, fetching is parallel to parsing and execution takes place after all parsing has finished. And with <script async>, fetching is parallel to parsing but once it finishes parsing is interrupted to execute the script.

The exact processing details for these attributes are, for mostly historical reasons, somewhat non-trivial, involving a number of aspects of HTML. The implementation requirements are therefore by necessity scattered throughout the specification. The algorithms below (in this section) describe the core of this processing, but these algorithms reference and are referenced by the parsing rules for script start and end tags in HTML, in foreign content, and in XML, the rules for the document.write() method, the handling of scripting, etc.

The defer attribute may be specified even if the async attribute is specified, to cause legacy Web browsers that only support defer (and not async) to fall back to the defer behavior instead of the blocking behavior that is the default.

The crossorigin attribute is a CORS settings attribute. For classic scripts, it controls whether error information will be exposed, when the script is obtained from other origins.

The nonce attribute represents a cryptographic nonce ("number used once") which can be used by Content Security Policy to determine whether or not the script specified by an element will be executed. The value is text. [CSP3]

Changing the src, type, charset, async, defer, crossorigin, and nonce attributes dynamically has no direct effect; these attributes are only used at specific times described below.

The IDL attributes src, type, charset, defer, and nonce, must each reflect the respective content attributes of the same name.

The crossOrigin IDL attribute must reflect the crossorigin content attribute.

The async IDL attribute controls whether the element will execute in parallel or not. If the element’s "non-blocking" flag is set, then, on getting, the async IDL attribute must return true, and on setting, the "non-blocking" flag must first be unset, and then the content attribute must be removed if the IDL attribute’s new value is false, and must be set to the empty string if the IDL attribute’s new value is true. If the element’s "non-blocking" flag is not set, the IDL attribute must reflect the async content attribute.

script . text [ = value ]
Returns the child text content of the element.

Can be set, to replace the element’s children with the given value.

The IDL attribute text must return the child text content of the script element. On setting, it must act the same way as the textContent IDL attribute.

When inserted using the document.write() method, script elements execute (typically blocking further script execution or HTML parsing), but when inserted using innerHTML and outerHTML attributes, they do not execute at all.

In this example, two script elements are used. One embeds an external classic script, and the other includes some data as a data block.
<script src="game-engine.js"></script>
<script type="text/x-game-map">
........U.........e
o............A....e
.....A.....AAA....e
.A..AAA...AAAAA...e
</script>

The data in this case might be used by the script to generate the map of a video game. The data doesn’t have to be used that way, though; maybe the map data is actually embedded in other parts of the page’s markup, and the data block here is just used by the site’s search engine to help users who are looking for particular features in their game maps.

The following sample shows how a script element can be used to define a function that is then used by other parts of the document, as part of a classic script. It also shows how a script element can be used to invoke script while the document is being parsed, in this case to initialize the form’s output.
<script>
  function calculate(form) {
    var price = 52000;
    if (form.elements.brakes.checked)
      price += 1000;
    if (form.elements.radio.checked)
      price += 2500;
    if (form.elements.turbo.checked)
      price += 5000;
    if (form.elements.sticker.checked)
      price += 250;
    form.elements.result.value = price;
  }
</script>
<form name="pricecalc" onsubmit="return false" onchange="calculate(this)">
  <fieldset>
  <legend>Work out the price of your car</legend>
  <p>Base cost: £52000.</p>
  <p>Select additional options:</p>
  <ul>
    <li><label><input type=checkbox name=brakes> Ceramic brakes (£1000)</label></li>
    <li><label><input type=checkbox name=radio> Satellite radio (£2500)</label></li>
    <li><label><input type=checkbox name=turbo> Turbo charger (£5000)</label></li>
    <li><label><input type=checkbox name=sticker> "XZ" sticker (£250)</label></li>
  </ul>
  <p>Total: £<output name=result></output></p>
  </fieldset>
  <script>
  calculate(document.forms.pricecalc);
  </script>
</form>
4.12.1.1. Processing model

A script element has several associated pieces of state.

The first is a flag indicating whether or not the script block has been "already started". Initially, script elements must have this flag unset (script blocks, when created, are not "already started"). The cloning steps for script elements must set the "already started" flag on the copy if it is set on the element being cloned.

The second is a flag indicating whether the element was "parser-inserted". Initially, script elements must have this flag unset. It is set by the HTML parser and the XML parser on script elements they insert and affects the processing of those elements.

The third is a flag indicating whether the element will "non-blocking". Initially, script elements must have this flag set. It is unset by the HTML parser and the XML parser on script elements they insert. In addition, whenever a script element whose "non-blocking" flag is set has an async content attribute added, the element’s "non-blocking" flag must be unset.

The fourth is a flag indicating whether or not the script block is "ready to be parser-executed". Initially, script elements must have this flag unset (script blocks, when created, are not "ready to be parser-executed"). This flag is used only for elements that are also "parser-inserted", to let the parser know when to execute the script.

The fifth is the script’s type, which is "classic". It is determined when the script is prepared, based on the type attribute of the element at that time. Initially, script elements must have this flag unset.

The sixth is a flag indicating whether or not the script is from an external file. It is determined when the script is prepared, based on the src attribute of the element at that time.

Finally, a script element has the script’s script, which is a script resulting from preparing the element. This is set asynchronously after the classic script is fetched. Once it is set, either to a script in the case of success or to null in the case of failure, the fetching algorithms will note that the script is ready, which can trigger other actions. The user agent must delay the load event of the element’s node document until the script is ready.

When a script element that is not marked as being "parser-inserted" experiences one of the events listed in the following list, the user agent must immediately prepare the script element:

To prepare a script, the user agent must act as follows:

  1. If the script element is marked as having "already started", then the user agent must abort these steps at this point. The script is not executed.

  2. If the element has its "parser-inserted" flag set, then set was-parser-inserted to true and unset the element’s "parser-inserted" flag. Otherwise, set was-parser-inserted to false.

    This is done so that if parser-inserted 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.

  3. If was-parser-inserted is true and the element does not have an async attribute, then set the element’s "non-blocking" flag to true.

    This is done so that if a parser-inserted 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 a non-blocking fashion even if the async attribute isn’t set.

  4. If the element has no src attribute, and its child nodes, if any, consist only of comment nodes and empty Text nodes, then abort these steps at this point. The script is not executed.

  5. If the element is not in a Document, then the user agent must abort these steps at this point. The script is not executed.

  6. If either:

    • the script element has a type attribute and its value is the empty string, or

    • the script element has no type attribute but it has a language attribute and that attribute’s value is the empty string, or

    • the script element has neither a type attribute nor a language attribute, then

    ...let the script block’s type string for this script element be "`text/javascript`".

    Otherwise, if the script element has a type attribute, let the script block’s type string for this script element be the value of that attribute with any leading or trailing sequences of space characters removed.

    Otherwise, the element has a non-empty language attribute; let the script block’s type string for this script element be the concatenation of the string "`text/`" followed by the value of the language attribute.

    The language attribute is never conforming, and is always ignored if there is a type attribute present.

    Determine the script’s type as follows:

  7. If was-parser-inserted is true, then flag the element as "parser-inserted" again, and set the element’s "non-blocking" flag to false.

  8. The user agent must set the element’s "already started" flag.

  9. If the element is flagged as "parser-inserted", but the element’s node document is not the Document of the parser that created the element, then abort these steps.

  10. If scripting is disabled for the script element, then abort these steps at this point. The script is not executed.

    The definition of scripting is disabled means that, amongst others, the following scripts will not execute: scripts in XMLHttpRequest's responseXML documents, scripts in DOMParser-created documents, scripts in documents created by XSLTProcessor’s transformToDocument feature, and scripts that are first inserted by a script into a Document that was created using the createDocument() API. [XHR] [DOM-Parsing] [DOM]

  11. If the script element does not have a src content attribute, and the Should element’s inline behavior be blocked by Content Security Policy? algorithm returns "Blocked" when executed upon the script element, "script", and the script element’s child text content, then abort these steps. The script is not executed. [CSP3]

  12. If the script element has an event attribute and a for attribute, and the script’s type is "classic", then run these substeps:

    1. Let for be the value of the for attribute.

    2. Let event be the value of the event attribute.

    3. Strip leading and trailing whitespace from event and for.

    4. If for is not an ASCII case-insensitive match for the string "window", then the user agent must abort these steps at this point. The script is not executed.

    5. If event is not an ASCII case-insensitive match for either the string "onload" or the string "`onload()`", then the user agent must abort these steps at this point. The script is not executed.

  13. If the script element has a charset attribute, then let encoding be the result of getting an encoding from the value of the charset attribute.

    If the script element does not have a charset attribute, or if getting an encoding failed, let encoding be the same as the encoding of the document itself.

  14. Let CORS setting be the current state of the element’s crossorigin content attribute.

  15. If the script element has a nonce attribute, then let cryptographic nonce be that attribute’s value.

    Otherwise, let cryptographic nonce be the empty string.

  16. Let parser state be "parser-inserted" if the script element has been flagged as "parser-inserted", and "`not parser-inserted`" otherwise.

  17. Let settings be the element’s node document’s Window object’s environment settings object.

  18. If the element has a src content attribute, run these substeps:

    1. Let src be the value of the element’s src attribute.

    2. If src is the empty string, queue a task to fire a simple event named error at the element, and abort these steps.

    3. Set the element’s from an external file flag.

    4. Parse src relative to the element’s node document.

    5. If the previous step failed, queue a task to fire a simple event named error at the element, and abort these steps.

      Otherwise, let url be the resulting URL record.

    6. Switch on the script’s type:

      `"classic"`
      Fetch a classic script given url, CORS setting, cryptographic nonce, parser state, settings, and encoding.
      When the chosen algorithm asynchronously completes, set the script’s script to the result. At that time, the script is ready.

      For performance reasons, user agents may start fetching the classic script (as defined above) as the src attribute is set, instead, in the hope that the element will be inserted into the document (and that the crossorigin attribute won’t change value in the meantime). Either way, once the element is inserted into the document, the load must have started as described in this step. If the UA performs such prefetching, but the element is never inserted in the document, or the src attribute is dynamically changed, or the 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.

  19. If the element does not have a src content attribute, run these substeps:

    1. Let source text be the value of the text IDL attribute.

    2. Switch on the script’s type:

      `"classic"`
      1. Let script be the result of creating a classic script using source text and settings.

      2. Set the script’s script to script.

      3. The script is ready.

  20. Then, follow the first of the following options that describes the situation:

    the script’s type src present? defer present? async present? other conditions
    `"classic"` yes yes no element flagged as "parser-inserted"
    Add the element to the end of the list of scripts that will execute when the document has finished parsing associated with the Document of the parser that created the element.

    When the the script is ready, set the element’s "ready to be parser-executed" flag. The parser will handle executing the script.

    the script’s type src present? defer present? async present? other conditions
    `"classic"` yes no no element flagged as "parser-inserted"
    The element is the pending parsing-blocking script of the Document of the parser that created the element. (There can only be one such script per Document at a time.)

    When the script is ready, set the element’s "ready to be parser-executed" flag. The parser will handle executing the script.

    the script’s type src present? defer present? async present? other conditions
    `"classic"` yes yes or no no "non-blocking" flag not set on element
    Add the element to the end of the list of scripts that will execute in order as soon as possible associated with the node document of the script element at the time the prepare a script algorithm started.

    When the script is ready, run the following steps:

    1. If the element is not now the first element in the list of scripts that will execute in order as soon as possible to which it was added above, then mark the element as ready but abort these steps without executing the script yet.

    2. Execution: Execute the script block corresponding to the first script element in this list of scripts that will execute in order as soon as possible.

    3. Remove the first element from this list of scripts that will execute in order as soon as possible.

    4. If this list of scripts that will execute in order as soon as possible is still not empty and the first entry has already been marked as ready, then jump back to the step labeled Execution.

    the script’s type src present? defer present? async present? other conditions
    `"classic"` yes yes or no yes or no n/a
    The element must be added to the set of scripts that will execute as soon as possible of the node document of the script element at the time the prepare a script algorithm started.

    When the script is ready, execute the script block and then remove the element from the set of scripts that will execute as soon as possible.

    the script’s type src present? defer present? async present? other conditions
    `"classic"` no yes or no yes or no All of the following:
    The element is the pending parsing-blocking script of the Document of the parser that created the element. (There can only be one such script per Document at a time.)

    Set the element’s "ready to be parser-executed" flag. The parser will handle executing the script.

    Otherwise
    Immediately execute the script block, even if other scripts are already executing.

The pending parsing-blocking script of a Document is used by the Document's parser(s).

If a script element that blocks a parser gets moved to another 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 pending parsing-blocking script because there was a style sheet that is blocking scripts when it was parsed, but then the script is moved to another Document before the style sheet loads, the script still blocks the parser until the style sheets are all loaded, at which time the script executes and the parser is unblocked).

When the user agent is required to execute a script block, it must run the following steps:

  1. If the element is flagged as "parser-inserted", but the element’s node document is not the Document of the parser that created the element, then abort these steps.

  2. If the script’s script is null, fire a simple event named error at the element, and abort these steps.

  3. If the script is from an external file, then increment the ignore-destructive-writes counter of the script element’s node document. Let neutralized doc be that Document.

  4. Let old script element be the value to which the script element’s node document’s currentScript object was most recently set.

  5. Switch on the script’s type:

    `"classic"`
    1. Set the script element’s node document’s currentScript attribute to the script element.

      This does not use the in a document check, as the script element could have been removed from the document prior to execution, and in that scenario currentScript still needs to point to it.

    2. Run the classic script given by the script’s script.

  6. Set the script element’s node document’s currentScript object to old script element.

  7. Decrement the ignore-destructive-writes counter of neutralized doc, if it was incremented in the earlier step.

  8. If the script’s type is "classic" and the script is from an external file, fire a simple event named load at the script element.

    Otherwise queue a task to fire a simple event named load at the script element.

4.12.1.2. Scripting languages

A JavaScript MIME type is a MIME type string that is one of the following and refers to JavaScript: [ECMA-262]

  • application/ecmascript
  • application/javascript
  • application/x-ecmascript
  • application/x-javascript
  • text/ecmascript
  • text/javascript
  • text/javascript1.0
  • text/javascript1.1
  • text/javascript1.2
  • text/javascript1.3
  • text/javascript1.4
  • text/javascript1.5
  • text/jscript
  • text/livescript
  • text/x-ecmascript
  • text/x-javascript

User agents must recognize all JavaScript MIME types.

User agents may support other MIME types for other languages, but must not support other MIME types for the languages in the list above. User agents are not required to support JavaScript. The processing model for languages other than JavaScript is outside the scope of this specification.

The following MIME types (with or without parameters) must not be interpreted as scripting languages:

  • `text/plain`

  • `text/xml`

  • `application/octet-stream`

  • `application/xml`

These types are explicitly listed here because they are poorly-defined types that are nonetheless likely to be used as formats for data blocks, and it would be problematic if they were suddenly to be interpreted as script by a user agent.

When examining types to determine if they represent supported languages, user agents must not ignore MIME parameters. Types are to be compared including all parameters.

For example, types that include the charset parameter will not be recognized as referencing any of the scripting languages listed above.

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 "`<!--`" as "`<\!--`", "`<script`" as "`<\script`", and "`</script`" as "`<\/script`" when these sequences appear in literals in scripts (e.g., in strings, regular expressions, or comments), and to avoid writing code that uses such constructs in expressions. Doing so avoids the pitfalls that the restrictions in this section are prone to triggering: namely, that, for historical reasons, parsing of script blocks in HTML is a strange and exotic practice that acts unintuitively in the face of these sequences.

The textContent of a script element must match the script production in the following ABNF, the character set for which is Unicode. [ABNF]

script        = outer *( comment-open inner comment-close outer )

outer         = < any string that doesn’t contain a substring that matches not-in-outer >
not-in-outer  = comment-open
inner         = < any string that doesn’t contain a substring that matches not-in-inner >
not-in-inner  = comment-close / script-open

comment-open  = "<!--"
comment-close = "-->"
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

tag-end       =  %x0009 ; U+0009 CHARACTER TABULATION (tab)
tag-end       =/ %x000A ; U+000A LINE FEED (LF)
tag-end       =/ %x000C ; U+000C FORM FEED (FF)
tag-end       =/ %x0020 ; U+0020 SPACE
tag-end       =/ %x002F ; U+002F SOLIDUS (/)
tag-end       =/ %x003E ; U+003E GREATER-THAN SIGN (>)

When a script element contains script documentation, there are further restrictions on the contents of the element, as described in the section below.

The following script illustrates this issue. Suppose you have a script that contains a string, as in:
var example = 'Consider this string: <!-- <script>';
console.log(example);

If one were to put this string directly in a script block, it would violate the restrictions above:

<script>
  var example = 'Consider this string: <!-- <script>';
  console.log(example);
</script>

The bigger problem, though, and the reason why it would violate those restrictions, is that actually the script would get parsed weirdly: the script block above is not terminated. That is, what looks like a "`</script>`" end tag in this snippet is actually still part of the script block. The script doesn’t execute (since it’s not terminated); if it somehow were to execute, as it might if the markup looked as follows, it would fail because the script is not valid JavaScript:

<script>
  var example = 'Consider this string: <!-- <script>';
  console.log(example);
</script>
<!-- despite appearances, this is actually part of the script still! -->
<script>
  ... // this is the same script block still...
</script>

What is going on here is that for legacy reasons, "`<!--`" and "`<script`" strings in script elements in HTML need to be balanced in order for the parser to consider closing the block.

By escaping the problematic strings as mentioned at the top of this section, the problem is avoided entirely:

<script>
  var example = 'Consider this string: <\!-- <\script>';
  console.log(example);
</script>
<!-- this is just a comment between script blocks -->
<script>
  ... // this is a new script block
</script>

It is possible for these sequences to naturally occur in script expressions, as in the following examples:

if (x<!--y) { ... }
if ( player<script ) { ... }

In such cases the characters cannot be escaped, but the expressions can be rewritten so that the sequences don’t occur, as in:

if (x < !--y) { ... }
if (!--y > x) { ... }
if (!(--y) > x) { ... }
if (player < script) { ... }
if (script > player) { ... }

Doing this also avoids a different pitfall as well: for related historical reasons, the string "`<!--`" in classic scripts is actually treated as a line comment start, just like "`//`".

4.12.1.4. Inline documentation for external scripts

If a script element’s src attribute is specified, then the contents of the script element, if any, must be such that the value of the text IDL attribute, which is derived from the element’s contents, matches the documentation production in the following ABNF, the character set for which is Unicode. [ABNF]

documentation = *( *( space / tab / comment ) [ line-comment ] newline )
comment       = slash star *( not-star / star not-slash ) 1*star slash
line-comment  = slash slash *not-newline

; characters
tab           = %x0009 ; U+0009 CHARACTER TABULATION (tab)
newline       = %x000A ; U+000A LINE FEED (LF)
space         = %x0020 ; U+0020 SPACE
star          = %x002A ; U+002A ASTERISK (*)
slash         = %x002F ; U+002F SOLIDUS (/)
not-newline   = %x0000-0009 / %x000B-10FFFF
                ; a Unicode character other than U+000A LINE FEED (LF)
not-star      = %x0000-0029 / %x002B-10FFFF
                ; a Unicode character other than U+002A ASTERISK (*)
not-slash     = %x0000-002E / %x0030-10FFFF
                ; a Unicode character other than U+002F SOLIDUS (/)

This corresponds to putting the contents of the element in JavaScript comments.

This requirement is in addition to the earlier restrictions on the syntax of contents of script elements.

This allows authors to include documentation, such as license information or API information, inside their documents while still referring to external script files. The syntax is constrained so that authors don’t accidentally include what looks like valid script while also providing a src attribute.
<script src="cool-effects.js">
  // create new instances using:
  //    var e = new Effect();
  // start the effect using .play, stop using .stop:
  //    e.play();
  //    e.stop();
</script>
4.12.1.5. Interaction of script elements and XSLT

This section is non-normative.

This specification does not define how XSLT interacts with the script element. However, in the absence of another specification actually defining this, here are some guidelines for implementors, based on existing implementations:

The main distinction between the first two cases and the last case is that the first two operate on Documents and the last operates on a fragment.

4.12.2. The noscript element

Categories:
Metadata content.
Flow content.
Phrasing content.
Contexts in which this element can be used:
In a head element of an HTML document, if there are no ancestor noscript elements.
Where phrasing content is expected in HTML documents, if there are no ancestor noscript elements.
Content model:
When scripting is disabled, in a head element: in any order, zero or more link elements, zero or more style elements, and zero or more meta elements.
When scripting is disabled, not in a head element: transparent, but there must be no noscript element descendants.
Otherwise: text that conforms to the requirements given in the prose.
Tag omission in text/html:
Neither tag is omissible
Content attributes:
Global attributes
Allowed ARIA role attribute values:
None
Allowed ARIA state and property attributes:
Global aria-* attributes
DOM interface:
Uses HTMLElement.

The noscript element represents nothing if scripting is enabled, and represents its children if scripting is disabled. It is used to present different markup to user agents that support scripting and those that don’t support scripting, by affecting how the document is parsed.

When used in HTML documents, the allowed content model is as follows:

In a head element, if scripting is disabled for the noscript element

The noscript element must contain only link, style, and meta elements.

In a head element, if scripting is enabled for the noscript element

The noscript element must contain only text, except that invoking the HTML fragment parsing algorithm with the noscript element as the context element and the text contents as the input must result in a list of nodes that consists only of link, style, and meta elements that would be conforming if they were children of the noscript element, and no parse errors.

Outside of head elements, if scripting is disabled for the noscript element

The noscript element’s content model is transparent, with the additional restriction that a noscript element must not have a noscript element as an ancestor (that is, noscript can’t be nested).

Outside of head elements, if scripting is enabled for the noscript element

The noscript element must contain only text, except that the text must be such that running the following algorithm results in a conforming document with no noscript elements and no script elements, and such that no step in the algorithm throws an exception or causes an HTML parser to flag a parse error:

  1. Remove every script element from the document.

  2. Make a list of every noscript element in the document. For every noscript element in that list, perform the following steps:

    1. Let s be the concatenation of all the Text node children of the noscript element.

    2. Set the outerHTML attribute of the noscript element to the value of s. (This, as a side-effect, causes the noscript element to be removed from the document.) [DOM-Parsing]

All these contortions are required because, for historical reasons, the noscript element is handled differently by the HTML parser based on whether scripting was enabled or not when the parser was invoked.

The noscript element must not be used in XML documents.

The noscript element is only effective in the HTML syntax, it has no effect in the XHTML syntax. This is because the way it works is by essentially "turning off" the parser when scripts are enabled, so that the contents of the element are treated as pure text and not as real elements. XML does not define a mechanism by which to do this.

The noscript element has no other requirements. In particular, children of the noscript element are not exempt from §4.10.22 Form submission, scripting, and so forth, even when scripting is enabled for the element.

In the following example, a noscript element is used to provide fallback for a script.
<form action="calcSquare.php">
  <p>
  <label for=x>Number</label>:
  <input id="x" name="x" type="number">
  </p>
  <script>
  var x = document.getElementById('x');
  var output = document.createElement('p');
  output.textContent = 'Type a number; it will be squared right then!';
  x.form.appendChild(output);
  x.form.onsubmit = function () { return false; }
  x.oninput = function () {
    var v = x.valueAsNumber;
    output.textContent = v + ' squared is ' + v * v;
  };
  </script>
  <noscript>
  <input type=submit value="Calculate Square">
  </noscript>
</form>

When script is disabled, a button appears to do the calculation on the server side. When script is enabled, the value is computed on-the-fly instead.

The noscript element is a blunt instrument. Sometimes, scripts might be enabled, but for some reason the page’s script might fail. For this reason, it’s generally better to avoid using noscript, and to instead design the script to change the page from being a scriptless page to a scripted page on the fly, as in the next example:

<form action="calcSquare.php">
  <p>
  <label for=x>Number</label>:
  <input id="x" name="x" type="number">
  </p>
  <input id="submit" type=submit value="Calculate Square">
  <script>
  var x = document.getElementById('x');
  var output = document.createElement('p');
  output.textContent = 'Type a number; it will be squared right then!';
  x.form.appendChild(output);
  x.form.onsubmit = function () { return false; }
  x.oninput = function () {
    var v = x.valueAsNumber;
    output.textContent = v + ' squared is ' + v * v;
  };
  var submit = document.getElementById('submit');
  submit.parentNode.removeChild(submit);
  </script>
</form>

The above technique is also useful in XHTML, since noscript is not supported in the XHTML syntax.

4.12.3. The template element

Categories:
Metadata content.
Flow content.
Phrasing content.
Script-supporting element.
Contexts in which this element can be used:
Where metadata content is expected.
Where phrasing content is expected.
Where script-supporting elements are expected.
As a child of a colgroup element that doesn’t have a span attribute.
Content model:
Either: Metadata content.
Or: Flow content.
Or: The content model of ol and ul elements.
Or: The content model of dl elements.
Or: The content model of figure elements.
Or: The content model of ruby elements.
Or: The content model of object elements.
Or: The content model of video and audio elements.
Or: The content model of table elements.
Or: The content model of colgroup elements.
Or: The content model of thead, tbody, and tfoot elements.
Or: The content model of tr elements.
Or: The content model of fieldset elements.
Or: The content model of select elements.
Or: The content model of details elements.
Or: The content model of menu elements whose type attribute is in the popup menu state.
Tag omission in text/html:
Neither tag is omissible
Content attributes:
Global attributes
Allowed ARIA role attribute values:
None
Allowed ARIA state and property attributes:
Global aria-* attributes
DOM interface:
interface HTMLTemplateElement : HTMLElement {
  readonly attribute DocumentFragment content;
};

The template element is used to declare fragments of HTML that can be cloned and inserted in the document by script.

Templates provide a method for declaring inert DOM subtrees and manipulating them to instantiate document fragments with identical contents.

When web pages dynamically alter the contents of their documents (e.g., in response to user interaction or new data arriving from the server), it is common that they require fragments of HTML which may require further modification before use, such as the insertion of values appropriate for the usage context.

The template element allows for the declaration of document fragments which are unused by the document when loaded, but are parsed as HTML and are available at runtime for use by the web page.

In a rendering, the template element represents nothing.

template . content

Returns the contents of the template, which are stored in a DocumentFragment associated with a different Document so as to avoid the template contents interfering with the main Document. (For example, this avoids form controls from being submitted, scripts from executing, and so forth.)

Each template element has an associated DocumentFragment object that is its template contents. When a template element is created, the user agent must run the following steps to establish the template contents:

  1. Let doc be the template element’s node document’s appropriate template contents owner document.
  2. Create a DocumentFragment object whose node document is doc.
  3. Set the template element’s template contents to the newly created DocumentFragment object.

A Document doc’s appropriate template contents owner document is the Document returned by the following algorithm:

  1. If doc is not a Document created by this algorithm, run these substeps:

    1. If doc does not yet have an associated inert template document then run these substeps:

      1. Let new doc be a new Document (that does not have a browsing context). This is "a Document created by this algorithm" for the purposes of the step above.
      2. If doc is an HTML document, mark new doc as an HTML document also.
      3. Let doc’s associated inert template document be new doc.
    2. Set doc to doc’s associated inert template document.

    Each Document not created by this algorithm thus gets a single Document to act as its proxy for owning the template contents of all its template elements, so that they aren’t in a browsing context and thus remain inert (e.g., scripts do not run). Meanwhile, template elements inside Document objects that are created by this algorithm just reuse the same Document owner for their contents.

  2. Return doc.

The adopting steps (with node and oldDocument as parameters) for template elements are the following:

  1. Let doc be node’s node document’s appropriate template contents owner document.

    node’s node document is the Document object that node was just adopted into.

  2. Adopt node’s template contents (a DocumentFragment object) into doc.

The content IDL attribute must return the template element’s template contents.


The cloning steps for a template element node being cloned to a copy copy must run the following steps:

  1. If the clone children flag is not set in the calling clone algorithm, abort these steps.
  2. Let copied contents be the result of cloning all the children of node’s template contents, with document set to copy’s template contents’s node document, and with the clone children flag set.
  3. Append copied contents to copy’s template contents.
In this example, a script populates a table four-column with data from a data structure, using a template to provide the element structure instead of manually generating the structure from markup.
<!DOCTYPE html>
<title>Cat data</title>
<script>
  // Data is hard-coded here, but could come from the server
  var data = [
    { name: 'Pillar', color: 'Ticked Tabby', sex: 'Female (neutered)', legs: 3 },
    { name: 'Hedral', color: 'Tuxedo', sex: 'Male (neutered)', legs: 4 },
  ];
</script>
<table>
  <thead>
  <tr>
    <th>Name <th>Color <th>Sex <th>Legs
  <tbody>
  <template id="row">
    <tr><td><td><td><td>
  </template>
</table>
<script>
  var template = document.querySelector('#row');
  for (var i = 0; i < data.length; i += 1) {
    var cat = data[i];
    var clone = template.content.cloneNode(true);
    var cells = clone.querySelectorAll('td');
    cells[0].textContent = cat.name;
    cells[1].textContent = cat.color;
    cells[2].textContent = cat.sex;
    cells[3].textContent = cat.legs;
    template.parentNode.appendChild(clone);
  }
</script>

This example uses cloneNode() on the template’s contents; it could equivalently have used document.importNode(), which does the same thing. The only difference between these two APIs is when the node document is updated: with cloneNode() it is updated when the nodes are appended with appendChild(), with document.importNode() it is updated when the nodes are cloned.

4.12.3.1. Interaction of template elements with XSLT and XPath

This section is non-normative.

This specification does not define how XSLT and XPath interact with the template element. However, in the absence of another specification actually defining this, here are some guidelines for implementors, which are intended to be consistent with other processing described in this specification:

  • An XSLT processor based on an XML parser that acts as described in this specification needs to act as if template elements contain as descendants their template contents for the purposes of the transform.
  • An XSLT processor that outputs a DOM needs to ensure that nodes that would go into a template element are instead placed into the element’s template contents.
  • XPath evaluation using the XPath DOM API when applied to a Document parsed using the HTML parser or the XML parser described in this specification needs to ignore template contents.

4.12.4. The canvas element

Categories:
Flow content.
Phrasing content.
Embedded content.
Palpable content.
Contexts in which this element can be used:
Where embedded content is expected.
Content model:
Transparent.
Tag omission in text/html:
Neither tag is omissible
Content attributes:
Global attributes
width - Horizontal dimension
height - Vertical dimension
Allowed ARIA role attribute values:
Any role value.
Allowed ARIA state and property attributes:
Global aria-* attributes
Any aria-* attributes applicable to the allowed roles.
DOM interface:
typedef (CanvasRenderingContext2D or WebGLRenderingContext) RenderingContext;

interface HTMLCanvasElement : HTMLElement {
  attribute unsigned long width;
  attribute unsigned long height;

  RenderingContext? getContext(DOMString contextId, any... arguments);
  boolean probablySupportsContext(DOMString contextId, any... arguments);

  DOMString toDataURL(optional DOMString type, any... arguments);
  void toBlob(BlobCallback _callback, optional DOMString type, any... arguments);
};

callback BlobCallback = void (Blob? blob);

The canvas element provides scripts with a resolution-dependent bitmap canvas, which can be used for rendering graphs, game graphics, art, or other visual images on the fly.

Authors should not use the canvas element in a document when a more suitable element is available. For example, it is inappropriate to use a canvas element to render a page heading: if the desired presentation of the heading is graphically intense, it should be marked up using appropriate elements (typically h1) and then styled using CSS and supporting technologies such as Web Components.

When authors use the canvas element, they must also provide content that, when presented to the user, conveys essentially the same function or purpose as the canvas's bitmap. This content may be placed as content of the canvas element. The contents of the canvas element, if any, are the element’s fallback content.


In interactive visual media, if scripting is enabled for the canvas element, and if support for canvas elements has been enabled, the canvas element represents embedded content consisting of a dynamically created image, the element’s bitmap.

In non-interactive, static, visual media, if the canvas element has been previously associated with a rendering context (e.g., if the page was viewed in an interactive visual medium and is now being printed, or if some script that ran during the page layout process painted on the element), then the canvas element represents embedded content with the element’s current bitmap and size. Otherwise, the element represents its fallback content instead.

In non-visual media, and in visual media if scripting is disabled for the canvas element or if support for canvas elements has been disabled, the canvas element represents its fallback content instead.

When a canvas element represents embedded content, the user can still focus descendants of the canvas element (in the fallback content). When an element is focused, it is the target of keyboard interaction events (even though the element itself is not visible). This allows authors to make an interactive canvas keyboard-accessible: authors should have a one-to-one mapping of interactive regions to focusable areas in the fallback content. (Focus has no effect on mouse interaction events.) [UIEVENTS]

An element whose nearest canvas element ancestor is being rendered and represents embedded content is an element that is being used as relevant canvas fallback content.


The canvas element has two attributes to control the size of the element’s bitmap: width and height. These attributes, when specified, must have values that are valid non-negative integers. The rules for parsing non-negative integers must be used to obtain their numeric values. If an attribute is missing, or if parsing its value returns an error, then the default value must be used instead. The width attribute defaults to 300, and the height attribute defaults to 150.

The intrinsic dimensions of the canvas element when it represents embedded content are equal to the dimensions of the element’s bitmap.

The user agent must use a square pixel density consisting of one pixel of image data per coordinate space unit for the bitmaps of a canvas and its rendering contexts.

A canvas element can be sized arbitrarily by a style sheet, its bitmap is then subject to the object-fit CSS property. [CSS3-IMAGES]


The bitmaps of canvas elements, the bitmaps of ImageBitmap objects, as well as some of the bitmaps of rendering contexts, such as those described in the section on the CanvasRenderingContext2D object below, have an origin-clean flag, which can be set to true or false. Initially, when the canvas element or ImageBitmap object is created, its bitmap’s origin-clean flag must be set to true.

A canvas bitmap can also have a hit region list, as described in the CanvasRenderingContext2D section below.

A canvas element 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, a canvas also has a canvas context mode, which is initially none but can be changed to either 2d, webgl by algorithms defined in this specification.

When its canvas context mode is none, a canvas element has no rendering context, and its bitmap must be fully transparent black with an intrinsic width equal to the numeric value of the element’s width attribute and an intrinsic height equal to the numeric value of the element’s height attribute, those values being interpreted in CSS pixels, and being updated as the attributes are set, changed, or removed.

When a canvas element represents embedded content, it provides a paint source whose width is the element’s intrinsic width, whose height is the element’s intrinsic height, and whose appearance is the element’s bitmap.

Whenever the width and height content attributes are set, removed, changed, or redundantly set to the value they already have, if the canvas context mode is 2d, the user agent must set bitmap dimensions to the numeric values of the width and height content attributes.

The width and height IDL attributes must reflect the respective content attributes of the same name, with the same defaults.


context = canvas . getContext(contextId [, ... ] )

Returns an object that exposes an API for drawing on the canvas. The first argument specifies the desired API, either "2d" or "webgl". Subsequent arguments are handled by that API.

The list of defined contexts is given on the WHATWG Wiki CanvasContexts page. [WHATWGWIKI]

Example contexts are the "2d" [CANVAS-2D] and the "webgl" context [WEBGL].

Returns null if the given context ID is not supported or if the canvas has already been initialized with some other (incompatible) context type (e.g., trying to get a "2d" context after getting a "webgl" context).

supported = canvas . probablySupportsContext(contextId [, ... ] )

Returns false if calling getContext() with the same arguments would definitely return null, and true otherwise.

This return value is not a guarantee that getContext() will or will not return an object, as conditions (e.g., availability of system resources) can vary over time.

The getContext(contextId, arguments...) method of the canvas element, when invoked, must run the steps in the cell of the following table whose column header describes the canvas element’s canvas context mode and whose row header describes the method’s first argument.

getContext() invocation steps
none 2d webgl
"2d"

Set the canvas element’s context mode to 2d, obtain a CanvasRenderingContext2D object as defined in the HTML Canvas 2D Context specification [CANVAS-2D], set the obtained CanvasRenderingContext2D object’s context mode to 2d, and return the CanvasRenderingContext2D object

Return the same object as was return the last time the method was invoked with this same first argument. Return null.
"webgl", if the user agent supports the WebGL feature in its current configuration Follow the instructions given in the WebGL specification’s Context Creation section to obtain either a WebGLRenderingContext or null; if the returned value is null, then return null and abort these steps, otherwise, set the canvas element’s context mode to webgl, set the new WebGLRenderingContext object’s context mode to webgl, and return the WebGLRenderingContext object‡ [WEBGL] Return null. Return the same object as was return the last time the method was invoked with this same first argument.
A vendor-specific extension* Behave as defined for the extension. Behave as defined for the extension. Behave as defined for the extension.
An unsupported value† Return null. Return null. Return null.

* Vendors may define experimental contexts using the syntax vendorname-context, for example, moz-3d.

† For example, the "webgl" value in the case of a user agent having exhausted the graphics hardware’s abilities and having no software fallback implementation.

‡ The second (and subsequent) argument(s) to the method, if any, are ignored in all cases except this one. See the WebGL specification for details.


There is no known native implementation of the probablySupportsContext() method. Therefore this feature should not be relied upon.

The probablySupportsContext(contextId, arguments...) method of the canvas element, when invoked, must return false if calling getContext() on the same object and with the same arguments would definitely return null at this time, and true otherwise.


url = canvas . toDataURL( [ type, ... ] )

Returns a data: URL for the image in the canvas.

The first argument, if provided, controls the type of the image to be returned (e.g., PNG or JPEG). The default is image/png; that type is also used if the given type isn’t supported. The other arguments are specific to the type, and control the way that the image is generated, as given in the table below.

When trying to use types other than "image/png", authors can check if the image was really returned in the requested format by checking to see if the returned string starts with one of the exact strings "data:image/png," or "data:image/png;". If it does, the image is PNG, and thus the requested type was not supported. (The one exception to this is if the canvas has either no height or no width, in which case the result might simply be "data:,".)

canvas . toBlob(callback [, type, ... ] )

Creates a Blob object representing a file containing the image in the canvas, and invokes a callback with a handle to that object.

The second argument, if provided, controls the type of the image to be returned (e.g., PNG or JPEG). The default is image/png; that type is also used if the given type isn’t supported. The other arguments are specific to the type, and control the way that the image is generated, as given in the table below.

The toDataURL() method must run the following steps:

  1. If the canvas element’s bitmap’s origin-clean flag is set to false, throw a "SecurityError" DOMException and abort these steps.
  2. If the canvas element’s bitmap has no pixels (i.e., either its horizontal dimension or its vertical dimension is zero) then return the string "data:," and abort these steps. (This is the shortest data: URL; it represents the empty string in a text/plain resource.)
  3. Let file be a serialization of the canvas element’s bitmap as a file, using the method’s arguments (if any) as the arguments.
  4. Return a data: URL representing file. [RFC2397]

The toBlob() method must run the following steps:

  1. If the canvas element’s bitmap’s origin-clean flag is set to false, throw a "SecurityError" DOMException and abort these steps.
  2. Let callback be the first argument.
  3. Let arguments be the second and subsequent arguments to the method, if any.
  4. If the canvas element’s bitmap has no pixels (i.e., either its horizontal dimension or its vertical dimension is zero) then let result be null.

    Otherwise, let result be a Blob object representing a serialization of the canvas element’s bitmap as a file, using arguments. [FILEAPI]

  5. Return, but continue running these steps in parallel.
  6. Queue a task to invoke the BlobCallback callback with result as its argument. The task source for this task is the canvas blob serialization task source.
4.12.4.1. Color spaces and color correction

The canvas APIs must perform color correction at only two points: when rendering images with their own gamma correction and color space information onto a bitmap, to convert the image to the color space used by the bitmaps (e.g., using the 2D Context’s drawImage() method with an HTMLImageElement object), and when rendering the actual canvas bitmap to the output device.

Thus, in the 2D context, colors used to draw shapes onto the canvas will exactly match colors obtained through the getImageData() method.

The toDataURL() method must not include color space information in the resources they return. Where the output format allows it, the color of pixels in resources created by toDataURL() must match those returned by the getImageData() method.

In user agents that support CSS, the color space used by a canvas element must match the color space used for processing any colors for that element in CSS.

The gamma correction and color space information of images must be handled in such a way that an image rendered directly using an img element would use the same colors as one painted on a canvas element that is then itself rendered. Furthermore, the rendering of images that have no color correction information (such as those returned by the toDataURL() method) must be rendered with no color correction.

Thus, in the 2D context, calling the drawImage() method to render the output of the toDataURL() method to the canvas, given the appropriate dimensions, has no visible effect.

4.12.4.2. Serializing bitmaps to a file

When a user agent is to create a serialization of the bitmap as a file, optionally with some given arguments, and optionally with a native flag set, it must create an image file in the format given by the first value of arguments, or, if there are no arguments, in the PNG format. [PNG]

If the native flag is set, or if the bitmap has one pixel per coordinate space unit, then the image file must have the same pixel data (before compression, if applicable) as the bitmap, and if the file format used supports encoding resolution metadata, the resolution of that bitmap (device pixels per coordinate space units being interpreted as image pixels per CSS pixel) must be given as well.

Otherwise, 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 CSS pixel).

If arguments is not empty, the first value must be interpreted as a MIME type giving the format to use. If the type has any parameters, it must be treated as not supported.

For example, the value "image/png" would mean to generate a PNG image, the value "image/jpeg" would mean to generate a JPEG image, and the value "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 ("image/png"). User agents may support other types. If the user agent does not support the requested type, it must create the file using the PNG format. [PNG]

User agents must convert the provided type to ASCII lowercase before establishing if they support that type.

For image types that do not support an alpha channel, the serialized image must be the bitmap image composited onto a solid black background using the source-over operator.

If the first argument in arguments gives a type corresponding to one of the types given in the first column of the following table, and the user agent supports that type, then the subsequent arguments, if any, must be treated as described in the second cell of that row.

Arguments for serialization methods
Type Other arguments Reference
image/jpeg The second argument, if it is a number in the range 0.0 to 1.0 inclusive, must be treated as the desired quality level. If it is not a number or is outside that range, the user agent must use its default value, as if the argument had been omitted. [JPEG]

For the purposes of these rules, an argument is considered to be a number if it is converted to an IDL double value by the rules for handling arguments of type any in the Web IDL specification. [WEBIDL]

Other arguments must be ignored and must not cause the user agent to throw an exception. A future version of this specification will probably define other parameters to be passed to these methods to allow authors to more carefully control compression settings, image metadata, etc.

4.12.4.3. Security with canvas elements

This section is non-normative.

Information leakage can occur if scripts from one origin can access information (e.g., read pixels) from images from another origin (one that isn’t the same).

To mitigate this, bitmaps used with canvas elements and ImageBitmap objects are defined to have a flag indicating whether they are origin-clean. All bitmaps start with their origin-clean set to true. The flag is set to false when cross-origin images or fonts are used.

The toDataURL(), toBlob(), and getImageData() methods check the flag and will throw a "SecurityError" DOMException rather than leak cross-origin data.

The value of the origin-clean flag is propagated from a source canvas element’s bitmap to a new ImageBitmap object by createImageBitmap(). Conversely, a destination canvas element’s bitmap will have its origin-clean flags set to false by drawImage if the source image is an ImageBitmap object whose bitmap has its origin-clean flag set to false.

The flag can be reset in certain situations; for example, when a CanvasRenderingContext2D is bound to a new canvas, the bitmap is cleared and its flag reset.

4.13. Common idioms without dedicated elements

4.13.1. Subheadings, subtitles, alternative titles and taglines

HTML does not have a dedicated mechanism for marking up subheadings, alternative titles or taglines. Here are the suggested alternatives. h1h6 elements must not be used to markup subheadings, subtitles, alternative titles and taglines unless intended to be the heading for a new section or subsection.
In the following example the title and subtitles of a web page are grouped using a header element. As the author does not want the subtitles to be included the table of contents and they are not intended to signify the start of a new section, they are marked up using p elements. A sample CSS styled rendering of the title and subtitles is provided below the code example.
<header>
  <h1>HTML 5.1 Nightly</h1>
  <p>A vocabulary and associated APIs for HTML and XHTML</p>
  <p>Editor’s Draft 9 May 2013</p>
</header>

Title:'HTML 5.1 Nightly' in a mid blue Sans Serif font.
    Subtitle 1:'A vocabulary and associated APIs for HTML and XHTML' on a new line, same style smaller font size.
    Subtitle 2:'Editor’s Draft 9 May 2013' on a new line, same style and size as subtitle 1.

In the following example the subtitle of a book is on the same line as the title separated by a colon. A sample CSS styled rendering of the title and subtitle is provided below the code example.
<h1>The Lord of the Rings: The Two Towers</h1>

Title and subtitle:'The Lord of the Rings: The Two Towers' in a gold colored Gothic style Serif font on a black background.

In the following example part of an album title is included in a span element, allowing it to be styled differently from the rest of the title. A br element is used to place the album title on a new line. A sample CSS styled rendering of the heading is provided below the code example.
<h1>Ramones <br>
<span>Hey! Ho! Let’s Go</span>
</h1>

 Line 1:'Ramones' displayed in a large bold angular hand writing style font with a spray can paint effect. Line 2:'Hey! Ho! Let’s Go' displayed in a smaller, standard sans serif style font.

In the following example the title and tagline for a news article are grouped using a header element. The title is marked up using a h2 element and the tagline is in a p element. A sample CSS styled rendering of the title and tagline is provided below the code example.
<header>
  <h2>3D films set for popularity slide </h2>
  <p>First drop in 3D box office projected for this year despite hotly tipped summer blockbusters,
  according to Fitch Ratings report</p>
</header>

 Title:'3D films set for popularity slide' in a large, bold, dark blue Serif font style. Paragraph: 'First drop in 3D box office projected for this year despite...' in a smaller, dark grey, Sans Serif font style.

In this last example the title and taglines for a news magazine are grouped using a header element. The title is marked up using a h1 element and the taglines are each in a p element. A sample CSS styled rendering of the title and taglines is provided below the code example.
<header>
  <p>Magazine of the Decade</p>
  <h1>THE MONTH</h1>
  <p>The Best of UK and Foreign Media</p>
</header>

Tagline above the heading:'Magazine of the Decade'. Tagline below the heading 'The Best of UK and Foreign Media' both in a small,all caps, sans-serif font style. Heading:'The Month' in a large, Serif font style. All text is black against a red background.

This specification does not provide a machine-readable way of describing bread-crumb navigation menus. Authors are encouraged to markup bread-crumb navigation as a list. The nav element can be used to mark the list containing links as being a navigation block.

In the following example, the current page can be reached via the path indicated. The path is indicated using the right arrow symbol "→". A text label is provided to give the user context. The links are structured as a list, which provides users with an indication of item number.
<nav>
  <h2>You are here:</h2>
  <ul id="navlist">
    <li><a href="/">Main</a></li>
    <li><a href="/products/">Products</a></li>
    <li><a href="/products/dishwashers/">Dishwashers</a></li>
    <li><a>Second hand</a></li>
  </ul>
</nav>

The breadcrumb code example could be styled as a horizonatal list using CSS: The heading and the links are displayed on one line.

The use of the right angle bracket symbol ">" to indicate path direction is discouraged as its meaning, in the context used, is not clearly conveyed to all users.

4.13.3. Tag clouds

This specification does not define any markup specifically for marking up lists of keywords that apply to a group of pages (also known as tag clouds). In general, authors are encouraged to either mark up such lists using ul elements with explicit inline counts that are then hidden and turned into a presentational effect using a style sheet, or to use SVG.

Here, three tags are included in a short tag cloud:
<style>
@media screen, print, handheld, tv {
  /* should be ignored by non-visual browsers */
  .tag-cloud > li > span { display: none; }
  .tag-cloud > li { display: inline; }
  .tag-cloud-1 { font-size: 0.7em; }
  .tag-cloud-2 { font-size: 0.9em; }
  .tag-cloud-3 { font-size: 1.1em; }
  .tag-cloud-4 { font-size: 1.3em; }
  .tag-cloud-5 { font-size: 1.5em; }
}
</style>
...
<ul class="tag-cloud">
  <li class="tag-cloud-4"><a title="28 instances" href="/t/apple">apple</a> <span>(popular)</span>
  <li class="tag-cloud-2"><a title="6 instances"  href="/t/kiwi">kiwi</a> <span>(rare)</span>
  <li class="tag-cloud-5"><a title="41 instances" href="/t/pear">pear</a> <span>(very popular)</span>
</ul>

The actual frequency of each tag is given using the title attribute. A CSS style sheet is provided to convert the markup into a cloud of differently-sized words, but for user agents that do not support CSS or are not visual, the markup contains annotations like "(popular)" or "(rare)" to categorize the various tags by frequency, thus enabling all users to benefit from the information.

The ul element is used (rather than ol) because the order is not particularly important: while the list is in fact ordered alphabetically, it would convey the same information if ordered by, say, the length of the tag.

The tag rel-keyword is not used on these a elements because they do not represent tags that apply to the page itself; they are just part of an index listing the tags themselves.

4.13.4. Conversations

This specification does not define a specific element for marking up conversations, meeting minutes, chat transcripts, dialogs in screenplays, instant message logs, and other situations where different players take turns in discourse.

Instead, authors are encouraged to mark up conversations using p elements and punctuation. Authors who need to mark the speaker for styling purposes are encouraged to use span or b. Paragraphs with their text wrapped in the i element can be used for marking up stage directions.

This example demonstrates this using an extract from Abbot and Costello’s famous sketch, Who’s on first:
<p> Costello: Look, you gotta first baseman?
<p> Abbott: Certainly.
<p> Costello: Who’s playing first?
<p> Abbott: That’s right.
<p> Costello becomes exasperated.
<p> Costello: When you pay off the first baseman every month, who gets the money?
<p> Abbott: Every dollar of it.
The following extract shows how an IM conversation log could be marked up, using the data element to provide Unix timestamps for each line. Note that the timestamps are provided in a format that the time element does not support, so the data element is used instead (namely, Unix time_t timestamps). Had the author wished to mark up the data using one of the date and time formats supported by the time element, that element could have been used instead of data. This could be advantageous as it would allow data analysis tools to detect the timestamps unambiguously, without coordination with the page author.
<p> <data value="1319898155">14:22</data> <b>egof</b> I’m not that nerdy, I’ve only seen 30% of the star trek episodes
<p> <data value="1319898192">14:23</data> <b>kaj</b> if you know what percentage of the star trek episodes you have seen, you are inarguably nerdy
<p> <data value="1319898200">14:23</data> <b>egof</b> it’s unarguably
<p> <data value="1319898228">14:23</data> <i>* kaj blinks</i>
<p> <data value="1319898260">14:24</data> <b>kaj</b> you are not helping your case
HTML does not have a good way to mark up graphs, so descriptions of interactive conversations from games are more difficult to mark up. This example shows one possible convention using dl elements to list the possible responses at each point in the conversation. Another option to consider is describing the conversation in the form of a DOT file, and outputting the result as an SVG image to place in the document. [DOT]
<p> Next, you meet a fisherman. You can say one of several greetings:
<dl>
  <dt> "Hello there!"
  <dd>
  <p> He responds with "Hello, how may I help you?"; you can respond with:
  <dl>
    <dt> "I would like to buy a fish."
    <dd> <p> He sells you a fish and the conversation finishes.
    <dt> "Can I borrow your boat?"
    <dd>
    <p> He is surprised and asks "What are you offering in return?".
    <dl>
      <dt> "Five gold." (if you have enough)
      <dt> "Ten gold." (if you have enough)
      <dt> "Fifteen gold." (if you have enough)
      <dd> <p> He lends you the boat. The conversation ends.
      <dt> "A fish." (if you have one)
      <dt> "A newspaper." (if you have one)
      <dt> "A pebble." (if you have one)
      <dd> <p> "No thanks", he replies. Your conversation options
      at this point are the same as they were after asking to borrow
      the boat, minus any options you’ve suggested before.
    </dl>
    </dd>
  </dl>
  </dd>
  <dt> "Vote for me in the next election!"
  <dd> <p> He turns away. The conversation finishes.
  <dt> "Sir, are you aware that your fish are running away?"
  <dd>
  <p> He looks at you skeptically and says "Fish cannot run, sir".
  <dl>
    <dt> "You got me!"
    <dd> <p> The fisherman sighs and the conversation ends.
    <dt> "Only kidding."
    <dd> <p> "Good one!" he retorts. Your conversation options at this
    point are the same as those following "Hello there!" above.
    <dt> "Oh, then what are they doing?"
    <dd> <p> He looks at his fish, giving you an opportunity to steal
    his boat, which you do. The conversation ends.
  </dl>
  </dd>
</dl>
In some games, conversations are simpler: each character merely has a fixed set of lines that they say. In this example, a game FAQ/walkthrough lists some of the known possible responses for each character:
<section>
  <h1>Dialog</h1>
  <p><small>Some characters repeat their lines in order each time you interact
  with them, others randomly pick from amongst their lines. Those who respond in
  order have numbered entries in the lists below.</small>
  <h2>The Shopkeeper</h2>
  <ul>
  <li>How may I help you?
  <li>Fresh apples!
  <li>A loaf of bread for madam?
  </ul>
  <h2>The pilot</h2>
  <p>Before the accident:
  <ul>
  </li>I’m about to fly out, sorry!
  </li>Sorry, I’m just waiting for flight clearance and then I’ll be off!
  </ul>
  <p>After the accident:
  <ol>
  <li>I’m about to fly out, sorry!
  <li>Ok, I’m not leaving right now, my plane is being cleaned.
  <li>Ok, it’s not being cleaned, it needs a minor repair first.
  <li>Ok, ok, stop bothering me! Truth is, I had a crash.
  </ol>
  <h2>Clan Leader</h2>
  <p>During the first clan meeting:
  <ul>
  <li>Hey, have you seen my daughter? I bet she’s up to something nefarious again...
  <li>Nice weather we’re having today, eh?
  <li>The name is Bailey, Jeff Bailey. How can I help you today?
  <li>A glass of water? Fresh from the well!
  </ul>
  <p>After the earthquake:
  <ol>
  <li>Everyone is safe in the shelter, we just have to put out the fire!
  <li>I’ll go and tell the fire brigade, you keep hosing it down!
  </ol>
</section>

4.13.5. Footnotes

HTML does not have a dedicated mechanism for marking up footnotes. Here are the suggested alternatives.


For short inline annotations, the title attribute could be used.

In this example, two parts of a dialog are annotated with footnote-like content using the title attribute.
<p> <b>Customer</b>: Hello! I wish to register a complaint. Hello. Miss?
<p> <b>Shopkeeper</b>: <span title="Colloquial pronunciation of 'What do you'"
>Watcha</span> mean, miss?
<p> <b>Customer</b>: Uh, I’m sorry, I have a cold. I wish to make a complaint.
<p> <b>Shopkeeper</b>: Sorry, <span title="This is, of course, a lie.">we’re
closing for lunch</span>.

Relying on the title attribute for the visual display of text content is currently discouraged as many user agents do not expose the attribute in an accessible manner as required by this specification (e.g., requiring a pointing device such as a mouse to cause a tooltip to appear, which excludes keyboard-only users and touch-only users, such as anyone with a modern phone or tablet).

If the title attribute is used, CSS can 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 title attribute.
[title] { border-bottom: thin dashed; }

For annotations, the a element should be used, pointing to an element later in the document. The convention is that the contents of the link be a number in square brackets.

In this example, a footnote in the dialog links to a paragraph below the dialog. The paragraph then reciprocally links back to the dialog, allowing the user to return to the location of the footnote.
<p> Announcer: Number 16: The <i>hand</i>.
<p> Interviewer: Good evening. I have with me in the studio tonight
Mr Norman St John Polevaulter, who for the past few years has been
contradicting people. Mr Polevaulter, why <em>do</em> you
contradict people?
<p> Norman: I don’t. <sup><a href="#fn1" id="r1">[1]</a></sup>
<p> Interviewer: You told me you did!
...
<section>
  <p id="fn1"><a href="#r1">[1]</a> This is, naturally, a lie,
  but paradoxically if it were true he could not say so without
  contradicting the interviewer and thus making it false.</p>
</section>

For side notes, longer annotations that apply to entire sections of the text rather than just specific words or sentences, the aside element should be used.

In this example, a sidebar is given after a dialog, giving it some context.
<p> <span class="speaker">Customer</span>: I will not buy this record, it is scratched.
<p> <span class="speaker">Shopkeeper</span>: I’m sorry?
<p> <span class="speaker">Customer</span>: I will not buy this record, it is scratched.
<p> <span class="speaker">Shopkeeper</span>: No no no, this is a tobacconist’s.
<aside role="note">
  <p>In 1970, the British Empire lay in ruins, and foreign
  nationalists frequented the streets — many of them Hungarians
  (not the streets — the foreign nationals). Sadly, Alexander
  Yalt has been publishing incompetently-written phrase books.
</aside>

In the example above an ARIA role="note", permitted for use on aside, has been added to override the default semantics of the aside element, as the use of the element in this context, more closely matches the note role.


For figures or tables, footnotes can be included in the relevant figcaption or caption element, or in surrounding prose.

In this example, a table has cells with footnotes that are given in prose. A figure element is used to give a single legend to the combination of the table and its footnotes.
<figure>
  <figcaption>Table 1. Alternative activities for knights.</figcaption>
  <table>
  <tr>
    <th> Activity
    <th> Location
    <th> Cost
  <tr>
    <td> Dance
    <td> Wherever possible
    <td> £0<sup><a href="#fn1">1</a></sup>
  <tr>
    <td> Routines, chorus scenes<sup><a href="#fn2">2</a></sup>
    <td> Undisclosed
    <td> Undisclosed
  <tr>
    <td> Dining<sup><a href="#fn3">3</a></sup>
    <td> Camelot
    <td> Cost of ham, jam, and spam<sup><a href="#fn4">4</a></sup>
  </table>
  <p id="fn1">1. Assumed.</p>
  <p id="fn2">2. Footwork impeccable.</p>
  <p id="fn3">3. Quality described as "well".</p>
  <p id="fn4">4. A lot.</p>
</figure>

4.14. Disabled elements

An element is said to be actually disabled if it falls into one of the following categories:

This definition is used to determine what elements can be focused and which elements match the :disabled pseudo-class.

4.15. Matching HTML elements using selectors

4.15.1. Case-sensitivity

The Selectors specification leaves the case-sensitivity of element names, attribute names, and attribute values to be defined by the host language. [CSS3-SELECTORS]

Selectors defines that ID and class selectors, when matched against elements in documents that are in quirks mode, will be matched in an ASCII case-insensitive manner.

When comparing a CSS element type selector to the names of html elements in HTML documents, the CSS element type selector must first be converted to ASCII lowercase. The same selector when compared to other elements must be compared according to its original case. In both cases, the comparison is case-sensitive.

When comparing the name part of a CSS attribute selector to the names of namespace-less attributes on html elements in HTML documents, the name part of the CSS attribute selector must first be 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.

Attribute selectors on an HTML element in an HTML document must treat the values of attributes with the following names as ASCII case-insensitive, with one exception as noted in §10 Rendering:

  • 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 (except as specified in §10 Rendering)
  • valign
  • valuetype
  • vlink

All other attribute values and everything else must be treated as entirely case-sensitive for the purposes of selector matching. This includes:

4.15.2. Pseudo-classes

There is only one known native implementation of :dir(ltr) pseudo-class matching (Firefox/Gecko). Therefore this feature should not be relied upon.

There are a number of dynamic selectors that can be used with HTML. This section defines when these selectors match HTML elements. [CSS3-SELECTORS] [CSS-UI-3]

:link
:visited

All a elements that have an href attribute, all area elements that have an href attribute, and all link elements that have an href attribute, must match one of :link and :visited.

Other specifications might apply more specific rules regarding how these elements are to match these pseudo-classes, to mitigate some privacy concerns that apply with straightforward implementations of this requirement.

:active

The :active pseudo-class is defined to match an element while an element is being activated by the user.

To determine whether a particular element is being activated for the purposes of defining the :active pseudo-class only, an HTML user agent must use the first relevant entry in the following list.

If the element has a descendant that is currently matching the :active pseudo-class
The element is being activated.
If the element is the labeled control of a label element that is currently matching :active
The element is being activated.
If the element is a button element
If the element is an input element whose type attribute is in the submit button, image button, Reset Button, or Button state

The element is being activated if it is in a formal activation state and it is not disabled.

For example, if the user is using a keyboard to push a button element by pressing the space bar, the element would match this pseudo-class in between the time that the element received the keydown event and the time the element received the keyup event.

If the element is a menuitem element
The element is being activated if it is in a formal activation state and it does not have a disabled attribute.
If the element is an a element that has an href attribute
If the element is an area element that has an href attribute
If the element is a link element that has an href attribute
If the element has its tabindex focus flag set
The element is being activated if it is in a formal activation state.
If the element is being actively pointed at
The element is 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 activation behavior and either the time the user stops indicating an intent to trigger the element’s activation behavior, or the time the element’s 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).

:hover

The :hover pseudo-class is defined to match an element while the user designates an element with a pointing device. For the purposes of defining the :hover pseudo-class only, an HTML user agent must consider an element as being one that the user designates if it is:

  • An element that the user indicates using a pointing device.

  • An element that has a descendant that the user indicates using a pointing device.

  • An element that is the labeled control of a label element that is currently matching :hover.

Consider in particular a fragment such as:
<p> <label for=c> <input id=a> </label> <span id=b> <input id=c> </span> </p>

If the user designates the element with ID "a" with their pointing device, then the p element (and all its ancestors not shown in the snippet above), the label element, the element with ID "a", and the element with ID "c" will match the :hover pseudo-class. The element with ID "a" matches it from condition 1, the label and p elements match it because of condition 2 (one of their descendants is designated), and the element with ID "c" matches it through condition 3 (its label element matches :hover). However, the element with ID "b" does not match :hover: its descendant is not designated, even though it matches :hover.

:focus

For the purposes of the CSS ':focus' pseudo-class, an element has the focus when its top-level browsing context has the system focus, it is not itself a browsing context container, and it is one of the elements listed in the focus chain of the currently focused area of the top-level browsing context.

:enabled

The :enabled pseudo-class must match any element that is one of the following:

  • a button element that is not disabled
  • an input element that is not disabled
  • a select element that is not disabled
  • a textarea element that is not disabled
  • an optgroup element that does not have a disabled attribute
  • an option element that is not disabled
  • a menuitem element that does not have a disabled attribute
  • a fieldset element that is not a disabled fieldset
:disabled

The :disabled pseudo-class must match any element that is actually disabled.

:checked

The :checked pseudo-class must match any element falling into one of the following categories:

:indeterminate

The :indeterminate pseudo-class must match any element falling into one of the following categories:

:default

The :default pseudo-class must match any element falling into one of the following categories:

:valid

The :valid pseudo-class must match any element falling into one of the following categories:

:invalid

The :invalid pseudo-class must match any element falling into one of the following categories:

:in-range

The :in-range pseudo-class must match all elements that are candidates for constraint validation, have range limitations, and that are neither suffering from an underflow nor suffering from an overflow.

:out-of-range

The :out-of-range pseudo-class must match all elements that are candidates for constraint validation, have range limitations, and that are either suffering from an underflow or suffering from an overflow.

:required

The :required pseudo-class must match any element falling into one of the following categories:

  • input elements that are required
  • select elements that have a required attribute
  • textarea elements that have a required attribute
:optional

The :optional pseudo-class must match any element falling into one of the following categories:

  • input elements to which the required attribute applies that are not required
  • select elements that do not have a required attribute
  • textarea elements that do not have a required attribute
:read-only
:read-write

The :read-write pseudo-class must match any element falling into one of the following categories, which for the purposes of Selectors are thus considered user-alterable: [CSS3-SELECTORS]

  • input elements to which the readonly attribute applies, and that are mutable (i.e., that do not have the readonly attribute specified and that are not disabled)
  • textarea elements that do not have a readonly attribute, and that are not disabled
  • elements that are editing hosts or editable and are neither input elements nor textarea elements

The :read-only pseudo-class must match all other html elements.

:dir(ltr)

The :dir(ltr) pseudo-class must match all elements whose directionality is 'ltr'.

:dir(rtl)

The :dir(rtl) pseudo-class must match all elements whose directionality is 'rtl'.

Another section of this specification defines the target element used with the :target pseudo-class.

This specification does not define when an element matches the :lang() dynamic pseudo-class, as it is defined in sufficient detail in a language-agnostic fashion in the Selectors specification. [CSS3-SELECTORS]

5. User interaction

5.1. The hidden attribute

All html elements may have the hidden content attribute set. The hidden attribute is a boolean attribute. When specified on an element, it indicates that the element is not yet, or is no longer, directly relevant to the page’s current state, or that it is being used to declare content to be reused by other parts of the page as opposed to being directly accessed by the user. User agents should not render elements that have the hidden attribute specified. This requirement may be implemented indirectly through the style layer. For example, an HTML+CSS user agent could implement these requirements using the rules suggested in §10 Rendering.

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 hidden attribute. Authors therefore have to take care when writing their style sheets to make sure that the attribute is still styled as expected.

In the following skeletal example, the attribute is used to hide the Web game’s main screen until the user logs in:
<h1>The Example Game</h1>
<section>
  <h2>Login</h2>
  <form>
  ...
  <!-- calls login() once the user’s credentials have been checked -->
  </form>
  <script>
  function login() {
    // switch screens
    document.getElementById('login').hidden = true;
    document.getElementById('game').hidden = false;
  }
  </script>
</section>
<section hidden>
  ...
</section>

The hidden attribute must not be used to hide content just from one presentation — if something is marked hidden, it is hidden from all presentations, including, for instance, screen readers.

Elements that are not themselves hidden must not hyperlink to elements that are hidden. The for attributes of label and output elements that are not themselves hidden must similarly not refer to elements that are hidden. In both cases, such references would cause user confusion.

Elements and scripts may, however, refer to elements that are hidden in other contexts.

For example, it would be incorrect to use the href attribute to link to a section marked with the hidden attribute. If the content is not applicable or relevant, then there is no reason to link to it.

It would be fine, however, to use the ARIA aria-describedby attribute to refer to descriptions that are themselves hidden. While hiding the descriptions implies that they are not useful alone, they could be written in such a way that they are useful in the specific context of being referenced from the images that they describe.

Similarly, a canvas element with the hidden attribute could be used by a scripted graphics engine as an off-screen buffer, and a form control could refer to a hidden form element using its form attribute.

Accessibility APIs are encouraged to provide a way to expose structured content while marking it as hidden in the default view. Such content should not be perceivable to users in the normal document flow in any modality, whether using Assistive Technology (AT) or mainstream User Agents.

When such features are available, User Agents may use them to expose the full semantics of hidden elements to AT when appropriate, if such content is referenced indirectly by an ID reference or valid hash-name reference. This allows ATs to access the structure of these hidden elements upon user request, while keeping the content hidden in all presentations of the normal document flow. Authors who wish to prevent user-initiated viewing of a hidden element should not reference the element with such a mechanism.

Because some User Agents have flattened hidden content when exposing such content to AT, authors should not reference hidden content which would lose essential meaning when flattened.

For example, it would be incorrect to use the href attribute to link to a section marked with the hidden attribute. If the content is not applicable or relevant, then there is no reason to link to it.

It would be fine, however, to use the ARIA aria-describedby attribute to refer to descriptions that are themselves hidden. While hiding the descriptions implies that they are not useful alone, they could be written in such a way that they are useful in the specific context of being referenced from the images that they describe.

Similarly, a canvas element with the hidden attribute could be used by a scripted graphics engine as an off-screen buffer, and a form control could refer to a hidden form element using its form attribute.

Elements in a section hidden by the hidden attribute are still active, e.g., scripts and form controls in such sections still execute and submit respectively. Only their presentation to the user changes.

The hidden IDL attribute must reflect the content attribute of the same name.

5.2. Inert subtrees

This section does not define or create any content attribute named "inert". This section merely defines an abstract concept of inertness.

A node (in particular elements and text nodes) can be marked as inert. When a node is inert, then the user agent must act as if the node was absent for the purposes of targeting user interaction events, may ignore the node for the purposes of text search user interfaces (commonly known as "find in page"), and may prevent the user from selecting text in that node. User agents should allow the user to override the restrictions on search and text selection, however.

For example, consider a page that consists of just a single inert paragraph positioned in the middle of a body. If a user moves their pointing device from the body over to the inert paragraph and clicks on the paragraph, no mouseover event would be fired, and the mousemove and click events would be fired on the body element rather than the paragraph.

When a node is inert, it generally cannot be focused. Inert nodes that are commands will also get disabled.

While a browsing context container is marked as inert, its nested browsing context’s active document, and all nodes in that Document, must be marked as inert.

An entire Document can be marked as blocked by a modal dialog subject. While a Document is so marked, every node that is in the Document, with the exception of the subject element and its descendants, must be marked inert. (The elements excepted by this paragraph can additionally be marked inert through other means; being part of a modal dialog does not "protect" a node from being marked inert.)

Only one element at a time can mark a Document as being blocked by a modal dialog.

5.3. Activation

Certain elements in HTML have an activation behavior, which means that the user can activate them. This triggers a sequence of events dependent on the activation mechanism, and normally culminating in a click event, as described below.

The user agent should allow the user to manually trigger elements that have an activation behavior, for instance using keyboard or voice input, or through mouse clicks. When the user triggers an element with a defined activation behavior in a manner other than clicking it, the default action of the interaction event must be to run synthetic click activation steps on the element.

Each element has a click in progress flag, initially set to false.

When a user agent is to run synthetic click activation steps on an element, the user agent must run the following steps:

  1. If the element’s click in progress flag is set to true, then abort these steps.
  2. Set the click in progress flag on the element to true.
  3. Run pre-click activation steps on the element.
  4. Fire a click event at the element. If the run synthetic click activation steps algorithm was invoked because the click() method was invoked, then the isTrusted attribute must be initialized to false.
  5. If this click event is not canceled, run post-click activation steps on the element.

    If the event is canceled, the user agent must run canceled activation steps on the element instead.

  6. Set the click in progress flag on the element to false.

When a pointing device is clicked, the user agent must run authentic click activation steps instead of firing the click event. When a user agent is to run authentic click activation steps for a given event event, it must follow these steps:

  1. Let target be the element designated by the user (the target of event).
  2. If target is a canvas element, run the canvas MouseEvent rerouting steps. If this changes event’s target, then let target be the new target.
  3. Set the click in progress flag on target to true.
  4. Let e be the nearest activatable element of target (defined below), if any.
  5. If there is an element e, run pre-click activation steps on it.
  6. Dispatch event (the required click event) at target.

    If there is an element e and the click event is not canceled, run post-click activation steps on element e.

    If there is an element e and the event is canceled, run canceled activation steps on element e.

  7. Set the click in progress flag on target to false.

The algorithms above don’t run for arbitrary synthetic events dispatched by author script. The click() method can be used to make the run synthetic click activation steps algorithm happen programmatically.

Click-focusing behavior (e.g., the focusing of a text field when user clicks in one) typically happens before the click, when the mouse button is first depressed, and is therefore not discussed here.

Given an element target, the nearest activatable element is the element returned by the following algorithm:

  1. If target has a defined activation behavior, then return target and abort these steps.
  2. If target has a parent element, then set target to that parent element and return to the first step.
  3. Otherwise, there is no nearest activatable element.

When a user agent is to run pre-click activation steps on an element, it must run the pre-click activation steps defined for that element, if any.

When a user agent is to run canceled activation steps on an element, it must run the canceled activation steps defined for that element, if any.

When a user agent is to run post-click activation steps on an element, it must run the activation behavior defined for that element, if any. Activation behaviors can refer to the click event that was fired by the steps above leading up to this point.

element . click()
Acts as if the element was clicked.
The click() method must run the following steps:
  1. If the element is a form control that is disabled, abort these steps.

  2. Run synthetic click activation steps on the element.

5.4. Focus

5.4.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) 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 focused.

Consider an HTML application running in a browser tab running in a graphical environment. Suppose this application had a page with some text fields and links, and was currently showing a modal dialog, which itself had a text field 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 fields, as well as the dialog. The dialog itself would have as its children the text field and the button.

If the widget with focus in this example was the text field 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 field.

Keyboard events are always targeted at this focused element.

5.4.2. Data model

The term focusable area is used to refer to regions of the interface that can become the target of keyboard input. Focusable areas can be elements, parts of elements, or other regions managed by the user agent.

Each focusable area has a DOM anchor, which is a Node object that represents the position of the focusable area in the DOM. (When the focusable area is itself a Node, it is its own DOM anchor.) The DOM anchor is used in some APIs as a substitute for the focusable area when there is no other DOM object to represent the focusable area.

The following table describes what objects can be focusable areas. The cells in the left column describe objects that can be focusable areas; the cells in the right column describe the DOM anchors for those elements. (The cells that span both columns are non-normative examples.)

Focusable area DOM anchor
Examples
Elements that have their tabindex focus flag set, that are not actually disabled, that are not expressly inert, and that are either being rendered or being used as relevant canvas fallback content. The element itself.

iframe, <input type=text>, sometimes <a href=""> (depending on platform conventions).

The shapes of area elements in an image map associated with an img element that is being rendered and is not expressly inert. The img element.
In the following example, the area element creates two shapes, one on each image. The DOM anchor of the first shape is the first img element, and the DOM anchor of the second shape is the second img element.
<map id=wallmap><area alt="Enter Door" coords="10,10,100,200" href="door.html"></map>
...
<img src="images/innerwall.jpeg" alt="There is a white wall here, with a door." usemap="#wallmap">
...
<img src="images/outerwall.jpeg" alt="There is a red wall here, with a door." usemap="#wallmap">
The user-agent provided subwidgets of elements that are being rendered and are not actually disabled or expressly inert. The element for which the focusable area is a subwidget.

The controls in the user interface that is exposed to the user for a video element, the up and down buttons in a spin-control version of <input type=number>, the part of a details element’s rendering that enabled the element to be opened or closed using keyboard input.

The scrollable regions of elements that are being rendered and are not expressly inert. The element for which the box that the scrollable region scrolls was created.

The CSS overflow property’s scroll value typically creates a scrollable region.

The viewport of a Document that is in a browsing context and is not inert. The Document for which the viewport was created.

The contents of an iframe.

Any other element or part of an element, especially to aid with accessibility or to better match platform conventions. The element.

A user agent could make all list item bullets focusable, so that a user can more easily navigate lists.

Similarly, a user agent could make all elements with title attributes focusable, so that their advisory information can be accessed.

A browsing context container (e.g., an iframe) is a focusable area, but key events routed to a browsing context container get immediately routed to the nested browsing context’s active document. Similarly, in sequential focus navigation a browsing context container essentially acts merely as a placeholder for its nested browsing context’s active document.

Each focusable area belongs to a control group. Each control group has an owner. Control group owners are control group owner objects. The following are control group owner objects:

Each control group owner object owns one control group (though that group might be empty).

If the DOM anchor of a focusable area is a control group owner object, then that focusable area belongs to that control group owner object’s control group. Otherwise, the focusable area belongs to its DOM anchor’s nearest ancestor control group owner object.

Thus, a viewport always belongs to the control group of the Document for which the viewport was created, an input control belongs to the control group of its nearest ancestor Document, and an image map’s shapes belong to the nearest ancestor Document of the img elements (not the area elements — this means one area element might create multiple shapes in different control groups).

An element is expressly inert if it is inert but it is not a control group owner object and its nearest ancestor control group owner object is not inert.

One focusable area in each non-empty control group is designated the focused area of the control group. Which control is so designated changes over time, based on algorithms in this specification. If a control group is empty, it has no focused area.


Focusable areas in control groups are ordered relative to the tree order of their DOM anchors. Focusable areas with the same DOM anchor in a control group are ordered relative to their CSS box’s relative positions in a pre-order, depth-first traversal of the box tree. [CSS-2015]


The currently focused area of a top-level browsing context at any particular time is the focusable area returned by this algorithm:

  1. Let candidate be the Document of the top-level browsing context.
  2. If candidate has a non-empty control group, and the designated focused area of the control group is a browsing context container, then let candidate be the active document of that browsing context container’s nested browsing context, and redo this step.

    Otherwise, if candidate has a non-empty control group, let candidate be the designated focused area of the control group.

  3. Return candidate.

An element that is the DOM anchor of a focusable area is said to gain focus when that focusable area becomes the currently focused area of a top-level browsing context. When an element is the DOM anchor of a focusable area of the currently focused area of a top-level browsing context, it is focused.

The focus chain of a focusable area or control group owner object subject is the ordered list constructed as follows:
  1. Let current object be subject.
  2. Let output be an empty list.
  3. Loop: Append current object to output.
  4. If current object is an area element’s shape, append that area element to output.

    Otherwise, if current object is a focusable area whose DOM anchor is an element that is not current object itself, append that DOM anchor element to output.

  5. If current object is a focusable area, let current object be that focusable area’s control group’s owner, and return to the step labeled loop.

    Otherwise, if current object is a Document in a nested browsing context, let current object be its browsing context container, and return to the step labeled loop.

  6. Return output.

    The chain starts with subject and (if subject is or can be the currently focused area of a top-level browsing context) continues up the focus hierarchy up to the Document of the top-level browsing context.

5.4.3. The tabindex attribute

The tabindex content attribute allows authors to indicate that an element is supposed to be focusable, and whether it is supposed to be reachable using sequential focus navigation and, if so, what is to be the relative order of the element for the purposes of sequential focus navigation. The name "tab index" comes from the common use of the "tab" key to navigate through the focusable elements. The term "tabbing" refers to moving forward through the focusable elements that can be reached using sequential focus navigation.

When the attribute is omitted, the user agent applies defaults. (There is no way to make an element that is being rendered be not focusable at all without disabling it or making it inert.)

The tabindex attribute, if specified, must have a value that is a valid integer. Positive numbers specify the relative position of the element’s focusable areas in the sequential focus navigation order, and negative numbers indicate that the control is to be unreachable by sequential focus navigation.

Each element can have a tabindex focus flag set, as defined below. This flag is a factor that contributes towards determining whether an element is a focusable area, as described in the previous section.

If the tabindex attribute is specified on an element, it must be parsed using the rules for parsing integers. The attribute’s values, or lack thereof, must be interpreted as follows:

If the attribute is omitted or parsing the value returns an error

The user agent should follow platform conventions to determine if the element’s tabindex focus flag is set and, if so, whether the element and any focusable areas that have the element as their DOM anchor can be reached using sequential focus navigation, and if so, what their relative position in the sequential focus navigation order is to be.

Modulo platform conventions, it is suggested that for the following elements, the tabindex focus flag be set:

One valid reason to ignore the platform conventions and always allow an element to be focused (by setting its tabindex focus flag) would be if the user’s only mechanism for activating an element is through a keyboard action that triggers the focused element.

If the value is a negative integer

The user agent must set the element’s tabindex focus flag, but should omit the element from the sequential focus navigation order.

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 field with a negative 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 set the element’s tabindex focus flag, should allow the element and any focusable areas that have the element as their DOM anchor to be reached using sequential focus navigation, following platform conventions to determine the element’s relative position in the sequential focus navigation order.

If the value is greater than zero

The user agent must set the element’s tabindex focus flag, should allow the element and any focusable areas that have the element as their DOM anchor to be reached using sequential focus navigation, and should place the element — referenced as candidate below — and the aforementioned focusable areas in the sequential focus navigation order so that, relative to other focusable areas in the sequential focus navigation order, they are:

  • before any focusable area whose DOM anchor is an element whose tabindex attribute has been omitted or whose value, when parsed, returns an error,
  • before any focusable area whose DOM anchor is an element whose tabindex attribute has a value equal to or less than zero,
  • after any focusable area whose DOM anchor is an element whose tabindex attribute has a value greater than zero but less than the value of the tabindex attribute on candidate,
  • after any focusable area whose DOM anchor is an element whose tabindex attribute has a value equal to the value of the tabindex attribute on candidate but that is earlier in the document in tree order than candidate,
  • before any focusable area whose DOM anchor is an element whose tabindex attribute has a value equal to the value of the tabindex attribute on candidate but that is later in the document in tree order than candidate, and
  • before any focusable area whose DOM anchor is an element whose tabindex attribute has a value greater than the value of the tabindex attribute on candidate.

An element that has its tabindex focus flag set but does not otherwise have an activation behavior defined has an activation behavior that does nothing.

This means that an element that is only focusable because of its tabindex attribute will fire a click event in response to a non-mouse activation (e.g., hitting the "enter" key while the element is focused).

An element with the tabindex attribute specified is interactive content.

The tabIndex IDL attribute must reflect the value of the tabindex content attribute. Its default value is 0 for elements that are focusable and -1 for elements that are not focusable.

Most current browsers instead give the tabIndex IDL attribute a value of 0 for some list of elements that are by default a focusable area, and -1 for other elements, if there is no tabindex content attribute set. This behaviour is not well-defined and will hopefully be improved in the future.

5.4.4. Processing model

The focusing steps for an object new focus target that is either a focusable area, or an element that is not a focusable area, or a browsing context, are as follows. They can optionally be run with a fallback target.

  1. If new focus target is not a focusable area, then run the first matching set of steps from the following list:

    If new focus target is an area element with one or more shapes that are focusable areas

    Let new focus target be the shape corresponding to the first img element in tree order that uses the image map to which the area element belongs.

    If new focus target is an element with one or more scrollable regions that are focusable areas

    Let new focus target be the element’s first scrollable region, according to a pre-order, depth-first traversal of the box tree. [CSS-2015]

    If new focus target is the root element of its Document

    Let new focus target be the Document’s viewport.

    If new focus target is a browsing context

    Let new focus target be the browsing context’s active document.

    If new focus target is a browsing context container

    Let new focus target be the browsing context container’s nested browsing context’s active document.

    Otherwise

    If no fallback target was specified, abort the focusing steps.

    Otherwise, let new focus target be the fallback target.

  2. If new focus target is a control group owner object that is not a focusable area, and its control group is not empty, then designate new focus target as the focused area of the control group, and redo this step.

    Otherwise, if new focus target is a browsing context container, then let new focus target be the nested browsing context’s active document, and redo this step.

  3. If new focus target is a focusable area and its DOM anchor is inert, then abort these steps.
  4. If new focus target is the currently focused area of a top-level browsing context, then abort these steps.
  5. Let old chain be the focus chain of the currently focused area of the top-level browsing context in which new focus target finds itself.
  6. Let new chain be the focus chain of new focus target.
  7. Run the focus update steps with old chain, new chain, and new focus target respectively.

User agents must immediately run the focusing steps for a focusable area, or browsing context candidate whenever the user attempts to move the focus to candidate.

The unfocusing steps for an object old focus target that is either a focusable area or an element that is not a focusable area are as follows:

  1. If old focus target is inert, then abort these steps.
  2. If old focus target is an area element and one of its shapes is the currently focused area of a top-level browsing context, or, if old focus target is an element with one or more scrollable regions, and one of them is the currently focused area of a top-level browsing context, then let old focus target be that currently focused area of a top-level browsing context.

  3. Let old chain be the focus chain of the currently focused area of a top-level browsing context.
  4. If old focus target is not one of the entries in old chain, then abort these steps.
  5. If old focus target is a focusable area, then let new focus target be the first focusable area of its control group (if the control group owner is a Document, this will always be a viewport).

    Otherwise, let new focus target be null.

  6. If new focus target is not null, then run the focusing steps for new focus target.

When the currently focused area of a top-level browsing context is somehow unfocused without another element being explicitly focused in its stead, the user agent must immediately run the unfocusing steps for that object.

The unfocusing steps do not always result in the focus changing, even when applied to the currently focused area of a top-level browsing context. For example, if the currently focused area of a top-level browsing context is a viewport, then it will usually keep its focus regardless until another focusable area is explicitly focused with the focusing steps.


When a focusable area is added to an empty control group, it must be designated the focused area of the control group.

Focus fixup rule one: When the designated focused area of a control group is removed from that control group in some way (e.g., it stops being a focusable area, it is removed from the DOM, it becomes expressly inert, etc), and the control group is still not empty: designate the first non-inert focused area in that control group to be the new focused area of the control group, if any; if they are all inert, then designate the first focused area in that control group to be the new focused area of the control group regardless of inertness. If such a removal instead results in the control group being empty, then there is simply no longer a focused area of the control group.

For example, this might happen because an element is removed from its Document, or has a hidden attribute added. It might also happen to an input element when the element gets disabled.

When the currently focused area of a top-level browsing context was a focusable area but stops being a focusable area, or when it starts being inert, the user agent must run the following steps:

  1. Let old focus target be whatever the currently focused area of the top-level browsing context was immediately before this algorithm became applicable (e.g., before the element was disabled, or the dialog was closed, or whatever caused this algorithm to run).
  2. Let old chain be the focus chain of the currently focused area of the top-level browsing context at the same time.
  3. Make sure that the changes implied by the focus fixup rules one, two, and three above are applied.
  4. Let new focus target be the currently focused area of a top-level browsing context.
  5. If old focus target and new focus target are the same, abort these steps.
  6. Let new chain be the focus chain of new focus target.
  7. Run the focus update steps with old chain, new chain, and new focus target respectively.

The focus update steps, given an old chain, a new chain, and a new focus target respectively, are as follows:

  1. Unset the sequential focus navigation starting point.
  2. 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.
  3. For each entry entry in old chain, in order, run these substeps:

    1. If entry is an input element, and the change event applies to the element, and the element does not have a defined activation behavior, and the user has changed the element’s value or its list of selected files while the control was focused without committing that change, then fire a simple event that bubbles named change at the element.
    2. If entry is an element, let blur event target be entry.

      If entry is a Document object, let blur event target be that Document object’s Window object.

      Otherwise, let blur event target be null.

    3. If entry is the last entry in old chain, and entry is an Element, and the last entry in new chain is also an 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, fire a focus event named blur at blur event target, with related blur target as the related target.

      In some cases, e.g., if entry is an area element’s shape, a scrollable region, or a viewport, no event is fired.

  4. Apply any relevant platform-specific conventions for focusing new focus target. (For example, some platforms select the contents of a text field when that field is focused.)
  5. For each entry entry in new chain, in reverse order, run these substeps:

    1. If entry is a focusable area: Designate entry as the focused area of the control group.

    2. If entry is an element, let focus event target be entry.

      If entry is a Document object, let focus event target be that Document object’s Window object.

      Otherwise, let focus event target be null.

    3. If entry is the last entry in new chain, and entry is an Element, and the last entry in old chain is also an 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, fire a focus event named focus at focus event target, with related focus target as the related target.

      In some cases, e.g., if entry is an area element’s shape, a scrollable region, or a viewport, no event is fired.

When a user agent is required to fire a focus event named e at an element t and with a given related target r, the user agent must create a trusted FocusEvent object, initialize it to have the given name e, to not bubble, to not be cancelable, and to have the relatedTarget attribute initialized to r, the view attribute initialized to the Window object of the Document object of t, and the detail attribute initialized to 0, and must then dispatch the newly created FocusEvent object at the specified target element t.


When a key event is to be routed in a top-level browsing context, the user agent must run the following steps:

  1. Let target area be the currently focused area of the top-level browsing context.
  2. If target area is a focusable area, let target node be target area’s DOM anchor.
  3. If target node is a Document that has a body element, then let target node be the body element of that Document.

    Otherwise, if target node is a Document that has a root element, then let target node be the root element of that Document.

  4. If target node is not inert, fire the event at target node.

    It is possible for the currently focused area of a top-level browsing context to be inert. It is likely to be the result of a logic error in the application, though.

  5. If the event was not canceled, then let target area handle the key event. This might include running synthetic click activation steps for target node.

The has focus steps, given a Document object target, are as follows:

  1. Let candidate be the Document of the top-level browsing context.
  2. If candidate is target, return true and abort these steps.
  3. If candidate has a non-empty control group, and the designated focused area of the control group is a browsing context container, and the active document of that browsing context container’s nested browsing context is target, then return true and abort these steps.

    Otherwise, if candidate has a non-empty control group, and the designated focused area of the control group is a browsing context container, then let candidate be the active document of that browsing context container’s nested browsing context, and redo this step.

    Otherwise, return false and abort these steps.

5.4.5. Sequential focus navigation

Each control group has a sequential focus navigation order, which orders some or all of the focusable areas in the control group relative to each other. The order in the sequential focus navigation order does not have to be related to the order in the control group itself. If a focusable area is omitted from the sequential focus navigation order of its control group, then it is unreachable via 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.

When the user requests that focus move from the currently focused area of a top-level browsing context to the next or previous focusable area (e.g., as the default action of pressing the tab key), or when the user requests that focus sequentially move to a top-level browsing context 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 currently focused area of a top-level browsing context, if the user requested to move focus sequentially from there, or else the top-level browsing context itself, if the user instead requested to move focus from outside the top-level browsing context.
  2. If there is a sequential focus navigation starting point defined and it is inside starting point, then let starting point be the sequential focus navigation starting point instead.
  3. Let direction be forward if the user requested the next control, and 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 sequential if the starting point is a browsing context or if starting point is in its control group’s sequential focus navigation order.

    Otherwise, starting point is not in its control group’s sequential focus navigation order; let selection mechanism be DOM.

  5. Let candidate be the result of running the sequential navigation search algorithm with starting point, direction, and selection mechanism as the arguments.
  6. If candidate is not null, then run the focusing steps for candidate and abort these steps.
  7. Otherwise, unset the sequential focus navigation starting point.
  8. If starting point is the top-level browsing context, or a focusable area in the top-level browsing context, the user agent should transfer focus to its own controls appropriately (if any), honouring direction, and then abort these steps.

    For example, if direction is backward, then the last focusable control before the browser’s rendering area would be the control to focus.

    If the user agent has no focusable controls — a kiosk-mode browser, for instance — then the user agent may instead restart these steps with the starting point being the top-level browsing context itself.

  9. Otherwise, starting point is a focusable area in a nested browsing context. Let starting point be that nested browsing context’s browsing context container, and return to the step labeled loop.

The sequential navigation search algorithm consists of the following steps. This algorithm takes three arguments: starting point, direction, and selection mechanism.

  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 forward direction is backward
    starting point is a browsing context Let candidate be the first suitable sequentially focusable area in starting point’s active document’s primary control group, if any; or else null Let candidate be the last suitable sequentially focusable area in starting point’s active document’s primary control group, if any; or else null
    selection mechanism is DOM Let candidate be the first suitable sequentially focusable area in the home control group following starting point, if any; or else null Let candidate be the last suitable sequentially focusable area in the home control group preceding starting point, if any; or else null
    selection mechanism is sequential Let candidate be the first suitable sequentially focusable area in the home sequential focus navigation order following starting point, if any; or else null Let candidate be the last suitable sequentially focusable area in the home sequential focus navigation order preceding starting point, if any; or else null

    A suitable sequentially focusable area is a focusable area whose DOM anchor is not inert and that is in its control group’s sequential focus navigation order.

    The primary control group of a control group owner object X is the control group of X.

    The home control group is the control group to which starting point belongs.

    The home sequential focus navigation order is the sequential focus navigation order to which starting point belongs.

    The home sequential focus navigation order is the home control group’s sequential focus navigation order, but is only used when the starting point is in that sequential focus navigation order (when it’s not, selection mechanism will be DOM).

  2. If candidate is a browsing context container, then let new candidate be the result of running the sequential navigation search algorithm with candidate’s nested browsing context as the first argument, direction as the second, and sequential as the third.

    If new candidate is null, then let starting point be candidate, and return to the top of this algorithm. Otherwise, let candidate be new candidate.

  3. Return candidate.

5.4.6. Focus management APIs

document . activeElement

Returns the deepest element in the document 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 child browsing context is focused, its browsing context container is focused in the parent browsing context. For example, if the user moves the focus to a text field in an iframe, the iframe is the element returned by the activeElement API in the iframe’s node document.

document . hasFocus()

Returns true if key events are being routed through or to the document; otherwise, returns false. Roughly speaking, this corresponds to the document, or a document nested inside this one, being focused.

window . focus()

Moves the focus to the window’s browsing context, if any.

element . focus()

Moves the focus to the element.

If the element is a browsing context container, moves the focus to the nested browsing context instead.

element . blur()

Moves the focus to the viewport. Use of this method is discouraged; if you want to focus the viewport, call the focus() method on the Document’s root element.

Do not use this method to hide the focus ring if you find the focus ring unsightly. Instead, use a CSS rule to override the outline property, 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 links and instead use a yellow background to indicate focus, you could use:
:link:focus, :visited:focus { outline: none; background: yellow; color: black; }

Do not use this method to hide the focus ring. Do not use any other method that hides the focus ring from keyboard users, in particular do not use a CSS rule to override the outline property. Removal of the focus ring leads to serious accessibility issues for users who navigate and interact with interactive content using the keyboard.

The activeElement attribute on Document objects must return the value returned by the following steps:

  1. Let candidate be the Document on which the method was invoked.
  2. If candidate has a non-empty control group, let candidate be the designated focused area of the control group.
  3. If candidate is a focusable area, let candidate be candidate’s DOM anchor.
  4. If candidate is a Document that has a body element, then let candidate be the body element of that Document.

    Otherwise, if candidate is a Document that has a root element, then let candidate be the root element of that Document.

    Otherwise, if candidate is a Document, then let candidate be null.

  5. Return candidate.

The hasFocus() method on the Document object, when invoked, must return the result of running the has focus steps with the Document object as the argument.

The focus() method on the Window object, when invoked, must run the focusing steps with the Window object’s browsing context. Additionally, if this browsing context is a top-level browsing context, user agents are encouraged to trigger some sort of notification to indicate to the user that the page is attempting to gain focus.

The blur() method on the Window object, when invoked, provides a hint to the user agent that the script believes the user probably is not currently interested in the contents of the browsing context of the Window object on which the method was invoked, but that the contents might become interesting again in the future.

User agents are encouraged to ignore calls to this blur() method entirely.

Historically, the focus() and blur() methods actually affected the system-level focus of the system widget (e.g., tab or window) that contained the browsing context, but hostile sites widely abuse this behavior to the user’s detriment.

The focus() method on elements, when invoked, must run the following algorithm:

  1. If the element is marked as locked for focus, then abort these steps.
  2. Mark the element as locked for focus.
  3. Run the focusing steps for the element.
  4. Unmark the element as locked for focus.

The blur() method, when invoked, should run the unfocusing steps for the element on which the method was called. User agents may selectively or uniformly ignore calls to this method for usability reasons.

For example, if the 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.

5.5. Assigning keyboard shortcuts

5.5.1. Introduction

This section is non-normative.

Each element that can be activated or focused can be assigned a shortcut key combination to activate it, using the accesskey attribute.

The exact shortcut is determined by the user agent, potentially using information about the user’s preferences, what keyboard shortcuts already exist on the platform, and what other shortcuts have been specified on the page, as well as the value of the accesskey attribute.

A valid value for accesskey 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.

In this example, an author has provided a button that can be invoked using a shortcut key, and suggested "C" as a memorable and useful shortcut.
<input type=button value=Collect onclick="collect()" accesskey="C" id=c>

5.5.2. The accesskey attribute

All html elements may have the accesskey content attribute set. The accesskey attribute’s value is used by the user agent as a guide for creating a keyboard shortcut that activates or focuses the element.

If specified, the value must be a single printable character: a string exactly one Unicode code point in length.

Authors should not use " ", nor characters that normally require a modifier key to generate, as a value of accesskey.

In the following example, a variety of links are given with access keys so that keyboard users familiar with the site can more quickly navigate to the relevant pages:
<nav>
  <p>
    <a title="Consortium Activities" accesskey="A" href="/Consortium/activities">Activities</a> |
    <a title="Technical Reports and Recommendations" accesskey="T" href="/TR/">Technical Reports</a> |
    <a title="Alphabetical Site Index" accesskey="S" href="/Consortium/siteindex">Site Index</a> |
    <a title="About This Site" accesskey="B" href="/Consortium/">About Consortium</a> |
    <a title="Contact Consortium" accesskey="C" href="/Consortium/contact">Contact</a>
  </p>
</nav>

5.5.3. Processing model

An element’s assigned access key is a key combination derived from the element’s accesskey content attribute, or assigned by the user agent, optionally based on a user preference. Initially, an element must not have an assigned access key.

Whenever an element’s accesskey attribute is set, changed, or removed, the user agent must update the element’s assigned access key by running the following steps:

  1. If the element has no accesskey attribute, then skip to the fallback step below.
  2. The user agent may assign a key combination based on stored user preferences as the element’s assigned access key and then abort these steps.
  3. Let value be the value of the accesskey attribute.
  4. The user agent may strip content from value to reduce the length of value to a single unicode code point.
  5. If value is not a string exactly one Unicode code point in length, then abort these steps.
  6. The user agent may assign a combination of a mix of zero or more modifier keys and value as the element’s assigned access key and abort these steps.
  7. Fallback: Optionally, the user agent may assign a key combination of its choosing as the element’s assigned access key and then abort these steps.
  8. If this step is reached, the element has no 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 assigned access key unless the accesskey content attribute is changed or the element is moved to another Document.

When the user presses the key combination corresponding to the assigned access key for an element, if the element defines a command, the command’s Hidden State facet is false (visible), the command’s Disabled State facet is also false (enabled), the element is in a Document that has an associated browsing context, and neither the element nor any of its ancestors has a hidden attribute specified, then the user agent must trigger the Action of the command.

User agents might expose elements that have an accesskey attribute in other ways as well, e.g., in a menu displayed in response to a specific key combination.


The accessKey IDL attribute must reflect the accesskey content attribute.

5.6. Editing

5.6.1. Making document regions editable: The contenteditable content attribute

[NoInterfaceObject]
interface ElementContentEditable {
  attribute DOMString contentEditable;
  readonly attribute boolean isContentEditable;
};

The contenteditable content attribute is an enumerated attribute whose keywords are the empty string, true, and false. The empty string and the true keyword map to the true state. The false keyword maps to the false state. In addition, there is a third state, the inherit state, which is the missing value default (and the invalid value default).

The true state indicates that the element is editable. The inherit state indicates that the element is editable if its parent is. The false state indicates that the element is not editable.

element . contentEditable [ = value ]

Returns "true", "false", or "inherit", based on the state of the contenteditable attribute.

Can be set, to change that state.

Throws a "SyntaxError" DOMException if the new value isn’t one of those strings.

element . isContentEditable

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 true state, "false" if the content attribute is set to the false state, and "inherit" otherwise. On setting, if the new value is an ASCII case-insensitive match for the string "inherit" then the content attribute must be removed, if the new value is an 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 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 "SyntaxError" DOMException.

The isContentEditable IDL attribute, on getting, must return true if the element is either an editing host or editable, and false otherwise.

5.6.2. Making entire documents editable: The designMode IDL attribute

Documents have a designMode, which can be either enabled or disabled.

document . designMode [ = value ]

Returns "on" if the document is editable, and "off" if it isn’t.

Can be set, to change the document’s current state. This focuses the document and resets the selection in that document.

The designMode IDL attribute on the Document object takes two values, "on" and "off". On setting, the new value must be compared in an ASCII case-insensitive manner to these two values; if it matches the "on" value, then designMode must be enabled, and if it matches the "off" value, then designMode must be disabled. Other values must be ignored.

On getting, if designMode is enabled, the IDL attribute must return the value "on"; otherwise it is disabled, and the attribute must return the value "off".

The last state set must persist until the document is destroyed or the state is changed. Initially, documents must have their designMode disabled.

When the designMode changes from being disabled to being enabled, the user agent must immediately reset the document’s active range’s start and end boundary points to be at the start of the Document and then run the focusing steps for the root element of the Document, if any.

5.6.3. Best practices for in-page editors

Authors are encouraged to set the white-space property on editing hosts and on markup that was originally created through these editing mechanisms to the value pre-wrap. Default HTML whitespace handling is not well suited to WYSIWYG editing, and line wrapping will not work correctly in some corner cases if white-space is left at its default value.

As an example of problems that occur if the default normal value is used instead, consider the case of the user typing "yellow␣␣ball", with two spaces (here represented by "␣") between the words. With the editing rules in place for the default value of white-space (normal), the resulting markup will either consist of "yellow&nbsp; ball" or "yellow &nbsp;ball"; i.e., there will be a non-breaking space between the two words in addition to the regular space. This is necessary because the normal value for white-space requires adjacent regular spaces to be collapsed together.

In the former case, "yellow⍽" might wrap to the next line ("⍽" being used here to represent a non-breaking space) even though "yellow" alone might fit at the end of the line; in the latter case, "⍽ball", if wrapped to the start of the line, would have visible indentation from the non-breaking space.

When white-space is set to pre-wrap, however, the editing rules will instead simply put two regular spaces between the words, and should the two words be split at the end of a line, the spaces would be neatly removed from the rendering.

5.6.4. Editing APIs

The definition of the terms active range, editing host, and editable, the user interface requirements of elements that are editing hosts or editable, the execCommand(), queryCommandEnabled(), queryCommandIndeterm(), queryCommandState(), queryCommandSupported(), and queryCommandValue() methods, text selections, and the delete the selection algorithm are being specified in the various developing HTML Editing specification drafts [EDITING]. The interaction of editing and undo/redo features are being specified in the UndoManager and DOM Transaction specification. [UNDO]

5.6.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 textarea elements), or in elements in an editing host (e.g., using 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 spellcheck attribute.
false-by-default
The element will never be checked for spelling and grammar unless spellchecking is explicitly enabled through the 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.

The spellcheck attribute is an enumerated attribute whose keywords are the empty string, true and false. The empty string and the true keyword map to the true state. The false keyword maps to the false state. In addition, there is a third state, the default state, which is the missing value default (and the invalid value default).

The true state indicates that the element is to have its spelling and grammar checked. The default state indicates that the element is to act according to a default behavior, possibly based on the parent element’s own spellcheck state, as defined below. The false state indicates that the element is not to be checked.


element . spellcheck [ = value ]

Returns true if the element is to have its spelling and grammar checked; otherwise, returns false.

Can be set, to override the default and set the spellcheck content attribute.

element . forceSpellCheck()

Forces the user agent to report spelling and grammar errors on the element (if checking is enabled), even if the user has never focused the element. (If the method is not invoked, user agents can hide errors in text that wasn’t just entered by the user.)

The spellcheck IDL attribute, on getting, must return true if the element’s spellcheck content attribute is in the true state, or if the element’s spellcheck content attribute is in the default state and the element’s default behavior is true-by-default, or if the element’s spellcheck content attribute is in the default state and the element’s default behavior is inherit-by-default and the element’s parent element’s spellcheck IDL attribute would return true; otherwise, if none of those conditions applies, then the attribute must instead return false.

The spellcheck IDL attribute is not affected by user preferences that override the spellcheck content attribute, and therefore might not reflect the actual spellchecking state.

On setting, if the new value is true, then the element’s spellcheck content attribute must be set to the literal string "true", otherwise it must be set to the literal string "false".


User agents must only consider the following pieces of text as checkable for the purposes of this feature:

  • The value of input elements whose type attributes are in the Text, Search, URL, or E-mail states and that are mutable (i.e., that do not have the readonly attribute specified and that are not disabled).
  • The value of textarea elements that do not have a readonly attribute and that are not disabled.
  • Text in Text nodes that are children of editing hosts or editable elements.
  • Text in attributes of editable elements.

For text that is part of a 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 input and 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 user agent 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 spellcheck content attribute, then: if that attribute is in the true state, then checking is enabled; otherwise, if that attribute is in the false state, then checking is disabled.
  4. Otherwise, if there is an ancestor element with a spellcheck content attribute that is not in the default state, then: if the nearest such ancestor’s spellcheck content attribute is in the true state, then checking is enabled; otherwise, checking is disabled.
  5. Otherwise, if the element’s default behavior is true-by-default, then checking is enabled.
  6. Otherwise, if the element’s default behavior is 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. user agents should use input element attributes such as 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.

Even when checking is enabled, user agents may opt to not report spelling or grammar errors in text that the user agent deems the user has no interest in having checked (e.g., text that was already present when the page was loaded, or that the user did not type, or text in controls that the user has not focused, or in parts of e-mail addresses that the user agent is not confident were misspelt). The forceSpellCheck() method, when invoked on an element, must override this behavior, forcing the user agent to consider all spelling and grammar errors in text in that element for which checking is enabled to be of interest to the user.

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.
<div contenteditable="true">
<span spellcheck="false">Hell</span><em>o!</em>
</div>

The element with ID "b" in the following example would have checking enabled (the leading space character in the attribute’s value on the input element causes the attribute to be ignored, so the ancestor’s value is used instead, regardless of the default).

<p spellcheck="true"><label>Name: <input spellcheck=" false"></label>
</p>

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.

5.7. Drag and drop

This section defines an event-based drag-and-drop mechanism.

This specification does not define exactly what a drag-and-drop operation actually is.

On a visual medium with a pointing device, a drag operation could be the default action of a mousedown event that is followed by a series of mousemove events, and the drop could be triggered by the mouse being released.

When using an input modality other than a pointing device, users would probably have to explicitly indicate their intention to perform a drag-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 he cycles 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).

5.7.1. Introduction

This section is non-normative.

To make an element draggable is simple: give the element a draggable attribute, and set an event listener for dragstart that stores the data being dragged.

The event handler typically needs to check that it’s not a text selection that is being dragged, and then needs to store data into the DataTransfer object and set the allowed effects (copy, move, link, or some combination).

For example:

<p>What fruits do you like?</p>
<ol ondragstart="dragStartHandler(event)">
<li draggable="true">Apples</li>
<li draggable="true">Oranges</li>
<li draggable="true">Pears</li>
</ol>
<script>
var internalDNDType = 'text/x-example'; // set this to something specific to your site
function dragStartHandler(event) {
  if (event.target instanceof HTMLLIElement) {
    // use the element’s>

To accept a drop, the drop target has to have a dropzone attribute and listen to the drop event.

The value of the dropzone attribute specifies what kind of data to accept (e.g., "string:text/plain" to accept any text strings, or "file:image/png" to accept a PNG image file) and what kind of feedback to give (e.g., "move" to indicate that the data will be moved).

Instead of using the dropzone attribute, a drop target can handle the dragenter event (to report whether or not the drop target is to accept the drop) and the dragover event (to specify what feedback is to be shown to the user).

The drop event allows the actual drop to be performed. This event needs to be canceled, so that the dropEffect attribute’s value can be used by the source (otherwise it’s reset).

For example:

<p>Drop your favorite fruits below:</p>
<ol dropzone="move string:text/x-example" ondrop="dropHandler(event)">
<!-- don’t forget to change the "text/x-example" type to something
specific to your site -->
</ol>
<script>
var internalDNDType = 'text/x-example'; // set this to something specific to your site
function dropHandler(event) {
  var li = document.createElement('li');
  var data = event.dataTransfer.getData(internalDNDType);
  if (data == 'fruit-apple') {
    li.textContent = 'Apples';
  } else if (data == 'fruit-orange') {
    li.textContent = 'Oranges';
  } else if (data == 'fruit-pear') {
    li.textContent = 'Pears';
  } else {
    li.textContent = 'Unknown Fruit';
  }
  event.target.appendChild(li);
}
</script>

To remove the original element (the one that was dragged) from the display, the dragend event can be used.

For our example here, that means updating the original markup to handle that event:

<p>What fruits do you like?</p>
<ol ondragstart="dragStartHandler(event)" ondragend="dragEndHandler(event)">
  <!-- ...as before... -->
</ol>
<script>
function dragStartHandler(event) {
  // ...as before...
}
function dragEndHandler(event) {
  if (event.dataTransfer.dropEffect == 'move') {
    // remove the dragged element
    event.target.parentNode.removeChild(event.target);
  }
}
</script>

5.7.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:

When a drag data store is created, it must be initialized such that its drag data store item list is empty, it has no drag data store default feedback, it has no drag data store bitmap and drag data store hot spot coordinate, its drag data store mode is protected mode, and its drag data store allowed effects state is the string "uninitialized".

5.7.3. The DataTransfer interface

DataTransfer objects are used to expose the drag data store that underlies a drag-and-drop operation.

interface DataTransfer {
  attribute DOMString dropEffect;
  attribute DOMString effectAllowed;

  [SameObject] readonly attribute DataTransferItemList items;

  void setDragImage(Element image, long x, long y);

  /* old interface */
  [SameObject] readonly attribute DOMString[] types;
  DOMString getData(DOMString format);
  void setData(DOMString format, DOMString data);
  void clearData(optional DOMString format);
  [SameObject] readonly attribute FileList files;
};
dataTransfer . dropEffect [ = value ]

Returns the kind of operation that is currently selected. If the kind of operation isn’t one of those that is allowed by the effectAllowed attribute, then the operation will fail.

Can be set, to change the selected operation.

The possible values are "none", "copy", "link", and "move".

dataTransfer . effectAllowed [ = value ]

Returns the kinds of operations that are to be allowed.

Can be set (during the dragstart event), to change the allowed operations.

The possible values are "none", "copy", "copyLink", "copyMove", "link", "linkMove", "move", "all", and "uninitialized",

dataTransfer . items

Returns a DataTransferItemList object, with the drag data.

dataTransfer . setDragImage(element, x, y)

Uses the given element to update the drag feedback, replacing any previously specified feedback.

dataTransfer . types

Returns an array listing the formats that were set in the dragstart event. In addition, if any files are being dragged, then one of the types will be the string "Files".

data = dataTransfer . getData(format)

Returns the specified data. If there is no such data, returns the empty string.

dataTransfer . setData(format, data)

Adds the specified data.

dataTransfer . clearData( [ format ] )

Removes the data of the specified formats. Removes all data if the argument is omitted.

dataTransfer . files

Returns a FileList of the files being dragged, if any.

DataTransfer objects are used during the drag-and-drop events, and are only valid while those events are being fired.

A DataTransfer object is associated with a drag data store while it is valid.

The dropEffect attribute controls the drag-and-drop feedback that the user is given during a drag-and-drop operation. When the DataTransfer object is created, the 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 dropEffect attribute during the dragenter and dragover events. When the DataTransfer object is created, the effectAllowed attribute is set to a string value. On getting, it must return its current value. On setting, if drag data store’s mode is the 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 DataTransferItemList object associated with the DataTransfer object.

The setDragImage(element, x, y) method must run the following steps:

  1. If the DataTransfer object is no longer associated with a drag data store, abort these steps. Nothing happens.
  2. If the drag data store’s mode is not the read/write mode, abort these steps. Nothing happens.
  3. If the element argument is an img element, then set the drag data store bitmap to the element’s image (at its intrinsic size); otherwise, set the 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 drag data store hot spot coordinate to the given x, y coordinate.

The types attribute must return a live read only array giving the strings that the following steps would produce.

  1. Start with an empty list L.
  2. If the DataTransfer object is no longer associated with a drag data store, the array is empty. Abort these steps; return the empty list L.
  3. For each item in the drag data store item list whose kind is Plain Unicode string, add an entry to the list L consisting of the item’s type string.
  4. If there are any items in the drag data store item list whose kind is File, then add an entry to the list L consisting of the string "Files". (This value can be distinguished from the other values because it is not lowercase.)
  5. The strings produced by these steps are those in the list L.

The getData(format) method must run the following steps:

  1. If the DataTransfer object is no longer associated with a drag data store, return the empty string and abort these steps.
  2. If the drag data store’s mode is the protected mode, return the empty string and abort these steps.
  3. Let format be the first argument, 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 drag data store item list whose kind is Plain Unicode string and whose type string is equal to format, return the empty string and abort these steps.
  8. Let result be the data of the item in the drag data store item list whose kind is Plain Unicode string and whose 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. [RFC2483]
  10. Return result.

The setData(format, data) method must run the following steps:

  1. If the DataTransfer object is no longer associated with a drag data store, abort these steps. Nothing happens.
  2. If the drag data store’s mode is not the read/write mode, abort these steps. Nothing happens.
  3. Let format be the first argument, 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 drag data store item list whose kind is Plain Unicode string and whose type string is equal to format, if there is one.
  6. Add an item to the drag data store item list whose kind is Plain Unicode string, whose type string is equal to format, and whose data is the string given by the method’s second argument.

The clearData() method must run the following steps:

  1. If the DataTransfer object is no longer associated with a drag data store, abort these steps. Nothing happens.
  2. If the drag data store’s mode is not the read/write mode, abort these steps. Nothing happens.
  3. If the method was called with no arguments, remove each item in the drag data store item list whose kind is Plain Unicode string, and abort these steps.
  4. Let format be the first argument, 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 drag data store item list whose kind is Plain Unicode string and whose type string is equal to format, if there is one.

The clearData() method does not affect whether any files were included in the drag, so the types attribute’s list might still not be empty after calling clearData() (it would still contain the "Files" string if any files were included in the drag).

The files attribute must return a live FileList sequence consisting of File objects representing the files found by the following steps. Furthermore, for a given FileList object and a given underlying file, the same File object must be used each time.

  1. Start with an empty list L.
  2. If the DataTransfer object is no longer associated with a drag data store, the FileList is empty. Abort these steps; return the empty list L.
  3. If the drag data store’s mode is the protected mode, abort these steps; return the empty list L.
  4. For each item in the drag data store item list whose kind is File , add the item’s data (the file, in particular its name and contents, as well as its 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.

5.7.3.1. The DataTransferItemList interface

Each DataTransfer object is associated with a DataTransferItemList object.

interface DataTransferItemList {
  readonly attribute unsigned long length;
  getter DataTransferItem (unsigned long index);
  DataTransferItem? add(DOMString data, DOMString type);
  DataTransferItem? add(File data);
  void remove(unsigned long index);
  void clear();
};
items . length
Returns the number of items in the drag data store.
items[index]

Returns the DataTransferItem object representing the indexth entry in the drag data store.

items . remove(index)

Removes the indexth entry in the drag data store.

items . clear()

Removes all the entries in the drag data store.

items . add(data)
items . add(data, type)

Adds a new entry for the given data to the drag data store. If the data is plain text then a type string has to be provided also.

While the DataTransferItemList object’s DataTransfer object is associated with a drag data store, the DataTransferItemList object’s mode is the same as the drag data store mode. When the DataTransferItemList object’s DataTransfer object is not associated with a drag data store, the DataTransferItemList object’s mode is the disabled mode. The drag data store referenced in this section (which is used only when the DataTransferItemList object is not in the disabled mode) is the drag data store with which the DataTransferItemList object’s 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 drag data store item list.

When a DataTransferItemList object is not in the disabled mode, its supported property indices are the numbers in the range 0 .. n-1, where n is the number of items in the drag data store item list.

To determine the value of an indexed property i of a DataTransferItemList object, the user agent must return a DataTransferItem object representing the ith item in the drag data store. The same object must be returned each time a particular item is obtained from this DataTransferItemList object. The DataTransferItem object must be associated with the same DataTransfer object as the DataTransferItemList object when it is first created.

The add() method must run the following steps:

  1. If the DataTransferItemList object is not in the read/write mode, return null and abort these steps.
  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 drag data store item list whose kind is Plain Unicode string and whose type string is equal to the value of the method’s second argument, converted to ASCII lowercase, then throw a NotSupportedError exception and abort these steps.

    Otherwise, add an item to the drag data store item list whose kind is Plain Unicode string, whose type string is equal to the value of the method’s second argument, 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 File

    Add an item to the drag data store item list whose kind is File, whose type string is the type of the File, converted to ASCII lowercase, and whose data is the same as the File’s data.

  3. Determine the value of the indexed property corresponding to the newly added item, and return that value (a newly created DataTransferItem object).

The remove() method, when invoked with the argument i, must run these steps:

  1. If the DataTransferItemList object is not in the read/write mode, throw an InvalidStateError exception and abort these steps.
  2. Remove the ith item from the drag data store.

The clear() method, if the DataTransferItemList object is in the read/write mode, must remove all the items from the drag data store. Otherwise, it must do nothing.

5.7.3.2. The DataTransferItem interface

Each DataTransferItem object is associated with a DataTransfer object.

interface DataTransferItem {
  readonly attribute DOMString kind;
  readonly attribute DOMString type;
  void getAsString(FunctionStringCallback? _callback);
  File? getAsFile();
};

callback FunctionStringCallback = void (DOMString data);
item . kind

Returns the drag data item kind, one of: "string", "file".

item . type

Returns the drag data item type string.

item . getAsString(callback)

Invokes the callback with the string data as the argument, if the drag data item kind is Plain Unicode string.

file = item . getAsFile()

Returns a File object, if the drag data item kind is File.

While the DataTransferItem object’s DataTransfer object is associated with a drag data store and that drag data store’s drag data store item list still contains the item that the DataTransferItem object represents, the DataTransferItem object’s mode is the same as the drag data store mode. When the DataTransferItem object’s DataTransfer object is not associated with a drag data store, or if the item that the DataTransferItem object represents has been removed from the relevant drag data store item list, the DataTransferItem object’s mode is the disabled mode. The drag data store referenced in this section (which is used only when the DataTransferItem object is not in the disabled mode) is the drag data store with which the DataTransferItem object’s DataTransfer object is associated.

The kind attribute must return the empty string if the 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 the drag data item kind of the item represented by the DataTransferItem object:

Kind String
Plain Unicode string "string"
File "file"

The type attribute must return the empty string if the DataTransferItem object is in the disabled mode; otherwise it must return the drag data item type string of the item represented by the DataTransferItem object.

The getAsString(callback) method must run the following steps:

  1. If the callback is null, abort these steps.
  2. If the DataTransferItem object is not in the read/write mode or the read-only mode, abort these steps. The callback is never invoked.
  3. If the drag data item kind is not Plain Unicode string, abort these steps. The callback is never invoked.
  4. Otherwise, queue a task to invoke callback, passing the actual data of the item represented by the DataTransferItem object as the argument.

The getAsFile() method must run the following steps:

  1. If the DataTransferItem object is not in the read/write mode or the read-only mode, return null and abort these steps.
  2. If the drag data item kind is not File, then return null and abort these steps.
  3. Return a new File object representing the actual data of the item represented by the DataTransferItem object.

5.7.4. The DragEvent interface

The drag-and-drop processing model involves several events. They all use the DragEvent interface.

[Constructor(DOMString type, optional DragEventInit eventInitDict)]
interface DragEvent : MouseEvent {
  readonly attribute DataTransfer? dataTransfer;
};

dictionary DragEventInit : MouseEventInit {
  DataTransfer? dataTransfer = null;
};
event . dataTransfer

Returns the DataTransfer object for the event.

Although, for consistency with other event interfaces, the DragEvent interface has a constructor, it is not particularly useful. In particular, there’s no way to create a useful DataTransfer object from script, as DataTransfer objects have a processing and security model that is coordinated by the browser during drag-and-drops.

The dataTransfer attribute of the 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 drag data store, and optionally with a specific related target, the user agent must run the following steps:

  1. If no specific related target was provided, set related target to null.
  2. Let window be the Window object of the Document object of the specified target element.
  3. If e is dragstart, set the drag data store mode to the read/write mode.

    If e is drop, set the drag data store mode to the read-only mode.

  4. Let dataTransfer be a newly created DataTransfer object associated with the given drag data store.
  5. Set the effectAllowed attribute to the drag data store’s drag data store allowed effects state.
  6. Set the dropEffect attribute to "none" if e is dragstart, drag, dragexit, or dragleave; to the value corresponding to the current drag operation if e is drop or dragend; and to a value based on the effectAllowed attribute’s value and the drag-and-drop source, as given by the following table, otherwise (i.e., if e is dragenter or dragover):

    effectAllowed dropEffect
    "none" "none"
    "copy" "copy"
    "copyLink" "copy", or, if appropriate, "link"
    "copyMove" "copy", or, if appropriate, "move"
    "all" "copy", or, if appropriate, either "link" or "move"
    "link" "link"
    "linkMove" "link", or, if appropriate, "move"
    "move" "move"
    "uninitialized" when what is being dragged is a selection from a text field "move", or, if appropriate, either "copy" or "link"
    "uninitialized" when what is being dragged is a selection "copy", or, if appropriate, either "link" or "move"
    "uninitialized" when what is being dragged is an a element with an href attribute "link", or, if appropriate, either "copy" or "move"
    Any other case "copy", or, if appropriate, either "link" or "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 "link" is an option according to the table above while the "alt" key is depressed, the user agent could select that instead of "copy" or "move".

  7. Create a trusted DragEvent object and initialize it to have the given name e, to bubble, to be cancelable unless e is dragexit, dragleave, or dragend, and to have the view attribute initialized to window, the detail attribute initialized to zero, the mouse and key attributes initialized according to the state of the input devices as they would be for user interaction events, the relatedTarget attribute initialized to related target, and the dataTransfer attribute initialized to dataTransfer, the DataTransfer object created above.

    If there is no relevant pointing device, the object must have its screenX, screenY, clientX, clientY, and button attributes set to 0.

  8. Dispatch the newly created DragEvent object at the specified target element.
  9. Set the drag data store allowed effects state to the current value of dataTransfer’s effectAllowed attribute. (It can only have changed value if e is dragstart.)
  10. Set the drag data store mode back to the protected mode if it was changed in the first step.
  11. Break the association between dataTransfer and the drag data store.

5.7.5. Drag-and-drop 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 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 draggable set to true. If there is no such element, then nothing is being dragged; abort these steps, 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.

    img elements and a elements with an href attribute have their draggable attribute set to true by default.

  2. Create a drag data store. All the DND events fired subsequently by the steps in this section must use this 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 source node is the Text node that the user started the drag on (typically the 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 source node is the first Text node containing a part of the selection.

    Otherwise, if it is an element that is being dragged, then the source node is the element that is being dragged.

    Otherwise, the source node is part of another document or application. When this specification requires that an event be dispatched at the 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 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 list of dragged nodes contains, in tree order, every node that is partially or completely included in the selection (including all their ancestors).

    Otherwise, the list of dragged nodes contains only the source node, if any.

  5. If it is a selection that is being dragged, then add an item to the drag data store item list, with its properties set as follows:

    The drag data item type string
    "text/plain"
    The drag data item kind
    Plain Unicode string
    The actual data
    The text of the selection

    Otherwise, if any files are being dragged, then add one item per file to the drag data store item list, with their properties set as follows:

    The drag data item type string
    The MIME type of the file, if known, or "application/octet-stream" otherwise.
    The drag data item kind
    File
    The actual data
    The file’s contents and name.

    Dragging files can currently only happen from outside a browsing context, for example from a file system manager application.

    If the drag initiated outside of the application, the user agent must add items to the 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 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 drag data item type strings must be 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 list of dragged nodes is not empty, then extract the microdata from those nodes into a JSON form, and add one item to the drag data store item list, with its properties set as follows:

    The drag data item type string
    application/microdata+json
    The drag data item kind
    Plain Unicode string
    The actual data
    The resulting JSON string.
  7. Run the following substeps:

    1. Let urls be an empty list of absolute URLs.
    2. For each node in the list of dragged nodes:

      If the node is an a element with an href attribute
      Add to urls the result of parsing the element’s href content attribute relative to the element.
      If the node is an img element with a src attribute
      Add to urls the result of parsing the element’s src content attribute relative to the element.
    3. If urls is still empty, abort these substeps.
    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 drag data store item list, with its properties set as follows:
      The drag data item type string
      text/uri-list
      The drag data item kind
      Plain Unicode string
      The actual data
      url string
  8. Update the 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. Fire a DND event named dragstart at the source node.

    If the event is canceled, then the drag-and-drop operation should not occur; abort these steps.

    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. 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 drag data store bitmap, if any. In this case, the 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 CSS pixels from the left side and from the top side of the image respectively. [CSS-2015]
    2. The 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 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 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 current target element changes when the immediate user selection changes, based on the results of event listeners in the document, as described below.

Both the current target element and the 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 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 "none". It is updated by the user agent as described in the steps below.

User agents must, as soon as the drag operation is initiated and every 350ms (±200ms) thereafter for as long as the drag operation is ongoing, 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, abort these steps for this iteration (effectively "skipping missed frames" of the drag-and-drop operation).

  2. Fire a DND event named drag at the source node. If this event is canceled, the user agent must set the current drag operation to "none" (no drag operation).

  3. If the 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 immediate user selection than during the last iteration (or if this is the first iteration), and if this immediate user selection is not the same as the current target element, then fire a DND event named dragexit at the current target element, and then update the current target element as follows:

      If the new immediate user selection is null
      Set the current target element to null also.
      If the new immediate user selection is in a non-DOM document or application
      Set the current target element to the immediate user selection.
      Otherwise

      Fire a DND event named dragenter at the immediate user selection.

      If the event is canceled, then set the current target element to the immediate user selection.

      Otherwise, run the appropriate step from the following list:

      If the immediate user selection is a text field (e.g., textarea, or an input element whose type attribute is in the Text state) or an editing host or editable element, and the drag data store item list has an item with the drag data item type string "text/plain" and the drag data item kind Plain Unicode string
      Set the current target element to the immediate user selection anyway.
      If the immediate user selection is an element with a dropzone attribute that matches the drag data store
      Set the current target element to the immediate user selection anyway.
      If the immediate user selection is an element that itself has an ancestor element with a dropzone attribute that matches the drag data store

      Let new target be the nearest (deepest) such ancestor element.

      If the immediate user selection is new target, then leave the current target element unchanged.

      Otherwise, fire a DND event named dragenter at new target, with the current current target element as the specific related target. Then, set the current target element to new target, regardless of whether that event was canceled or not.

      If the immediate user selection is the body element
      Leave the current target element unchanged.
      Otherwise

      Fire a DND event named dragenter at the body element, if there is one, or at the Document object, if not. Then, set the current target element to the body element, regardless of whether that event was canceled or not.

    2. If the previous step caused the current target element to change, and if the previous target element was not null or a part of a non-DOM document, then fire a DND event named dragleave at the previous target element, with the new current target element as the specific related target.

    3. If the current target element is a DOM element, then fire a DND event named dragover at this current target element.

      If the dragover event is not canceled, run the appropriate step from the following list:

      If the current target element is a text field (e.g., textarea, or an input element whose type attribute is in the Text state) or an editing host or editable element, and the drag data store item list has an item with the drag data item type string "text/plain" and the drag data item kind Plain Unicode string
      Set the current drag operation to either "copy" or "move", as appropriate given the platform conventions.
      If the current target element is an element with a dropzone attribute that matches the drag data store and specifies an operation
      Set the current drag operation to the operation specified by the dropzone attribute of the current target element.
      If the current target element is an element with a dropzone attribute that matches the drag data store and does not specify an operation
      Set the current drag operation to "copy".
      Otherwise
      Reset the current drag operation to "none".

      Otherwise (if the dragover event is canceled), set the current drag operation based on the values of the effectAllowed and dropEffect attributes of the DragEvent object’s dataTransfer object as they stood after the event dispatch finished, as per the following table:

      effectAllowed dropEffect Drag operation
      "uninitialized", "copy", "copyLink", "copyMove", or "all" "copy" "copy"
      "uninitialized", "link", "copyLink", "linkMove", or "all" "link" "link"
      "uninitialized", "move", "copyMove", "linkMove", or "all" "move" "move"
      Any other case "none"
    4. Otherwise, if the 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 current drag operation accordingly.

    5. Update the drag feedback (e.g., the mouse cursor) to match the current drag operation, as follows:

      Drag operation Feedback
      "copy" Data will be copied if dropped here.
      "link" Data will be linked if dropped here.
      "move" Data will be moved if dropped here.
      "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 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 current drag operation is "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 current target element is null, then the drag operation failed. Run these substeps:

      1. Let dropped be false.
      2. If the current target element is a DOM element, fire a DND event named dragleave at it; otherwise, if it is not null, use platform-specific conventions for drag cancelation.
      3. Set the current drag operation to "none".

      Otherwise, the drag operation might be a success; run these substeps:

      1. Let dropped be true.
      2. If the current target element is a DOM element, fire a DND event named drop at it; otherwise, use platform-specific conventions for indicating a drop.
      3. If the event is canceled, set the current drag operation to the value of the dropEffect attribute of the DragEvent object’s dataTransfer object as it stood after the event dispatch finished.

        Otherwise, the event is not canceled; perform the event’s default action, which depends on the exact target as follows:

        If the current target element is a text field (e.g., textarea, or an input element whose type attribute is in the Text state) or an editing host or editable element, and the drag data store item list has an item with the drag data item type string "text/plain" and the drag data item kind Plain Unicode string
        Insert the actual data of the first item in the drag data store item list to have a drag data item type string of "text/plain" and a drag data item kind that is Plain Unicode string into the text field or editing host or 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 current drag operation to "none".
    2. Fire a DND event named dragend at the source node.

    3. Run the appropriate steps from the following list as the default action of the dragend event:

      If dropped is true, the current target element is a text field (see below), the current drag operation is "move", and the source of the drag-and-drop operation is a selection in the DOM that is entirely contained within an editing host
      Delete the selection.
      If dropped is true, the current target element is a text field (see below), the current drag operation is "move", and the source of the drag-and-drop operation is a selection in a text field
      The user agent should delete the dragged selection from the relevant text field.
      If dropped is false or if the current drag operation is "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 field is a textarea element or an input element whose type attribute is in one of the Text, Search, Telephone, URL, E-mail, Password, or 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 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 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.

5.7.6. Events summary

This section is non-normative.

The following events are involved in the drag-and-drop model.

Event Name Target Cancelable? Drag data store mode dropEffect Default Action
dragstart Source node ✓ Cancelable Read/write mode "none" Initiate the drag-and-drop operation
drag Source node ✓ Cancelable Protected mode "none" Continue the drag-and-drop operation
dragenter Immediate user selection or the body element ✓ Cancelable Protected mode Based on effectAllowed value Reject immediate user selection as potential target element
dragexit Previous target element Protected mode "none" None
dragleave Previous target element Protected mode "none" None
dragover Current target element ✓ Cancelable Protected mode Based on effectAllowed value Reset the current drag operation to "none"
drop Current target element ✓ Cancelable Read-only mode Current drag operation Varies
dragend Source node Protected mode Current drag operation Varies

Not shown in the above table: all these events bubble, and the effectAllowed attribute always has the value it had after the dragstart event, defaulting to "uninitialized" in the dragstart event.

5.7.7. The draggable attribute

All html elements may have the draggable content attribute set. The draggable attribute is an enumerated attribute. It has three states. The first state is true and it has the keyword true. The second state is false and it has the keyword false. The third state is auto; it has no keywords but it is the missing value default.

The true state means the element is draggable; the false state means that it is not. The auto state uses the default behavior of the user agent.

An element with a draggable attribute should also have a title attribute that names the element for the purpose of non-visual interactions.

element . draggable [ = value ]
Returns true if the element is draggable; otherwise, returns false.

Can be set, to override the default and set the draggable content attribute.

The 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 draggable IDL attribute is true become draggable as well.

If an element’s draggable content attribute has the state true, the draggable IDL attribute must return true.

Otherwise, if the element’s draggable content attribute has the state false, the draggable IDL attribute must return false.

Otherwise, the element’s draggable content attribute has the state auto. If the element is an img element, an object element that represents an image, or an a element with an href content attribute, the draggable IDL attribute must return true; otherwise, the draggable IDL attribute must return false.

If the draggable IDL attribute is set to the value false, the draggable content attribute must be set to the literal value "false". If the draggable IDL attribute is set to the value true, the draggable content attribute must be set to the literal value "true".

5.7.8. The dropzone attribute

All html elements may have the dropzone content attribute set. When specified, its value must be an unordered set of unique space-separated tokens that are ASCII case-insensitive. The allowed values are the following:

copy

Indicates that dropping an accepted item on the element will result in a copy of the dragged data.

move

Indicates that dropping an accepted item on the element will result in the dragged data being moved to the new location.

link

Indicates that dropping an accepted item on the element will result in a link to the original data.

Any keyword with eight characters or more, beginning with an ASCII case-insensitive match for the string "string:"

Indicates that items with the drag data item kind Plain Unicode string and the drag data item type string set to a value that matches the remainder of the keyword are accepted.

Any keyword with six characters or more, beginning with an ASCII case-insensitive match for the string "file:"

Indicates that items with the drag data item kind File and the drag data item type string set to a value that matches the remainder of the keyword are accepted.

The dropzone content attribute’s values must not have more than one of the three feedback values (copy, move, and link) specified. If none are specified, the copy value is implied.

An element with a dropzone attribute should also have a title attribute that names the element for the purpose of non-visual interactions.

A dropzone attribute matches a drag data store if the dropzone processing steps result in a match.

A dropzone attribute specifies an operation if the dropzone processing steps result in a specified operation. The specified operation is as given by those steps.

The dropzone processing steps are as follows. They either result in a match or not, and separate from this result either in a specified operation or not, as defined below.

  1. Let value be the value of the dropzone attribute.

  2. Let keywords be the result of splitting value on spaces.

  3. Let matched be false.

  4. Let operation be unspecified.

  5. For each value in keywords, if any, in the order that they were found in value, run the following steps.

    1. Let keyword be the keyword.

    2. If keyword is one of "copy", "move", or "link", then: run the following substeps:

      1. If operation is still unspecified, then let operation be the string given by keyword.

      2. Skip to the step labeled end of keyword below.

    3. If keyword does not contain a U+003A COLON character (:), or if the first such character in keyword is either the first character or the last character in the string, then skip to the step labeled end of keyword below.

    4. Let kind code be the substring of keyword from the first character in the string to the last character in the string that is before the first U+003A COLON character (:) in the string, converted to ASCII lowercase.

    5. Jump to the appropriate step from the list below, based on the value of kind code:

      If kind code is the string "string"
      Let kind be Plain Unicode string.
      If kind code is the string "file"
      Let kind be File.
      Otherwise
      Skip to the step labeled end of keyword below.
    6. Let type be the substring of keyword from the first character after the first U+003A COLON character (:) in the string, to the last character in the string, converted to ASCII lowercase.

    7. If there exist any items in the drag data store item list whose drag data item kind is the kind given in kind and whose drag data item type string is type, then let matched be true.

    8. End of keyword: Go on to the next keyword, if any, or the next step in the overall algorithm, if there are no more.

  6. The algorithm results in a match if matched is true, and does not otherwise.

    The algorithm results in a specified operation if operation is not unspecified. The specified operation, if one is specified, is the one given by operation.

The dropzone IDL attribute must reflect the content attribute of the same name.

The supported tokens for dropzone are the allowed values defined for the dropzone attribute that are supported by the user agent.

In this example, a div element is made into a drop target for image files using the dropzone attribute. Images dropped into the target are then displayed.
<div dropzone="copy file:image/png file:image/gif file:image/jpeg" ondrop="receive(event, this)">
<p>Drop an image here to have it displayed.</p>
</div>
<script>
function receive(event, element) {
  var data = event.dataTransfer.items;
  for (var i = 0; i < data.length; i += 1) {
    if ((data[i].kind == 'file') && (data[i].type.match('^image/'))) {
      var img = new Image();
      img.src = window.createObjectURL(data[i].getAsFile());
      element.appendChild(img);
    }
  }
}
</script>

5.7.9. Security risks in the drag-and-drop model

User agents must not make the data added to the DataTransfer object during the dragstart event available to scripts until the 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 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 his mouse button depressed, the user agent would not consider that to start a drag. This is important because otherwise user agents 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, 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 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. 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.

6.1. Browsing contexts

A 브라우징 컨텍스트 is an environment in which Document objects are presented to the user.

A tab or window in a Web browser typically contains a browsing context, as does an iframe or frames in a frameset.

A browsing context has a corresponding WindowProxy object.

A browsing context has a session history, which lists the Document objects that the browsing context has presented, is presenting, or will present. At any time, one Document in each browsing context is designated the active document. A Document's browsing context is that browsing context whose session history contains the Document, if any. (A Document created using an API such as createDocument() has no browsing context.) Each Document in a browsing context is associated with a Window object.

In general, there is a 1-to-1 mapping from the Window object to the Document object. There are two exceptions. First, a Window can be reused for the presentation of a second Document in the same browsing context, such that the mapping is then 1-to-2. This occurs when a browsing context is navigated from the initial about:blank Document to another, with replacement enabled. Second, a Document can end up being reused for several Window objects when the document.open() method is used, such that the mapping is then many-to-1.

A Document does not necessarily have a browsing context associated with it. In particular, data mining tools are likely to never instantiate browsing contexts.


A browsing context can have a creator browsing context, the browsing context that was responsible for its creation. If a browsing context has a parent browsing context, then that is its creator browsing context. Otherwise, if the browsing context has an opener browsing context, then that is its creator browsing context. Otherwise, the browsing context has no creator browsing context.

If a browsing context A has a creator browsing context, then the creator origin, creator URL, and creator base URL are the origin, URL, and base URL, respectively, of the Document that was the active document of that creator browsing context at the time A was created.

To create a new browsing context:

  1. Call the JavaScript InitializeHostDefinedRealm() abstract operation with the following customizations:

    • For the global object, create a new Window object window.

    • For the global this value, create a new WindowProxy object windowProxy, whose [[Window]] internal slot value is window.

      The internal slot value is updated when navigations occur.

    • Let realm execution context be the created JavaScript execution context.

  2. Set the new browsing context’s associated WindowProxy to windowProxy.

  3. Let document be a new Document, whose URL is about:blank, which is marked as being an HTML document, whose character encoding is UTF-8, and which is both ready for post-load tasks and completely loaded immediately.

  4. Set the origin of document:

  5. If the new browsing context has a creator browsing context, then set document’s referrer to the creator URL.

  6. Ensure that document has a single child html node, which itself has two empty child nodes: a head element, and a body element.

  7. Implement the sandboxing for document.

  8. Add document to the new browsing context’s session history.

  9. Set window’s associated Document to document.

  10. Set up a browsing context environment settings object with realm execution context.

6.1.1. Nested browsing contexts

Certain elements (for example, iframe elements) can instantiate further browsing contexts. These are called nested browsing contexts. If a browsing context P has a Document D with an element E that nests another browsing context C inside it, then C is said to be nested through D, and E is said to be the browsing context container of C. If the browsing context container element E is in the Document D, then P is said to be the parent browsing context of C and C is said to be a child browsing context of P. Otherwise, the nested browsing context C has no parent browsing context.

A browsing context A is said to be an ancestor of a browsing context B if there exists a browsing context A that is a child browsing context of A and that is itself an ancestor of B, or if the browsing context A is the parent browsing context of B.

A browsing context that is not a nested browsing context has no parent browsing context, and is the top-level browsing context of all the browsing contexts for which it is an ancestor browsing context.

The transitive closure of parent browsing contexts for a nested browsing context gives the list of ancestor browsing contexts.

The list of the descendant browsing contexts of a Document d is the (ordered) list returned by the following algorithm:

  1. Let list be an empty list.
  2. For each child browsing context of d that is nested through an element that is in the Document d, in the tree order of the elements nesting those browsing contexts, run these substeps:

    1. Append that child browsing context to the list list.
    2. Append the list of the descendant browsing contexts of the active document of that child browsing context to the list list.
  3. Return the constructed list.

A Document is said to be fully active when it has a browsing context and it is the active document of that browsing context, and either its browsing context is a top-level browsing context, or it has a parent browsing context and the Document through which it is nested is itself fully active.

Because they are nested through an element, child browsing contexts are always tied to a specific Document in their parent browsing context. User agents must not allow the user to interact with child browsing contexts of elements that are in Documents that are not themselves fully active.

A nested browsing context can be put into a delaying load events mode. This is used when it is navigated, to delay the load event of the browsing context container before the new Document is created.

The document family of a browsing context consists of the union of all the Document objects in that browsing context’s session history and the document families of all those Document objects. The document family of a Document object consists of the union of all the document families of the browsing contexts that are nested through the Document object.

window . top

Returns the WindowProxy for the top-level browsing context.

window . parent

Returns the WindowProxy for the parent browsing context.

window . frameElement

Returns the Element for the browsing context container.

Returns null if there isn’t one, and in cross-origin situations.

The top IDL attribute on the Window object of a Document in a browsing context b must return the WindowProxy object of its top-level browsing context (which would be its own WindowProxy object if it was a top-level browsing context itself), if it has one, or its own WindowProxy object otherwise (e.g., if it was a detached nested browsing context).

The parent IDL attribute on the Window object of a Document that has a browsing context b must return the WindowProxy object of the parent browsing context, if there is one (i.e., if b is a child browsing context), or the WindowProxy object of the browsing context b itself, otherwise (i.e., if it is a top-level browsing context or a detached nested browsing context).

The frameElement IDL attribute, on getting, must run the following algorithm:

  1. Let d be the Window object’s associated Document.

  2. Let context be d’s browsing context.

  3. If context is not a nested browsing context, return null and abort these steps.

  4. Let container be context’s browsing context container.

  5. If container’s node document’s origin is not same origin-domain with the entry settings object’s origin, then return null and abort these steps.

  6. Return container.

6.1.2. Auxiliary browsing contexts

It is possible to create new browsing contexts that are related to a top-level browsing context without being nested through an element. Such browsing contexts are called auxiliary browsing contexts. Auxiliary browsing contexts are always top-level browsing contexts.

An auxiliary browsing context has an opener browsing context, which is the browsing context from which the auxiliary browsing context was created.

The opener IDL attribute on the Window object, on getting, must return the WindowProxy object of the browsing context from which the current browsing context was created (its opener browsing context), if there is one, if it is still available, and if the current browsing context has not disowned its opener; otherwise, it must return null. On setting, if the new value is null then the current browsing context must disown its opener; if the new value is anything else then the user agent must call the [[DefineOwnProperty]] internal method of the Window object, passing the property name "opener" as the property key, and the Property Descriptor { [[Value]]: value, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true } as the property descriptor, where value is the new value.

6.1.3. Security

A browsing context A is familiar with a second browsing context B if one of the following conditions is true:


A browsing context A is allowed to navigate a second browsing context B if the following algorithm terminates positively:

  1. If A is not the same browsing context as B, and A is not one of the ancestor browsing contexts of B, and B is not a top-level browsing context, and A’s active document’s active sandboxing flag set has its sandboxed navigation browsing context flag set, then abort these steps negatively.
  2. Otherwise, if B is a top-level browsing context, and is one of the ancestor browsing contexts of A, and A’s active document’s active sandboxing flag set has its sandboxed top-level navigation browsing context flag set, then abort these steps negatively.
  3. Otherwise, if B is a top-level browsing context, and is neither A nor one of the ancestor browsing contexts of A, and A’s Document's active sandboxing flag set has its sandboxed navigation browsing context flag set, and A is not the one permitted sandboxed navigator of B, then abort these steps negatively.
  4. Otherwise, terminate positively!

An element has a browsing context scope origin if its Document's browsing context is a top-level browsing context or if all of its Document's ancestor browsing contexts all have active documents whose origin are the same origin as the element’s node document’s origin. If an element has a browsing context scope origin, then its value is the origin of the element’s node document.

6.1.4. Groupings of browsing contexts

Each browsing context is defined as having a list of one or more directly reachable browsing contexts. These are:

The transitive closure of all the browsing contexts that are directly reachable browsing contexts forms a unit of related browsing contexts.

Each unit of related browsing contexts is then further divided into the smallest number of groups such that every member of each group has an active document with an origin that, through appropriate manipulation of the document.domain attribute, could be made to be same origin-domain with other members of the group, but could not be made the same as members of any other group. Each such group is a unit of related similar-origin browsing contexts.

There is also at most one event loop per unit of related similar-origin browsing contexts (though several units of related similar-origin browsing contexts can have a shared event loop).

6.1.5. Browsing context names

Browsing contexts can have a browsing context name. By default, a browsing context has no name (its name is not set).

A valid browsing context name is any string with at least one character that does not start with a U+005F LOW LINE character. (Names starting with an underscore are reserved for special keywords.)

A valid browsing context name or keyword is any string that is either a valid browsing context name or that is an ASCII case-insensitive match for one of: _blank, _self, _parent, or _top.

These values have different meanings based on whether the page is sandboxed or not, as summarized in the following (non-normative) table. In this table, "current" means the browsing context that the link or script is in, "parent" means the parent browsing context of the one the link or script is in, "top" means the top-level browsing context of the one the link or script is in, "new" means a new top-level browsing context or auxiliary browsing context is to be created, subject to various user preferences and user agent policies, "none" means that nothing will happen, and "maybe new" means the same as "new" if the "allow-popups" keyword is also specified on the sandbox attribute (or if the user overrode the sandboxing), and the same as "none" otherwise.

Keyword Ordinary effect Effect in an iframe with...
sandbox="" sandbox="allow-top-navigation"
none specified, for links and form submissions current current current
empty string current current current
_blank new maybe new maybe new
_self current current current
_parent if there isn’t a parent current current current
_parent if parent is also top parent/top none parent/top
_parent if there is one and it’s not top parent none none
_top if top is current current current current
_top if top is not current top none top
name that doesn’t exist new maybe new maybe new
name that exists and is a descendant specified descendant specified descendant specified descendant
name that exists and is current current current current
name that exists and is an ancestor that is top specified ancestor none specified ancestor/top
name that exists and is an ancestor that is not top specified ancestor none none
other name that exists with common top specified none none
name that exists with different top, if familiar and one permitted sandboxed navigator specified specified specified
name that exists with different top, if familiar but not one permitted sandboxed navigator specified none none
name that exists with different top, not familiar new maybe new maybe new

Most of the restrictions on sandboxed browsing contexts are applied by other algorithms, e.g., the navigation algorithm, not the rules for choosing a browsing context given a browsing context name given below.


An algorithm is allowed to show a popup if any of the following conditions is true:

  • The task in which the algorithm is running is currently processing an activation behavior whose click event was trusted.
  • The task in which the algorithm is running is currently running the event listener for a trusted event whose type is in the following list:

    • change
    • click
    • dblclick
    • mouseup
    • reset
    • submit
  • The task in which the algorithm is running was queued by an algorithm that was allowed to show a popup, and the chain of such algorithms started within a user-agent defined timeframe.

    For example, if a user clicked a button, it might be acceptable for a popup to result from that after 4 seconds, but it would likely not be acceptable for a popup to result from that after 4 hours.


The rules for choosing a browsing context given a browsing context name are as follows. The rules assume that they are being applied in the context of a browsing context, as part of the execution of a task.

  1. If the given browsing context name is the empty string or _self, then the chosen browsing context must be the current one.
  2. If the given browsing context name is _parent, then the chosen browsing context must be the parent browsing context of the current one, unless there isn’t one, in which case the chosen browsing context must be the current browsing context.
  3. If the given browsing context name is _top, then the chosen browsing context must be the top-level browsing context of the current one, if there is one, or else the current browsing context.
  4. If the given browsing context name is not _blank and there exists a browsing context whose name is the same as the given browsing context name, and the current browsing context is familiar with that browsing context, and the user agent determines that the two browsing contexts are related enough that it is ok if they reach each other, then that browsing context must be the chosen one. If there are multiple matching browsing contexts, the user agent should select one in some arbitrary consistent manner, such as the most recently opened, most recently focused, or more closely related.
  5. Otherwise, a new browsing context is being requested, and what happens depends on the user agent’s configuration and abilities — it is determined by the rules given for the first applicable option from the following list:
    If the algorithm is not allowed to show a popup and the user agent has been configured to not show popups (i.e., the user agent has a "popup blocker" enabled)

    There is no chosen browsing context. The user agent may inform the user that a popup has been blocked.

    If the current browsing context’s active document’s active sandboxing flag set has the sandboxed auxiliary navigation browsing context flag set.

    Typically, there is no chosen browsing context.

    The user agent may offer to create a new top-level browsing context or reuse an existing top-level browsing context. If the user picks one of those options, then the designated browsing context must be the chosen one (the browsing context’s name isn’t set to the given browsing context name). The default behavior (if the user agent doesn’t offer the option to the user, or if the user declines to allow a browsing context to be used) must be that there must not be a chosen browsing context.

    If this case occurs, it means that an author has explicitly sandboxed the document that is trying to open a link.

    If the user agent has been configured such that in this instance it will create a new browsing context, and the browsing context is being requested as part of following a hyperlink whose link types include the noreferrer keyword
    A new top-level browsing context must be created. If the given browsing context name is not _blank, then the new top-level browsing context’s name must be the given browsing context name (otherwise, it has no name). The chosen browsing context must be this new browsing context. The creation of such a browsing context is a new start for session storage.

    If it is immediately navigated, then the navigation will be done with replacement enabled.

    If the user agent has been configured such that in this instance it will create a new browsing context, and the noreferrer keyword doesn’t apply
    A new auxiliary browsing context must be created, with the opener browsing context being the current one. If the given browsing context name is not _blank, then the new auxiliary browsing context’s name must be the given browsing context name (otherwise, it has no name). The chosen browsing context must be this new browsing context.

    If it is immediately navigated, then the navigation will be done with replacement enabled.

    If the user agent has been configured such that in this instance it will reuse the current browsing context
    The chosen browsing context is the current browsing context.
    If the user agent has been configured such that in this instance it will not find a browsing context
    There must not be a chosen browsing context.

    User agent implementors are encouraged to provide a way for users to configure the user agent to always reuse the current browsing context.

    If the current browsing context’s active document’s active sandboxing flag set has both the sandboxed navigation browsing context flag and sandbox propagates to auxiliary browsing contexts flag set, and the chosen browsing context picked above, if any, is a new browsing context, then all the flags that are set in the current browsing context’s active document’s active sandboxing flag set when the new browsing context is created must be set in the new browsing context’s popup sandboxing flag set, and the current browsing context must be set as the new browsing context’s one permitted sandboxed navigator.

6.1.6. Script settings for browsing contexts

When the user agent is required to set up a browsing context environment settings object, given a JavaScript execution context execution context, it must run the following steps:

  1. Let realm be the value of execution context’s Realm component.

  2. Let window be realm’s global object.

  3. Let url be a copy of the URL of the Document with which window is associated.

  4. Let settings object be a new environment settings object whose algorithms are defined as follows:

    The realm execution context

    Return execution context.

    The responsible browsing context

    Return the browsing context with which window is associated.

    The responsible event loop

    Return the event loop that is associated with the unit of related similar-origin browsing contexts to which window’s browsing context belongs.

    The responsible document

    Return the Document with which window is currently associated.

    The API URL character encoding

    Return the current character encoding of the Document with which window is currently associated.

    The API base URL

    Return the current base URL of the Document with which window is currently associated.

    The origin

    Return the origin of the Document with which window is currently associated.

    The creation URL

    Return url.

    The HTTPS state

    Return the HTTPS state of the Document with which window is currently associated.

  5. Set realm’s [[HostDefined]] field to settings object.

  6. Return settings object.

6.2. Security infrastructure for Window, WindowProxy, and Location objects

Although typically objects cannot be accessed across origins, the web platform would not be true to itself if it did not have some legacy exceptions to that rule that the web depends upon.

6.2.1. Integration with IDL

When perform a security check is invoked, with a platformObject, realm, identifier, and type, run these steps:

  1. If platformObject is a Window or Location object, then:

    1. Repeat for each e that is an element of CrossOriginProperties(platformObject):

      1. If SameValue(e.[[Property]], identifier) is true, then:

        1. If type is "method" and e has neither [[NeedsGet]] nor [[NeedsGet]], then return.

        2. Otherwise, if type is "getter" and e.[[NeedsGet]] is true, then return.

        3. Otherwise, if type is "setter" and e.[[NeedsSet]] is true, then return.

  2. If IsPlatformObjectSameOrigin(platformObject) is false, then throw a "SecurityError" DOMException.

6.2.2. Shared internal slot: [[CrossOriginPropertyDescriptorMap]]

Window and Location objects both have a [[CrossOriginPropertyDescriptorMap]] internal slot, whose value is initially an empty map.

The [[CrossOriginPropertyDescriptorMap]] internal slot contains a map with entries whose keys are (currentOrigin, objectOrigin, propertyKey)-tuples and values are property descriptors, as a memoization of what is visible to scripts when currentOrigin inspects a Window or Location object from objectOrigin. It is filled lazily by CrossOriginGetOwnPropertyHelper, which consults it on future lookups.

User agents should allow a value held in the map to be garbage collected along with its corresponding key when nothing holds a reference to any part of the value. That is, as long as garbage collection is not observable.

For example, with
const href = Object.getOwnPropertyDescriptor(crossOriginLocation, "href").set

the value and its corresponding key in the map cannot be garbage collected as that would be observable.

User agents may have an optimization whereby they remove key-value pairs from the map when document.domain is set. This is not observable as document.domain cannot revisit an earlier value.

For example, setting document.domain to "example.com" on www.example.com means user agents can remove all key-value pairs from the map where part of the key is www.example.com, as that can never be part of the origin again and therefore the corresponding value could never be retrieved from the map.

6.2.3. Shared abstract operations

6.2.3.1. CrossOriginProperties ( O )
  1. Assert: O is a Location or Window object.

  2. If O is a Location object, then return

      « {
          [[Property]]: "href",
          [[NeedsGet]]: false,
          [[NeedsSet]]: true
        },
        {
          [[Property]]: "replace"
        } »

  3. Let crossOriginWindowProperties be

      « {
          [[Property]]: "window",
          [[NeedsGet]]: true,
          [[NeedsSet]]: false
        },
        {
          [[Property]]: "self",
          [[NeedsGet]]: true,
          [[NeedsSet]]: false
        },
        {
          [[Property]]: "location",
          [[NeedsGet]]: true,
          [[NeedsSet]]: true
        },
        {
          [[Property]]: "close"
        },
        {
          [[Property]]: "closed",
          [[NeedsGet]]: true,
          [[NeedsSet]]: false
        },
        {
          [[Property]]: "focus"
        },
        {
          [[Property]]: "blur"
        },
        {
          [[Property]]: "frames",
          [[NeedsGet]]: true,
          [[NeedsSet]]: false
        },
        {
          [[Property]]: "length",
          [[NeedsGet]]: true,
          [[NeedsSet]]: false
        },
        {
          [[Property]]: "top",
          [[NeedsGet]]: true,
          [[NeedsSet]]: false
        },
        {
          [[Property]]: "opener",
          [[NeedsGet]]: true,
          [[NeedsSet]]: false
        },
        {
          [[Property]]: "parent",
          [[NeedsGet]]: true,
          [[NeedsSet]]: false
        },
        {
          [[Property]]: "postMessage"
        } »

  4. Repeat for each e that is an element of the child browsing context name property set:

    1. Add { [[Property]]: e } as the last element of crossOriginWindowProperties.

  5. Return crossOriginWindowProperties.

Indexed properties do not need to be safelisted as they are handled directly by the WindowProxy object.

6.2.3.2. IsPlatformObjectSameOrigin ( O )
  1. Return true if the current settings object’s origin is same origin-domain with O’s relevant settings object’s origin, and false otherwise.

6.2.3.3. CrossOriginGetOwnPropertyHelper ( O, P )

If this abstract operation returns undefined and there is no custom behavior, the caller needs to throw a "SecurityError" DOMException.

  1. If P is @@toStringTag, @@hasInstance, or @@isConcatSpreadable, then return PropertyDescriptor { [[Value]]: undefined, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

  2. Let crossOriginKey be a tuple consisting of the current settings object’s origin’s effective domain, O’s relevant settings object’s origin’s effective domain, and P.

  3. Repeat for each e that is an element of CrossOriginProperties(O):

    1. If SameValue(e.[[Property]], P) is true, then:

      1. If the value of the [[CrossOriginPropertyDescriptorMap]] internal slot of O contains an entry whose key is crossOriginKey, then return that entry’s value.

      2. Let originalDesc be OrdinaryGetOwnProperty(O, P).

      3. Let crossOriginDesc be CrossOriginPropertyDescriptor(e, originalDesc).

      4. Create an entry in the value of the [[CrossOriginPropertyDescriptorMap]] internal slot of O with key crossOriginKey and value crossOriginDesc.

      5. Return crossOriginDesc.

  4. Return undefined.

6.2.3.3.1. CrossOriginPropertyDescriptor ( crossOriginProperty, originalDesc )
  1. If crossOriginProperty.[[NeedsGet]] and crossOriginProperty.[[NeedsSet]] are absent, then:

    1. Let value be originalDesc.[[Value]].

    2. If IsCallable(value) is true, set value to CrossOriginFunctionWrapper(true, value).

    3. Return PropertyDescriptor{ [[Value]]: value, [[Enumerable]]: false, [[Writable]]: false, [[Configurable]]: true }.

  2. Otherwise:

    1. Let crossOriginGet be CrossOriginFunctionWrapper(crossOriginProperty.[[NeedsGet]], originalDesc.[[Get]]).

    2. Let crossOriginSet be CrossOriginFunctionWrapper(crossOriginProperty.[[NeedsSet]], originalDesc.[[Set]]).

    3. Return PropertyDescriptor{ [[Get]]: crossOriginGet, [[Set]]: crossOriginSet, [[Enumerable]]: false, [[Configurable]]: true }.

6.2.3.3.2. CrossOriginFunctionWrapper ( needsWrapping, functionToWrap )
  1. If needsWrapping is false, then return undefined.

  2. Return a new cross-origin wrapper function whose [[Wrapped]] internal slot is functionToWrap.

A cross-origin wrapper function is an anonymous built-in function that has a [[Wrapped]] internal slot.

When a cross-origin wrapper function F is called with a list of arguments argumentsList, the following steps are taken:

  1. Assert: F has a [[Wrapped]] internal slot that is a function.

  2. Let wrappedFunction be the [[Wrapped]] internal slot of F.

  3. Return Call(wrappedFunction, this, argumentsList).

Due to this being invoked from a different origin, a cross-origin wrapper function will have a different value for Function.prototype from the function being wrapped. This follows from how JavaScript creates anonymous built-in functions.

6.2.3.4. CrossOriginGet ( O, P, Receiver )
  1. Let desc be O.[[GetOwnProperty]](P).

  2. Assert: desc is not undefined.

  3. If IsDataDescriptor(desc) is true, then return desc.[[Value]].

  4. Assert: IsAccessorDescriptor(desc) is true.

  5. Let getter be desc.[[Get]].

  6. If getter is undefined, throw a "SecurityError" DOMException.

  7. Return Call(getter, Receiver).

6.2.3.5. CrossOriginSet ( O, P, V, Receiver )
  1. Let desc be O.[[GetOwnProperty]](P).

  2. Assert: desc is not undefined.

  3. If IsAccessorDescriptor(desc) is true, then:

    1. Let setter be desc.[[Set]].

    2. If setter is undefined, return false.

    3. Perform Call(setter, Receiver, «V»).

    4. Return true.

  4. Return false.

6.2.3.6. CrossOriginOwnPropertyKeys ( O )
  1. Let keys be a new empty List.

  2. Repeat for each e that is an element of CrossOriginProperties(O):

    1. Add e.[[Property]] as the last element of keys.

  3. Return keys.

6.3. The Window object

[PrimaryGlobal, LegacyUnenumerableNamedProperties]
/*sealed*/ interface Window : EventTarget {
// the current browsing context
[Unforgeable] readonly attribute WindowProxy window;
[Replaceable] readonly attribute WindowProxy self;
[Unforgeable] readonly attribute Document document;
attribute DOMString name;
[PutForwards=href, Unforgeable] readonly attribute Location location;
readonly attribute History history;
[Replaceable] readonly attribute BarProp locationbar;
[Replaceable] readonly attribute BarProp menubar;
[Replaceable] readonly attribute BarProp personalbar;
[Replaceable] readonly attribute BarProp scrollbars;
[Replaceable] readonly attribute BarProp statusbar;
[Replaceable] readonly attribute BarProp toolbar;
attribute DOMString status;
void close();
readonly attribute boolean closed;
void stop();
void focus();
void blur();

// other browsing contexts
[Replaceable] readonly attribute WindowProxy frames;
[Replaceable] readonly attribute unsigned long length;
[Unforgeable] readonly attribute WindowProxy top;
attribute any opener;
[Replaceable] readonly attribute WindowProxy parent;
readonly attribute Element? frameElement;
WindowProxy open(optional DOMString url = "about:blank", optional DOMString target = "_blank", [TreatNullAs=EmptyString] optional DOMString features = "", optional boolean replace = false);
getter WindowProxy (unsigned long index);
getter object (DOMString name);

// the user agent
readonly attribute Navigator navigator;

// user prompts
void alert();
void alert(DOMString message);
boolean confirm(optional DOMString message = "");
DOMString? prompt(optional DOMString message = "", optional DOMString default = "");
void print();
any showModalDialog(DOMString url, optional any argument); // deprecated

unsigned long requestAnimationFrame(FrameRequestCallback callback);
void cancelAnimationFrame(unsigned long handle);
};
Window implements GlobalEventHandlers;
Window implements WindowEventHandlers;

callback FrameRequestCallback = void (DOMHighResTimeStamp time);
window . window
window . frames
window . self

These attributes all return window.

window . document

Returns the Document associated with window.

document . defaultView

Returns the Window object of the active document.

The window, frames, and self IDL attributes must all return the Window object’s browsing context’s WindowProxy object.

The document IDL attribute must return the Window object’s newest Document object.

The Document object associated with a Window object can change in exactly one case: when the navigate algorithm initializes a new Document object for the first page loaded in a browsing context. In that specific case, the Window object of the original about:blank page is reused and gets a new Document object.

The defaultView IDL attribute of the Document interface must return the Document's browsing context’s WindowProxy object, if there is one, or null otherwise.


For historical reasons, Window objects must also have a writable, configurable, non-enumerable property named HTMLDocument whose value is the Document interface object.

6.3.1. APIs for creating and navigating browsing contexts by name

window = window . open( [ url [, target [, features [, replace ] ] ] ] )

Opens a window to show url (defaults to about:blank), and returns it. The target argument gives the name of the new window. If a window exists with that name already, it is reused. The replace attribute, if true, means that whatever page is currently open in that window will be removed from the window’s session history. The features argument can be used to influence the rendering of the new window.

window . name [ = value ]

Returns the name of the window.

Can be set, to change the name.

window . close()

Closes the window.

window . closed

Returns true if the window has been closed, false otherwise.

window . stop()

Cancels the document load.

The open() method on Window objects provides a mechanism for navigating an existing browsing context or opening and navigating an auxiliary browsing context.

When the method is invoked, the user agent must run the following steps:

  1. Let entry settings be the entry settings object when the method was invoked.
  2. Let url be the first argument.
  3. Let target be the second argument.
  4. Let features be the third argument.
  5. Let replace be the fourth argument.
  6. Let source browsing context be the responsible browsing context specified by entry settings.
  7. If target is the empty string, let it be the string "_blank" instead.
  8. If the user has indicated a preference for which browsing context to navigate, follow these substeps:

    1. Let target browsing context be the browsing context indicated by the user.
    2. If target browsing context is a new top-level browsing context, let the source browsing context be set as target browsing context’s one permitted sandboxed navigator.

    For example, suppose there is a user agent that supports control-clicking a link to open it in a new tab. If a user clicks in that user agent on an element whose onclick handler uses the window.open() API to open a page in an iframe, but, while doing so, holds the control key down, the user agent could override the selection of the target browsing context to instead target a new tab.

    Otherwise, apply the rules for choosing a browsing context given a browsing context name using target as the name and source browsing context as the context in which the algorithm is executed. If this results in there not being a chosen browsing context, then throw an InvalidAccessError exception and abort these steps. Otherwise, let target browsing context be the browsing context so obtained.

  9. If target browsing context was just created, either as part of the rules for choosing a browsing context given a browsing context name or due to the user indicating a preference for navigating a new top-level browsing context, then let new be true. Otherwise, let it be false.
  10. Interpret features as defined in the CSSOM View specification. [CSSOM-VIEW]
  11. If url is the empty string, run the appropriate steps from the following list:

    If new is false
    Jump to the step labeled end.
    If new is true
    Let resource be the URL "about:blank".

    Otherwise, parse url relative to entry settings, and let resource be the resulting URL record, if any. If the parse a URL algorithm failed, then run one of the following two steps instead:

    • Let resource be a resource representing an inline error page.
    • If new is false, jump to the step labeled end, otherwise, let resource be the URL "about:blank".
  12. If resource is "about:blank" and new is true, queue a task to fire a simple event named load at target browsing context’s Window object, with target override set to target browsing context’s Window object’s Document object.

    Otherwise, navigate target browsing context to resource, with the exceptions enabled flag set. If new is true, then replacement must be enabled also. The source browsing context is source browsing context.

  13. End: Return the WindowProxy object of target browsing context.

The name attribute of the Window object must, on getting, return the current name of the browsing context, if one is set, or the empty string otherwise; and, on setting, set the name of the browsing context to the new value.

The name gets reset when the browsing context is navigated to another domain.


The close() method on Window objects should, if all the following conditions are met, close the browsing context A:

A browsing context is script-closable if it is an auxiliary browsing context that was created by a script (as opposed to by an action of the user), or if it is a top-level browsing context whose session history contains only one Document.

The closed attribute on Window objects must return true if the Window object’s browsing context has been discarded, and false otherwise.

The stop() method on Window objects should, if there is an existing attempt to navigate the browsing context and that attempt is not currently running the unload a document algorithm, cancel that navigation; then, it must abort the active document of the browsing context of the Window object on which it was invoked.

6.3.2. Accessing other browsing contexts

window . length
Returns the number of child browsing contexts.
window[index]
Returns the indicated child browsing context.

The number of child browsing contexts of a Window object W is the number of child browsing contexts that are nested through elements that are in a Document that is the active document of the Window object’s associated Document object’s browsing context.

The length IDL attribute’s getter must return the number of child browsing contexts of this Window object.

Indexed access to child browsing contexts is defined through the [[GetOwnProperty]] internal method of the WindowProxy object.

6.3.3. Named access on the Window object

window[name]
Returns the indicated element or collection of elements.

As a general rule, relying on this will lead to brittle code. Which IDs end up mapping to this API can vary over time, as new features are added to the Web platform, for example. Instead of this, use document.getElementById() or document.querySelector().

The child browsing context name property set consists of the browsing context names of any child browsing context of the active document whose name is not the empty string, with duplicates omitted.

The Window interface supports named properties. The supported property names at any moment consist of the following, in tree order, ignoring later duplicates:

To determine the value of a named property name when the Window object is indexed for property retrieval, the user agent must return the value obtained using the following steps:

  1. Let objects be the list of named objects with the name name in the active document.

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

  2. If objects contains a nested browsing context, then return the WindowProxy object of the nested browsing context corresponding to the first browsing context container in tree order whose browsing context is in objects, and abort these steps.

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

  4. Otherwise return an HTMLCollection rooted at the Document node, whose filter matches only named objects with the name name. (By definition, these will all be elements.)

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

6.3.4. Garbage collection and browsing contexts

A browsing context has a strong reference to each of its Documents and its WindowProxy object, and the user agent itself has a strong reference to its top-level browsing contexts.

A Document has a strong reference to its Window object.

A Window object has a strong reference to its Document object through its document attribute. Thus, references from other scripts to either of those objects will keep both alive. Similarly, both Document and Window objects have implied strong references to the WindowProxy object.

Each script has a strong reference to its settings object, and each environment settings object has strong references to its global object, responsible browsing context, and responsible document (if any).

When a browsing context is to discard a Document, the user agent must run the following steps:

  1. Set the Document's salvageable state to false.
  2. Run any unloading document cleanup steps for the Document that are defined by this specification and other applicable specifications.
  3. Abort the Document.
  4. Remove any tasks associated with the Document in any task source, without running those tasks.
  5. Discard all the child browsing contexts of the Document.
  6. Lose the strong reference from the Document's browsing context to the Document.

Whenever a Document object is discarded, it is also removed from the list of the worker’s Documents of each worker whose list contains that Document.

When a browsing context is discarded, the strong reference from the user agent itself to the browsing context must be severed, and all the Document objects for all the entries in the browsing context’s session history must be discarded as well.

User agents may discard top-level browsing contexts at any time (typically, in response to user requests, e.g., when a user force-closes a window containing one or more top-level browsing contexts). Other browsing contexts must be discarded once their WindowProxy object is eligible for garbage collection.

6.3.5. Closing browsing contexts

When the user agent is required to close a browsing context, it must run the following steps:

  1. Let specified browsing context be the browsing context being closed.
  2. Prompt to unload the active document of the specified browsing context. If the user refused to allow the document to be unloaded, then abort these steps.
  3. Unload the active document of the specified browsing context with the recycle parameter set to false.
  4. Remove the specified browsing context from the user interface (e.g., close or hide its tab in a tabbed browser).
  5. Discard the specified browsing context.

User agents should offer users the ability to arbitrarily close any top-level browsing context.

6.3.6. Browser interface elements

To allow Web pages to integrate with Web browsers, certain Web browser interface elements are exposed in a limited way to scripts in Web pages.

Each interface element is represented by a BarProp object:

interface BarProp {
  readonly attribute boolean visible;
};
window . locationbar . visible
Returns true if the location bar is visible; otherwise, returns false.
window . menubar . visible
Returns true if the menu bar is visible; otherwise, returns false.
window . personalbar . visible
Returns true if the personal bar is visible; otherwise, returns false.
window . scrollbars . visible
Returns true if the scroll bars are visible; otherwise, returns false.
window . statusbar . visible
Returns true if the status bar is visible; otherwise, returns false.
window . toolbar . visible
Returns true if the toolbar is visible; otherwise, returns false.

The visible attribute, on getting, must return either true or a value determined by the user agent to most accurately represent the visibility state of the user interface element that the object represents, as described below.

The following BarProp objects exist for each Document object in a browsing context. Some of the user interface elements represented by these objects might have no equivalent in some user agents; for those user agents, except when otherwise specified, the object must act as if it was present and visible (i.e., its visible attribute must return true).

The location bar BarProp object
Represents the user interface element that contains a control that displays the URL of the active document, or some similar interface concept.
The menu bar BarProp object
Represents the user interface element that contains a list of commands in menu form, or some similar interface concept.
The personal bar BarProp object
Represents the user interface element that contains links to the user’s favorite pages, or some similar interface concept.
The scrollbar BarProp object
Represents the user interface element that contains a scrolling mechanism, or some similar interface concept.
The status bar BarProp object
Represents a user interface element found immediately below or after the document, as appropriate for the user’s media, which typically provides information about ongoing network activity or information about elements that the user’s pointing device is current indicating. If the user agent has no such user interface element, then the object may act as if the corresponding user interface element was absent (i.e., its visible attribute may return false).
The toolbar BarProp object
Represents the user interface element found immediately above or before the document, as appropriate for the user’s media, which typically provides session history traversal controls (back and forward buttons, reload buttons, etc). If the user agent has no such user interface element, then the object may act as if the corresponding user interface element was absent (i.e., its visible attribute may return false).

The locationbar attribute must return the location bar BarProp object.

The menubar attribute must return the menu bar BarProp object.

The personalbar attribute must return the personal bar BarProp object.

The scrollbars attribute must return the scrollbar BarProp object.

The statusbar attribute must return the status bar BarProp object.

The toolbar attribute must return the toolbar BarProp object.


For historical reasons, the status attribute on the Window object must, on getting, return the last string it was set to, and on setting, must set itself to the new value. When the Window object is created, the attribute must be set to the empty string. It does not do anything else.

6.3.7. The WindowProxy object

A WindowProxy is an exotic object that wraps a Window ordinary object, indirecting most operations through to the wrapped object. Each browsing context has an associated WindowProxy object. When the browsing context is navigated, the Window object wrapped by the browsing context’s associated WindowProxy object is changed.

There is no WindowProxy interface object.

Every WindowProxy object has a [[Window]] internal slot representing the wrapped Window object.

Although WindowProxy is named as a "proxy", it does not do polymorphic dispatch on its target’s internal methods as a real proxy would, due to a desire to reuse machinery between WindowProxy and Location objects. As long as the Window object remains an ordinary object this is unobservable and can be implemented either way.

In the following example, the variable x is set to the WindowProxy object returned by the window accessor on the global object. All of the expressions following the assignment return true, because the WindowProxy object passes most operations through to the underlying ordinary Window object.
var x = window;
x instanceof Window; // true
x === this; // true
6.3.7.1. The WindowProxy internal methods

The WindowProxy object internal methods are described in the subsections below.

6.3.7.1.1. [[GetPrototypeOf]] ( )
  1. Let W be the value of the [[Window]] internal slot of this.

  2. If IsPlatformObjectSameOrigin(W) is true, then return ! OrdinaryGetPrototypeOf(W).

  3. Return null.

6.3.7.1.2. [[SetPrototypeOf]] ( V )
  1. Return false.

6.3.7.1.3. [[IsExtensible]] ( )
  1. Return true.

6.3.7.1.4. [[PreventExtensions]] ( )
  1. Return false.

6.3.7.1.5. [[GetOwnProperty]] ( P )
  1. Let W be the value of the [[Window]] internal slot of this.

  2. If P is an array index property name, then:

    1. Let index be ToUint32(P).

    2. Let maxProperties be the number of child browsing contexts of W.

    3. Let value be undefined.

    4. If maxProperties is greater than 0 and index is less than maxProperties, then:

      1. Set value to the WindowProxy object of the indexth child browsing context of the Document that is nested through an element that is in W’s Document, sorted in the order that the elements nesting those browsing contexts were most recently inserted into the Document, the WindowProxy object of the most recently inserted browsing context container’s nested browsing context being last.

    5. Return PropertyDescriptor{ [[Value]]: value, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

  3. If IsPlatformObjectSameOrigin(W) is true, then return OrdinaryGetOwnProperty(W, P).

    This violates JavaScript’s internal method invariants.

  4. Let property be CrossOriginGetOwnPropertyHelper(W, P).

  5. If property is not undefined, return property.

  6. If property is undefined and P is in the child browsing context name property set, then:

    1. Let value be the WindowProxy object of the named object with the name P.

    2. Return PropertyDescriptor{ [[Value]]: value, [[Enumerable]]: false, [[Writable]]: false, [[Configurable]]: true }.

  7. Throw a "SecurityError" DOMException.

6.3.7.1.6. [[DefineOwnProperty]] ( P, Desc )
  1. If P is an array index property name, return false.

  2. Let W be the value of the [[Window]] internal slot of this.

  3. If IsPlatformObjectSameOrigin(W) is true, then return OrdinaryDefineOwnProperty(W, P, Desc).

    See above about how this violates JavaScript’s internal method invariants.

  4. Return false.

6.3.7.1.7. [[Get]] ( P, Receiver )
  1. Let W be the value of the [[Window]] internal slot of this.

  2. If IsPlatformObjectSameOrigin(W) is true, then return OrdinaryGet(this, P, Receiver).

  3. Return ? CrossOriginGet(this, P, Receiver).

6.3.7.1.8. [[Set]] ( P, V, Receiver )
  1. Let W be the value of the [[Window]] internal slot of this.

  2. If IsPlatformObjectSameOrigin(W) is true, then return OrdinarySet(W, this, Receiver).

  3. Return CrossOriginSet(this, P, V, Receiver).

6.3.7.1.9. [[Delete]] ( P )
  1. If P is an array index property name, return false.

  2. Let W be the value of the [[Window]] internal slot of this.

  3. If IsPlatformObjectSameOrigin(W) is true, then return OrdinaryDelete(W, P).

  4. Return false.

6.3.7.1.10. [[OwnPropertyKeys]] ( )
  1. Let W be the value of the [[Window]] internal slot of this.

  2. Let keys be a new empty List.

  3. Let maxProperties be the number of child browsing contexts of W.

  4. Let index be 0.

  5. Repeat while index < maxProperties,

    1. Add ! ToString(index) as the last element of keys.

    2. Increment index by 1.

  6. If IsPlatformObjectSameOrigin(W) is true, then return the concatenation of keys and ! OrdinaryOwnPropertyKeys(W).

  7. Return the concatenation of keys and ! CrossOriginOwnPropertyKeys(W).

6.4. Origin

Origins are the fundamental currency of the Web’s security model. Two actors in the Web platform that share an origin are assumed to trust each other and to have the same authority. Actors with differing origins are considered potentially hostile versus each other, and are isolated from each other to varying degrees.

For example, if Example Bank’s Web site, hosted at bank.example.com, tries to examine the DOM of Example Charity’s Web site, hosted at charity.example.org, a "SecurityError" DOMException will be raised.


An origin is one of the following:

An opaque origin

An internal value, with no serialisation, for which the only meaningful operation is testing for equality.

A tuple origin

A tuple consists of:

  • A scheme (a scheme).

  • A host (a host).

  • A port (a port).

  • A domain (null or a domain). Null unless stated otherwise.

Origins can be shared, e.g., among multiple Document objects. Furthermore, origins are generally immutable. Only the domain of a tuple origin can be changed, and only through the document.domain API.

The effective domain of an origin origin is computed as follows:

  1. If origin is an opaque origin, then return origin.

  2. If origin’s domain is non-null, then return origin’s domain.

  3. Return origin’s host.

Various specification objects are defined to have an origin. These origins are determined as follows:

For Document objects

If the Document's active sandboxing flag set has its sandboxed origin browsing context flag set
A unique opaque origin is assigned when the Document is created.
If the Document's URL’s scheme is a network scheme
A copy of the Document's URL’s origin assigned when the Document is created.

The document.open() method can change the Document's URL to "about:blank". Therefore the origin is assigned when the Document is created.

If the Document is the initial "about:blank" document
The one it was assigned when its browsing context was created.
If the Document is a non-initial "about:blank" document
If the Document was generated from a data: URL found in another Document or in a script
The origin of the incumbent settings object when the navigate algorithm was invoked, or, if no script was involved, of the node document of the element that initiated the navigation to that URL.
If the Document was created as part of the processing for javascript: URLs
The origin of the active document of the browsing context being navigated when the navigate algorithm was invoked.
If the Document is an iframe srcdoc document
The origin of the Document's browsing context’s browsing context container’s node document.
If the Document was obtained in some other manner (e.g., a data: URL typed in by the user or that was returned as the location of a redirect, a Document created using the createDocument() API, etc)
The default behavior as defined in the DOM standard applies. [DOM].

The origin is a unique opaque origin assigned when the Document is created.

For images of img elements

If the image data is CORS-cross-origin
A unique opaque origin assigned when the image is created.
If the image data is CORS-same-origin
The img element’s node document’s origin.

For audio and video elements

If the media data is CORS-cross-origin
A unique opaque origin assigned when the media data is fetched.
If the media data is CORS-same-origin
The media element’s node document’s origin.

For fonts

For a downloadable Web font it is a copy of the origin of the URL record used to obtain the font (after any redirects). [CSS-FONTS-3] [CSS-FONT-LOADING-3]

For a locally installed system font it is the origin of the Document in which that font is being used.

Other specifications can override the above definitions by themselves specifying the origin of a particular Document object, image, media element, or font.


The Unicode serialization of an origin is the string obtained by applying the following algorithm to the given origin origin:

  1. If origin is an opaque origin, then return "null".

  2. Let host be origin’s host.

  3. Let unicodeHost be host if host is not a domain, and the result of applying domain to Unicode to host otherwise.

  4. Let unicodeOrigin be a new tuple origin consisting origin’s scheme, unicodeHost, and origin’s port.

  5. Return the ASCII serialization of an origin, given unicodeOrigin.

    The name ASCII serialization of an origin is misleading, as it merely serialises an origin, which are all ASCII by default due to the URL parser.

The Unicode serialization of ("https", "xn--maraa-rta.example", null, null) is "https://maraña.example".

The ASCII serialization of an origin is the string obtained by applying the following algorithm to the given origin origin:

  1. If origin is an opaque origin, then return "null".

  2. Otherwise, let result be origin’s scheme.

  3. Append "://" to result.

  4. Append origin’s host, serialized, to result.

  5. If origin’s port is non-null, append a U+003A COLON character (:), and origin’s port, serialized, to result.

  6. Return result.

Two origins A and B are said to be same origin if the following algorithm returns true:

  1. If A and B are the same opaque origin, then return true.

  2. If A and B are both tuple origins, and their schemes, hosts, and ports are identical, then return true.

  3. Return false.

Two 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 opaque origin, then return true.

  2. If A and B are both tuple origins, run these substeps:

    1. If A and B’s schemes are identical, and their domains are identical and non-null, then return true.

    2. Otherwise, if A and B are same origin and their domains are identical and null, then return true.

  3. Return false.

The following table shows how A and B are related:
A B same origin same origin-domain
("https", "example.org", null, null) ("https", "example.org", null, null)
("https", "example.org", 314, "example.org") ("https", "example.org", 420, "example.org")
("https", "example.org", null, null) ("https", "example.org", null, "example.org")
("https", "example.org", null, "example.org") ("http", "example.org", null, "example.org")

6.4.1. Relaxing the same-origin restriction

document . domain [ = domain ]
Returns the current domain used for security checks.

Can be set to a value that removes subdomains, to change the origin’s domain to allow pages on other subdomains of the same domain (if they do the same thing) to access each other. (Can’t be set in sandboxed iframes.)

The domain attribute’s getter must run these steps:

  1. If this Document object does not have a browsing context, then return the empty string.

  2. Let effectiveDomain be this Document's origin’s effective domain.

  3. If effectiveDomain is an opaque origin, then return the empty string.

  4. Return effectiveDomain, serialised.

The domain attribute on setting must run these steps:

  1. If this Document object has no browsing context, throw a "SecurityError" DOMException.

  2. If this Document object’s active sandboxing flag set has its sandboxed document.domain browsing context flag set, then throw a "SecurityError" DOMException.

  3. If the given value is the empty string, then throw a "SecurityError" DOMException.

  4. Let host be the result of parsing the given value.

  5. If host is failure, then throw a "SecurityError" DOMException.

  6. Let effectiveDomain be this Document object’s origin’s effective domain.

  7. If host is not equal to effectiveDomain, then run these substeps:

    1. If host or effectiveDomain is not domain, then throw a "SecurityError" DOMException.

      This is meant to exclude hosts that are an IPv4 address or an IPv6 address.

    2. If host, prefixed by a U+002E FULL STOP (.), does not exactly match the effectiveDomain, then throw a "SecurityError" DOMException.

    3. If host matches a suffix in the Public Suffix List, or, if host, prefixed by a U+002E FULL STOP (.), matches the end of a suffix in the Public Suffix List, then throw a "SecurityError" DOMException. [PSL]

      Suffixes must be compared after applying the host parser algorithm. [URL]

  8. Set origin’s domain to host.

The document.domain attribute is used to enable pages on different hosts of a domain to access each others' DOMs.

Do not use the document.domain attribute when using shared hosting. If an untrusted third party is able to host an HTTP server at the same IP address but on a different port, then the same-origin protection that normally protects two different sites on the same host will fail, as the ports are ignored when comparing origins after the document.domain attribute has been used.

6.5. Sandboxing

A sandboxing flag set is a set of zero or more of the following flags, which are used to restrict the abilities that potentially untrusted resources have:

The sandboxed navigation browsing context flag

This flag prevents content from navigating browsing contexts other than the sandboxed browsing context itself (or browsing contexts further nested inside it), auxiliary browsing contexts (which are protected by the sandboxed auxiliary navigation browsing context flag defined next), and the top-level browsing context (which is protected by the sandboxed top-level navigation browsing context flag defined below).

If the sandboxed auxiliary navigation browsing context flag is not set, then in certain cases the restrictions nonetheless allow popups (new top-level browsing contexts) to be opened. These browsing contexts always have one permitted sandboxed navigator, set when the browsing context is created, which allows the browsing context that created them to actually navigate them. (Otherwise, the sandboxed navigation browsing context flag would prevent them from being navigated even if they were opened.)

The sandboxed auxiliary navigation browsing context flag

This flag prevents content from creating new auxiliary browsing contexts, e.g., using the target attribute, the window.open() method, or the showModalDialog() method.

The sandboxed top-level navigation browsing context flag

This flag prevents content from navigating their top-level browsing context and prevents content from closing their top-level browsing context.

When the sandboxed top-level navigation browsing context flag is not set, content can navigate its top-level browsing context, but other browsing contexts are still protected by the sandboxed navigation browsing context flag and possibly the sandboxed auxiliary navigation browsing context flag.

The sandboxed plugins browsing context flag

This flag prevents content from instantiating plugins, whether using the embed element, the object element, the applet element, or through navigation of a nested browsing context, unless those plugins can be secured.

The sandboxed origin browsing context flag

This flag forces content into a unique origin, thus preventing it from accessing other content from the same origin.

This flag also prevents script from reading from or writing to the document.cookie IDL attribute, and blocks access to localStorage. [WEBSTORAGE]

The sandboxed forms browsing context flag

This flag blocks form submission.

The sandboxed pointer lock browsing context flag

This flag disables the Pointer Lock API. [POINTERLOCK]

The sandboxed scripts browsing context flag

This flag blocks script execution.

The sandboxed automatic features browsing context flag

This flag blocks features that trigger automatically, such as automatically playing a video or automatically focusing a form control.

The sandboxed storage area URLs flag

This flag prevents URL schemes that use storage areas from being able to access the origin’s data.

The sandboxed fullscreen browsing context flag

This flag prevents content from using the requestFullscreen() method.

The sandboxed document.domain browsing context flag
This flag prevents content from using the document.domain setter.
The sandbox propagates to auxiliary browsing contexts flag

This flag prevents content from escaping the sandbox by ensuring that any auxiliary browsing context it creates inherits the content’s active sandboxing flag set.

The sandboxed modals flag

This flag prevents content from using any of the following features to produce modal dialogs:

  • window.alert()
  • window.confirm()
  • window.print()
  • window.prompt()
  • window.showModalDialog()
  • the beforeunload event

When the user agent is to parse a sandboxing directive, given a string input, a sandboxing flag set output, and optionally an allow fullscreen flag, it must run the following steps:

  1. Split input on spaces, to obtain tokens.
  2. Let output be empty.
  3. Add the following flags to output:


Every top-level browsing context has a popup sandboxing flag set, which is a sandboxing flag set. When a browsing context is created, its popup sandboxing flag set must be empty. It is populated by the rules for choosing a browsing context given a browsing context name.

Every nested browsing context has an iframe sandboxing flag set, which is a sandboxing flag set. Which flags in a nested browsing context’s iframe sandboxing flag set are set at any particular time is determined by the iframe element’s sandbox attribute.

Every Document has an active sandboxing flag set, which is a sandboxing flag set. When the Document is created, its active sandboxing flag set must be empty. It is populated by the navigation algorithm.

Every resource that is obtained by the navigation algorithm has a forced sandboxing flag set, which is a sandboxing flag set. A resource by default has no flags set in its forced sandboxing flag set, but other specifications can define that certain flags are set.

In particular, the forced sandboxing flag set is used by the Content Security Policy specification. [CSP3]


When a user agent is to implement the sandboxing for a Document, it must populate Document's active sandboxing flag set with the union of the flags that are present in the following sandboxing flag sets at the time the Document object is created:

6.6. Session history and navigation

6.6.1. The session history of browsing contexts

The sequence of Documents in a browsing context is its session history. Each browsing context, including nested browsing contexts, has a distinct session history. A browsing context’s session history consists of a flat list of session history entries. Each session history entry consists, at a minimum, of a URL, and each entry may in addition have a state object, a title, a Document object, form data, a scroll restoration mode, a scroll position, and other information associated with it.

Each entry, when first created, has a Document. However, when a Document is not active, it’s possible for it to be discarded to free resources. The URL and other data in a session history entry is then used to bring a new Document into being to take the place of the original, should the user agent find itself having to reactivate that Document.

Titles associated with session history entries need not have any relation with the current title of the Document. The title of a session history entry is intended to explain the state of the document at that point, so that the user can navigate the document’s history.

URLs without associated state objects are added to the session history as the user (or script) navigates from page to page.


Each Document object in a browsing context’s session history is associated with a unique History object which must all model the same underlying session history.

The history attribute of the Window interface must return the object implementing the History interface for that Window object’s newest Document.

A state object is an object representing a user interface state.

Pages can add state objects to the session history. These are then returned to the script when the user (or script) goes back in the history, thus enabling authors to use the "navigation" metaphor even in one-page applications.

State objects are intended to be used for two main purposes: first, storing a preparsed description of the state in the URL so that in the simple case an author doesn’t have to do the parsing (though one would still need the parsing for handling URLs passed around by users, so it’s only a minor optimization), and second, so that the author can store state that one wouldn’t store in the URL because it only applies to the current Document instance and it would have to be reconstructed if a new Document were opened.

An example of the latter would be something like keeping track of the precise coordinate from which a pop-up div was made to animate, so that if the user goes back, it can be made to animate to the same location. Or alternatively, it could be used to keep a pointer into a cache of data that would be fetched from the server based on the information in the URL, so that when going back and forward, the information doesn’t have to be fetched again.


At any point, one of the entries in the session history is the current entry. This is the entry representing the active document of the browsing context. Which entry is the current entry is changed by the algorithms defined in this specification, e.g., during session history traversal.

The current entry is usually an entry for the address of the Document. However, it can also be one of the entries for state objects added to the history by that document.

An entry with persisted user state is one that also has user-agent defined state. This specification does not specify what kind of state can be stored.

For example, some user agents might want to persist the scroll position, or the values of form controls.

User agents that persist the value of form controls are encouraged to also persist their directionality (the value of the element’s dir attribute). This prevents values from being displayed incorrectly after a history traversal when the user had originally entered the values with an explicit, non-default directionality.

An entry’s scroll restoration mode indicates whether the user agent should restore the persisted scroll position (if any) when traversing to it. The scroll restoration mode may be one of the following:

"auto"
The user agent is responsible for restoring the scroll position upon navigation.
"manual"
The page is responsible for restoring the scroll position and the user agent does not attempt to do so automatically

If unspecified, the scroll restoration mode of a new entry must be set to "auto".

Entries that consist of state objects share the same Document as the entry for the page that was active when they were added.

Contiguous entries that differ just by fragment identifier also share the same Document.

All entries that share the same Document (and that are therefore merely different states of one particular document) are contiguous by definition.

Each Document in a browsing context can also have a latest entry. This is the entry for that Document to which the browsing context’s session history was most recently traversed. When a Document is created, it initially has no latest entry.

User agents may discard the Document objects of entries other than the current entry that are not referenced from any script, reloading the pages afresh when the user or script navigates back to such pages. This specification does not specify when user agents should discard Document objects and when they should cache them.

Entries that have had their Document objects discarded must, for the purposes of the algorithms given below, act as if they had not. When the user or script navigates back or forwards to a page which has no in-memory DOM objects, any other entries that shared the same Document object with it must share the new object as well.

6.6.2. The History interface

enum ScrollRestoration { "auto", "manual" };
interface History {
  readonly attribute unsigned long length;
  attribute ScrollRestoration scrollRestoration;
  readonly attribute any state;
  void go(optional long delta = 0);
  void back();
  void forward();
  void pushState(any data, DOMString title, optional DOMString? url = null);
  void replaceState(any data, DOMString title, optional DOMString? url = null);
};
window . history . length

Returns the number of entries in the joint session history.

window . history . scrollRestoration [ = value ]

Returns the scroll restoration mode of the current entry in the session history.

Can be set, to change the scroll restoration mode of the current entry in the session history.

window . history . state

Returns the current state object.

window . history . go( [ delta ] )

Goes back or forward the specified number of steps in the joint session history.

A zero delta will reload the current page.

If the delta is out of range, does nothing.

window . history . back()

Goes back one step in the joint session history.

If there is no previous page, does nothing.

window . history . forward()

Goes forward one step in the joint session history.

If there is no next page, does nothing.

window . history . pushState(data, title [, url ] )

Pushes the given data onto the session history, with the given title, and, if provided and not null, the given URL.

window . history . replaceState(data, title [, url ] )

Updates the current entry in the session history to have the given data, title, and, if provided and not null, URL.

The joint session history of a top-level browsing context is the union of all the session histories of all browsing contexts of all the fully active Document objects that share that top-level browsing context, with all the entries that are current entries in their respective session histories removed except for the current entry of the joint session history.

The current entry of the joint session history is the entry that most recently became a current entry in its session history.

Entries in the joint session history are ordered chronologically by the time they were added to their respective session histories. Each entry has an index; the earliest entry has index 0, and the subsequent entries are numbered with consecutively increasing integers (1, 2, 3, etc).

Since each Document in a browsing context might have a different event loop, the actual state of the joint session history can be somewhat nebulous. For example, two sibling iframe elements could both traverse from one unique origin to another at the same time, so their precise order might not be well-defined; similarly, since they might only find out about each other later, they might disagree about the length of the joint session history.

The length attribute of the History interface, on getting, must return the number of entries in the top-level browsing context’s joint session history. If this History object is associated with a Document that is not fully active, getting must instead throw a "SecurityError" DOMException.

The actual entries are not accessible from script.

The scrollRestoration attribute of the History interface, on getting, must return the scroll restoration mode of the current entry in the session history. On setting, the scroll restoration mode of the current entry in the session history must be set to the new value. If this History object is associated with a Document that is not fully active, both getting and setting must instead throw a "SecurityError" DOMException.

The state attribute of the History interface, on getting, must return the last value it was set to by the user agent. If this History object is associated with a Document that is not fully active, getting must instead throw a SecurityError DOMException. Initially, its value must be null.

When the go(delta) method is invoked, if delta is zero, the user agent must act as if the location.reload() method was called instead. Otherwise, the user agent must traverse the history by a delta whose value is delta If this History object is associated with a Document that is not fully active, invoking must instead throw a "SecurityError" DOMException.

When the back() method is invoked, the user agent must traverse the history by a delta −1. If this History object is associated with a Document that is not fully active, invoking must instead throw a "SecurityError" DOMException.

When the forward()method is invoked, the user agent must traverse the history by a delta +1. If this History object is associated with a Document that is not fully active, invoking must instead throw a "SecurityError" DOMException.


Each top-level browsing context has a session history traversal queue, initially empty, to which tasks can be added.

Each top-level browsing context, when created, must begin running the following algorithm, known as the session history event loop for that top-level browsing context, in parallel:

  1. Wait until this top-level browsing context’s session history traversal queue is not empty.
  2. Pull the first task from this top-level browsing context’s session history traversal queue, and execute it.
  3. Return to the first step of this algorithm.

The session history event loop helps coordinate cross-browsing-context transitions of the joint session history: since each browsing context might, at any particular time, have a different event loop (this can happen if the user agent has more than one event loop per unit of related browsing contexts), transitions would otherwise have to involve cross-event-loop synchronization.


To traverse the history by a delta delta, the user agent must append a task to this top-level browsing context’s session history traversal queue, the task consisting of running the following steps:

  1. If the index of the current entry of the joint session history plus delta is less than zero or greater than or equal to the number of items in the joint session history, then abort these steps.
  2. Let specified entry be the entry in the joint session history whose index is the sum of delta and the index of the current entry of the joint session history.
  3. Let specified browsing context be the browsing context of the specified entry.
  4. If the specified browsing context’s active document’s unload a document algorithm is currently running, abort these steps.
  5. Queue a task that consists of running the following substeps. The relevant event loop is that of the specified browsing context’s active document. The task source for the queued task is the history traversal task source.

    1. If there is an ongoing attempt to navigate specified browsing context that has not yet matured (i.e., it has not passed the point of making its Document the active document), then cancel that attempt to navigate the browsing context.
    2. If the specified browsing context’s active document is not the same Document as the Document of the specified entry, then run these substeps:

      1. Prompt to unload the active document of the specified browsing context. If the user refused to allow the document to be unloaded, then abort these steps.
      2. Unload the active document of the specified browsing context with the recycle parameter set to false.
    3. Traverse the history of the specified browsing context to the specified entry.

When the user navigates through a browsing context, e.g., using a browser’s back and forward buttons, the user agent must traverse the history by a delta equivalent to the action specified by the user.


The pushState() method adds a state object entry to the history.

The replaceState() method updates the state object, title, and optionally the URL of the current entry in the history.

When either of these methods is invoked, the user agent must run the following steps:

  1. If this History object is associated with a Document that is not fully active, throw a "SecurityError" DOMException.

  2. Optionally, abort these steps. (For example, the user agent might disallow calls to these methods that are invoked on a timer, or from event listeners that are not triggered in response to a clear user action, or that are invoked in rapid succession.)

  3. Let targetRealm be this History object’s relevant settings object’s Realm.

  4. Let cloned data be a StructuredClone(data, targetRealm). Rethrow any exceptions.

  5. If the third argument is not null, run these substeps:

    1. Parse the value of the third argument, relative to the entry settings object.

    2. If that fails, throw a "SecurityError" DOMException and abort these steps.

    3. Let new URL be the resulting URL record.

    4. Compare new URL to the document’s URL. If any component of these two URL records differ other than the path, query, and fragment components, then throw a "SecurityError" DOMException and abort these steps.

    5. If the origin of new URL is not the same as the origin of the responsible document specified by the entry settings object, and either the path or query components of the two URL records compared in the previous step differ, throw a "SecurityError" DOMException and abort these steps. (This prevents sandboxed content from spoofing other pages on the same origin.)

  6. If the third argument is null, then let new URL be the URL of the current entry.

  7. If the method invoked was the pushState() method:

    1. Remove all the entries in the browsing context’s session history after the current entry. If the current entry is the last entry in the session history, then no entries are removed.

      This doesn’t necessarily have to affect the user agent’s user interface.

    2. Remove any tasks queued by the history traversal task source that are associated with any Document objects in the top-level browsing context’s document family.

    3. If appropriate, update the current entry to reflect any state that the user agent wishes to persist. The entry is then said to be an entry with persisted user state.

    4. Add a state object entry to the session history, after the current entry, with cloned data as the state object, the given title as the title, new URL as the URL of the entry, and the scroll restoration mode of the current entry in the session history as the scroll restoration mode.

    5. Update the current entry to be this newly added entry.

    Otherwise, if the method invoked was the replaceState() method:

    1. Update the current entry in the session history so that cloned data is the entry’s new state object, the given title is the new title, and new URL is the entry’s new URL.

  8. If the current entry in the session history represents a non-GET request (e.g., it was the result of a POST submission) then update it to instead represent a GET request.

  9. Set the document’s URL to new URL.

    Since this is neither a navigation of the browsing context nor a history traversal, it does not cause a hashchange event to be fired.

  10. Let targetRealm be this History object’s relevant settings object’s Realm.

  11. Set history.state to StructuredClone(cloned data, targetRealm).

  12. Let the latest entry of the Document of the current entry be the current entry.

The title is purely advisory. User agents might use the title in the user interface.

User agents may limit the number of state objects added to the session history per page. If a page hits the user agent-defined limit, user agents must remove the entry immediately after the first entry for that Document object in the session history after having added the new entry. (Thus the state history acts as a FIFO buffer for eviction, but as a LIFO buffer for navigation.)

Consider a game where the user can navigate along a line, such that the user is always at some coordinate, and such that the user can bookmark the page corresponding to a particular coordinate, to return to it later.

A static page implementing the x=5 position in such a game could look like the following:

<!DOCTYPE HTML>
<!-- this is https://example.com/line?x=5 -->
<title>Line Game - 5</title>
<p>You are at coordinate 5 on the line.</p>
<p>
<a href="?x=6">Advance to 6</a> or
<a href="?x=4">retreat to 4</a>?
</p>

The problem with such a system is that each time the user clicks, the whole page has to be reloaded. Here instead is another way of doing it, using script:

<!DOCTYPE HTML>
<!-- this starts off as https://example.com/line?x=5 -->
<title>Line Game - 5</title>
<p>You are at coordinate <span>5</span> on the line.</p>
<p>
<a href="?x=6" onclick="go(1); return false;">Advance to 6</a> or
<a href="?x=4" onclick="go(-1); return false;">retreat to 4</a>?
</p>
<script>
var currentPage = 5; // prefilled by server
function go(d) {
  setupPage(currentPage + d);
  history.pushState(currentPage, document.title, '?x=' + currentPage);
}
onpopstate = function(event) {
  setupPage(event.state);
}
function setupPage(page) {
  currentPage = page;
  document.title = 'Line Game - ' + currentPage;
  document.getElementById('coord').textContent = currentPage;
  document.links[0].href = '?x=' + (currentPage+1);
  document.links[0].textContent = 'Advance to ' + (currentPage+1);
  document.links[1].href = '?x=' + (currentPage-1);
  document.links[1].textContent = 'retreat to ' + (currentPage-1);
}
</script>

In systems without script, this still works like the previous example. However, users that do have script support can now navigate much faster, since there is no network access for the same experience. Furthermore, contrary to the experience the user would have with just a naïve script-based approach, bookmarking and navigating the session history still work.

In the example above, the data argument to the pushState() method is the same information as would be sent to the server, but in a more convenient form, so that the script doesn’t have to parse the URL each time the user navigates.

Applications might not use the same title for a session history entry as the value of the document’s title element at that time. For example, here is a simple page that shows a block in the title element. Clearly, when navigating backwards to a previous state the user does not go back in time, and therefore it would be inappropriate to put the time in the session history title.
<!DOCTYPE HTML>
<TITLE>Line</TITLE>
<SCRIPT>
setInterval(function () { document.title = 'Line - ' + new Date(); }, 1000);
var i = 1;
function inc() {
  set(i+1);
  history.pushState(i, 'Line - ' + i);
}
function set(newI) {
  i = newI;
  document.forms.F.I.value = newI;
}
</SCRIPT>
<BODY ONPOPSTATE="set(event.state)">
<FORM NAME=F>
State: <OUTPUT NAME=I>1</OUTPUT> <INPUT VALUE="Increment" TYPE=BUTTON ONCLICK="inc()">
</FORM>
Most applications want to use the same scroll restoration mode value for all of their history entries. To achieve this they should set the scrollRestoration attribute as soon as possible (e.g., in the first script element in the document’s head element) to ensure that any entry added to the history session gets the desired scroll restoration mode.
<head>
  <script>
    if ('scrollRestoration' in history)
      history.scrollRestoration = 'manual';
  </script>
</head>

6.6.3. Implementation notes for session history

This section is non-normative.

The History interface is not meant to place restrictions on how implementations represent the session history to the user.

For example, session history could be implemented in a tree-like manner, with each page having multiple "forward" pages. This specification doesn’t define how the linear list of pages in the history object are derived from the actual session history as seen from the user’s perspective.

Similarly, a page containing two iframes has a history object distinct from the iframes' history objects, despite the fact that typical Web browsers present the user with just one "Back" button, with a session history that interleaves the navigation of the two inner frames and the outer page.

Security: It is suggested that to avoid letting a page "hijack" the history navigation facilities of a UA by abusing pushState(), the UA provide the user with a way to jump back to the previous page (rather than just going back to the previous state). For example, the back button could have a drop down showing just the pages in the session history, and not showing any of the states. Similarly, an aural browser could have two "back" commands, one that goes back to the previous state, and one that jumps straight back to the previous page.

For both pushState() and replaceState(), user agents are encouraged to prevent abuse of these APIs via too-frequent calls or over-large state objects. As detailed above, the algorithm explicitly allows user agents to ignore any such calls when appropriate.

6.6.4. The Location interface

Each Window object is associated with a unique instance of a Location object, allocated when the Window object is created.

To create a Location object, run these steps:

  1. Let location be a new Location platform object.

  2. Perform ! location.[[DefineOwnProperty]]("toString", { [[Value]]: %ObjProto_toString%, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }).

  3. Perform ! location.[[DefineOwnProperty]]("toJSON", { [[Value]]: undefined, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }).

  4. Perform ! location.[[DefineOwnProperty]]("valueOf", { [[Value]]: %ObjProto_valueOf%, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }).

  5. Perform ! location.[[DefineOwnProperty]](@@toPrimitive, { [[Value]]: undefined, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }).

  6. Set the value of the [[DefaultProperties]] internal slot of location to location.[[OwnPropertyKeys]]().

  7. Return location.

document . location [ = value ]
window . location [ = value ]
Returns a Location object with the current page’s location.

Can be set, to navigate to another page.

The location attribute of the Document interface must return the Location object for that Document object’s global object, if it has a browsing context, and null otherwise.

The location attribute of the Window interface must return the Location object for that Window object.

Location objects provide a representation of the URL of the active document of their Document's browsing context, and allow the current entry of the browsing context’s session history to be changed, by adding or replacing entries in the history object.

[Unforgeable]
interface Location {
  stringifier attribute USVString href;
  readonly attribute USVString origin;
  attribute USVString protocol;
  attribute USVString host;
  attribute USVString hostname;
  attribute USVString port;
  attribute USVString pathname;
  attribute USVString search;
  attribute USVString hash;

  void assign(USVString url);
  void replace(USVString url);
  void reload();

  [SameObject] readonly attribute USVString[] ancestorOrigins;
};
location . toString()
location . href
Returns the Location object’s URL.

Can be set, to navigate to the given URL.

location . origin
Returns the Location object’s URL’s origin.
location . protocol
Returns the Location object’s URL’s scheme.

Can be set, to navigate to the same URL with a changed scheme.

location . host
Returns the Location object’s URL’s host and port (if different from the default port for the scheme).

Can be set, to navigate to the same URL with a changed host and port.

location . hostname
Returns the Location object’s URL’s host.

Can be set, to navigate to the same URL with a changed host.

location . port
Returns the Location object’s URL’s port.

Can be set, to navigate to the same URL with a changed port.

location . pathname
Returns the Location object’s URL’s path.

Can be set, to navigate to the same URL with a changed path.

location . search
Returns the Location object’s URL’s query (includes leading "?" if non-empty).

Can be set, to navigate to the same URL with a changed query (ignores leading "?").

location . hash
Returns the Location object’s URL’s fragment (includes leading "#" if non-empty).

Can be set, to navigate to the same URL with a changed fragment (ignores leading "#").

location . assign(url)
Navigates to the given URL.
location . replace(url)
Removes the current page from the session history and navigates to the given URL.
location . reload()
Reloads the current page.
location . ancestorOrigins
Returns an array whose values are the origins of the ancestor browsing contexts, from the parent browsing context to the top-level browsing context.

A Location object has an associated relevant Document, which is this Location object’s associated Document object’s browsing context’s active document.

A Location object has an associated url, which is this Location object’s relevant Document’s URL.

A Location object has an associated ancestor origins array. When a Location object is created, its ancestor origins array must be set to a array created from the list of strings that the following steps would produce:

  1. Let output be an empty ordered list of strings.

  2. Let current be the browsing context of the Document with which the Location object is associated.

  3. Loop: If current has no parent browsing context, jump to the step labeled End.

  4. Let current be current’s parent browsing context.

  5. Append the Unicode serialization of current’s active document’s origin to output as a new value.

  6. Return to the step labeled Loop.

  7. End: Return output.

A Location object has an associated Location-object-setter navigate algorithm, which given a url, runs these steps:

  1. If any of the following conditions are met, let replacement flag be unset; otherwise, let it be set:

  2. Location-object navigate, given url and replacement flag.

To Location-object navigate, given a url and replacement flag, run these steps:

  1. The source browsing context is the responsible browsing context specified by the incumbent settings object.

  2. Navigate the browsing context to url, with the exceptions enabled flag set. Rethrow any exceptions.

    If the replacement flag is set or the browsing context’s session history contains only one Document, and that was the about:blank Document created when the browsing context was created, then the navigation must be done with replacement enabled.

The href attribute’s getter must return this Location object’s URL, serialized.

The href attribute’s setter must run these steps:

  1. Let newURL be the resulting URL string of parsing the given value relative to the entry settings object’s API base URL.
  2. If that aborted with an error, throw a TypeError exception.
  3. Location-object-setter navigate to newURL.

The origin attribute’s getter must return the Unicode serialization of this Location object’s URL’s origin.

It returns the Unicode rather than the ASCII serialization for compatibility with MessageEvent.

The protocol attribute’s getter must return this Location object’s URL’s scheme, followed by ":".

The protocol attribute’s setter must run these steps:

  1. Let copyURL be a copy of this Location object’s URL.
  2. Let possibleFailure be the result of basic URL parsing the given value, followed by ":", with copyURL as url and scheme start state as state override.
  3. If possibleFailure is failure, throw a TypeError exception.
  4. If copyURL’s scheme is not "http" or "https", terminate these steps.
  5. Location-object-setter navigate to copyURL.

The host attribute’s getter must run these steps:

  1. Let url be this Location object’s URL.
  2. If url’s host is null, return the empty string.
  3. If url’s port is null, return url’s host, serialized.
  4. Return url’s host, serialized, followed by ":" and url’s port, serialized.

The host attribute’s setter must run these steps:

  1. Let copyURL be a copy of this Location object’s URL.
  2. If copyURL’s non-relative flag is set, terminate these steps.
  3. Basic URL parse the given value, with copyURL as url and host state as state override.
  4. Location-object-setter navigate to copyURL.

The hostname attribute’s getter must run these steps:

  1. If this Location object’s URL’s host is null, return the empty string.
  2. Return this Location object’s URL’s host, serialized.

The hostname attribute’s setter must run these steps:

  1. Let copyURL be a copy of this Location object’s URL.
  2. If copyURL’s non-relative flag is set, terminate these steps.
  3. Basic URL parse the given value, with copyURL as url and hostname state as state override.
  4. Location-object-setter navigate to copyURL.

The port attribute’s getter must run these steps:

  1. If this Location object’s URL’s port is null, return the empty string.
  2. Return this Location object’s URL’s port, serialized.

The port attribute’s setter must run these steps:

  1. Let copyURL be a copy of this Location object’s URL.
  2. If copyURL’s host is null, copyURL’s non-relative flag is set, or copyURL’s scheme is "file", terminate these steps.
  3. Basic URL parse the given value, with copyURL as url and port state as state override.
  4. Location-object-setter navigate to copyURL.

The pathname attribute’s getter must run these steps:

  1. Let url be this Location object’s URL.
  2. If url’s non-relative flag is set, return the first string in url’s path.
  3. Return "/", followed by the strings in url’s path (including empty strings), separated from each other by "/".

The pathname attribute’s setter must run these steps:

  1. Let copyURL be a copy of this Location object’s URL.
  2. If copyURL’s non-relative flag is set, terminate these steps.
  3. Set copyURL’s path to the empty list.
  4. Basic URL parse the given value, with copyURL as url and path start state as state override.
  5. Location-object-setter navigate to copyURL.

The search attribute’s getter must run these steps:

  1. If this Location object’s URL’s query is either null or the empty string, return the empty string.
  2. Return "?", followed by this Location object’s URL’s query.

The search attribute’s setter must run these steps:

  1. Let copyURL be a copy of this Location object’s URL.
  2. If the given value is the empty string, set copyURL’s query to null.
  3. Otherwise, run these substeps:
    1. Let input be the given value with a single leading "?" removed, if any.
    2. Set copyURL’s query to the empty string.
    3. Basic URL parse input, with copyURL as url and query state as state override, and the relevant Document’s document’s character encoding as encoding override.
  4. Location-object-setter navigate to copyURL.

The hash attribute’s getter must run these steps:

  1. If this Location object’s URL’s fragment is either null or the empty string, return the empty string.
  2. Return "#", followed by this Location object’s URL’s fragment.

The hash attribute’s setter must run these steps:

  1. Let copyURL be a copy of this Location object’s URL.
  2. If copyURL’s scheme is "javascript", terminate these steps.
  3. If the given value is the empty string, set copyURL’s fragment to null.
  4. Otherwise, run these substeps:
    1. Let input be the given value with a single leading "#" removed, if any.
    2. Set copyURL’s fragment to the empty string.
    3. Basic URL parse input, with copyURL as url and fragment state as state override.
  5. Location-object-setter navigate to copyURL.

When the assign(url) method is invoked, the user agent must run the following steps:

  1. Parse url, relative to the API base URL specified by the entry settings object and let parsedURL be the resulting URL string.

    If this is not successful, throw a "SyntaxError" DOMException and abort these steps.

  2. Location-object navigate to parsedURL.

When the replace(url) method is invoked, the user agent must run the following steps:

  1. Parse url, relative to the API base URL specified by the entry settings object and let parsedURL be the resulting URL string.

    If this is not successful, throw a "SyntaxError" DOMException and abort these steps.

  2. Location-object navigate to parsedURL with the replacement flag set.

When the reload() method is invoked, the user agent must run the appropriate steps from the following list:

If the currently executing task is the dispatch of a resize event in response to the user resizing the browsing context
Repaint the browsing context and abort these steps.
If the browsing context’s active document is an iframe srcdoc document
Reprocess the iframe attributes of the browsing context’s browsing context container.
If the browsing context’s active document has its reload override flag set
Perform an overridden reload, with the browsing context being navigated as the responsible browsing context.
Otherwise
Navigate the browsing context to the document’s URL with the exceptions enabled flag set and replacement enabled. The source browsing context must be the browsing context being navigated. This is a reload-triggered navigation. Rethrow any exceptions.

When a user requests that the active document of a browsing context be reloaded through a user interface element, the user agent should navigate the browsing context to the same resource as that Document, with replacement enabled. In the case of non-idempotent methods (e.g., HTTP POST), the user agent should prompt the user to confirm the operation first, since otherwise transactions (e.g., purchases or database modifications) could be repeated. User agents may allow the user to explicitly override any caches when reloading. If browsing context’s active document’s reload override flag is set, then the user agent may instead perform an overridden reload rather than the navigation described in this paragraph (with the browsing context being reloaded as the source browsing context).

The ancestorOrigins attribute’s getter must run these steps:

  1. If this Location object’s relevant Document’s origin is not same origin-domain with the entry settings object’s origin, then throw a "SecurityError" DOMException.

  2. Otherwise, return this Location object’s ancestor origins array.

The Location object requires additional logic beyond IDL for security purposes. The internal slot and internal methods Location objects must implement are defined below.

Every Location object has a [[DefaultProperties]] internal slot representing its own properties at time of its creation.

6.7. Browsing the Web

Certain actions cause the browsing context to navigate to a new resource. A user agent may provide various ways for the user to explicitly cause a browsing context to navigate, in addition to those defined in this specification.

For example, following a hyperlink, §4.10.22 Form submission, and the window.open() and location.assign() methods can all cause a browsing context to navigate.

A resource has a URL, but that might not be the only information necessary to identify it. For example, a form submission that uses HTTP POST would also have the HTTP method and payload. Similarly, an iframe srcdoc document needs to know the data it is to use.

Navigation always involves source browsing context, which is the browsing context which was responsible for starting the navigation.

When a browsing context is navigated to a new resource, the user agent must run the following steps:

  1. If the source browsing context is not allowed to navigate the browsing context being navigated, then abort these steps.

    If these steps are aborted here, the user agent may instead offer to open the new resource in a new top-level browsing context or in the top-level browsing context of the source browsing context, at the user’s option, in which case the user agent must navigate that designated top-level browsing context to the new resource as if the user had requested it independently.

    Doing so, however, can be dangerous, as it means that the user is overriding the author’s explicit request to sandbox the content.

    If the navigate algorithm was invoked optionally with an exceptions enabled flag, and it is aborted on this step, then in addition to aborting this algorithm, the user agent must also throw a "SecurityError" DOMException.

  2. If there is a preexisting attempt to navigate the browsing context, and the source browsing context is the same as the browsing context being navigated, and that attempt is currently running the unload a document algorithm, and the origin of the URL of the resource being loaded in that navigation is not the same origin as the origin of the URL of the resource being loaded in this navigation, then abort these steps without affecting the preexisting attempt to navigate the browsing context.
  3. If a task queued by the traverse the history by a delta algorithm is running the unload a document algorithm for the active document of the browsing context being navigated, then abort these steps without affecting the unload a document algorithm or the aforementioned history traversal task.
  4. If the prompt to unload a document algorithm is being run for the active document of the browsing context being navigated, then abort these steps without affecting the prompt to unload a document algorithm.
  5. Let gone async be false.

    The handle redirects step later in this algorithm can in certain cases jump back to the step labeled fragment identifiers. Since, between those two steps, this algorithm goes from operating immediately in the context of the calling task to operating in parallel independent of the event loop, some of the intervening steps need to be able to handle both being run as part of a task and running in parallel. The gone async flag is thus used to make these steps aware of which mode they are operating in.

  6. Fragment identifiers: If this is not a reload-triggered navigation: apply the URL parser algorithm to the absolute URL of the new resource and the address of the active document of the browsing context being navigated; if all the components of the resulting parsed URLs, ignoring any fragment components, are identical, and the new resource is to be fetched using GET, and the URL record of the new resource has a fragment component that is not null (even if it is empty), then navigate to that fragment identifier and abort these steps.
  7. If gone async is false, cancel any preexisting but not yet mature attempt to navigate the browsing context, including canceling any instances of the fetch algorithm started by those attempts. If one of those attempts has already created and initialized a new Document object, abort that Document also. (Navigation attempts that have matured already have session history entries, and are therefore handled during the update the session history with the new page algorithm, later.)
  8. If the new resource is to be handled using a mechanism that does not affect the browsing context, e.g., ignoring the navigation request altogether because the specified scheme is not one of the supported protocols, then abort these steps and proceed with that mechanism instead.
  9. If gone async is false, prompt to unload the Document object. If the user refused to allow the document to be unloaded, then abort these steps.

    If this instance of the navigation algorithm gets canceled while this step is running, the prompt to unload a document algorithm must nonetheless be run to completion.

  10. If gone async is false, abort the active document of the browsing context.
  11. If the new resource is to be handled by displaying some sort of inline content, e.g., an error message because the specified scheme is not one of the supported protocols, or an inline prompt to allow the user to select a registered handler for the given scheme, then display the inline content and abort these steps.

    In the case of a registered handler being used, the algorithm will be reinvoked with a new URL to handle the request.

  12. If the browsing context being navigated is a nested browsing context, then put it in the delaying load events mode.

    The user agent must take this nested browsing context out of the delaying load events mode when this navigation algorithm later matures, or when it terminates (whether due to having run all the steps, or being canceled, or being aborted), whichever happens first.

  13. This is the step that attempts to obtain the resource, if necessary. Jump to the first appropriate substep:

    If the resource has already been obtained (e.g., because it is being used to populate an object element’s new child browsing context)
    Skip this step. The data is already available.
    If the new resource is a URL whose scheme is javascript

    Queue a task to run these "javascript: URL" steps, associated with the active document of the browsing context being navigated:

    1. If the origin of the source browsing context is not the same origin as the origin of the active document of the browsing context being navigated, then let result be undefined, and jump to the step labeled process results below.

    2. Let urlRecord be the result of running the URL parser on the URL of the new resource.

    3. Let script source be the empty string.

    4. Append the first string of urlRecord’s path component to script source.

    5. If urlRecord’s query component is not null, then first append a U+003F QUESTION MARK character (?) to script source, and then append urlRecord’s query component to script source.

    6. If urlRecord’s fragment component is not null, then first append a U+0023 NUMBER SIGN character (#) to script source, and then append urlRecord’s fragment component to script source.

    7. Replace script source with the result of applying the percent decode algorithm to script source.

    8. Replace script source with the result of applying the UTF-8 decode algorithm to script source.

    9. Let address be the address of the active document of the browsing context being navigated.

    10. Let settings be the relevant settings object of the browsing context being navigated.

    11. Let script be the result of creating a classic script given script source and settings.

    12. Let result be the result of running the classic script script. If evaluation was unsuccessful, let result be undefined instead. (The result will also be undefined if scripting is disabled.)

    13. Process results: If Type(result) is not String, then the result of obtaining the resource for the URL is a response whose status is 204.

      Otherwise, the result of obtaining the resource for the URL is a response whose header list consists of Content-Type/text/html and whose body is result, and whose HTTPS state is settings’s HTTPS state.

      When it comes time to set the document’s address in the navigation algorithm, use address as the override URL.

    The task source for this task is the DOM manipulation task source.

    So for example a javascript: URL in an href attribute of an a element would only be evaluated when the link was followed, while such a URL in the src attribute of an iframe element would be evaluated in the context of the iframe’s own nested browsing context when the iframe is being set up; once evaluated, its return value (if it was not void) would replace that browsing context’s Document, thus also changing the Window object of that browsing context.
    Otherwise
    1. Let request be the new resource.
    2. If request is a URL, set request to a new request whose URL is request.
    3. Set request’s client to the source browsing context’s active document’s Window object’s environment settings object, target browsing context to the browsing context being navigated, destination to "document", mode to "navigate", credentials mode to "include", use-URL-credentials flag, and redirect mode to "manual".
    4. Set request’s omit-Origin-header flag.
    5. If request’s method is not GET, or, if the navigation algorithm was invoked as a result of the form submission algorithm, then if there is an origin of the active document of the source browsing context, unset request’s omit-Origin-header flag.
    6. Otherwise, if the browsing context being navigated is a child browsing context, and the browsing context container of the browsing context being navigated has a browsing context scope origin, set request’s origin to that browsing context scope origin and unset request’s omit-Origin-header flag.
    7. Fetch request.
  14. If gone async is false, return to whatever algorithm invoked the navigation steps and continue running these steps in parallel.

  15. Let gone async be true.
  16. Wait for one or more bytes to be available or for the user agent to establish that the resource in question is empty. During this time, the user agent may allow the user to cancel this navigation attempt or start other navigation attempts.
  17. Handle redirects: If fetching the resource results in a redirect, and either the URL of the target of the redirect has the same origin as the original resource, or the resource is being obtained using the POST method or a safe method (in HTTP terms), return to the step labeled fragment identifiers with the new resource, except that if the URL of the target of the redirect does not have a fragment identifier and the URL of the resource that led to the redirect does, then the fragment identifier of the resource that led to the redirect must be propagated to the URL of the target of the redirect.

    So for instance, if the original URL was "https://example.com/#!sample" and "https://example.com/" is found to redirect to "https://example.com/", the URL of the new resource will be "https://example.com/#!sample".

    Otherwise, if fetching the resource results in a redirect but the URL of the target of the redirect does not have the same origin as the original resource and the resource is being obtained using a method that is neither the POST method nor a safe method (in HTTP terms), then abort these steps. The user agent may indicate to the user that the navigation has been aborted for security reasons.

  18. Resource handling: If the resource’s out-of-band metadata (e.g., HTTP headers), not counting any type information (such as the Content-Type HTTP header), requires some sort of processing that will not affect the browsing context, then perform that processing and abort these steps.

    Such processing might be triggered by, amongst other things, the following:
    • HTTP status codes (e.g., 204 No Content or 205 Reset Content)
    • Network errors (e.g., the network interface being unavailable)
    • Cryptographic protocol failures (e.g., an incorrect TLS certificate)

    Responses with HTTP Content-Disposition headers specifying the attachment disposition type must be handled as a download.

    HTTP 401 responses that do not include a challenge recognized by the user agent must be processed as if they had no challenge, e.g., rendering the entity body as if the response had been 200 OK.

    User agents may show the entity body of an HTTP 401 response even when the response does include a recognized challenge, with the option to login being included in a non-modal fashion, to enable the information provided by the server to be used by the user before authenticating. Similarly, user agents should allow the user to authenticate (in a non-modal fashion) against authentication challenges included in other responses such as HTTP 200 OK responses, effectively allowing resources to present HTTP login forms without requiring their use.

  19. Let type be the computed type of the resource.
  20. If the user agent has been configured to process resources of the given type using some mechanism other than rendering the content in a browsing context, then skip this step. Otherwise, if the type is one of the following types, jump to the appropriate entry in the following list, and process the resource as described there:
    an HTML MIME type
    Follow the steps given in the HTML document section, and then, once they have completed, abort this navigate algorithm.
    an XML MIME type that is not an explicitly supported XML type
    Follow the steps given in the XML document section. If that section determines that the content is not to be displayed as a generic XML document, then proceed to the next step in this overall set of steps. Otherwise, once the steps given in the XML document section have completed, abort this navigate algorithm.
    a JavaScript MIME type
    a JSON MIME type that is not an explicitly supported JSON type
    "text/css"
    "text/plain"
    "text/vtt"
    Follow the steps given in the plain text file section, and then, once they have completed, abort this navigate algorithm.
    "multipart/x-mixed-replace"
    Follow the steps given in the §12.2 multipart/x-mixed-replace section, and then, once they have completed, abort this navigate algorithm.
    A supported image, video, or audio type
    Follow the steps given in the media section, and then, once they have completed, abort this navigate algorithm.
    A type that will use an external application to render the content in the browsing context
    Follow the steps given in the plugin section, and then, once they have completed, abort this navigate algorithm.

    An explicitly supported XML type is one for which the user agent is configured to use an external application to render the content (either a plugin rendering directly in the browsing context, or a separate application), or one for which the user agent has dedicated processing rules (e.g., a Web browser with a built-in Atom feed viewer would be said to explicitly support the application/atom+xml MIME type).

    The term JSON MIME type is used to refer to the MIME types application/json, text/json, and any MIME type whose subtype ends with the five characters "+json".

    An explicitly supported JSON type is one for which the user agent is configured to use an external application to render the content (either a plugin rendering directly in the browsing context, or a separate application), or one for which the user agent has dedicated processing rules.

    Setting the document’s address: If there is no override URL, then any Document created by these steps must have its address set to the URL that was originally to be fetched, ignoring any other data that was used to obtain the resource. However, if there is an override URL, then any Document created by these steps must have its address set to that URL instead.

    An override URL is set when dereferencing a javascript: URL and when performing an overridden reload.

    Initializing a new Document object: when a Document is created as part of the above steps, the user agent will be required to additionally run the following algorithm after creating the new object:

    1. If browsingContext’s only entry in its session history is the about:blank Document that was added when browsingContext was created, and navigation is occurring with replacement enabled, and that Document has the same origin as the new Document, then

      1. Let window be the Window object of that Document.

      2. Change the document attribute of window to point to the new Document.

    2. Otherwise,

      1. Call the JavaScript InitializeHostDefinedRealm() abstract operation with the following customizations:

        • For the global object, create a new Window object window.

        • For the global this value, use browsingContext’s WindowProxy object.

        • Let realm execution context be the created JavaScript execution context.

        • Do not obtain any source texts for scripts.

      2. Set up a browsing context environment settings object with realm execution context, and let settings object be the result.

      3. Set window’s associated Document to the new Document.

    3. Set browsingContext’s WindowProxy object’s [[Window]] internal slot value to window.

    4. Set the Document's HTTPS state to the HTTPS state of the resource used to generate the document.

    5. Execute the Initialize a Document’s CSP list algorithm on the Document object and the resource used to generate the document. [CSP3]

    6. Set the document’s referrer to the address of the resource from which Request-URIs are obtained as determined when the fetch algorithm obtained the resource, if that algorithm was used and determined such a value; otherwise, set it to the empty string.

    7. Implement the sandboxing for the Document.

    8. If the active sandboxing flag set of the Document's browsing context or any of its ancestor browsing contexts (if any) have the sandboxed fullscreen browsing context flag set, then skip this step.

      If the Document's browsing context has a browsing context container and either it is not an iframe element, or it does not have the allowfullscreen attribute specified, or its Document does not have the fullscreen enabled flag set, then also skip this step.

      Otherwise, set the Document's fullscreen enabled flag.

    9. Non-document content: If, given type, the new resource is to be handled by displaying some sort of inline content, e.g., a native rendering of the content, an error message because the specified type is not supported, or an inline prompt to allow the user to select a registered handler for the given type, then display the inline content, and then abort these steps.

      In the case of a registered handler being used, the algorithm will be reinvoked with a new URL to handle the request.

    10. Otherwise, the document’s type is such that the resource will not affect the browsing context, e.g., because the resource is to be handed to an external application or because it is an unknown type that will be processed as a download. Process the resource appropriately.

When a resource is handled by passing its URL or data to an external software package separate from the user agent (e.g., handing a mailto: URL to a mail client, or a Word document to a word processor), user agents should attempt to mitigate the risk that this is an attempt to exploit the target software, e.g., by prompting the user to confirm that the source browsing context’s active document’s origin is to be allowed to invoke the specified software. In particular, if the navigate algorithm, when it was invoked, was not allowed to show a popup, the user agent should not invoke the external software package without prior user confirmation.

For example, there could be a vulnerability in the target software’s URL handler which a hostile page would attempt to exploit by tricking a user into clicking a link.


Some of the sections below, to which the above algorithm defers in certain cases, require the user agent to update the session history with the new page. When a user agent is required to do this, it must queue a task (associated with the Document object of the current entry, not the new one) to run the following steps:

  1. Unload the Document object of the current entry, with the recycle parameter set to false.

    If this instance of the navigation algorithm is canceled while this step is running the unload a document algorithm, then the unload a document algorithm must be allowed to run to completion, but this instance of the navigation algorithm must not run beyond this step. (In particular, for instance, the cancelation of this algorithm does not abort any event dispatch or script execution occurring as part of unloading the document or its descendants.)

  2. If the navigation was initiated for entry update of an entry
    1. Replace the Document of the entry being updated, and any other entries that referenced the same document as that entry, with the new Document.
    2. Traverse the history to the new entry.

    This can only happen if the entry being updated is not the current entry, and can never happen with replacement enabled. (It happens when the user tried to traverse to a session history entry that no longer had a Document object.)

    Otherwise
    1. Remove all the entries in the browsing context’s session history after the current entry. If the current entry is the last entry in the session history, then no entries are removed.

      This doesn’t necessarily have to affect the user agent’s user interface.

    2. Append a new entry at the end of the History object representing the new resource and its Document object, related state, and the default scroll restoration mode of "auto".
    3. Traverse the history to the new entry. If the navigation was initiated with replacement enabled, then the traversal must itself be initiated with replacement enabled.
  3. The navigation algorithm has now matured.
  4. Fragment identifier loop: Spin the event loop for a user-agent-defined amount of time, as desired by the user agent implementor. (This is intended to allow the user agent to optimize the user experience in the face of performance concerns.)
  5. If the Document object has no parser, or its parser has stopped parsing, or the user agent has reason to believe the user is no longer interested in scrolling to the fragment identifier, then abort these steps.
  6. Scroll to the fragment identifier given in the document’s address. If this fails to find an indicated part of the document, then return to the fragment identifier loop step.

The task source for this task is the networking task source.

6.7.2. Page load processing model for HTML files

When an HTML document is to be loaded in a browsing context, the user agent must queue a task to create a Document object, mark it as being an HTML document, set its content type to "text/html", initialize the Document object, and finally create an HTML parser and associate it with the Document. Each task that the networking task source places on the task queue while fetching runs must then fill the parser’s input byte stream with the fetched bytes and cause the HTML parser to perform the appropriate processing of the input stream.

The input byte stream converts bytes into characters for use in the tokenizer. This process relies, in part, on character encoding information found in the real Content-Type metadata of the resource; the "computed type" is not used for this purpose.

When no more bytes are available, the user agent must queue a task for the parser to process the implied EOF character, which eventually causes a load event to be fired.

After creating the Document object, but before any script execution, certainly before the parser stops, the user agent must update the session history with the new page.

The task source for the two tasks mentioned in this section must be the networking task source.

6.7.3. Page load processing model for XML files

When faced with displaying an XML file inline, user agents must follow the requirements defined in the XML and Namespaces in XML recommendations, RFC 7303, DOM, and other relevant specifications to create a Document object and a corresponding XML parser. [XML] [XML-NAMES] [RFC7303] [DOM]

At the time of writing, the XML specification community had not actually yet specified how XML and the DOM interact.

After the Document is created, the user agent must initialize the Document object.

The actual HTTP headers and other metadata, not the headers as mutated or implied by the algorithms given in this specification, are the ones that must be used when determining the character encoding according to the rules given in the above specifications. Once the character encoding is established, the document’s character encoding must be set to that character encoding.

User agents may examine the namespace of the root Element node of this Document object to perform namespace-based dispatch to alternative processing tools, e.g., determining that the content is actually a syndication feed and passing it to a feed handler. If such processing is to take place, abort the steps in this section, and jump to the next step (labeled non-document content) in the navigate steps above.

Otherwise, then, with the newly created Document, the user agent must update the session history with the new page. User agents may do this before the complete document has been parsed (thus achieving incremental rendering), and must do this before any scripts are to be executed.

Error messages from the parse process (e.g., XML namespace well-formedness errors) may be reported inline by mutating the Document.

6.7.4. Page load processing model for text files

When a plain text document is to be loaded in a browsing context, the user agent must queue a task to create a Document object, mark it as being an HTML document, set its content type to the computed MIME type of the resource (type in the navigate algorithm), initialize the Document object, create an HTML parser, associate it with the Document, act as if the tokenizer had emitted a start tag token with the tag name "pre" followed by a single U+000A LINE FEED (LF) character, and switch the HTML parser’s tokenizer to the §8.2.4.7 PLAINTEXT state. Each task that the networking task source places on the task queue while fetching runs must then fill the parser’s input byte stream with the fetched bytes and cause the HTML parser to perform the appropriate processing of the input stream.

The rules for how to convert the bytes of the plain text document into actual characters, and the rules for actually rendering the text to the user, are defined by the specifications for the computed MIME type of the resource (type in the navigate algorithm).

The document’s character encoding must be set to the character encoding used to decode the document.

When no more bytes are available, the user agent must queue a task for the parser to process the implied EOF character, which eventually causes a load event to be fired.

After creating the Document object, but potentially before the page has finished parsing, the user agent must update the session history with the new page.

User agents may add content to the head element of the Document, e.g., to link to a style sheet, provide a script, give the document a title, etc.

In particular, if the user agent supports the Format=Flowed feature of RFC3676 then the user agent would need to apply extra styling to cause the text to wrap correctly and to handle the quoting feature. [RFC3676]

The task source for the two tasks mentioned in this section must be the networking task source.

6.7.5. Page load processing model for multipart/x-mixed-replace resources

When a resource with the type multipart/x-mixed-replace is to be loaded in a browsing context, the user agent must parse the resource using the rules for multipart types. [RFC2046]

For each body part obtained from the resource, the user agent must run a new instance of the navigate algorithm, starting from the resource handling step, using the new body part as the resource being navigated, with replacement enabled if a previous body part from the same resource resulted in a Document object being created and initialized, and otherwise using the same setup as the navigate attempt that caused this section to be invoked in the first place.

For the purposes of algorithms processing these body parts as if they were complete stand-alone resources, the user agent must act as if there were no more bytes for those resources whenever the boundary following the body part is reached.

Thus, load events (and for that matter unload events) do fire for each body part loaded.

6.7.6. Page load processing model for media

When an image, video, or audio resource is to be loaded in a browsing context, the user agent should create a Document object, mark it as being an HTML document, set its content type to the computed MIME type of the resource (type in the navigate algorithm), initialize the Document object, append an html element to the Document, append a head element and a body element to the html element, append an element host element for the media, as described below, to the body element, and set the appropriate attribute of the element host element, as described below, to the address of the image, video, or audio resource.

The element host element to create for the media is the element given in the table below in the second cell of the row whose first cell describes the media. The appropriate attribute to set is the one given by the third cell in that same row.

Type of media Element for the media Appropriate attribute
Image img src
Video video src
Audio audio src

Then, the user agent must act as if it had stopped parsing.

After creating the Document object, but potentially before the page has finished fully loading, the user agent must update the session history with the new page.

User agents may add content to the head element of the Document, or attributes to the element host element, e.g., to link to a style sheet, provide a script, give the document a title, make the media autoplay, etc.

6.7.7. Page load processing model for content that uses plugins

When a resource that requires an external resource to be rendered is to be loaded in a browsing context, the user agent should create a Document object, mark it as being an HTML document and mark it as being a plugin document, set its content type to the computed MIME type of the resource (type in the navigate algorithm), initialize the Document object, append an html element to the Document, append a head element and a body element to the html element, append an embed to the body element, and set the src attribute of the embed element to the address of the resource.

The term plugin document is used by Content Security Policy as part of the mechanism that ensures iframes can’t be used to evade plugin-types directives. [CSP3]

Then, the user agent must act as if it had stopped parsing.

After creating the Document object, but potentially before the page has finished fully loading, the user agent must update the session history with the new page.

User agents may add content to the head element of the Document, or attributes to the embed element, e.g., to link to a style sheet, to give the document a title, etc.

If the Document's active sandboxing flag set has its sandboxed plugins browsing context flag set, the synthesized embed element will fail to render the content if the relevant plugin cannot be secured.

6.7.8. Page load processing model for inline content that doesn’t have a DOM

When the user agent is to display a user agent page inline in a browsing context, the user agent should create a Document object, mark it as being an HTML document, set its content type to "text/html", initialize the Document object, and then either associate that Document with a custom rendering that is not rendered using the normal Document rendering rules, or mutate that Document until it represents the content the user agent wants to render.

Once the page has been set up, the user agent must act as if it had stopped parsing.

After creating the Document object, but potentially before the page has been completely set up, the user agent must update the session history with the new page.

When a user agent is supposed to navigate to a fragment identifier, then the user agent must run the following steps:

  1. Remove all the entries in the browsing context’s session history after the current entry. If the current entry is the last entry in the session history, then no entries are removed.

    This doesn’t necessarily have to affect the user agent’s user interface.

  2. Remove any tasks queued by the history traversal task source that are associated with any Document objects in the top-level browsing context’s document family.
  3. Append a new entry at the end of the History object representing the new resource and its Document object, related state, and current history scroll restoration preference. Its URL must be set to the address to which the user agent was navigating. The title must be left unset.
  4. Traverse the history to the new entry, with the non-blocking events flag set. This will scroll to the fragment identifier given in what is now the document’s address.

If the scrolling fails because the relevant ID has not yet been parsed, then the original navigation algorithm will take care of the scrolling instead, as the last few steps of its update the session history with the new page algorithm.


When the user agent is required to scroll to the fragment identifier and the indicated part of the document, if any, is being rendered, the user agent must either change the scrolling position of the document using the following algorithm, or perform some other action such that the indicated part of the document is brought to the user’s attention. If there is no indicated part, or if the indicated part is not being rendered, then the user agent must do nothing. The aforementioned algorithm is as follows:

  1. Let target be the indicated part of the document, as defined below.
  2. If target is the top of the document, then scroll to the beginning of the document for the Document, and abort these steps. [CSSOM-VIEW]
  3. Use the scroll an element into view algorithm to scroll target into view, with the align to top flag set. [CSSOM-VIEW]
  4. Run the focusing steps for that element, with the Document's viewport as the fallback target.
  5. Move the sequential focus navigation starting point to target.

The indicated part of the document is the one that the fragment identifier, if any, identifies. The semantics of the fragment identifier in terms of mapping it to a specific DOM Node is defined by the specification that defines the MIME type used by the Document (for example, the processing of fragment identifiers for XML MIME types is the responsibility of RFC7303). [RFC7303]

For HTML documents (and HTML MIME types), the following processing model must be followed to determine what the indicated part of the document is.

  1. Apply the URL parser algorithm to the URL, and let fragid be the fragment component of the resulting URL record.
  2. If fragid is the empty string, then the indicated part of the document is the top of the document; stop the algorithm here.
  3. Let fragid bytes be the result of percent decoding fragid.
  4. Let decoded fragid be the result of running UTF-8 decode without BOM or fail on fragid bytes. If decoded fragid is failure, jump to the step labeled no decoded fragid.
  5. If there is an element in the DOM that has an ID exactly equal to decoded fragid, then the first such element in tree order is the indicated part of the document; stop the algorithm here.
  6. No decoded fragid: If there is an a element in the DOM that has a name attribute whose value is exactly equal to fragid (not decoded fragid), then the first such element in tree order is the indicated part of the document; stop the algorithm here.
  7. If fragid is an ASCII case-insensitive match for the string top, then the indicated part of the document is the top of the document; stop the algorithm here.
  8. Otherwise, there is no indicated part of the document.

For the purposes of the interaction of HTML with Selectors' :target pseudo-class, the target element is the indicated part of the document, if that is an element; otherwise there is no target element. [CSS3-SELECTORS]

The task source for the task mentioned in this section must be the DOM manipulation task source.

6.7.10. History traversal

When a user agent is required to traverse the history to a specified entry, optionally with replacement enabled, and optionally with the non-blocking events flag set, the user agent must act as follows.

This algorithm is not just invoked when explicitly going back or forwards in the session history — it is also invoked in other situations, for example when navigating a browsing context, as part of updating the session history with the new page.

  1. If there is no longer a Document object for the entry in question, navigate the browsing context to the resource for that entry to perform an entry update of that entry, and abort these steps. The "navigate" algorithm reinvokes this "traverse" algorithm to complete the traversal, at which point there is a Document object and so this step gets skipped. The navigation must be done using the same source browsing context as was used the first time this entry was created. (This can never happen with replacement enabled.)

    If the resource was obtained using a non-idempotent action, for example a POST form submission, or if the resource is no longer available, for example because the computer is now offline and the page wasn’t cached, navigating to it again might not be possible. In this case, the navigation will result in a different page than previously; for example, it might be an error message explaining the problem or offering to resubmit the form.

  2. If the current entry’s title was not set by the pushState() or replaceState() methods, then set its title to the value returned by the document.title IDL attribute.
  3. If appropriate, update the current entry in the browsing context’s Document object’s History object to reflect any state that the user agent wishes to persist. The entry is then said to be an entry with persisted user state.
  4. If the specified entry has a different Document object than the current entry, then run the following substeps:
    1. Remove any tasks queued by the history traversal task source that are associated with any Document objects in the top-level browsing context’s document family.
    2. If the origin of the Document of the specified entry is not the same as the origin of the Document of the current entry, then run the following sub-sub-steps:

      1. The current browsing context name must be stored with all the entries in the history that are associated with Document objects with the same origin as the active document and that are contiguous with the current entry.
      2. If the browsing context is a top-level browsing context, but not an auxiliary browsing context, then the browsing context’s browsing context name must be unset.
    3. Make the specified entry’s Document object the active document of the browsing context.
    4. If the specified entry has a browsing context name stored with it, then run the following sub-sub-steps:

      1. Set the browsing context’s browsing context name to the name stored with the specified entry.
      2. Clear any browsing context names stored with all entries in the history that are associated with Document objects with the same origin as the new active document and that are contiguous with the specified entry.
    5. If the specified entry’s Document has any form controls whose autofill field name is "off", invoke the reset algorithm of each of those elements.
    6. If the current document readiness of the specified entry’s Document is "complete", queue a task to run the following sub-sub-steps:

      1. If the Document's page showing flag is true, then abort this task (i.e., don’t fire the event below).
      2. Set the Document's page showing flag to true.
      3. Run any session history document visibility change steps for Document that are defined by other applicable specifications.

        This is specifically intended for use by the Page Visibility specification. [PAGE-VISIBILITY]

      4. Fire a trusted event with the name pageshow at the Window object of that Document, with target override set to the Document object, using the PageTransitionEvent interface, with the persisted attribute initialized to true. This event must not bubble, must not be cancelable, and has no default action.
  5. Set the document’s address to the URL of the specified entry.
  6. If the specified entry has a URL whose fragment identifier differs from that of the current entry’s when compared in a case-sensitive manner, and the two share the same Document object, then let hash changed be true, and let old URL be the URL of the current entry and new URL be the URL of the specified entry. Otherwise, let hash changed be false.
  7. If the traversal was initiated with replacement enabled, remove the entry immediately before the specified entry in the session history.
  8. If the specified entry is not an entry with persisted user state, but its URL has a fragment identifier, scroll to the fragment identifier.
  9. If the entry is an entry with persisted user state, the user agent may restore persisted user state and update aspects of the document and its rendering.
  10. Let targetRealm be the current Realm Record.
  11. If the entry is a state object entry, let state be StructuredClone(that state object, targetRealm) of that state object. Otherwise, let state be null.
  12. Set history.state to state.
  13. Let state changed be true if the Document of the specified entry has a latest entry, and that entry is not the specified entry; otherwise let it be false.
  14. Let the latest entry of the Document of the specified entry be the specified entry.
  15. If the non-blocking events flag is not set, then run the following steps immediately. Otherwise, the non-blocking events flag is set; queue a task to run the following substeps instead.

    1. If state changed is true, fire a trusted event with the name popstate at the Window object of the Document, using the PopStateEvent interface, with the state attribute initialized to the value of state. This event must bubble but not be cancelable and has no default action.
    2. If hash changed is true, then fire a trusted event with the name hashchange at the browsing context’s Window object, using the HashChangeEvent interface, with the oldURL attribute initialized to old URL and the newURL attribute initialized to new URL. This event must bubble but not be cancelable and has no default action.
  16. The current entry is now the specified entry.

The task source for the tasks mentioned above is the DOM manipulation task source.

6.7.10.1. Persisted user state restoration

When the user agent is to restore persisted user state from a history entry, it must run the following steps immediately:

  1. If the entry has a scroll restoration mode, let scrollRestoration be that. Otherwise let scrollRestoration be "auto"
  2. If scrollRestoration is "manual" the user agent should not restore the scroll position for the document, otherwise, it may do so.
  3. Optionally, update other aspects of the document and its rendering, for instance values of form fields, that the user agent had previously recorded.

This can even include updating the dir attribute of textarea elements or input elements whose type attribute is in either the Text state or the Search state, if the persisted state includes the directionality of user input in such controls.

6.7.10.2. The PopStateEvent interface
[Constructor(DOMString type, optional PopStateEventInit eventInitDict), Exposed=(Window,Worker)]
interface PopStateEvent : Event {
  readonly attribute any state;
};
dictionary PopStateEventInit : EventInit {
  any state;
};
event . state

Returns a copy of the information that was provided to pushState() or replaceState().

The state attribute must return the value it was initialized to. When the object is created, this attribute must be initialized to null. It represents the context information for the event, or null, if the state represented is the initial state of the Document.

6.7.10.3. The HashChangeEvent interface
[Constructor(DOMString type, optional HashChangeEventInit eventInitDict), Exposed=(Window,Worker)]
interface HashChangeEvent : Event {
  readonly attribute DOMString oldURL;
  readonly attribute DOMString newURL;
};
dictionary HashChangeEventInit : EventInit {
  DOMString oldURL;
  DOMString newURL;
};
event . oldURL

Returns the URL of the session history entry that was previously current.

event . newURL

Returns the URL of the session history entry that is now current.

The oldURL attribute must return the value it was initialized to. When the object is created, this attribute must be initialized to null. It represents context information for the event, specifically the URL of the session history entry that was traversed from.

The newURL attribute must return the value it was initialized to. When the object is created, this attribute must be initialized to null. It represents context information for the event, specifically the URL of the session history entry that was traversed to.

6.7.10.4. The PageTransitionEvent interface
[Constructor(DOMString type, optional PageTransitionEventInit eventInitDict), Exposed=(Window,Worker)]
interface PageTransitionEvent : Event {
  readonly attribute boolean persisted;
};
dictionary PageTransitionEventInit : EventInit {
  boolean persisted;
};
event . persisted

For the pageshow event, returns false if the page is newly being loaded (and the load event will fire). Otherwise, returns true.

For the pagehide event, returns false if the page is going away for the last time. Otherwise, returns true, meaning that (if nothing conspires to make the page unsalvageable) the page might be reused if the user navigates back to this page.

Things that can cause the page to be unsalvageable include:

  • document.open()
  • Listening for beforeunload events
  • Listening for unload events
  • Having iframes that are not salvageable
  • Active WebSocket objects
  • Aborting a Document

The persisted attribute must return the value it was initialized to. When the object is created, this attribute must be initialized to false. It represents the context information for the event.

6.7.11. Unloading documents

A Document has a salvageable state, which must initially be true, a fired unload flag, which must initially be false, and a page showing flag, which must initially be false. The page showing flag is used to ensure that scripts receive pageshow and pagehide events in a consistent manner (e.g., that they never receive two pagehide events in a row without an intervening pageshow, or vice versa).

Event loops have a termination nesting level counter, which must initially be zero.

When a user agent is to prompt to unload a document, it must run the following steps.

  1. Increase the event loop’s termination nesting level by one.
  2. Increase the Document's ignore-opens-during-unload counter by one.
  3. Let event be a new trusted BeforeUnloadEvent event object with the name beforeunload, which does not bubble but is cancelable.
  4. Dispatch: Dispatch event at the Document's Window object.
  5. Decrease the event loop’s termination nesting level by one.
  6. If any event listeners were triggered by the earlier dispatch step, then set the Document's salvageable state to false.
  7. If the Document's active sandboxing flag set does not have its sandboxed modals flag set, and the returnValue attribute of the event object is not the empty string, or if the event was canceled, then the user agent should ask the user to confirm that they wish to unload the document.

    The prompt shown by the user agent may include the string of the returnValue attribute, or some leading subset thereof. (A user agent may want to truncate the string to 1024 characters for display, for instance.)

    The user agent must pause while waiting for the user’s response.

    If the user did not confirm the page navigation, then the user agent refused to allow the document to be unloaded.

  8. If this algorithm was invoked by another instance of the "prompt to unload a document" algorithm (i.e., through the steps below that invoke this algorithm for all descendant browsing contexts), then jump to the step labeled end.
  9. Let descendants be the list of the descendant browsing contexts of the Document.
  10. If descendants is not an empty list, then for each browsing context b in descendants run the following substeps:

    1. Prompt to unload the active document of the browsing context b. If the user refused to allow the document to be unloaded, then the user implicitly also refused to allow this document to be unloaded; jump to the step labeled end.
    2. If the salvageable state of the active document of the browsing context b is false, then set the salvageable state of this document to false also.
  11. End: Decrease the Document's ignore-opens-during-unload counter by one.

When a user agent is to unload a document, it must run the following steps. These steps are passed an argument, recycle, which is either true or false, indicating whether the Document object is going to be re-used. (This is set by the document.open() method.)

  1. Increase the event loop’s termination nesting level by one.
  2. Increase the Document's ignore-opens-during-unload counter by one.
  3. If the Document's page showing flag is false, then jump to the step labeled unload event below (i.e., skip firing the pagehide event and don’t rerun the unloading document visibility change steps).
  4. Set the Document's page showing flag to false.
  5. Fire a trusted event with the name pagehide at the Window object of the Document, with target override set to the Document object, using the PageTransitionEvent interface, with the persisted attribute initialized to true if the Document object’s salvageable state is true, and false otherwise. This event must not bubble, must not be cancelable, and has no default action.
  6. Run any unloading document visibility change steps for Document that are defined by other applicable specifications.

    This is specifically intended for use by the Page Visibility specification. [PAGE-VISIBILITY]

  7. Unload event: If the Document's fired unload flag is false, fire a simple event named unload at the Document's Window object, with target override set to the Document object.
  8. Decrease the event loop’s termination nesting level by one.
  9. If any event listeners were triggered by the earlier unload event step, then set the Document object’s salvageable state to false and set the Document's fired unload flag to true.
  10. Run any unloading document cleanup steps for Document that are defined by this specification and other applicable specifications.
  11. If this algorithm was invoked by another instance of the "unload a document" algorithm (i.e., by the steps below that invoke this algorithm for all descendant browsing contexts), then jump to the step labeled end.
  12. Let descendants be the list of the descendant browsing contexts of the Document.
  13. If descendants is not an empty list, then for each browsing context b in descendants run the following substeps:

    1. Unload the active document of the browsing context b with the recycle parameter set to false.
    2. If the salvageable state of the active document of the browsing context b is false, then set the salvageable state of this document to false also.
  14. If both the Document's salvageable state and recycle are false, then the Document's browsing context must discard the Document.
  15. End: Decrease the Document's ignore-opens-during-unload counter by one.

This specification defines the following unloading document cleanup steps. Other specifications can define more.

  1. Make disappear any WebSocket objects that were created by the WebSocket() constructor from the Document's Window object.

    If this affected any WebSocket objects, then set Document's salvageable state to false.

  2. If the Document's salvageable state is false, forcibly close any EventSource objects that whose constructor was invoked from the Document's Window object.
  3. If the Document's salvageable state is false, empty the Document's Window’s list of active timers.
6.7.11.1. The BeforeUnloadEvent interface
interface BeforeUnloadEvent : Event {
  attribute DOMString returnValue;
};
event . returnValue [ = value ]

Returns the current return value of the event (the message to show the user).

Can be set, to update the message.

There are no BeforeUnloadEvent-specific initialization methods.

The returnValue attribute represents the message to show the user. When the event is created, the attribute must be set to the empty string. On getting, it must return the last value it was set to. On setting, the attribute must be set to the new value.

6.7.12. Aborting a document load

If a Document is aborted, the user agent must run the following steps:

  1. Abort the active documents of every child browsing context. If this results in any of those Document objects having their salvageable state set to false, then set this Document's salvageable state to false also.
  2. Cancel any instances of the fetch algorithm in the context of this Document, discarding any tasks queued for them, and discarding any further data received from the network for them. If this resulted in any instances of the fetch algorithm being canceled or any queued tasks or any network data getting discarded, then set the Document's salvageable state to false.
  3. If the Document has an active parser, then abort that parser and set the Document's salvageable state to false.

User agents may allow users to explicitly invoke the abort a document algorithm for a Document. If the user does so, then, if that Document is an active document, the user agent should queue a task to fire a simple event named abort at that Document's Window object before invoking the abort algorithm.

6.7.13. Browser state

[NoInterfaceObject, Exposed=(Window, Worker)]
interface NavigatorOnLine {
  readonly attribute boolean onLine;
};
window . navigator . onLine

Returns false if the user agent is definitely offline (disconnected from the network). Returns true if the user agent might be online.

The events online and offline are fired when the value of this attribute changes.

The navigator.onLine attribute must return false if the user agent will not contact the network when the user follows links or when a script requests a remote page (or knows that such an attempt would fail), and must return true otherwise.

When the value that would be returned by the navigator.onLine attribute of a Window or WorkerGlobalScope changes from true to false, the user agent must queue a task to fire a simple event named offline at the Window or WorkerGlobalScope object.

On the other hand, when the value that would be returned by the navigator.onLine attribute of a Window or WorkerGlobalScope changes from false to true, the user agent must queue a task to fire a simple event named online at the Window or WorkerGlobalScope object.

The task source for these tasks is the networking task source.

This attribute is inherently unreliable. A computer can be connected to a network without having Internet access.

In this example, an indicator is updated as the browser goes online and offline.
<!DOCTYPE HTML>
<html>
  <head>
    <title>Online status</title>
    <script>
      function updateIndicator() {
        document.getElementById('indicator').textContent = navigator.onLine ? 'online' : 'offline';
      }
    </script>
  </head>
  <body onload="updateIndicator()" ononline="updateIndicator()" onoffline="updateIndicator()">
    <p>The network is: <span>(state unknown)</span>
  </body>
</html>

7. Web application APIs

7.1. Scripting

7.1.1. Introduction

Various mechanisms can cause author-provided executable code to run in the context of a document. These mechanisms include, but are probably not limited to:

7.1.2. Enabling and disabling scripting

Scripting is enabled in a browsing context when all of the following conditions are true:

Scripting is disabled in a browsing context when any of the above conditions are false (i.e., when scripting is not enabled).


Scripting is enabled for a node if the node’s node document has a browsing context, and scripting is enabled in that browsing context.

Scripting is disabled for a node if there is no such browsing context, or if scripting is disabled in that browsing context.

7.1.3. Processing model

7.1.3.1. Definitions

A script is one of two possible structures. All scripts have:

A settings object

An environment settings object, containing various settings that are shared with other scripts in the same context.

A classic script additionally has:

A Source text

A string containing a block of executable code to be evaluated as a JavaScript Script.

Optionally, a muted errors flag

A flag which, if set, means that error information will not be provided for errors in this script (used to mute errors for cross-origin scripts, since that can leak private information).


An environment settings object specifies algorithms for obtaining the following:

A realm execution context

A JavaScript execution context shared by all script elements that use this settings object, i.e. all scripts in a given JavaScript realm. When we run a classic script this execution context becomes the top of the JavaScript execution context stack, on top of which another execution context specific to the script in question is pushed. (This setup ensures ParseScript knows which Realm to use.)

A responsible browsing context

A browsing context that is assigned responsibility for actions taken by the scripts that use this environment settings object.

When a script creates and navigates a new top-level browsing context, the opener attribute of the new browsing context’s Window object will be set to the responsible browsing context’s WindowProxy object.

A responsible event loop

An event loop that is used when it would not be immediately clear what event loop to use.

A responsible document

A Document that is assigned responsibility for actions taken by the scripts that use this environment settings object.

For example, the address of the responsible document is used to set the address of the Document after it has been reset using open().

If the responsible event loop is not a browsing context event loop, then the environment settings object has no responsible document.

An API URL character encoding

A character encoding used to encode URLs by APIs called by scripts that use this environment settings object.

An API base URL

An URL used by APIs called by scripts that use this environment settings object to parse URLs.

An origin

An instrument used in security checks.

A creation URL

An absolute URL representing the location of the resource with which the environment settings object is associated. Note that this URL might be distinct from the responsible document’s address, due to mechanisms such as history.pushState().

An HTTPS state

An HTTPS state value representing the security properties of the network channel used to deliver the resource with which the environment settings object is associated.

An environment settings object also has an outstanding rejected promises weak set and an about-to-be-notified rejected promises list, used to track unhandled promise rejections. The outstanding rejected promises weak set must not create strong references to any of its members, and implementations are free to limit its size, e.g., by removing old entries from it when new ones are added.

7.1.3.2. Fetching scripts

The various script-fetching algorithms below have two hooks that may be customized by their callers:

Service Workers is an example of a specification that runs these algorithms with its own options for the hooks. [SERVICE-WORKERS]

To fetch a classic script for a script element element, given a url, a CORS setting, a cryptographic nonce, a parser state, a settings object, and a character encoding, run these steps. The algorithm will asynchronously complete with either null (on failure) or a new classic script (on success).

  1. Let request be the result of creating a potential-CORS request given url and CORS setting.

  2. Set request’s client to settings object, its type to "script", its destination to "script", its cryptographic nonce metadata to cryptographic nonce, and its parser metadata to parser state.

  3. If the caller specified custom steps to set up the request, perform them on request.

  4. Fetch request.

  5. Return from this algorithm, and run the remaining steps as part of the fetch’s process response for the response response.

    response can be either CORS-same-origin or CORS-cross-origin. This only affects how error reporting happens.

  6. If response’s type is "error", or response’s status is not an ok status, asynchronously complete this algorithm with null, and abort these steps.

  7. If the caller specified custom steps to process the response, perform them on response. If they return false, complete this algorithm with null, and abort these steps.

  8. If response’s Content-Type metadata, if any, specifies a character encoding, and the user agent supports that encoding, then set character encoding to that encoding (ignoring the passed-in value).

  9. Let source text be the result of decoding response’s body to Unicode, using character encoding as the fallback encoding.

    The decode algorithm overrides character encoding if the file contains a BOM.

  10. Let script be the result of creating a classic script using source text and settings object.

    If response was CORS-cross-origin, then pass the muted errors flag to the create a classic script algorithm as well.

  11. Asynchronously complete this algorithm with script.

To fetch a classic worker script given a url, a referrer, a settings object, and a destination, run these steps. The algorithm will asynchronously complete with either null (on failure) or a new classic script (on success).

  1. Let request be a new request whose url is url, client is settings object, type is "script", destination is destination, referrer is referrer, mode is "same-origin", credentials mode is "same-origin", parser metadata is "not parser-inserted", and whose use-URL-credentials flag is set.

  2. If the caller specified custom steps to set up the request, perform them on request.

  3. Fetch request.

  4. Return from this algorithm, and run the remaining steps as part of the fetch’s process response for the response response.

  5. If response’s type is "error", or response’s status is not an ok status, asynchronously complete this algorithm with null, and abort these steps.

  6. If the caller specified custom steps to process the response, perform them on response. If they return false, complete this algorithm with null, and abort these steps.

  7. Let source text be the result of UTF-8 decoding response’s body.

  8. Let script be the result of creating a classic script using source text and settings object.

  9. Asynchronously complete this algorithm with script.

7.1.3.3. Creating scripts

To create a classic script, given some script source, an environment settings object, and an optional muted errors flag:

  1. Let script be a new classic script that this algorithm will subsequently initialize.

  2. Set script’s settings object to the environment settings object provided.

  3. If scripting is disabled for the given environment settings object’s responsible browsing context, set script’s source text to the empty string. Otherwise, set script’s source text to the supplied script source.

  4. If the muted errors flag was set, then set script’s muted errors flag.

  5. Return script.

7.1.3.4. Calling scripts

To run a classic script given a classic script s and an optional rethrow errors flag:

  1. Let settings be the settings object of s.

  2. Check if we can run script with settings. If this returns "do not run", then return undefined and abort these steps.

  3. Let realm be settings’s Realm.

  4. Prepare to run script with settings.

  5. Let result be ParseScript(s’s source text, realm, s).

  6. If result is a List of errors, set result to the first element of result and go to the step labeled error.

  7. Let evaluationStatus be ScriptEvaluation(result).

  8. If evaluationStatus is an abrupt completion, set result to evaluationStatus.[[value]] and go to the next step (labeled Error). If evaluationStatus is a normal completion, or if ScriptEvaluation does not complete because the user agent has aborted the running script, skip to the step labeled Cleanup.

  9. Error: At this point result must be an exception. Perform the following steps:

    1. If the rethrow errors flag is set and s’s muted errors flag is not set, rethrow result.

    2. If the rethrow errors flag is set and s’s muted errors flag is set, throw a NetworkError exception.

    3. If the rethrow errors flag is not set, report the exception given by result for the script s.

  10. Cleanup: Clean up after running script with settings.

  11. If evaluationStatus exists and is a normal completion, return evaluationStatus.[[value]]. Otherwise, script execution was unsuccessful, either because an error occurred during parsing, or an exception occurred during evaluation, or because it was aborted prematurely.

The steps to check if we can run script with an environment settings object settings are as follows. They return either "run" or "do not run".

  1. If the global object specified by settings is a Window object whose Document object is not fully active, then return "do not run" and abort these steps.

  2. If scripting is disabled for the responsible browsing context specified by settings, then return "do not run" and abort these steps.

  3. Return "run".

The steps to prepare to run script with an environment settings object settings are as follows:

  1. Increment settings’s realm execution context’s entrance counter by one.

  2. Push settings’s realm execution context onto the JavaScript execution context stack; it is now the running JavaScript execution context.

The steps to clean up after running script with an environment settings object settings are as follows:

  1. Assert: settings’s realm execution context is the running JavaScript execution context.

  2. Decrement settings’s realm execution context’s entrance counter by one.

  3. Remove settings’s realm execution context from the JavaScript execution context stack.

  4. If the JavaScript execution context stack is now empty, run the global script clean-up jobs. (These cannot run scripts.)

  5. If the JavaScript execution context stack is now empty, perform a microtask checkpoint. (If this runs scripts, these algorithms will be invoked reentrantly.)

These algorithms are not invoked by one script directly calling another, but they can be invoked reentrantly in an indirect manner, e.g., if a script dispatches an event which has event listeners registered.

The running script is the script in the [[HostDefined]] field in the Script component of the running JavaScript execution context.

Each unit of related similar-origin browsing contexts has a global script clean-up jobs list, which must initially be empty. A global script clean-up job cannot run scripts, and cannot be sensitive to the order in which other clean-up jobs are executed. The File API uses this to release blob: URLs. [FILEAPI]

When the user agent is to run the global script clean-up jobs, the user agent must perform each of the jobs in the global script clean-up jobs list and then empty the list.

7.1.3.5. Realms, settings objects, and global objects

A global object is a JavaScript object that is the [[globalObject]] field of a JavaScript realm.

In this specification, all JavaScript realms are initialized with global objects that are either Window or WorkerGlobalScope objects.

There is always a 1:1:1 mapping between JavaScript realms, global objects, and environment settings objects:

When defining algorithm steps throughout this specification, it is often important to indicate what JavaScript realm is to be used—or, equivalently, what global object or environment settings object is to be used. In general, there are at least four possibilities:

Entry

This corresponds to the script that initiated the currently running script action: i.e., the function or script that the user agent called into when it called into author code.

Incumbent

This corresponds to the most-recently-entered author function or script on the stack.

Current

This corresponds to the currently-running function object, including built-in user-agent functions which might not be implemented as JavaScript. (It is derived from the current JavaScript realm.)

Relevant

Every platform object has a relevant Realm. When writing algorithms, the most prominent platform object whose relevant Realm might be important is the this value of the currently-running function object. In some cases, there can be other important relevant Realms, such as those of any arguments.

Note how the entry, incumbent, and current concepts are usable without qualification, whereas the relevant concept must be applied to a particular platform object.

Consider the following pages, with a.html being loaded in a browser window, b.html being loaded in an iframe as shown, and c.html and d.html omitted (they can simply be empty documents):
<!-- a/a.html -->
<!DOCTYPE HTML>
<html lang="en">
<title>Entry page</title>

<iframe src="b.html"></iframe>
<button onclick="frames[0].hello()">Hello</button>

<!-- b.html -->
<!DOCTYPE HTML>
<html lang="en">
<title>Incumbent page</title>

<iframe src="c.html" id="c"></iframe>
<iframe src="d.html" id="d"></iframe>

<script>
const c = document.querySelector("#c").contentWindow;
const d = document.querySelector("#d").contentWindow;

window.hello = () => {
  c.print.call(d);
};
</script>

Each page has its own browsing context, and thus its own JavaScript realm, global object, and environment settings object.

When the print() method is called in response to pressing the button in a.html, then:

The incumbent and entry concepts should not be used by new specifications, and we are considering whether we can remove almost all existing uses

Currently, the incumbent concept is used in some security checks, and the entry concept is sometimes used to obtain, amongst other things, the API base URL to parse a URL, used in scripts running in that unit of related similar-origin browsing contexts.

In general, the current concept is what should be used by specifications going forward. There is an important exception, however. If an algorithm is creating an object that is to be persisted and returned multiple times (instead of simply returned to author code right away, and never vended again), it should use the relevant concept with regard to the object on which the method in question is being executed. This prevents cross-realm calls from causing an object to store objects created in the "wrong" realm.

The navigator.getBattery() method creates promises in the relevant Realm for the Navigator object on which it is invoked. This has the following impact: [BATTERY-STATUS]
<!-- outer.html -->
<!DOCTYPE html>
<html lang="en">
<title>Relevant Realm demo: outer page</title>
<script>
  function doTest() {
    const promise = navigator.getBattery.call(frames[0].navigator);

    console.log(promise instanceof Promise);           // logs false
    console.log(promise instanceof frames[0].Promise); // logs true

    frames[0].hello();
  }
</script>
<iframe src="inner.html" onload="doTest()"></iframe>

<!-- inner.html -->
<!DOCTYPE html>
<html lang="en">
<title>Relevant Realm demo: inner page</title>
<script>
  function hello() {
    const promise = navigator.getBattery();

    console.log(promise instanceof Promise);        // logs true
    console.log(promise instanceof parent.Promise); // logs false
  }
</script>

If the algorithm for the getBattery() method had instead used the current Realm, all the results would be reversed. That is, after the first call to getBattery() in outer.html, the Navigator object in inner.html would be permanently storing a Promise object created in outer.html’s JavaScript realm, and calls like that inside the hello() function would thus return a promise from the "wrong" realm. Since this is undesirable, the algorithm instead uses the relevant Realm, giving the sensible results indicated in the comments above.

The rest of this section deals with formally defining the entry, incumbent, current, and relevant concepts.

7.1.3.5.1. Entry

All realm execution contexts must contain, as part of their code evaluation state, an entrance counter value, which is initially zero. In the process of calling scripts, this value will be incremented and decremented.

With this in hand, we define the entry execution context to be the most recently pushed entry in the JavaScript execution context stack whose entrance counter value is greater than zero. The entry Realm is the entry execution context’s Realm component.

Then, the entry settings object is the environment settings object of the entry Realm.

Similarly, the entry global object is the global object of the entry Realm.

7.1.3.5.2. Incumbent

The incumbent settings object is determined as follows:

  1. Let script be the result of JavaScript’s GetActiveScriptOrModule() abstract operation.

  2. If script is null, abort these steps; there is no incumbent settings object.

  3. Return the settings object of the script in script’s [[HostDefined]] field.

Then, the incumbent Realm is the Realm of the incumbent settings object.

Similarly, the incumbent global object is the global object of the incumbent settings object.

7.1.3.5.3. Current

The JavaScript specification defines the current Realm Record, sometimes abbreviated to the "current Realm". [ECMA-262]

Then, the current settings object is the environment settings object of the current Realm Record.

Similarly, the current global object is the global object of the current Realm Record.

7.1.3.5.4. Relevant

The relevant settings object for a platform object is defined as follows:

If the object is a global object
Each global object in this specification is created alongside a corresponding environment settings object; that is its relevant settings object.
Otherwise
The relevant settings object for a non-global platform object o is the environment settings object whose global object is the global object of the global environment associated with o.

The "global environment associated with" concept is from the olden days, before the modern JavaScript specification and its concept of realms. We expect that as the Web IDL specification gets updated, every platform object will have a Realm associated with it, and this definition can be re-cast in those terms. [ECMA-262] [WEBIDL]

Then, the relevant Realm for a platform object is the Realm of its relevant settings object.

Similarly, the relevant global object for a platform object is the global object of its relevant settings object.

7.1.3.6. Killing scripts

Although the JavaScript specification does not account for this possibility, it’s sometimes necessary to abort a running script. This causes any ScriptEvaluation to cease immediately, emptying the JavaScript execution context stack without triggering any of the normal mechanisms like finally blocks. [ECMA-262]

User agents may impose resource limitations on scripts, for example CPU quotas, memory limits, total execution time limits, or bandwidth limitations. When a script exceeds a limit, the user agent may either throw a QuotaExceededError exception, abort the script without an exception, prompt the user, or throttle script execution.

For example, the following script never terminates. A user agent could, after waiting for a few seconds, prompt the user to either terminate the script or let it continue.
<script>
  while (true) { /* loop */ }
</script>

User agents are encouraged to allow users to disable scripting whenever the user is prompted either by a script (e.g., using the window.alert() API) or because of a script’s actions (e.g., because it has exceeded a time limit).

If scripting is disabled while a script is executing, the script should be terminated immediately.

User agents may allow users to specifically disable scripts just for the purposes of closing a browsing context.

For example, the prompt mentioned in the example above could also offer the user with a mechanism to just close the page entirely, without running any unload event handlers.

7.1.3.7. Integration with the JavaScript job queue

The JavaScript specification defines the JavaScript job and job queue abstractions in order to specify certain invariants about how promise operations execute with a clean JavaScript execution context stack and in a certain order. However, as of the time of this writing the definition of EnqueueJob in that specification are not sufficiently flexible to integrate with HTML as a host environment. [ECMA-262]

This is not strictly true. It is in fact possible, by taking liberal advantage of the many "implementation defined" sections of the algorithm, to contort it to our purposes. However, the end result is a mass of messy indirection and workarounds that essentially bypasses the job queue infrastructure entirely, albeit in a way that is technically sanctioned within the bounds of implementation-defined behavior. We do not take this path, and instead introduce the following willful violation.

As such, user agents must instead use the following definition in place of that in the JavaScript specification. These ensure that the promise jobs enqueued by the JavaScript specification are properly integrated into the user agent’s event loops.

7.1.3.7.1. EnqueueJob(queueName, job, arguments)

When the JavaScript specification says to call the EnqueueJob abstract operation, the following algorithm must be used in place of JavaScript’s EnqueueJob:

  1. Assert: queueName is "PromiseJobs". ("ScriptJobs" must not be used by user agents.)

  2. Let settings be the settings object of job.[[Realm]]

  3. Queue a microtask, on settings’s responsible event loop, to perform the following steps:

    1. Check if we can run script with settings. If this returns "do not run" then abort these steps.

    2. Prepare to run script with settings.

    3. Let result be the result of performing the abstract operation specified by job, using the elements of arguments as its arguments.

    4. Clean up after running script with settings.

    5. If result is an abrupt completion, report the exception given by result.[[value]].

7.1.3.8. Runtime script errors

When the user agent is required to report an error for a particular script script with a particular position line:col, using a particular target target, it must run these steps, after which the error is either handled or not handled:

  1. If target is in error reporting mode, then abort these steps; the error is not handled.

  2. Let target be in error reporting mode.

  3. Let message be a user-agent-defined string describing the error in a helpful manner.

  4. Let error object be the object that represents the error: in the case of an uncaught exception, that would be the object that was thrown; in the case of a JavaScript error that would be an Error object. If there is no corresponding object, then the null value must be used instead.

  5. Let location be an absolute URL that corresponds to the resource from which script was obtained.

    The resource containing the script will typically be the file from which the Document was parsed, e.g., for inline script elements or event handler content attributes; or the JavaScript file that the script was in, for external scripts. Even for dynamically-generated scripts, user agents are strongly encouraged to attempt to keep track of the original source of a script. For example, if an external script uses the document.write() API to insert an inline script element during parsing, the URL of the resource containing the script would ideally be reported as being the external script, and the line number might ideally be reported as the line with the document.write() call or where the string passed to that call was first constructed. Naturally, implementing this can be somewhat non-trivial.

    User agents are similarly encouraged to keep careful track of the original line numbers, even in the face of document.write() calls mutating the document as it is parsed, or event handler content attributes spanning multiple lines.

  6. If script has muted errors, then set message to "Script error.", set location to the empty string, set line and col to 0, and set error object to null.

  7. Let event be a new trusted ErrorEvent object that does not bubble but is cancelable, and which has the event name error.

  8. Initialize event’s message attribute to message.

  9. Initialize event’s filename attribute to location.

  10. Initialize event’s lineno attribute to line.

  11. Initialize event’s colno attribute to col.

  12. Initialize event’s error attribute to error object.

  13. Dispatch event at target.

  14. Let target no longer be in error reporting mode.

  15. If event was canceled, then the error is handled. Otherwise, the error is not handled.

    Returning true cancels event per the event handler processing algorithm.

7.1.3.8.1. Runtime script errors in documents

When the user agent is to report an exception E, the user agent must report the error for the relevant script, with the problematic position (line number and column number) in the resource containing the script, using the global object specified by the script’s settings object as the target. If the error is still not handled after this, then the error may be reported to a developer console.

7.1.3.8.2. The ErrorEvent interface
[Constructor(DOMString type, optional ErrorEventInit eventInitDict), Exposed=(Window, Worker)]
interface ErrorEvent : Event {
  readonly attribute DOMString message;
  readonly attribute DOMString filename;
  readonly attribute unsigned long lineno;
  readonly attribute unsigned long colno;
  readonly attribute any error;
};
dictionary ErrorEventInit : EventInit {
  DOMString message = "";
  DOMString filename = "";
  unsigned long lineno = 0;
  unsigned long colno = 0;
  any error = null;
};

The message attribute must return the value it was initialized to. It represents the error message.

The filename attribute must return the value it was initialized to. It represents the absolute URL of the script in which the error originally occurred.

The lineno attribute must return the value it was initialized to. It represents the line number where the error occurred in the script.

The colno attribute must return the value it was initialized to. It represents the column number where the error occurred in the script.

The error attribute must return the value it was initialized to. Where appropriate, it is set to the object representing the error (e.g., the exception object in the case of an uncaught DOM exception).

7.1.3.9. Unhandled promise rejections

There is only one known native implementation of the unhandledrejection and rejectionhandled events (Chrome/Blink). Therefore these features should not be relied upon.

In addition to synchronous runtime script errors, scripts may experience asynchronous promise rejections, tracked via the unhandledrejection and rejectionhandled events.

When the user agent is to notify about rejected promises on a given environment settings object settings object, it must run these steps:

  1. Let list be a copy of settings object’s about-to-be-notified rejected promises list.

  2. If list is empty, abort these steps.

  3. Clear settings object’s about-to-be-notified rejected promises list.

  4. Queue a task to run the following substep:

    1. For each promise p in list:

      1. If p’s [[PromiseIsHandled]] internal slot is true, continue to the next iteration of the loop.

      2. Let event be a new trusted PromiseRejectionEvent object that does not bubble but is cancelable, and which has the event name unhandledrejection.

      3. Initialise event’s promise attribute to p.

      4. Initialise event’s reason attribute to the value of p’s [[PromiseResult]] internal slot.

      5. Dispatch event at settings object’s global object.

      6. If the event was canceled, then the promise rejection is handled. Otherwise, the promise rejection is not handled.

      7. If p’s [[PromiseIsHandled]] internal slot is false, add p to settings object’s outstanding rejected promises weak set.

This algorithm results in promise rejections being marked as handled or not handled. These concepts parallel handled and not handled script errors. If a rejection is still not handled after this, then the rejection may be reported to a developer console.

7.1.3.9.1. The HostPromiseRejectionTracker implementation

ECMAScript contains an implementation-defined HostPromiseRejectionTracker(promise, operation) abstract operation. User agents must use the following implementation: [ECMA-262]

  1. Let script be the running script.

  2. If script has muted errors, terminate these steps.

  3. Let settings object be script’s settings object.

  4. If operation is "reject",

    1. Add promise to settings object’s about-to-be-notified rejected promises list.

  5. If operation is "handle",

    1. If settings object’s about-to-be-notified rejected promises list contains promise, remove promise from that list and abort these steps.

    2. If settings object’s outstanding rejected promises weak set does not contain promise, abort these steps.

    3. Remove promise from settings object’s outstanding rejected promises weak set.

    4. Queue a task to run the following steps:

      1. Let event be a new trusted PromiseRejectionEvent object that does not bubble and is not cancelable, and which has the event name rejectionhandled.

      2. Initialise event’s promise attribute to promise.

      3. Initialise event’s reason attribute to the value of promise’s [[PromiseResult]] internal slot.

      4. Dispatch event at settings object’s global object.

7.1.3.9.2. The PromiseRejectionEvent interface
[Constructor(DOMString type, PromiseRejectionEventInit eventInitDict), Exposed=(Window,Worker)]
interface PromiseRejectionEvent : Event {
  readonly attribute Promise<any> promise;
  readonly attribute any reason;
};
dictionary PromiseRejectionEventInit : EventInit {
  required Promise<any> promise;
  any reason;
};

The promise attribute must return the value it was initialized to. It represents the promise which this notification is about.

The reason attribute must return the value it was initialized to. It represents the rejection reason for the promise.

7.1.3.10. HostEnsureCanCompileStrings(callerRealm, calleeRealm)

JavaScript contains an implementation-defined HostEnsureCanCompileStrings(callerRealm, calleeRealm) abstract operation. User agents must use the following implementation: [ECMA-262]

  1. Perform ? EnsureCSPDoesNotBlockStringCompilation(callerRealm, calleeRealm). [CSP3]

7.1.4. Event loops

7.1.4.1. Definitions

To coordinate events, user interaction, scripts, rendering, networking, and so forth, user agents must use event loops as described in this section. There are two kinds of event loops: those for browsing contexts, and those for workers.

There must be at least one browsing context event loop per user agent, and at most one per unit of related similar-origin browsing contexts.

When there is more than one event loop for a unit of related browsing contexts, complications arise when a browsing context in that group is navigated such that it switches from one unit of related similar-origin browsing contexts to another. This specification does not currently describe how to handle these complications.

A browsing context event loop always has at least one browsing context. If such an event loop’s browsing contexts all go away, then the event loop goes away as well. A browsing context always has an event loop coordinating its activities.

Worker event loops are simpler: each worker has one event loop, and the worker processing model manages the event loop’s lifetime.


An event loop has one or more task queues. A task queue is an ordered list of tasks, which are algorithms that are responsible for such work as:

Events

Dispatching an Event object at a particular EventTarget object is often done by a dedicated task.

Not all events are dispatched using the task queue, many are dispatched during other tasks.

Parsing

The HTML parser tokenizing one or more bytes, and then processing any resulting tokens, is typically a task.

Callbacks

Calling a callback is often done by a dedicated task.

Using a resource

When an algorithm fetches a resource, if the fetching occurs in a non-blocking fashion then the processing of the resource once some or all of the resource is available is performed by a task.

Reacting to DOM manipulation

Some elements have tasks that trigger in response to DOM manipulation, e.g., when that element is inserted into the document.

Each task in a browsing context event loop is associated with a Document; if the task was queued in the context of an element, then it is the element’s node document; if the task was queued in the context of a browsing context, then it is the browsing context’s active document at the time the task was queued; if the task was queued by or for a script then the document is the responsible document specified by the script’s settings object.

A task is intended for a specific event loop: the event loop that is handling tasks for the task’s associated Document or Worker.

When a user agent is to queue a task, it must add the given task to one of the task queues of the relevant event loop.

Each task is defined as coming from a specific task source. All the tasks from one particular task source and destined to a particular event loop (e.g., the callbacks generated by timers of a Document, the events fired for mouse movements over that Document, the tasks queued for the parser of that Document) must always be added to the same task queue, but tasks from different task sources may be placed in different task queues.

For example, a user agent could have one task queue for mouse and key events (the user interaction task source), and another for everything else. The user agent could then give keyboard and mouse events preference over other tasks three quarters of the time, keeping the interface responsive but not starving other task queues, and never processing events from any one task source out of order.

Each event loop has a currently running task. Initially, this is null. It is used to handle reentrancy. Each event loop also has a performing a microtask checkpoint flag, which must initially be false. It is used to prevent reentrant invocation of the perform a microtask checkpoint algorithm.

7.1.4.2. Processing model

An event loop must continually run through the following steps for as long as it exists:

  1. Select the oldest task on one of the event loop’s task queues, if any, ignoring, in the case of a browsing context event loop, tasks whose associated Documents are not fully active. The user agent may pick any task queue. If there is no task to select, then jump to the Microtasks step below.

  2. Set the event loop’s currently running task to the task selected in the previous step.

  3. Run: Run the selected task.

  4. Set the event loop’s currently running task back to null.

  5. Remove the task that was run in the Run step above from its task queue.

  6. Microtasks: Perform a microtask checkpoint.

  7. Update the rendering: If this event loop is a browsing context event loop (as opposed to a Worker event loop), then run the following substeps.

    1. Let now be the value that would be returned by the Performance object’s now() method. [HR-TIME-2]

    2. Let docs be the list of Document objects associated with the event loop in question, sorted arbitrarily except that the following conditions must be met:

      In the steps below that iterate over docs, each Document must be processed in the order it is found in the list.

    3. If there is a top-level browsing context B that the user agent believes would not benefit from having its rendering updated at this time, then remove from docs all Document objects whose browsing context’s top-level browsing context is B.

      Whether a top-level browsing context would benefit from having its rendering updated depends on various factors, such as the update frequency. For example, if the browser is attempting to achieve a 60 Hz refresh rate, then these steps are only necessary every 60th of a second (about 16.7ms). If the browser finds that a top-level browsing context is not able to sustain this rate, it might drop to a more sustainable 30Hz for that set of Documents, rather than occasionally dropping frames. (This specification does not mandate any particular model for when to update the rendering.) Similarly, if a top-level browsing context is in the background, the user agent might decide to drop that page to a much slower 4Hz, or even less.

      Another example of why a browser might skip updating the rendering is to ensure certain tasks are executed immediately after each other, with only microtask checkpoints interleaved (and without, e.g., animation frame callbacks interleaved). For example, a user agent might wish to coalesce timer callbacks together, with no intermediate rendering updates.

    4. If there are a nested browsing contexts B that the user agent believes would not benefit from having their rendering updated at this time, then remove from docs all Document objects whose browsing context is in B.

      As with top-level browsing contexts, a variety of factors can influence whether it is profitable for a browser to update the rendering of nested browsing contexts. For example, a user agent might wish to spend less resources rendering third-party content, especially if it is not currently visible to the user or if resources are constrained. In such cases, the browser could decide to update the rendering for such content infrequently or never.

    5. For each fully active Document in docs, run the resize steps for that Document, passing in now as the timestamp. [CSSOM-VIEW]

    6. For each fully active Document in docs, run the scroll steps for that Document, passing in now as the timestamp. [CSSOM-VIEW]

    7. For each fully active Document in docs, evaluate media queries and report changes for that Document, passing in now as the timestamp. [CSSOM-VIEW]

    8. For each fully active Document in docs, run CSS animations and send events for that Document, passing in now as the timestamp. [CSS3-ANIMATIONS]

    9. For each fully active Document in docs, run the fullscreen rendering steps for that Document, passing in now as the timestamp. [FULLSCREEN]

    10. For each fully active Document in docs, run the animation frame callbacks for that Document, passing in now as the timestamp.

    11. For each fully active Document in docs, update the rendering or user interface of that Document and its browsing context to reflect the current state.

  8. If this is a Worker event loop (i.e., one running for a WorkerGlobalScope), but there are no tasks in the event loop’s task queues and the WorkerGlobalScope object’s closing flag is true, then destroy the event loop, aborting these steps, resuming the run a worker steps.

  9. Return to the first step of the event loop.


Each event loop has a microtask queue. A microtask is a task that is originally to be queued on the microtask queue rather than a task queue. There are two kinds of microtasks: solitary callback microtasks, and compound microtasks.

This specification only has solitary callback microtasks. Specifications that use compound microtasks have to take extra care to wrap callbacks to handle spinning the event loop.

When an algorithm requires a microtask to be queued, it must be appended to the relevant event loop’s microtask queue; the task source of such a microtask is the microtask task source.

It is possible for a microtask to be moved to a regular task queue, if, during its initial execution, it spins the event loop. In that case, the microtask task source is the task source used. Normally, the task source of a microtask is irrelevant.

When a user agent is to perform a microtask checkpoint, if the performing a microtask checkpoint flag is false, then the user agent must run the following steps:

  1. Let the performing a microtask checkpoint flag be true.

  2. Microtask queue handling: If the event loop’s microtask queue is empty, jump to the Done step below.

  3. Select the oldest microtask on the event loop’s microtask queue.

  4. Set the event loop’s currently running task to the task selected in the previous step.

  5. Run: Run the selected task.

    This might involve invoking scripted callbacks, which eventually calls the clean up after running script steps, which call this perform a microtask checkpoint algorithm again, which is why we use the performing a microtask checkpoint flag to avoid reentrancy.

  6. Set the event loop’s currently running task back to null.

  7. Remove the microtask run in the step above from the microtask queue, and return to the Microtask queue handling step.

  8. Done: For each environment settings object whose responsible event loop is this event loop, notify about rejected promises on that environment settings object.

  9. Let the performing a microtask checkpoint flag be false.

If, while a compound microtask is running, the user agent is required to execute a compound microtask subtask to run a series of steps, the user agent must run the following steps:

  1. Let parent be the event loop’s currently running task (the currently running compound microtask).

  2. Let subtask be a new task that consists of running the given series of steps. The task source of such a microtask is the microtask task source. This is a compound microtask subtask.

  3. Set the event loop’s currently running task to subtask.

  4. Run subtask.

  5. Set the event loop’s currently running task back to parent.


When an algorithm running in parallel is to await a stable state, the user agent must queue a microtask that runs the following steps, and must then stop executing (execution of the algorithm resumes when the microtask is run, as described in the following steps):

  1. Run the algorithm’s synchronous section.

  2. Resumes execution of the algorithm in parallel, if appropriate, as described in the algorithm’s steps.

Steps in synchronous sections are marked with ⌛.


When an algorithm says to spin the event loop until a condition goal is met, the user agent must run the following steps:

  1. Let task be the event loop’s currently running task.

    This might be a microtask, in which case it is a solitary callback microtask. It could also be a compound microtask subtask, or a regular task that is not a microtask. It will not be a compound microtask.

  2. Let task source be task’s task source.

  3. Let old stack be a copy of the JavaScript execution context stack.

  4. Empty the JavaScript execution context stack.

  5. Run the global script clean-up jobs.

  6. Perform a microtask checkpoint.

  7. Stop task, allowing whatever algorithm that invoked it to resume, but continue these steps in parallel.

    This causes one of the following algorithms to continue: the event loop’s main set of steps, the perform a microtask checkpoint algorithm, or the execute a compound microtask subtask algorithm to continue.

  8. Wait until the condition goal is met.

  9. Queue a task to continue running these steps, using the task source task source. Wait until this new task runs before continuing these steps.

  10. Replace the JavaScript execution context stack with the old stack.

  11. Return to the caller.


Some of the algorithms in this specification, for historical reasons, require the user agent to pause while running a task until a condition goal is met. This means running the following steps:

  1. If necessary, update the rendering or user interface of any Document or browsing context to reflect the current state.

  2. Wait until the condition goal is met. While a user agent has a paused task, the corresponding event loop must not run further tasks, and any script in the currently running task must block. User agents should remain responsive to user input while paused, however, albeit in a reduced capacity since the event loop will not be doing anything.

7.1.4.3. Generic task sources

The following task sources are used by a number of mostly unrelated features in this and other specifications.

The DOM manipulation task source

This task source is used for features that react to DOM manipulations, such as things that happen in a non-blocking fashion when an element is inserted into the document.

The user interaction task source

This task source is used for features that react to user interaction, for example keyboard or mouse input.

Events sent in response to user input (e.g., click events) must be fired using tasks queued with the user interaction task source. [UIEVENTS]

The networking task source

This task source is used for features that trigger in response to network activity.

The history traversal task source

This task source is used to queue calls to history.back() and similar APIs.

7.1.5. Events

7.1.5.1. Event handlers

Many objects can have event handlers specified. These act as non-capture event listeners for the object on which they are specified. [DOM]

An event handler has a name, which always starts with "on" and is followed by the name of the event for which it is intended.

An event handler has a value, which is either null, or is a callback object, or is an internal raw uncompiled handler. The EventHandler callback function type describes how this is exposed to scripts. Initially, an event handler’s value must be set to null.

Event handlers are exposed in one of two ways.

The first way, common to all event handlers, is as an event handler IDL attribute.

The second way is as an event handler content attribute. Event handlers on html elements and some of the event handlers on Window objects are exposed in this way.


An event handler IDL attribute is an IDL attribute for a specific event handler. The name of the IDL attribute is the same as the name of the event handler.

Event handler IDL attributes, on setting, must set the corresponding event handler to their new value, and on getting, must return the result of getting the current value of the event handler in question (this can throw an exception, in which case the getting propagates it to the caller, it does not catch it).

If an event handler IDL attribute exposes an event handler of an object that doesn’t exist, it must always return null on getting and must do nothing on setting.

This can happen in particular for event handler IDL attribute on body elements that do not have corresponding Window objects.

Certain event handler IDL attributes have additional requirements, in particular the onmessage attribute of MessagePort objects.


An event handler content attribute is a content attribute for a specific event handler. The name of the content attribute is the same as the name of the event handler.

Event handler content attributes, when specified, must contain valid JavaScript code which, when parsed, would match the FunctionBody production after automatic semicolon insertion. [ECMA-262]

When an event handler content attribute is set, execute the following steps:

  1. If the Should element’s inline behavior be blocked by Content Security Policy? algorithm returns "Blocked" when executed upon the attribute’s element "script attribute", and the attribute’s value, then abort these steps. [CSP3]

  2. Set the corresponding event handler to an internal raw uncompiled handler consisting of the attribute’s new value and the script location where the attribute was set to this value.

When an event handler content attribute is removed, the user agent must set the corresponding event handler to null.


When an event handler H of an element or object T implementing the EventTarget interface is first set to a non-null value, the user agent must append an event listener to the list of event listeners associated with T with type set to the event handler event type corresponding to H and callback set to the event handler processing algorithm defined below. [DOM]

The callback is emphatically not the event handler itself. Every event handler ends up registering the same callback the algorithm defined below, which takes care of invoking the right callback, and processing the callback’s return value.

This only happens the first time the event handler’s value is set. Since listeners are called in the order they were registered, the order of event listeners for a particular event type will always be first the event listeners registered with addEventListener() before the first time the event handler was set to a non-null value, then the callback to which it is currently set, if any, and finally the event listeners registered with addEventListener() after the first time the event handler was set to a non-null value.

This example demonstrates the order in which event listeners are invoked. If the button in this example is clicked by the user, the page will show four alerts, with the text "ONE", "TWO", "THREE", and "FOUR" respectively.
<button>Start Demo</button>
<script>
var button = document.getElementById('test');
button.addEventListener('click', function () { alert('ONE') }, false);
button.setAttribute('onclick', "alert('NOT CALLED')"); // event handler listener is registered here
button.addEventListener('click', function () { alert('THREE') }, false);
button.onclick = function () { alert('TWO'); };
button.addEventListener('click', function () { alert('FOUR') }, false);
</script>

The interfaces implemented by the event object do not influence whether an event handler is triggered or not.

The event handler processing algorithm for an event handler H and an Event object E is as follows:

  1. Let callback be the result of getting the current value of the event handler H.

  2. If callback is null, then abort these steps.

  3. Process the Event object E as follows:

    If E is an ErrorEvent object and the event handler IDL attribute’s type is OnErrorEventHandler
    Invoke callback with five arguments, the first one having the value of E’s message attribute, the second having the value of E’s filename attribute, the third having the value of E’s lineno attribute, the fourth having the value of E’s colno attribute, the fifth having the value of E’s error attribute, and with the callback this value set to E’s currentTarget. Let return value be the callback’s return value. [WEBIDL]
    Otherwise
    Invoke callback with one argument, the value of which is the Event object E, with the callback this value set to E’s currentTarget. Let return value be the callback’s return value. [WEBIDL]

    In this step, invoke means to invoke the Web IDL callback function.

    If an exception gets thrown by the callback, end these steps and allow the exception to propagate. (It will propagate to the DOM event dispatch logic, which will then report the exception.)

  4. Process return value as follows:

    If the event type is mouseover
    If the event type is error and E is an ErrorEvent object
    If return value is a Web IDL boolean true value, then cancel the event.
    If the event type is beforeunload

    The event handler IDL attribute’s type is OnBeforeUnloadEventHandler, and the return value will therefore have been coerced into either the value null or a DOMString.

    If the return value is null, then cancel the event.

    Otherwise, if the Event object E is a BeforeUnloadEvent object, and the Event object E’s returnValue attribute’s value is the empty string, then set the returnValue attribute’s value to return value.

    Otherwise
    If return value is a Web IDL boolean false value, then cancel the event.

The EventHandler callback function type represents a callback used for event handlers. It is represented in Web IDL as follows:

[TreatNonObjectAsNull]
callback EventHandlerNonNull = any (Event event);
typedef EventHandlerNonNull? EventHandler;

In JavaScript, any Function object implements this interface.

For example, the following document fragment:
<body onload="alert(this)" onclick="alert(this)">

...leads to an alert saying "[object Window]" when the document is loaded, and an alert saying "[object HTMLBodyElement]" whenever the user clicks something in the page.

The return value of the function affects whether the event is canceled or not: as described above, if the return value is false, the event is canceled (except for mouseover events, where the return value has to be true to cancel the event). With beforeunload events, the value is instead used to determine whether or not to prompt about unloading the document.

For historical reasons, the onerror handler has different arguments:

[TreatNonObjectAsNull]
callback OnErrorEventHandlerNonNull = any ((Event or DOMString) event, optional DOMString source, optional unsigned long lineno, optional unsigned long column, optional any error);
typedef OnErrorEventHandlerNonNull? OnErrorEventHandler;

Similarly, the onbeforeunload handler has a different return value:

[TreatNonObjectAsNull]
callback OnBeforeUnloadEventHandlerNonNull = DOMString? (Event event);
typedef OnBeforeUnloadEventHandlerNonNull? OnBeforeUnloadEventHandler;

An internal raw uncompiled handler is a tuple with the following information:

When the user agent is to get the current value of the event handler H, it must run these steps:

  1. If H’s value is an internal raw uncompiled handler, run these substeps:

    1. If H is an element’s event handler, then let element be the element, and document be the element’s node document.

      Otherwise, H is a Window object’s event handler: let element be null, and let document be the Document most recently associated with that Window object.

    2. If document does not have a browsing context, or if scripting is enabled for document’s browsing context, then return null.

    3. Let body be the uncompiled script body in the internal raw uncompiled handler.

    4. Let location be the location where the script body originated, as given by the internal raw uncompiled handler.

    5. If element is not null and element has a form owner, let form owner be that form owner. Otherwise, let form owner be null.

    6. Let script settings be the environment settings object created for the Window object with which document is currently associated.

    7. If body is not parsable as FunctionBody or if parsing detects an early error, then follow these substeps:

      1. Set H’s value to null.

      2. Report the error for the appropriate script and with the appropriate position (line number and column number) given by location, using the global object specified by script settings as the target. If the error is still not handled after this, then the error may be reported to a developer console.

      3. Return null.

    8. If body begins with a Directive Prologue that contains a Use Strict Directive then let strict be true, otherwise let strict be false.

    9. Let function be the result of calling FunctionCreate, with arguments:

      kind

      Normal

      ParameterList

      If H is an onerror event handler of a Window object
      Let the function have five arguments, named event, source, lineno, colno, and error.
      Otherwise
      Let the function have a single argument called event.

      Body

      The result of parsing body above.

      Scope

      1. If H is an element’s event handler, then let Scope be the result of NewObjectEnvironment(document, the global environment).

        Otherwise, H is a Window object’s event handler: let Scope be the global environment.

      2. If form owner is not null, let Scope be NewObjectEnvironment(form owner, Scope).

      3. If element is not null, let Scope be the NewObjectEnvironment(element, Scope).

      Strict

      The value of strict.

    10. Set H’s value to function.

  2. Return H’s value.

7.1.5.2. Event handlers on elements, Document objects, and Window objects

The following are the event handlers (and their corresponding event handler event types) that must be supported by all html elements, as both event handler content attributes and event handler IDL attributes; and that must be supported by all Document and Window objects, as event handler IDL attributes:

Event handler Event handler event type
onabort abort
oncancel cancel
oncanplay canplay
oncanplaythrough canplaythrough
onchange change
onclick click
onclose close
oncontextmenu contextmenu
oncuechange cuechange
ondblclick dblclick
ondrag drag
ondragend dragend
ondragenter dragenter
ondragexit dragexit
ondragleave dragleave
ondragover dragover
ondragstart dragstart
ondrop drop
ondurationchange durationchange
onemptied emptied
onended ended
oninput input
oninvalid invalid
onkeydown keydown
onkeypress keypress
onkeyup keyup
onloadeddata loadeddata
onloadedmetadata loadedmetadata
onloadstart loadstart
onmousedown mousedown
onmouseenter mouseenter
onmouseleave mouseleave
onmousemove mousemove
onmouseout mouseout
onmouseover mouseover
onmouseup mouseup
onwheel wheel
onpause pause
onplay play
onplaying playing
onprogress progress
onratechange ratechange
onreset reset
onseeked seeked
onseeking seeking
onselect select
onshow show
onstalled stalled
onsubmit submit
onsuspend suspend
ontimeupdate timeupdate
ontoggle toggle
onvolumechange volumechange
onwaiting waiting

The following are the event handlers (and their corresponding event handler event types) that must be supported by all html elements other than body and frameset elements, as both event handler content attributes and event handler IDL attributes; that must be supported by all Document objects, as event handler IDL attributes; and that must be supported by all Window objects, as event handler IDL attributes on the Window objects themselves, and with corresponding event handler content attributes and event handler IDL attributes exposed on all body and frameset elements that are owned by that Window object’s Documents:

Event handler Event handler event type
onblur blur
onerror error
onfocus focus
onload load
onresize resize
onscroll scroll

The following are the event handlers (and their corresponding event handler event types) that must be supported by Window objects, as event handler IDL attributes on the Window objects themselves, and with corresponding event handler content attributes and event handler IDL attributes exposed on all body and frameset elements that are owned by that Window object’s Documents:

Event handler Event handler event type
onafterprint afterprint
onbeforeprint beforeprint
onbeforeunload beforeunload
onhashchange hashchange
onlanguagechange languagechange
onmessage message
onoffline offline
ononline online
onpagehide pagehide
onpageshow pageshow
onrejectionhandled rejectionhandled
onpopstate popstate
onstorage storage
onunhandledrejection unhandledrejection
onunload unload

The following are the event handlers (and their corresponding event handler event types) that must be supported by all html elements, as both event handler content attributes and event handler IDL attributes and that must be supported by all Document objects, as event handler IDL attributes:

Event handler Event handler event type
oncut cut
oncopy copy
onpaste paste

The following are the event handlers (and their corresponding event handler event types) that must be supported on Document objects as event handler IDL attributes:

Event handler Event handler event type
onreadystatechange readystatechange
7.1.5.2.1. IDL definitions
[NoInterfaceObject]
interface GlobalEventHandlers {
  attribute EventHandler onabort;
  attribute EventHandler onblur;
  attribute EventHandler oncancel;
  attribute EventHandler oncanplay;
  attribute EventHandler oncanplaythrough;
  attribute EventHandler onchange;
  attribute EventHandler onclick;
  attribute EventHandler onclose;
  attribute EventHandler oncontextmenu;
  attribute EventHandler oncuechange;
  attribute EventHandler ondblclick;
  attribute EventHandler ondrag;
  attribute EventHandler ondragend;
  attribute EventHandler ondragenter;
  attribute EventHandler ondragexit;
  attribute EventHandler ondragleave;
  attribute EventHandler ondragover;
  attribute EventHandler ondragstart;
  attribute EventHandler ondrop;
  attribute EventHandler ondurationchange;
  attribute EventHandler onemptied;
  attribute EventHandler onended;
  attribute OnErrorEventHandler onerror;
  attribute EventHandler onfocus;
  attribute EventHandler oninput;
  attribute EventHandler oninvalid;
  attribute EventHandler onkeydown;
  attribute EventHandler onkeypress;
  attribute EventHandler onkeyup;
  attribute EventHandler onload;
  attribute EventHandler onloadeddata;
  attribute EventHandler onloadedmetadata;
  attribute EventHandler onloadstart;
  attribute EventHandler onmousedown;
  [LenientThis] attribute EventHandler onmouseenter;
  [LenientThis] attribute EventHandler onmouseleave;
  attribute EventHandler onmousemove;
  attribute EventHandler onmouseout;
  attribute EventHandler onmouseover;
  attribute EventHandler onmouseup;
  attribute EventHandler onwheel;
  attribute EventHandler onpause;
  attribute EventHandler onplay;
  attribute EventHandler onplaying;
  attribute EventHandler onprogress;
  attribute EventHandler onratechange;
  attribute EventHandler onreset;
  attribute EventHandler onresize;
  attribute EventHandler onscroll;
  attribute EventHandler onseeked;
  attribute EventHandler onseeking;
  attribute EventHandler onselect;
  attribute EventHandler onshow;
  attribute EventHandler onstalled;
  attribute EventHandler onsubmit;
  attribute EventHandler onsuspend;
  attribute EventHandler ontimeupdate;
  attribute EventHandler ontoggle;
  attribute EventHandler onvolumechange;
  attribute EventHandler onwaiting;
};
[NoInterfaceObject]
interface WindowEventHandlers {
  attribute EventHandler onafterprint;
  attribute EventHandler onbeforeprint;
  attribute OnBeforeUnloadEventHandler onbeforeunload;
  attribute EventHandler onhashchange;
  attribute EventHandler onlanguagechange;
  attribute EventHandler onmessage;
  attribute EventHandler onoffline;
  attribute EventHandler ononline;
  attribute EventHandler onpagehide;
  attribute EventHandler onpageshow;
  attribute EventHandler onrejectionhandled;
  attribute EventHandler onpopstate;
  attribute EventHandler onstorage;
  attribute EventHandler onunhandledrejection;
  attribute EventHandler onunload;
};
[NoInterfaceObject]
interface DocumentAndElementEventHandlers {
  attribute EventHandler oncopy;
  attribute EventHandler oncut;
  attribute EventHandler onpaste;
};
7.1.5.3. Event firing

Certain operations and methods are defined as firing events on elements. For example, the click() method on the HTMLElement interface is defined as firing a click event on the element. [UIEVENTS]

Firing a simple event named e means that a trusted event with the name e, which does not bubble (except where otherwise stated) and is not cancelable (except where otherwise stated), and which uses the Event interface, must be created and dispatched at the given target.

Firing a synthetic mouse event named e means that an event with the name e, which is trusted (except where otherwise stated), does not bubble (except where otherwise stated), is not cancelable (except where otherwise stated), and which uses the MouseEvent interface, must be created and dispatched at the given target. The event object must have its screenX, screenY, {{MouseEvent/clientX}, clientY, and button attributes initialized to 0, its ctrlKey, shiftKey, altKey, and metaKey attributes initialized according to the current state of the key input device, if any (false for any keys that are not available), its detail attribute initialized to 1, its relatedTarget attribute initialized to null (except where otherwise stated), and its view attribute initialized to the Window object of the Document object of the given target node, if any, or else null. The getModifierState() method on the object must return values appropriately describing the state of the key input device at the time the event is created.

Firing a click event means firing a synthetic mouse event named click, which bubbles and is cancelable.

The default action of these events is to do nothing except where otherwise stated.

7.1.5.4. Events and the Window object

When an event is dispatched at a DOM node in a Document in a browsing context, if the event is not a load event, the user agent must act as if, for the purposes of event dispatching, the Window object is the parent of the Document object. [DOM]

7.2. Base64 utility methods

The atob() and btoa() methods allow authors to transform content to and from the base64 encoding.

[NoInterfaceObject, Exposed=(Window, Worker)]
interface WindowBase64 {
  DOMString btoa(DOMString btoa);
  DOMString atob(DOMString atob);
};
Window implements WindowBase64;
WorkerGlobalScope implements WindowBase64;

In these APIs, for mnemonic purposes, the "b" can be considered to stand for "binary", and the "a" for "ASCII". In practice, though, for primarily historical reasons, both the input and output of these functions are Unicode strings.

result = window . btoa( data )

Takes the input data, in the form of a Unicode string containing only characters in the range U+0000 to U+00FF, each representing a binary byte with values 0x00 to 0xFF respectively, and converts it to its base64 representation, which it returns.

Throws an InvalidCharacterError exception if the input string contains any out-of-range characters.

result = window . atob( data )

Takes the input data, in the form of a Unicode string containing base64-encoded binary data, decodes it, and returns a string consisting of characters in the range U+0000 to U+00FF, each representing a binary byte with values 0x00 to 0xFF respectively, corresponding to that binary data.

Throws an InvalidCharacterError exception if the input string is not valid base64 data.

The btoa() method must throw an InvalidCharacterError exception if the method’s first argument contains any character whose code point is greater than U+00FF. Otherwise, the user agent must convert that argument to a sequence of octets whose nth octet is the eight-bit representation of the code point of the nth character of the argument, and then must apply the base64 algorithm to that sequence of octets, and return the result. [RFC4648]

The atob() method must run the following steps to parse the string passed in the method’s first argument:

  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. Remove all space characters from input.
  4. If the length of input divides by 4 leaving no remainder, then: if input ends with one or two U+003D EQUALS SIGN (=) characters, remove them from input.
  5. If the length of input divides by 4 leaving a remainder of 1, throw an InvalidCharacterError exception and abort these steps.
  6. If input contains a character that is not in the following list of characters and character ranges, throw an InvalidCharacterError exception and abort these steps:

  7. Let output be a string, initially empty.
  8. Let buffer be a buffer that can have bits appended to it, initially empty.
  9. While position does not point past the end of input, run these substeps:

    1. Find the character pointed to by position in the first column of the following table. Let n be the number given in the second cell of the same row.

      Character Number
      A 0
      B 1
      C 2
      D 3
      E 4
      F 5
      G 6
      H 7
      I 8
      J 9
      K 10
      L 11
      M 12
      N 13
      O 14
      P 15
      Q 16
      R 17
      S 18
      T 19
      U 20
      V 21
      W 22
      X 23
      Y 24
      Z 25
      a 26
      b 27
      c 28
      d 29
      e 30
      f 31
      g 32
      h 33
      i 34
      j 35
      k 36
      l 37
      m 38
      n 39
      o 40
      p 41
      q 42
      r 43
      s 44
      t 45
      u 46
      v 47
      w 48
      x 49
      y 50
      z 51
      0 52
      1 53
      2 54
      3 55
      4 56
      5 57
      6 58
      7 59
      8 60
      9 61
      + 62
      / 63
    2. Append to buffer the six bits corresponding to number, most significant bit first.
    3. If buffer has accumulated 24 bits, interpret them as three 8-bit big-endian numbers. Append the three characters with code points equal to those numbers to output, in the same order, and then empty buffer.
    4. Advance position by one character.
  10. If buffer is not empty, it contains either 12 or 18 bits. If it contains 12 bits, discard the last four and interpret the remaining eight as an 8-bit big-endian number. If it contains 18 bits, discard the last two and interpret the remaining 16 as two 8-bit big-endian numbers. Append the one or two characters with code points equal to those one or two numbers to output, in the same order.

    The discarded bits mean that, for instance, atob("YQ") and atob("YR") both return "a".

  11. Return output.

7.3. Dynamic markup insertion

APIs for dynamically inserting markup into the document interact with the parser, and thus their behavior varies depending on whether they are used with HTML documents (and the HTML parser) or XHTML in XML documents (and the XML parser).

7.3.1. Opening the input stream

The open() method comes in several variants with different numbers of arguments.

document = document . open( [ type [, replace ] ] )
Causes the Document to be replaced in-place, as if it was a new Document object, but reusing the previous object, which is then returned.

If the type argument is omitted or has the value "text/html", then the resulting Document has an HTML parser associated with it, which can be given data to parse using document.write(). Otherwise, all content passed to document.write() will be parsed as plain text.

If the replace argument is present and has the value "replace", the existing entries in the session history for the Document object are removed.

The method has no effect if the Document is still being parsed.

Throws an "InvalidStateError" DOMException if the Document is an XML document.

window = document . open( url, name, features [, replace ] )
Works like the window.open() method.

Document objects have an ignore-opens-during-unload counter, which is used to prevent scripts from invoking the document.open() method (directly or indirectly) while the document is being unloaded. Initially, the counter must be set to zero.

When called with two arguments (or fewer), the document.open() method must act as follows:

  1. If the Document object is an XML document, then throw an "InvalidStateError" DOMException and abort these steps.

  2. If the Document object is not an active document, then abort these steps.

  3. If the origin of the Document is not equal to the origin of the responsible document specified by the entry settings object, throw a "SecurityError" DOMException and abort these steps.

  4. Let type be the value of the first argument.

  5. If the second argument is an ASCII case-insensitive match for the value "replace", then let replace be true.

    Otherwise, if the browsing context’s session history contains only one Document, and that was the about:blank Document created when the browsing context was created, and that Document has never had the unload a document algorithm invoked on it (e.g., by a previous call to document.open()), then let replace be true.

    Otherwise, let replace be false.

  6. If the Document has an active parser whose script nesting level is greater than zero, then the method does nothing. Abort these steps and return the Document object on which the method was invoked.

    This basically causes document.open() to be ignored when it’s called in an inline script found during parsing, while still letting it have an effect when called from a non-parser task such as a timer callback or event handler.

  7. Similarly, if the Document's ignore-opens-during-unload counter is greater than zero, then the method does nothing. Abort these steps and return the Document object on which the method was invoked.

    This basically causes document.open() to be ignored when it’s called from a beforeunload pagehide, or unload event handler while the Document is being unloaded.

  8. Set the Document's salvageable state to false.

  9. Prompt to unload the Document object. If the user refused to allow the document to be unloaded, then abort these steps and return the Document object on which the method was invoked.

  10. Unload the Document object, with the recycle parameter set to true.

  11. Abort the Document.

  12. Unregister all event listeners registered on the Document node and its descendants.

  13. Remove any tasks associated with the Document in any task source.

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

  15. Call the JavaScript InitializeHostDefinedRealm() abstract operation with the following customizations:

  16. Set window’s associated Document to the Document.

  17. Set up a browsing context environment settings object with realm execution context.

  18. Replace the Document's singleton objects with new instances of those objects, created in window’s Realm. (This includes in particular the History, ApplicationCache and Navigator objects, the various BarProp objects, the two Storage objects, the various HTMLCollection objects, and objects defined by other specifications, like Selection. It also includes all the Web IDL prototypes in the JavaScript binding, including the Document object’s prototype.)

  19. Change the document’s character encoding to UTF-8.

  20. If the Document is ready for post-load tasks, then set the Document object’s reload override flag and set the Document's reload override buffer to the empty string.

  21. Set the Document's salvageable state back to true.

  22. Change the document’s URL to the URL of the responsible document specified by the entry settings object.

  23. If the Document's iframe load in progress flag is set, set the Document's mute iframe load flag.

  24. Create a new HTML parser and associate it with the document. This is a script-created parser (meaning that it can be closed by the document.open() and document.close() methods, and that the tokenizer will wait for an explicit call to document.close() before emitting an end-of-file token). The encoding confidence is irrelevant.

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

  26. If type is an ASCII case-insensitive match for the string "replace", then, for historical reasons, set it to the string "text/html".

    Otherwise:

    If the type string contains a U+003B SEMICOLON character (;), remove the first such character and all characters from it up to the end of the string.

    Strip leading and trailing whitespace from type.

  27. If type is not now an ASCII case-insensitive match for the string "text/html", then act as if the tokenizer had emitted a start tag token with the tag name "pre" followed by a single U+000A LINE FEED (LF) character, then switch the HTML parser’s tokenizer to the §8.2.4.7 PLAINTEXT state.

  28. Remove all the entries in the browsing context’s session history after the current entry. If the current entry is the last entry in the session history, then no entries are removed.

    This doesn’t necessarily have to affect the user agent’s user interface.

  29. Remove any tasks queued by the history traversal task source that are associated with any Document objects in the top-level browsing context’s document family.

  30. Remove any earlier entries that share the same Document.

  31. If replace is false, then add a new entry, just before the last entry, and associate with the new entry the text that was parsed by the previous parser associated with the Document object, as well as the state of the document at the start of these steps. This allows the user to step backwards in the session history to see the page before it was blown away by the document.open() call. This new entry does not have a Document object, so a new one will be created if the session history is traversed to that entry.

  32. Set the Document's fired unload flag to false. (It could have been set to true during the unload step above.)

  33. Finally, set the insertion point to point at just before the end of the input stream (which at this point will be empty).

  34. Return the Document on which the method was invoked.

The document.open() method does not affect whether a Document is ready for post-load tasks or completely loaded.

When called with four arguments, the open() method on the Document object must call the open() method on the Window object of the Document object, with the same arguments as the original call to the open() method, and return whatever that method returned. If the Document object has no Window object, then the method must throw an "InvalidAccessError" DOMException.

7.3.2. Closing the input stream

document . close()

Closes the input stream that was opened by the document.open() method.

Throws an InvalidStateError exception if the Document is an XML document.

The close() method must run the following steps:

  1. If the Document object is not flagged as an HTML document, throw an InvalidStateError exception and abort these steps.
  2. If there is no script-created parser associated with the document, then abort these steps.
  3. Insert an explicit "EOF" character at the end of the parser’s input stream.
  4. If there is a pending parsing-blocking script, then abort these steps.
  5. Run the tokenizer, processing resulting tokens as they are emitted, and stopping when the tokenizer reaches the explicit "EOF" character or spins the event loop.

7.3.3. document.write()

document . write(text...)

In general, adds the given string(s) to the Document’s input stream.

This method has very idiosyncratic behavior. In some cases, this method can affect the state of the HTML parser while the parser is running, resulting in a DOM that does not correspond to the source of the document (e.g., if the string written is the string "<plaintext>" or "<!--"). In other cases, the call can clear the current page first, as if document.open() had been called. In yet more cases, the method is simply ignored, or throws an exception. To make matters worse, the exact behavior of this method can in some cases be dependent on network latency, which can lead to failures that are very hard to debug. For all these reasons, use of this method is strongly discouraged.

This method throws an InvalidStateError exception when invoked on XML documents.

Document objects have an ignore-destructive-writes counter, which is used in conjunction with the processing of script elements to prevent external scripts from being able to use document.write() to blow away the document by implicitly calling document.open(). Initially, the counter must be set to zero.

The document.write(...) method must act as follows:

  1. If the method was invoked on an XML document, throw an InvalidStateError exception and abort these steps.

  2. If the Document object is not an active document, then abort these steps.
  3. If the insertion point is undefined and either the Document’s ignore-opens-during-unload counter is greater than zero or the Document’s ignore-destructive-writes counter is greater than zero, abort these steps.

  4. If the insertion point is undefined, call the open() method on the document object (with no arguments). If the user refused to allow the document to be unloaded, then abort these steps. Otherwise, the insertion point will point at just before the end of the (empty) input stream.

  5. Insert the string consisting of the concatenation of all the arguments to the method into the input stream just before the insertion point.

  6. If the Document object’s reload override flag is set, then append the string consisting of the concatenation of all the arguments to the method to the Document’s reload override buffer.

  7. If there is no pending parsing-blocking script, have the HTML parser process the characters that were inserted, one at a time, processing resulting tokens as they are emitted, and stopping when the tokenizer reaches the insertion point or when the processing of the tokenizer is aborted by the tree construction stage (this can happen if a script end tag token is emitted by the tokenizer).

    If the document.write() method was called from script executing inline (i.e., executing because the parser parsed a set of script tags), then this is a reentrant invocation of the parser.

  8. Finally, return from the method.

7.3.4. document.writeln()

document . writeln(text...)

Adds the given string(s) to the Document’s input stream, followed by a newline character. If necessary, calls the open() method implicitly first.

This method throws an InvalidStateError exception when invoked on XML documents.

The document.writeln(...) method, when invoked, must act as if the document.write() method had been invoked with the same argument(s), plus an extra argument consisting of a string containing a single line feed character (U+000A).

7.4. Timers

The setTimeout() and setInterval() methods allow authors to schedule timer-based callbacks.

[NoInterfaceObject, Exposed=(Window,Worker)]
interface WindowTimers {
  long setTimeout((Function or DOMString) handler, optional long timeout = 0, any... arguments);
  void clearTimeout(optional long handle = 0);
  long setInterval((Function or DOMString) handler, optional long timeout = 0, any... arguments);
  void clearInterval(optional long handle = 0);
};
Window implements WindowTimers;
WorkerGlobalScope implements WindowTimers;
handle = window . setTimeout( handler [, timeout [, arguments... ] ] )

Schedules a timeout to run handler after timeout milliseconds. Any arguments are passed straight through to the handler.

handle = window . setTimeout( code [, timeout ] )

Schedules a timeout to compile and run code after timeout milliseconds.

window . clearTimeout( handle )

Cancels the timeout set with setTimeout() or setInterval() identified by handle.

handle = window . setInterval( handler [, timeout [, arguments... ] ] )

Schedules a timeout to run handler every timeout milliseconds. Any arguments are passed straight through to the handler.

handle = window . setInterval( code [, timeout ] )

Schedules a timeout to compile and run code every timeout milliseconds.

window . clearInterval( handle )

Cancels the timeout set with setInterval() or setTimeout() identified by handle.

Timers can be nested; after five such nested timers, however, the interval is forced to be at least four milliseconds.

This API does not guarantee that timers will run exactly on schedule. Delays due to CPU load, other tasks, etc, are to be expected.

Objects that implement the WindowTimers interface have a list of active timers. Each entry in this lists is identified by a number, which must be unique within the list for the lifetime of the object that implements the WindowTimers interface.


The setTimeout() method must return the value returned by the timer initialization steps, passing them the method’s arguments, the object on which the method for which the algorithm is running is implemented (a Window or WorkerGlobalScope object) as the method context, and the repeat flag set to false.

The setInterval() method must return the value returned by the timer initialization steps, passing them the method’s arguments, the object on which the method for which the algorithm is running is implemented (a Window or WorkerGlobalScope object) as the method context, and the repeat flag set to true.

The clearTimeout() and clearInterval() methods must clear the entry identified as handle from the list of active timers of the WindowTimers object on which the method was invoked, if any, where handle is the argument passed to the method. (If handle does not identify an entry in the list of active timers of the WindowTimers object on which the method was invoked, the method does nothing.)

Because clearTimeout() and clearInterval() clear entries from the same list, either method can be used to clear timers created by setTimeout() or setInterval().


The timer initialization steps, which are invoked with some method arguments, a method context, a repeat flag which can be true or false, and optionally (and only if the repeat flag is true) a previous handle, are as follows:

  1. Let method context proxy be method context if that is a WorkerGlobalScope object, or else the WindowProxy that corresponds to method context.
  2. If previous handle was provided, let handle be previous handle; otherwise, let handle be a user-agent-defined integer that is greater than zero that will identify the timeout to be set by this call in the list of active timers.
  3. If previous handle was not provided, add an entry to the list of active timers for handle.
  4. Let callerRealm be the current Realm Record, and calleeRealm be method context’s JavaScript realm.
  5. Let task be a task that runs the following substeps:

    1. If the entry for handle in the list of active timers has been cleared, then abort this task’s substeps.
    2. Run the appropriate set of steps from the following list:

      If the first method argument is a Function

      Invoke the Function. Use the third and subsequent method arguments (if any) as the arguments for invoking the Function. Use method context proxy as the Callback this value. [ECMA-262]

      Otherwise
      1. Perform HostEnsureCanCompileStrings(callerRealm, calleeRealm). If this throws an exception, report the exception.
      2. Let script source be the first method argument.
      3. Let script language be JavaScript.
      4. Let settings object be method context’s environment settings object.
      5. Create a script using script source as the script source, the URL where script source can be found, scripting language as the scripting language, and settings object as the environment settings object.
    3. If the repeat flag is true, then call timer initialization steps again, passing them the same method arguments, the same method context, with the repeat flag still set to true, and with the previous handle set to handler.
  6. Let timeout be the second method argument.
  7. If the currently running task is a task that was created by this algorithm, then let nesting level be the task’s timer nesting level. Otherwise, let nesting level be zero.
  8. If nesting level is greater than 5, and timeout is less than 4, then increase timeout to 4.
  9. Increment nesting level by one.
  10. Let task’s timer nesting level be nesting level.
  11. Return handle, and then continue running this algorithm in parallel.
  12. If method context is a Window object, wait until the Document associated with method context has been fully active for a further timeout milliseconds (not necessarily consecutively).

    Otherwise, method context is a WorkerGlobalScope object; wait until timeout milliseconds have passed with the worker not suspended (not necessarily consecutively).

  13. Wait until any invocations of this algorithm that had the same method context, that started before this one, and whose timeout is equal to or less than this one’s, have completed.

    Argument conversion as defined by Web IDL (for example, invoking toString() methods on objects passed as the first argument) happens in the algorithms defined in Web IDL, before this algorithm is invoked.

    So for example, the following rather silly code will result in the log containing "ONE TWO ":
    var log = '';function logger(s) { log += s + ' '; }
    
    setTimeout({ toString: function () {
    setTimeout("logger('ONE')", 100);
    return "logger('TWO')";
    } }, 100);
  14. Optionally, wait a further user-agent defined length of time.

    This is intended to allow user agents to pad timeouts as needed to optimize the power usage of the device. For example, some processors have a low-power mode where the granularity of timers is reduced; on such platforms, user agents can slow timers down to fit this schedule instead of requiring the processor to use the more accurate mode with its associated higher power usage.

  15. Queue the task task.

    Once the task has been processed, if the repeat flag is false, it is safe to remove the entry for handle from the list of active timers (there is no way for the entry’s existence to be detected past this point, so it does not technically matter one way or the other).

The task source for these tasks is the timer task source.

To run tasks of several milliseconds back to back without any delay, while still yielding back to the browser to avoid starving the user interface (and to avoid the browser killing the script for hogging the CPU), simply queue the next timer before performing work:
function doExpensiveWork() {var done = false;
// ...
// this part of the function takes up to five milliseconds
// set done to true if we’re done
// ...
return done;
}

function rescheduleWork() {
var handle = setTimeout(rescheduleWork, 0); // preschedule next iteration
if (doExpensiveWork())
  clearTimeout(handle); // clear the timeout if we don’t need it
}

function scheduleWork() {
setTimeout(rescheduleWork, 0);
}

scheduleWork(); // queues a task to do lots of work

7.5. User prompts

7.5.1. Simple dialogs

window . alert(message)

Displays a modal alert with the given message, and waits for the user to dismiss it.

result = window . confirm(message)

Displays a modal OK/Cancel prompt with the given message, waits for the user to dismiss it, and returns true if the user clicks OK and false if the user clicks Cancel.

result = window . prompt(message [, default] )

Displays a modal text field prompt with the given message, waits for the user to dismiss it, and returns the value that the user entered. If the user cancels the prompt, then returns null instead. If the second argument is present, then the given value is used as a default.

Logic that depends on tasks or microtasks, such as media elements loading their media data, are stalled when these methods are invoked.

To optionally truncate a simple dialog string s, return either s itself or some string derived from s that is shorter. User agents should not provide UI for displaying the elided portion of s, as this makes it too easy for abusers to create dialogs of the form "Important security alert! Click 'Show More' for full details!".

For example, a user agent might want to only display the first 100 characters of a message. Or, a user agent might replace the middle of the string with "…". These types of modifications can be useful in limiting the abuse potential of unnaturally large, trustworthy-looking system dialogs.

The alert(message) method, when invoked, must run the following steps:

  1. If the event loop’s termination nesting level is non-zero, optionally abort these steps.
  2. If the active sandboxing flag set of the active document of the responsible browsing context specified by the incumbent settings object has the sandboxed modals flag set, then abort these steps.
  3. Optionally, abort these steps. (For example, the user agent might give the user the option to ignore all alerts, and would thus abort at this step whenever the method was invoked.)
  4. If the method was invoked with no arguments, then let message be the empty string; otherwise, let message be the method’s first argument.
  5. Show the given message to the user.
  6. Optionally, pause while waiting for the user to acknowledge the message.

The confirm(message) method, when invoked, must run the following steps:

  1. If the event loop’s termination nesting level is non-zero, optionally abort these steps, returning false.
  2. If the active sandboxing flag set of the active document of the responsible browsing context specified by the incumbent settings object has the sandboxed modals flag set, then return false and abort these steps.
  3. Optionally, return false and abort these steps. (For example, the user agent might give the user the option to ignore all prompts, and would thus abort at this step whenever the method was invoked.)
  4. Set message to the result of optionally truncating message.
  5. Show message to the user, and ask the user to respond with a positive or negative response.
  6. Pause until the user responds either positively or negatively.
  7. If the user responded positively, return true; otherwise, the user responded negatively: return false.

The prompt(message, default) method, when invoked, must run the following steps:

  1. If the event loop’s termination nesting level is non-zero, optionally abort these steps, returning null.
  2. If the active sandboxing flag set of the active document of the responsible browsing context specified by the incumbent settings object has the sandboxed modals flag set, then return null and abort these steps.
  3. Optionally, return null and abort these steps. (For example, the user agent might give the user the option to ignore all prompts, and would thus abort at this step whenever the method was invoked.)
  4. Set message to the result of optionally truncating message.
  5. Set default to the result of optionally truncating default.
  6. Show message to the user, and ask the user to either respond with a string value or abort. The response must be defaulted to the value given by default.
  7. Pause while waiting for the user’s response.
  8. If the user aborts, then return null; otherwise, return the string that the user responded with.

7.5.2. Printing

window . print()

Prompts the user to print the page.

When the print() method is invoked, if the Document is ready for post-load tasks, then the user agent must run the printing steps in parallel. Otherwise, the user agent must only set the print when loaded flag on the Document.

User agents should also run the printing steps whenever the user asks for the opportunity to obtain a physical form (e.g., printed copy), or the representation of a physical form (e.g., PDF copy), of a document.

The printing steps are as follows:

  1. The user agent may display a message to the user or abort these steps (or both).

    For instance, a kiosk browser could silently ignore any invocations of the print() method.

    For instance, a browser on a mobile device could detect that there are no printers in the vicinity and display a message saying so before continuing to offer a "save to PDF" option.

  2. If the active sandboxing flag set of the active document of the responsible browsing context specified by the incumbent settings object has the sandboxed modals flag set, then abort these steps.

    If the printing dialog is blocked by a Document’s sandbox, then neither the beforeprint nor afterprint events will be fired.

  3. The user agent must fire a simple event named beforeprint at the Window object of the Document that is being printed, as well as any nested browsing contexts in it.

    The beforeprint event can be used to annotate the printed copy, for instance adding the time at which the document was printed.

  4. The user agent should offer the user the opportunity to obtain a physical form (or the representation of a physical form) of the document. The user agent may wait for the user to either accept or decline before returning; if so, the user agent must pause while the method is waiting. Even if the user agent doesn’t wait at this point, the user agent must use the state of the relevant documents as they are at this point in the algorithm if and when it eventually creates the alternate form.

  5. The user agent must fire a simple event named afterprint at the Window object of the Document that is being printed, as well as any nested browsing contexts in it.

    The afterprint event can be used to revert annotations added in the earlier event, as well as showing post-printing UI. For instance, if a page is walking the user through the steps of applying for a home loan, the script could automatically advance to the next step after having printed a form or other.

7.5.3. Dialogs implemented using separate documents with showModalDialog()

This feature is in the process of being removed from the Web platform. (This is a long process that takes many years.) Using the showModalDialog() API at this time is highly discouraged.

The showModalDialog(url, argument) method, when invoked, must cause the user agent to run the following steps:

  1. Parse url relative to the API base URL specified by the entry settings object.

    If this fails, then throw a "SyntaxError" DOMException and abort these steps.

  2. If the event loop’s termination nesting level is non-zero, optionally abort these steps, returning the empty string.
  3. If the user agent is configured such that this invocation of showModalDialog() is somehow disabled, then return the empty string and abort these steps.

    User agents are expected to disable this method in certain cases to avoid user annoyance (e.g., as part of their popup blocker feature). For instance, a user agent could require that a site be safelisted before enabling this method, or the user agent could be configured to only allow one modal dialog at a time.

  4. If the active sandboxing flag set of the active document of the responsible browsing context specified by the incumbent settings object has either the sandboxed auxiliary navigation browsing context flag or sandboxed modals flag set, then return the empty string and abort these steps.

  5. Let incumbent origin be the origin specified by the incumbent settings object at the time the showModalDialog() method was called.

  6. Let the list of background browsing contexts be a list of all the browsing contexts that:

    ...as well as any browsing contexts that are nested inside any of the browsing contexts matching those conditions.

  7. Disable the user interface for all the browsing contexts in the list of background browsing contexts. This should prevent the user from navigating those browsing contexts, causing events to be sent to those browsing context, or editing any content in those browsing contexts. However, it does not prevent those browsing contexts from receiving events from sources other than the user, from running scripts, from running animations, and so forth.

  8. Create a new auxiliary browsing context, with the opener browsing context being the browsing context of the Window object on which the showModalDialog() method was called. The new auxiliary browsing context has no name.

    This browsing context’s Documents' Window objects all implement the WindowModal interface.

  9. Set all the flags in the new browsing context’s popup sandboxing flag set that are set in the active sandboxing flag set of the active document of the responsible browsing context specified by the incumbent settings object. The responsible browsing context specified by the incumbent settings object must be set as the new browsing context’s one permitted sandboxed navigator.

  10. Let the dialog arguments of the new browsing context be set to the value of argument, or the undefined value if the argument was omitted.

  11. Let the dialog arguments' origin be incumbent origin.

  12. Let the return value of the new browsing context be the undefined value.

  13. Let the return value origin be incumbent origin.

  14. Navigate the new browsing context to the absolute URL that resulted from parsing url earlier, with replacement enabled, and with the responsible browsing context specified by the incumbent settings object as the source browsing context.

  15. Spin the event loop until the new browsing context is closed. The user agent must allow the user to indicate that the browsing context is to be closed.

  16. Reenable the user interface for all the browsing contexts in the list of background browsing contexts.

  17. If the auxiliary browsing context’s return value origin at the time the browsing context was closed was the same as incumbent origin, then let return value be the auxiliary browsing context’s return value as it stood when the browsing context was closed.

    Otherwise, let return value be undefined.

  18. Return return value.

The Window objects of Documents hosted by browsing contexts created by the above algorithm must also implement the WindowModal interface.

When this happens, the members of the WindowModal interface, in JavaScript environments, appear to actually be part of the Window interface (e.g., they are on the same prototype chain as the window.alert() method).

[NoInterfaceObject]
interface WindowModal {
  readonly attribute any dialogArguments;
  attribute any returnValue;
};
window . dialogArguments

Returns the argument argument that was passed to the showModalDialog() method.

window . returnValue [ = value ]

Returns the current return value for the window.

Can be set, to change the value that will be returned by the showModalDialog() method.

Such browsing contexts have associated dialog arguments, which are stored along with the dialog arguments' origin. These values are set by the showModalDialog() method in the algorithm above, when the browsing context is created, based on the arguments provided to the method.

The dialogArguments IDL attribute, on getting, must check whether its browsing context’s active document’s origin is the same origin-domain as the dialog arguments' origin. If it is, then the browsing context’s dialog arguments must be returned unchanged. Otherwise, the IDL attribute must return undefined.

These browsing contexts also have an associated return value and return value origin. As with the previous two values, these values are set by the showModalDialog() method in the algorithm above, when the browsing context is created.

The returnValue IDL attribute, on getting, must check whether its browsing context’s active document’s origin is the same origin-domain as the current return value origin. If it is, then the browsing context’s return value must be returned unchanged. Otherwise, the IDL attribute must return undefined. On setting, the attribute must set the return value to the given new value, and the return value origin to the browsing context’s active document’s origin.

The window.close() method can be used to close the browsing context.

7.6. System state and capabilities

7.6.1. The Navigator object

The navigator attribute of the Window interface must return an instance of the Navigator interface, which represents the identity and state of the user agent (the client), and allows Web pages to register themselves as potential protocol and content handlers:

interface Navigator {
  // objects implementing this interface also implement the interfaces given below
};
Navigator implements NavigatorID;
Navigator implements NavigatorLanguage;
Navigator implements NavigatorOnLine;
Navigator implements NavigatorContentUtils;
Navigator implements NavigatorCookies;
Navigator implements NavigatorPlugins;

These interfaces are defined separately so that other specifications can re-use parts of the Navigator interface.

7.6.1.1. Client identification
[NoInterfaceObject, Exposed=(Window, Worker)]
interface NavigatorID {
  [Exposed=Window] readonly attribute DOMString appCodeName; // constant "Mozilla"
  readonly attribute DOMString appName; // constant "Netscape"
  readonly attribute DOMString appVersion;
  readonly attribute DOMString platform;
  [Exposed=Window]readonly attribute DOMString product; // constant "Gecko"
  readonly attribute DOMString userAgent;
};

In certain cases, despite the best efforts of the entire industry, Web browsers have bugs and limitations that Web authors are forced to work around.

This section defines a collection of attributes that can be used to determine, from script, the kind of user agent in use, in order to work around these issues.

Client detection should always be limited to detecting known current versions; future versions and unknown versions should always be assumed to be fully compliant.

window . navigator . appCodeName
Returns the string "Mozilla".
window . navigator . appName
Returns the string "Netscape".
window . navigator . appVersion
Returns the version of the browser.
window . navigator . platform
Returns the name of the platform.
window . navigator . product
Returns the string "Gecko".
window . navigator . taintEnabled()
Returns either the string "20030107", or the string "20100101".
window . navigator . userAgent
Returns the complete User-Agent header.
appCodeName, of type DOMString, readonly
Must return the string "Mozilla".
appName, of type DOMString, readonly
Must return the string "Netscape".
appVersion, of type DOMString, readonly
Must return either the string "4.0" or a string representing the version of the browser in detail, e.g., "1.0 (VMS; en-US) Mellblomenator/9000".
platform, of type DOMString, readonly
Must return either the empty string or a string representing the platform on which the browser is executing, e.g., "MacIntel", "Win32", "FreeBSD i386", "WebTV OS".
product, of type DOMString, readonly
Must return the string "Gecko".
taintEnabled()
Must return false.
userAgent, of type DOMString, readonly
Must return the string used for the value of the "User-Agent" header in HTTP requests, or the empty string if no such header is ever sent.

Any information in this API that varies from user to user can be used to profile the user. In fact, if enough such information is available, a user can actually be uniquely identified. For this reason, user agent implementors are strongly urged to include as little information in this API as possible.

7.6.1.2. Language preferences
[NoInterfaceObject, Exposed=(Window, Worker)]
interface NavigatorLanguage {
  readonly attribute DOMString? language;
  readonly attribute DOMString[] languages;
};
window . navigator . language
Returns a language tag representing the user’s preferred language.
window . navigator . languages
Returns an array of language tags representing the user’s preferred languages, with the most preferred language first. The most preferred language is the one returned by navigator.language.

A languagechange event is fired at the Window or WorkerGlobalScope object when the user agent’s understanding of what the user’s preferred languages are changes.

language, of type DOMString, readonly, nullable
Must return a valid BCP 47 language tag representing either a plausible language or the user’s most preferred language. [BCP47]
languages, of type DOMString[], readonly

Must return a read only array of valid BCP 47 language tags representing either one or more plausible languages, or the user’s preferred languages, ordered by preference with the most preferred language first. The same object must be returned until the user agent needs to return different values, or values in a different order. [BCP47]

Whenever the user agent needs to make the navigator.languages attribute of a Window or WorkerGlobalScope object return a new set of language tags, the user agent must queue a task to fire a simple event named languagechange at the Window or WorkerGlobalScope object and wait until that task begins to be executed before actually returning a new value.

The task source for this task is the DOM manipulation task source.

To determine a plausible language, the user agent should bear in mind the following:

To avoid introducing any more fingerprinting vectors, user agents should use the same list for the APIs defined in this function as for the HTTP Accept-Language header.

7.6.1.3. Custom scheme handler: the registerProtocolHandler() method
[NoInterfaceObject]
interface NavigatorContentUtils {
  // content handler registration
  void registerProtocolHandler(DOMString scheme, DOMString url, DOMString title);
  void unregisterProtocolHandler(DOMString scheme, DOMString url);
};

The registerProtocolHandler() method allows Web sites to register themselves as possible handlers for particular schemes. For example, an online telephone messaging service could register itself as a handler of the sms: scheme, so that if the user clicks on such a link, he is given the opportunity to use that Web site. [RFC5724]

window . navigator . registerProtocolHandler(scheme, url, title)

Registers a handler for the given scheme, at the given URL, with the given title.

The string "%s" in the URL is used as a placeholder for where to put the URL of the content to be handled.

Throws a "SecurityError" DOMException if the user agent blocks the registration (this might happen if trying to register as a handler for "http", for instance).

Throws a "SyntaxError" DOMException if the "%s" string is missing in the URL.

User agents may, within the constraints described in this section, do whatever they like when the method is called. A user agent could, for instance, prompt the user and offer the user the opportunity to add the site to a shortlist of handlers, or make the handler his default, or cancel the request. User agents could provide such a UI through modal UI or through a non-modal transient notification interface. user agents could also simply silently collect the information, providing it only when relevant to the user.

User agents should keep track of which sites have registered handlers (even if the user has declined such registrations) so that the user is not repeatedly prompted with the same request.

The arguments to the method have the following meanings and corresponding implementation requirements. The requirements that involve throwing exceptions must be processed in the order given below, stopping at the first exception thrown. (So the exceptions for the first argument take precedence over the exceptions for the second argument.)

scheme (registerProtocolHandler())

A scheme, such as "mailto" or "web+auth". The scheme must be compared in an ASCII case-insensitive manner by user agents for the purposes of comparing with the scheme part of URLs that they consider against the list of registered handlers.

The scheme value, if it contains a colon (as in "mailto:"), will never match anything, since schemes don’t contain colons.

If the registerProtocolHandler() method is invoked with a scheme that is neither a safelisted scheme nor a scheme whose value starts with the substring "web+" and otherwise contains only lowercase ASCII letters, and whose length is at least five characters (including the "web+" prefix), the user agent must throw a "SyntaxError" DOMException.

The following schemes are the safelisted schemes:

  • bitcoin
  • geo
  • im
  • irc
  • ircs
  • magnet
  • mailto
  • mms
  • news
  • nntp
  • openpgp4fpr
  • sip
  • sms
  • smsto
  • ssh
  • tel
  • urn
  • webcal
  • wtai
  • xmpp

This list can be changed. If there are schemes that should be added, please send feedback.

This list excludes any schemes that could reasonably be expected to be supported inline, e.g., in an iframe, such as http or (more theoretically) gopher. If those were supported, they could potentially be used in man-in-the-middle attacks, by replacing pages that have frames with such content with content under the control of the protocol handler. If the user agent has native support for the schemes, this could further be used for cookie-theft attacks.

url

A string used to build the URL of the page that will handle the requests.

User agents must throw a "SyntaxError" DOMException if the url argument passed to one of these methods does not contain the exact literal string "%s".

User agents must throw a "SyntaxError" DOMException if parsing the url argument relative to the API base URL specified by the entry settings object is not successful.

The resulting URL string would by definition not be a valid URL as it would include the string "%s" which is not a valid component in a URL.

User agents must throw a "SecurityError" DOMException if the resulting absolute URL has an origin that differs from the origin specified by the entry settings object.

This is forcibly the case if the %s placeholder is in the scheme, host, or port parts of the URL.

The resulting URL string is the proto-URL. It identifies the handler for the purposes of the methods described below.

When the user agent uses this handler, it must replace the first occurrence of the exact literal string "%s" in the url argument with an escaped version of the absolute URL of the content in question (as defined below), then parse the resulting URL, relative to the API base URL specified by the entry settings object at the time the registerProtocolHandler() method was invoked, and then navigate an appropriate browsing context to the resulting URL.

To get the escaped version of the absolute URL of the content in question, the user agent must replace every character in that absolute URL that is not a character in the URL default encode set with the result of UTF-8 percent encoding that character.

title

A descriptive title of the handler, which the user agent might use to remind the user what the site in question is.

This section does not define how the pages registered by these methods are used, beyond the requirements on how to process the url value (see above). To some extent, the processing model for navigating across documents defines some cases where these methods are relevant, but in general user agents may use this information wherever they would otherwise consider handing content to native plugins or helper applications.


In addition to the registration method, there is also a method for unregistering a handler.

window . navigator . unregisterProtocolHandler(scheme, url)

Unregisters the handler given by the arguments.


The unregisterProtocolHandler() method must unregister the handler described by the two arguments to the method, where the first argument gives the scheme and the second gives the string used to build the URL of the page that will handle the requests.

The first argument must be compared to the schemes for which custom protocol handlers are registered in an ASCII case-insensitive manner to find the relevant handlers.

The second argument must be preprocessed as described below, and if that is successful, must then be matched against the proto-URLs of the relevant handlers to find the described handler.


The second argument of the two methods described above must be preprocessed as follows:

  1. If the string does not contain the substring "%s", abort these steps. There’s no matching handler.

  2. Parse the string relative to the entry settings object. If this fails, then throw a "SyntaxError" DOMException.

  3. If the resulting URL record’s origin is not the same origin as the origin specified by the entry settings object, throw a "SecurityError" DOMException.

  4. Return the resulting URL string as the result of preprocessing the argument.

    7.6.1.3.1. Security and privacy

    These mechanisms can introduce a number of concerns, in particular privacy concerns.

    Hijacking all Web usage. User agents should not allow schemes that are key to its normal operation, such as http or https, to be rerouted through third-party sites. This would allow a user’s activities to be trivially tracked, and would allow user information, even in secure connections, to be collected.

    Hijacking defaults. User agents are strongly urged to not automatically change any defaults, as this could lead the user to send data to remote hosts that the user is not expecting. New handlers registering themselves should never automatically cause those sites to be used.

    Registration spamming. User agents should consider the possibility that a site will attempt to register a large number of handlers, possibly from multiple domains (e.g., by redirecting through a series of pages each on a different domain, and each registering a scheme handler — analogous practices abusing other Web browser features have been used by pornography Web sites for many years). User agents should gracefully handle such hostile attempts, protecting the user.

    Misleading titles. User agents should not rely wholly on the title argument to the methods when presenting the registered handlers to the user, since sites could easily lie. For example, a site hostile.example.net could claim that it was registering the "Cuddly Bear Happy Scheme Handler". User agents should therefore use the handler’s domain in any UI along with any title.

    Hostile handler metadata. User agents should protect against typical attacks against strings embedded in their interface, for example ensuring that markup or escape characters in such strings are not executed, that null bytes are properly handled, that over-long strings do not cause crashes or buffer overruns, and so forth.

    Leaking Intranet URLs. The mechanism described in this section can result in secret Intranet URLs being leaked, in the following manner:

    1. The user registers a third-party content handler as the default handler for a scheme.
    2. The user then browses his corporate Intranet site and accesses a link that uses that scheme.
    3. The user agent contacts the third party and hands the third party the URL to the Intranet content.

    No actual confidential file data is leaked in this manner, but the URLs themselves could contain confidential information. For example, the URL could be cuddly://www.corp.example.com/upcoming-aquisitions/the-sample-company.egf, which might tell the third party that Example Corporation is intending to merge with The Sample Company. Implementors might wish to consider allowing administrators to disable this feature for certain subdomains, or schemes.

    Leaking credentials. User agents must never send username or password information in the URLs that are escaped and included sent to the handler sites. User agents may even avoid attempting to pass to Web-based handlers the URLs of resources that are known to require authentication to access, as such sites would be unable to access the resources in question without prompting the user for credentials themselves (a practice that would require the user to know whether to trust the third-party handler, a decision many users are unable to make or even understand).

    Interface interference. User agents should be prepared to handle intentionally long arguments to the methods. For example, if the user interface exposed consists of an "accept" button and a "deny" button, with the "accept" binding containing the name of the handler, it’s important that a long name not cause the "deny" button to be pushed off the screen.

    Fingerprinting users. Since a site can detect if it has attempted to register a particular handler or not, whether or not the user responds, the mechanism can be used to store data. User agents are therefore strongly urged to treat registrations in the same manner as cookies: clearing cookies for a site should also clear all registrations for that site, and disabling cookies for a site should also disable registrations.

7.6.1.4. Cookies
[NoInterfaceObject]
interface NavigatorCookies {
  readonly attribute boolean cookieEnabled;
};
window . navigator . cookieEnabled
Returns false if setting a cookie will be ignored, and true otherwise.

The cookieEnabled attribute must return true if the user agent attempts to handle cookies according to the cookie specification, and false if it ignores cookie change requests. [COOKIES]

7.6.1.5. Plugins
[NoInterfaceObject]
  interface NavigatorPlugins {
  [SameObject] readonly attribute PluginArray plugins;
  [SameObject] readonly attribute MimeTypeArray mimeTypes;
  boolean javaEnabled();
};
interface PluginArray {
  void refresh(optional boolean reload = false);
  readonly attribute unsigned long length;
  getter Plugin? item(unsigned long index);
  getter Plugin? namedItem(DOMString name);
};
interface MimeTypeArray {
  readonly attribute unsigned long length;
  getter MimeType? item(unsigned long index);
  getter MimeType? namedItem(DOMString name);
};
interface Plugin {
  readonly attribute DOMString name;
  readonly attribute DOMString description;
  readonly attribute DOMString filename;
  readonly attribute unsigned long length;
  getter MimeType? item(unsigned long index);
  getter MimeType? namedItem(DOMString name);
};
interface MimeType {
  readonly attribute DOMString type;
  readonly attribute DOMString description;
  readonly attribute DOMString suffixes; // comma-separated
  readonly attribute Plugin enabledPlugin;
};
window . navigator . plugins . refresh( [ refresh ] )
Updates the lists of supported plugins and MIME types for this page, and reloads the page if the lists have changed.
window . navigator . plugins . length
Returns the number of plugins, represented by Plugin objects, that the user agent reports.
plugin = window . navigator . plugins . item(index)
window . navigator . plugins[index]
Returns the specified Plugin object.
plugin = window . navigator . plugins . item(name)
window . navigator . plugins[name]
Returns the Plugin object for the plugin with the given name.
window . navigator . mimeTypes . length
Returns the number of MIME types, represented by MimeType objects, supported by the plugins that the user agent reports.
mimeType = window . navigator . mimeTypes . item(index)
window . navigator . mimeTypes[index]
Returns the specified MimeType object.
mimeType = window . navigator . mimeTypes . item(name)
window . navigator . mimeTypes[name]
Returns the MimeType object for the given MIME type.
plugin . name
Returns the plugin’s name.
plugin . description
Returns the plugin’s description.
plugin . filename
Returns the plugin library’s filename, if applicable on the current platform.
plugin . length
Returns the number of MIME types, represented by MimeType objects, supported by the plugin.
mimeType = plugin . item(index)
plugin[index]
Returns the specified MimeType object.
mimeType = plugin . item(name)
plugin[name]
Returns the MimeType object for the given MIME type.
mimeType . type
Returns the MIME type.
mimeType . description
Returns the MIME type’s description.
mimeType . suffixes
Returns the MIME type’s typical file extensions, in a comma-separated list.
mimeType . enabledPlugin
Returns the Plugin object that implements this MIME type.
window . navigator . javaEnabled()
Returns true if there’s a plugin that supports the MIME type "application/x-java-vm".

The plugins attribute must return a PluginArray object.

The mimeTypes attribute must return a MimeTypeArray object.


A PluginArray object represents none, some, or all of the plugins supported by the user agent, each of which is represented by a Plugin object. Each of these Plugin objects may be hidden plugins. A hidden plugin can’t be enumerated, but can still be inspected by using its name.

The fewer plugins are represented by the PluginArray object, and of those, the more that are hidden, the more the user’s privacy will be protected. Each exposed plugin increases the number of bits that can be derived for fingerprinting. Hiding a plugin helps, but unless it is an extremely rare plugin, it is likely that a site attempting to derive the list of plugins can still determine whether the plugin is supported or not by probing for it by name (the names of popular plugins are widely known). Therefore not exposing a plugin at all is preferred. Unfortunately, many legacy sites use this feature to determine, for example, which plugin to use to play video. Not exposing any plugins at all might therefore not be entirely plausible.

The PluginArray objects created by a user agent must not be live. The set of plugins represented by the objects must not change once an object is created, except when it is updated by the refresh() method.

Each plugin represented by a PluginArray can support a number of MIME types. For each such plugin, the user agent must pick one or more of these MIME types to be those that are explicitly supported.

The explicitly supported MIME types of a plugin are those that are exposed through the Plugin and MimeTypeArray interfaces. As with plugins themselves, any variation between users regarding what is exposed allows sites to fingerprint users. User agents are therefore encouraged to expose the same MIME types for all users of a plugin, regardless of the actual types supported... at least, within the constraints imposed by compatibility with legacy content.

The supported property indices of a PluginArray object are the numbers from zero to the number of non-hidden plugins represented by the object, if any.

The length attribute must return the number of non-hidden plugins represented by the object.

The item() method of a PluginArray object must return null if the argument is not one of the object’s supported property indices, and otherwise must return the result of running the following steps, using the method’s argument as index:

  1. Let list be the Plugin objects representing the non-hidden plugins represented by the PluginArray object.
  2. Sort list alphabetically by the name of each Plugin.
  3. Return the indexth entry in list.

It is important for privacy that the order of plugins not leak additional information, e.g., the order in which plugins were installed.

The supported property names of a PluginArray object are the values of the name attributes of all the Plugin objects represented by the PluginArray object. The properties exposed in this way must be unenumerable.

The namedItem() method of a PluginArray object must return null if the argument is not one of the object’s supported property names, and otherwise must return the Plugin object, of those represented by the PluginArray object, that has a name equal to the method’s argument.

The refresh() method of the PluginArray object of a Navigator object, when invoked, must check to see if any plugins have been installed or reconfigured since the user agent created the PluginArray object. If so, and the method’s argument is true, then the user agent must act as if the location.reload() method was called instead. Otherwise, the user agent must update the PluginArray object and MimeTypeArray object created for attributes of that Navigator object, and the Plugin and MimeType objects created for those PluginArray and MimeTypeArray objects, using the same Plugin objects for cases where the name is the same, and the same MimeType objects for cases where the type is the same, and creating new objects for cases where there were no matching objects immediately prior to the refresh() call. Old Plugin and MimeType objects must continue to return the same values that they had prior to the update, though naturally now the data is stale and may appear inconsistent (for example, an old MimeType entry might list as its enabledPlugin a Plugin object that no longer lists that MimeType as a supported MimeType).


A MimeTypeArray object represents the MIME types explicitly supported by plugins supported by the user agent, each of which is represented by a MimeType object.

The MimeTypeArray objects created by a user agent must not be live. The set of MIME types represented by the objects must not change once an object is created, except when it is updated by the PluginArray object’s refresh() method.

The supported property indices of a MimeTypeArray object are the numbers from zero to the number of MIME types explicitly supported by non-hidden plugins represented by the corresponding PluginArray object, if any.

The length attribute must return the number of MIME types explicitly supported by non-hidden plugins represented by the corresponding PluginArray object, if any.

The item() method of a MimeTypeArray object must return null if the argument is not one of the object’s supported property indices, and otherwise must return the result of running the following steps, using the method’s argument as index:

  1. Let list be the MimeType objects representing the MIME types explicitly supported by non-hidden plugins represented by the corresponding PluginArray object, if any.
  2. Sort list alphabetically by the type of each MimeType.
  3. Return the indexth entry in list.

It is important for privacy that the order of MIME types not leak additional information, e.g., the order in which plugins were installed.

The supported property names of a MimeTypeArray object are the values of the type attributes of all the MimeType objects represented by the MimeTypeArray object. The properties exposed in this way must be unenumerable.

The namedItem() method of a MimeTypeArray object must return null if the argument is not one of the object’s supported property names, and otherwise must return the MimeType object that has a type equal to the method’s argument.


A Plugin object represents a plugin. It has several attributes to provide details about the plugin, and can be enumerated to obtain the list of MIME types that it explicitly supports.

The Plugin objects created by a user agent must not be live. The set of MIME types represented by the objects, and the values of the objects' attributes, must not change once an object is created, except when updated by the PluginArray object’s refresh() method.

The reported MIME types for a Plugin object are the MIME types explicitly supported by the corresponding plugin when this object was last created or updated by PluginArray.refresh(), whichever happened most recently.

The supported property indices of a Plugin object are the numbers from zero to the number of reported MIME types.

The length attribute must return the number of reported MIME types.

The item() method of a Plugin object must return null if the argument is not one of the object’s supported property indices, and otherwise must return the result of running the following steps, using the method’s argument as index:

  1. Let list be the MimeType objects representing the reported MIME types.
  2. Sort list alphabetically by the type of each MimeType.
  3. Return the indexth entry in list.

It is important for privacy that the order of MIME types not leak additional information, e.g., the order in which plugins were installed.

The supported property names of a Plugin object are the values of the type attributes of the MimeType objects representing the reported MIME types. The properties exposed in this way must be unenumerable.

The namedItem() method of a Plugin object must return null if the argument is not one of the object’s supported property names, and otherwise must return the MimeType object that has a type equal to the method’s argument.

The name attribute must return the plugin’s name.

The description and filename attributes must return user-agent-defined (or, in all likelihood, plugin-defined) strings. In each case, the same string must be returned each time, except that the strings returned may change when the PluginArray.refresh() method updates the object.

If the values returned by the description or filename attributes vary between versions of a plugin, they can be used both as a fingerprinting vector and, even more importantly, as a trivial way to determine what security vulnerabilities a plugin (and thus a browser) may have. It is thus highly recommended that the description attribute just return the same value as the name attribute, and that the filename attribute return the empty string.


A MimeType object represents a MIME type that is, or was, explicitly supported by a plugin.

The MimeType objects created by a user agent must not be live. The values of the objects' attributes must not change once an object is created, except when updated by the PluginArray object’s refresh() method.

The type attribute must return the valid MIME type with no parameters describing the MIME type.

The description and suffixes attributes must return user-agent-defined (or, in all likelihood, plugin-defined) strings. In each case, the same string must be returned each time, except that the strings returned may change when the PluginArray.refresh() method updates the object.

If the values returned by the description or suffixes attributes vary between versions of a plugin, they can be used both as a fingerprinting vector and, even more importantly, as a trivial way to determine what security vulnerabilities a plugin (and thus a browser) may have. It is thus highly recommended that the description attribute just return the same value as the type attribute, and that the suffixes attribute return the empty string.

Commas in the suffixes attribute are interpreted as separating subsequent filename extensions, as in "htm,html".

The enabledPlugin attribute must return the Plugin object that represents the plugin that explicitly supported the MIME type that this MimeType object represents when this object was last created or updated by PluginArray.refresh(), whichever happened most recently.


The javaEnabled() attribute must return true if the user agent supports a plugin that supports the MIME type "application/x-java-vm"; otherwise it must return false.

7.7. Images

[Exposed=(Window, Worker)]
interface ImageBitmap {
  readonly attribute unsigned long width;
  readonly attribute unsigned long height;
};

typedef (HTMLImageElement or
        HTMLVideoElement or
        HTMLCanvasElement or
        Blob or
        ImageData or
        CanvasRenderingContext2D or
        ImageBitmap) ImageBitmapSource;
[NoInterfaceObject, Exposed=(Window, Worker)]
interface ImageBitmapFactories {
  Promise<ImageBitmap> createImageBitmap(ImageBitmapSource image);
  Promise<ImageBitmap> createImageBitmap(ImageBitmapSource image, long sx, long sy, long sw, long sh);
};
Window implements ImageBitmapFactories;
WorkerGlobalScope implements ImageBitmapFactories;

An ImageBitmap object represents a bitmap image that can be painted to a canvas without undue latency.

The exact judgement of what is undue latency of this is left up to the implementer, but in general if making use of the bitmap requires network I/O, or even local disk I/O, then the latency is probably undue; whereas if it only requires a blocking read from a GPU or system RAM, the latency is probably acceptable.

promise = Window . createImageBitmap(image [, sx, sy, sw, sh ] )

Takes image, which can be an img element, video, or canvas element, a Blob object, an ImageData object, a CanvasRenderingContext2D object, or another ImageBitmap object, and returns a promise that is resolved when a new ImageBitmap is created.

If no ImageBitmap object can be constructed, for example because the provided image data is not actually an image, then the promise is rejected instead.

If sx, sy, sw, and sh arguments are provided, the source image is cropped to the given pixels, with any pixels missing in the original replaced by transparent black. These coordinates are in the source image’s pixel coordinate space, not in CSS pixels.

Rejects the promise with an InvalidStateError exception if the source image is not in a valid state (e.g., an img element that hasn’t finished loading, or a CanvasRenderingContext2D object whose bitmap data has zero length along one or both dimensions, or an ImageData object whose data is data attribute has been neutered). Rejects the promise with a "SyntaxError" DOMException if the script is not allowed to access the image data of the source image (e.g., a video that is CORS-cross-origin, or a canvas being drawn on by a script in a worker from another origin).

imageBitmap . width

Returns the intrinsic width of the image, in CSS pixels.

imageBitmap . height

Returns the intrinsic height of the image, in CSS pixels.

An ImageBitmap object always has associated bitmap data, with a width and a height. However, it is possible for this data to be corrupted. If an ImageBitmap object’s media data can be decoded without errors, it is said to be fully decodable.

An ImageBitmap object’s bitmap has an origin-clean flag, which indicates whether the bitmap is tainted by content from a different origin. The flag is initially set to true and may be changed to false by the steps of createImageBitmap().

An ImageBitmap object can be obtained from a variety of different objects, using the createImageBitmap() method. When invoked, the method must act as follows:

If image is an img element
  1. If either the sw or sh arguments are specified but zero, return a promise rejected with an IndexSizeError exception and abort these steps.
  2. If the img element is not completely available, then return a promise rejected with an InvalidStateError exception and abort these steps.
  3. If the img element’s media data is not a bitmap (e.g., it’s a vector graphic), then return a promise rejected with an InvalidStateError exception and abort these steps.
  4. Create a new ImageBitmap object.
  5. Let the ImageBitmap object’s bitmap data be a copy of the img element’s media data, cropped to the source rectangle. If this is an animated image, the ImageBitmap object’s bitmap data must only be taken from the default image of the animation (the one that the format defines is to be used when animation is not supported or is disabled), or, if there is no such image, the first frame of the animation.
  6. If the origin of the img element’s image is not the same origin as the origin specified by the entry settings object, then set the origin-clean flag of the ImageBitmap object’s bitmap to false.
  7. Return a new promise, but continue running these steps in parallel.
  8. Resolve the promise with the new ImageBitmap object as the value.
If image is a video element
  1. If either the sw or sh arguments are specified but zero, return a promise rejected with an IndexSizeError exception and abort these steps.
  2. If the video element’s networkState attribute is NETWORK_EMPTY, then return a promise rejected with an InvalidStateError exception and abort these steps.
  3. If the video element’s readyState attribute is either HAVE_NOTHING or HAVE_METADATA, then return a promise rejected with an InvalidStateError exception and abort these steps.
  4. Create a new ImageBitmap object.
  5. Let the ImageBitmap object’s bitmap data be a copy of the frame at the current playback position, at the media resource’s intrinsic width and intrinsic height (i.e., after any aspect-ratio correction has been applied), cropped to the source rectangle.
  6. If the origin of the video element’s image is not the same origin as the origin specified by the entry settings object, then set the origin-clean flag of the ImageBitmap object’s bitmap to false.
  7. Return a new promise, but continue running these steps in parallel.
  8. Resolve the promise with the new ImageBitmap object as the value.
If image is a canvas element
  1. If either the sw or sh arguments are specified but zero, return a promise rejected with an IndexSizeError exception and abort these steps.
  2. If the canvas element’s bitmap has either a horizontal dimension or a vertical dimension equal to zero, then return a promise rejected with an InvalidStateError exception and abort these steps.
  3. Create a new ImageBitmap object.
  4. Let the ImageBitmap object’s bitmap data be a copy of the canvas element’s bitmap data, cropped to the source rectangle.
  5. Set the origin of the ImageBitmap object’s bitmap to the same value as the origin-clean flag of the canvas element’s bitmap.
  6. Return a new promise, but continue running these steps in parallel.
  7. Resolve the promise with the new ImageBitmap object as the value.
If image is a Blob object
  1. If either the sw or sh arguments are specified but zero, return a promise rejected with an IndexSizeError exception and abort these steps.
  2. There are no known native implementations of the File API closed method. Therefore this feature cannot be relied upon.

    If image is closed, then return a promise rejected with an InvalidStateError exception and abort these steps.
  3. Return a new promise, but continue running these steps in parallel.
  4. Read the Blob object’s data. If an error occurs during reading of the object, then reject the promise with null, and abort these steps.
  5. Apply the image sniffing rules to determine the file format of the image data, with MIME type of the Blob (as given by the Blob object’s type attribute) giving the official type.
  6. If the image data is not in a supported file format (e.g., it’s not actually an image at all), or if the image data is corrupted in some fatal way such that the image dimensions cannot be obtained, then reject the promise with null, and abort these steps.
  7. Create a new ImageBitmap object.
  8. Let the ImageBitmap object’s bitmap data be the image data read from the Blob object, cropped to the source rectangle. If this is an animated image, the ImageBitmap object’s bitmap data must only be taken from the default image of the animation (the one that the format defines is to be used when animation is not supported or is disabled), or, if there is no such image, the first frame of the animation.
  9. Resolve the promise with the new ImageBitmap object as the value.
If image is an ImageData object
  1. If either the sw or sh arguments are specified but zero, return a promise rejected with an IndexSizeError exception and abort these steps.
  2. If the image object’s data attribute has been neutered, return a promise rejected with an InvalidStateError exception and abort these steps.
  3. Create a new ImageBitmap object.
  4. Let the ImageBitmap object’s bitmap data be the image data given by the ImageData object, cropped to the source rectangle.
  5. Return a new promise, but continue running these steps in parallel.
  6. Resolve the promise with the new ImageBitmap object as the value.
If image is a CanvasRenderingContext2D object
  1. If either the sw or sh arguments are specified but zero, return a promise rejected with an IndexSizeError exception and abort these steps.
  2. If the CanvasRenderingContext2D object’s scratch bitmap has either a horizontal dimension or a vertical dimension equal to zero, then return a promise rejected with an InvalidStateError exception and abort these steps.
  3. Create a new ImageBitmap object.
  4. Let the ImageBitmap object’s bitmap data be a copy of the CanvasRenderingContext2D object’s scratch bitmap, cropped to the source rectangle.
  5. Set the origin-clean flag of the ImageBitmap object’s bitmap to the same value as the origin-clean flag of the CanvasRenderingContext2D object’s scratch bitmap
  6. Return a new promise, but continue running these steps in parallel.
  7. Resolve the promise with the new ImageBitmap object as the value.
If image is an ImageBitmap object
  1. If either the sw or sh arguments are specified but zero, return a promise rejected with an IndexSizeError exception and abort these steps.
  2. Create a new ImageBitmap object.
  3. Let the ImageBitmap object’s bitmap data be a copy of the image argument’s bitmap data, cropped to the source rectangle.
  4. Set the origin-clean flag of the ImageBitmap object’s bitmap to the same value as the origin-clean flag of the bitmap of the image argument.
  5. Return a new promise, but continue running these steps in parallel.
  6. Resolve the promise with the new ImageBitmap object as the value.
When the steps above require that the user agent crop bitmap data to the source rectangle, the user agent must run the following steps:
  1. Let input be the image data being cropped.
  2. If the sx, sy, sw, and sh arguments are omitted, return input.
  3. Place input on an infinite transparent black grid plane, positioned so that it’s top left corner is at the origin of the plane, with the x-coordinate increasing to the right, and the y-coordinate increasing down, and with each pixel in the input image data occupying a cell on the plane’s grid.
  4. Let output be the rectangle on the plane denoted by the rectangle whose corners are the four points (sx, sy), (sx+sw, sy), (sx+sw, sy+sh), (sx, sy+sh).

    If either sw or sh are negative, then the top-left corner of this rectangle will be to the left or above the (sx, sy) point. If any of the pixels on this rectangle are outside the area where the input bitmap was placed, then they will be transparent black in output.

  5. Return output.

The width attribute must return the ImageBitmap object’s width, in CSS pixels.

The height attribute must return the ImageBitmap object’s height, in CSS pixels.

Using this API, a sprite sheet can be precut and prepared:
var sprites = {};
function loadMySprites() {
var image = new Image();
image.src = 'mysprites.png';
var resolver;
var promise = new Promise(function (arg) { resolver = arg });
image.onload = function () {
  resolver(Promise.all(
    createImageBitmap(image,  0,  0, 40, 40).then(function (image) { sprites.woman = image }),
    createImageBitmap(image, 40,  0, 40, 40).then(function (image) { sprites.man   = image }),
    createImageBitmap(image, 80,  0, 40, 40).then(function (image) { sprites.tree  = image }),
    createImageBitmap(image,  0, 40, 40, 40).then(function (image) { sprites.hut   = image }),
    createImageBitmap(image, 40, 40, 40, 40).then(function (image) { sprites.apple = image }),
    createImageBitmap(image, 80, 40, 40, 40).then(function (image) { sprites.snake = image }),
  ));
};
return promise;
}

function runDemo() {
var canvas = document.querySelector('canvas#demo');
var context = canvas.getContext('2d');
context.drawImage(sprites.tree, 30, 10);
context.drawImage(sprites.snake, 70, 10);
}

loadMySprites().then(runDemo);

7.8. Animation Frames

Each Document associated with a top-level browsing context has a list of animation frame callbacks, which must be initially empty, and an animation frame callback identifier, which is a number which must initially be zero.

When the requestAnimationFrame() method is called, the user agent must run the following steps:

  1. Let document be the Window object’s Document object

  2. Increment document’s animation frame callback identifier by one.

  3. Append the method’s argument to document’s list of animation frame callbacks, associated with document’s animation frame callback identifier’s current value

  4. Return document’s animation frame callback identifier’s current value

When the cancelAnimationFrame() method is called, the user agent must run the following steps:

  1. Let document be the Window object’s Document object

  2. Find the entry in document’s list of animation frame callbacks that is associated with the value given by the method’s argument handle

  3. If there is such an entry, remove it from document’s list of animation frame callbacks

When the user agent is to run the animation frame callbacks for a Document document with a timestamp now, it must run the following steps:

  1. If the value returned by the document object’s hidden attribute is true, abort these steps. [PAGE-VISIBILITY]

  2. Let callbacks be a list of the entries in document’s list of animation frame callbacks, in the order in which they were added to the list.

  3. Set document’s list of animation frame callbacks to the empty list.

  4. For each entry in callbacks, in order: invoke the Web IDL callback function, passing now as the only argument, and if an exception is thrown, report the exception. [WEBIDL]

8. The HTML syntax

This section only describes the rules for resources labeled with an HTML MIME type. Rules for XML resources are discussed in the section below entitled "the XHTML syntax".

8.1. Writing HTML documents

This section only applies to documents, authoring tools, and markup generators. In particular, it does not apply to conformance checkers; conformance checkers must use the requirements given in the next section ("parsing HTML documents").

Documents must consist of the following parts, in the given order:

  1. Optionally, a single U+FEFF BYTE ORDER MARK (BOM) character.
  2. Any number of comments and space characters.
  3. A DOCTYPE.
  4. Any number of comments and space characters.
  5. The root element, in the form of an html element.
  6. Any number of comments and space characters.

The various types of content mentioned above are described in the next few sections.

In addition, there are some restrictions on how character encoding declarations are to be serialized, as discussed in the section on that topic.

Space characters before the root html element, and space characters at the start of the html element and before the head element, will be dropped when the document is parsed; space characters after the root html element will be parsed as if they were at the end of the body element. Thus, space characters around the root element do not round-trip.

It is suggested that newlines be inserted after the DOCTYPE, after any comments that are before the root element, after the html element’s start tag (if it is not omitted), and after any comments that are inside the html element but before the head element.

Many strings in the HTML syntax (e.g., the names of elements and their attributes) are case-insensitive, but only for uppercase ASCII letters and lowercase ASCII letters. For convenience, in this section this is just referred to as "case-insensitive".

8.1.1. The DOCTYPE

A DOCTYPE is a required preamble.

DOCTYPEs are required for legacy reasons. When omitted, browsers tend to use a different rendering mode that is incompatible with some specifications. Including the DOCTYPE in a document ensures that the browser makes a best-effort attempt at following the relevant specifications.

A DOCTYPE must consist of the following components, in this order:

  1. A string that is an ASCII case-insensitive match for the string "<!DOCTYPE".
  2. One or more space characters.
  3. A string that is an ASCII case-insensitive match for the string "html".
  4. Optionally, a DOCTYPE legacy string or an obsolete permitted DOCTYPE string (defined below).
  5. Zero or more space characters.
  6. A U+003E GREATER-THAN SIGN character (>).

In other words, <!DOCTYPE html>, case-insensitively.


For the purposes of HTML generators that cannot output HTML markup with the short DOCTYPE "<!DOCTYPE html>", a DOCTYPE legacy string may be inserted into the DOCTYPE (in the position defined above). This string must consist of:

  1. One or more space characters.
  2. A string that is an ASCII case-insensitive match for the string "SYSTEM".
  3. One or more space characters.
  4. A U+0022 QUOTATION MARK or U+0027 APOSTROPHE character (the quote mark).
  5. The literal string "about:legacy-compat".
  6. A matching U+0022 QUOTATION MARK or U+0027 APOSTROPHE character (i.e., the same character as in the earlier step labeled quote mark).

In other words, <!DOCTYPE html SYSTEM "about:legacy-compat"> or <!DOCTYPE html SYSTEM 'about:legacy-compat'>, case-insensitively except for the part in single or double quotes.

The DOCTYPE legacy string should not be used unless the document is generated from a system that cannot output the shorter string.


To help authors transition from HTML 4.01 and XHTML 1.1, an obsolete permitted DOCTYPE string can be inserted into the DOCTYPE (in the position defined above). This string must consist of:

  1. One or more space characters.
  2. A string that is an ASCII case-insensitive match for the string "PUBLIC".
  3. One or more space characters.
  4. A U+0022 QUOTATION MARK or U+0027 APOSTROPHE character (the first quote mark).
  5. The string from one of the cells in the first column of the table below. The row to which this cell belongs is the selected row.
  6. A matching U+0022 QUOTATION MARK or U+0027 APOSTROPHE character (i.e., the same character as in the earlier step labeled first quote mark).
  7. If a system identifier is used,
    1. One or more space characters.
    2. A U+0022 QUOTATION MARK or U+0027 APOSTROPHE character (the third quote mark).
    3. The string from the cell in the second column of the selected row.
    4. A matching U+0022 QUOTATION MARK or U+0027 APOSTROPHE character (i.e., the same character as in the earlier step labeled third quote mark).
Allowed values for public and system identifiers in an obsolete permitted DOCTYPE string.
Public identifier System identifier System identifier optional?
-//W3C//DTD HTML 4.0//EN https://www.w3.org/TR/REC-html40/strict.dtd Yes
-//W3C//DTD HTML 4.01//EN https://www.w3.org/TR/html4/strict.dtd Yes
-//W3C//DTD XHTML 1.0 Strict//EN https://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd No
-//W3C//DTD XHTML 1.1//EN https://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd No

A DOCTYPE containing an obsolete permitted DOCTYPE string is an obsolete permitted DOCTYPE. Authors should not use obsolete permitted DOCTYPEs, as they are unnecessarily long.

8.1.2. Elements

There are five different kinds of elements: void elements, raw text elements, escapable raw text elements, foreign elements, and normal elements.

Void elements
area, base, br, col, embed, hr, img, input, keygen, link, menuitem, meta, param, source, track, wbr
Raw text elements
script, style
escapable raw text elements
textarea, title
Foreign elements
Elements from the MathML namespace and the SVG namespace.
Normal elements
All other allowed html elements are normal elements.

Tags are used to delimit the start and end of elements in the markup. Raw text, escapable raw text, and normal elements have a start tag to indicate where they begin, and an end tag to indicate where they end. The start and end tags of certain normal elements can be omitted, as described below in the section on optional tags. Those that cannot be omitted must not be omitted. Void elements only have a start tag; end tags must not be specified for void elements. Foreign elements must either have a start tag and an end tag, or a start tag that is marked as self-closing, in which case they must not have an end tag.

The contents of the element must be placed between just after the start tag (which might be implied, in certain cases) and just before the end tag (which again, might be implied, in certain cases). The exact allowed contents of each individual element depend on the content model of that element, as described earlier in this specification. Elements must not contain content that their content model disallows. In addition to the restrictions placed on the contents by those content models, however, the five types of elements have additional syntactic requirements.

Void elements can’t have any contents (since there’s no end tag, no content can be put between the start tag and the end tag).

Raw text elements can have text, though it has restrictions described below.

Escapable raw text elements can have text and character references, but the text must not contain an ambiguous ampersand. There are also further restrictions described below.

Foreign elements whose start tag is marked as self-closing can’t have any contents (since, again, as there’s no end tag, no content can be put between the start tag and the end tag). Foreign elements whose start tag is not marked as self-closing can have text, character references, CDATA sections, other elements, and comments, but the text must not contain the character U+003C LESS-THAN SIGN (<) or an ambiguous ampersand.

The HTML syntax does not support namespace declarations, even in foreign elements.

For instance, consider the following HTML fragment:

<p>
<svg>
<metadata>
  <!-- this is invalid -->
  <cdr:license xmlns:cdr="https://www.example.com/cdr/metadata" name="MIT"/>
</metadata>
</svg>
</p>

The innermost element, cdr:license, is actually in the SVG namespace, as the "xmlns:cdr" attribute has no effect (unlike in XML). In fact, as the comment in the fragment above says, the fragment is actually non-conforming. This is because the SVG specification does not define any elements called "cdr:license" in the SVG namespace.

Normal elements can have text, character references, other elements, and comments, but the text must not contain the character U+003C LESS-THAN SIGN (<) or an ambiguous ampersand. Some normal elements also have yet more restrictions on what content they are allowed to hold, beyond the restrictions imposed by the content model and those described in this paragraph. Those restrictions are described below.

Tags contain a tag name, giving the element’s name. HTML elements all have names that only use alphanumeric ASCII characters. In the HTML syntax, tag names, even those for foreign elements, may be written with any mix of lower- and uppercase letters that, when converted to all-lowercase, matches the element’s tag name; tag names are case-insensitive.

8.1.2.1. Start tags

Start tags must have the following format:

  1. The first character of a start tag must be a U+003C LESS-THAN SIGN character (<).
  2. The next few characters of a start tag must be the element’s tag name.
  3. If there are to be any attributes in the next step, there must first be one or more space characters.
  4. Then, the start tag may have a number of attributes, the syntax for which is described below. Attributes must be separated from each other by one or more space characters.
  5. After the attributes, or after the tag name if there are no attributes, there may be one or more space characters. (Some attributes are required to be followed by a space. See §8.1.2.3 Attributes below.)
  6. Then, if the element is one of the void elements, or if the element is a foreign element, then there may be a single U+002F SOLIDUS character (/). This character has no effect on void elements, but on foreign elements it marks the start tag as self-closing.
  7. Finally, start tags must be closed by a U+003E GREATER-THAN SIGN character (>).
8.1.2.2. End tags

End tags must have the following format:

  1. The first character of an end tag must be a U+003C LESS-THAN SIGN character (<).
  2. The second character of an end tag must be a U+002F SOLIDUS character (/).
  3. The next few characters of an end tag must be the element’s tag name.
  4. After the tag name, there may be one or more space characters.
  5. Finally, end tags must be closed by a U+003E GREATER-THAN SIGN character (>).
8.1.2.3. Attributes

Attributes for an element are expressed inside the element’s start tag.

Attributes have a name and a value. Attribute names must consist of one or more characters other than the space characters, U+0000 NULL, U+0022 QUOTATION MARK ("), U+0027 APOSTROPHE ('), U+003E GREATER-THAN SIGN (>), U+002F SOLIDUS (/), and U+003D EQUALS SIGN (=) characters, the control characters, and any characters that are not defined by Unicode. In the HTML syntax, attribute names, even those for foreign elements, may be written with any mix of lower- and uppercase letters that are an ASCII case-insensitive match for the attribute’s name.

Attribute values are a mixture of text and character references, except with the additional restriction that the text cannot contain an ambiguous ampersand.

Attributes can be specified in four different ways:

Empty attribute syntax

Just the attribute name. The value is implicitly the empty string.

In the following example, the disabled attribute is given with the empty attribute syntax:
<input disabled>

If an attribute using the empty attribute syntax is to be followed by another attribute, then there must be a space character separating the two.

Unquoted attribute value syntax

The attribute name, followed by zero or more space characters, followed by a single U+003D EQUALS SIGN character, followed by zero or more space characters, followed by the attribute value, which, in addition to the requirements given above for attribute values, must not contain any literal space characters, any U+0022 QUOTATION MARK characters ("), U+0027 APOSTROPHE characters ('), U+003D EQUALS SIGN characters (=), U+003C LESS-THAN SIGN characters (<), U+003E GREATER-THAN SIGN characters (>), or U+0060 GRAVE ACCENT characters (`), and must not be the empty string.

In the following example, the value attribute is given with the unquoted attribute value syntax:
<input value=yes>

If an attribute using the unquoted attribute syntax is to be followed by another attribute or by the optional U+002F SOLIDUS character (/) allowed in step 6 of the start tag syntax above, then there must be a space character separating the two.

Single-quoted attribute value syntax

The attribute name, followed by zero or more space characters, followed by a single U+003D EQUALS SIGN character, followed by zero or more space characters, followed by a single U+0027 APOSTROPHE character ('), followed by the attribute value, which, in addition to the requirements given above for attribute values, must not contain any literal U+0027 APOSTROPHE characters ('), and finally followed by a second single U+0027 APOSTROPHE character (').

In the following example, the type attribute is given with the single-quoted attribute value syntax:
<input type='checkbox'>

If an attribute using the single-quoted attribute syntax is to be followed by another attribute, then there must be a space character separating the two.

Double-quoted attribute value syntax

The attribute name, followed by zero or more space characters, followed by a single U+003D EQUALS SIGN character, followed by zero or more space characters, followed by a single U+0022 QUOTATION MARK character ("), followed by the attribute value, which, in addition to the requirements given above for attribute values, must not contain any literal U+0022 QUOTATION MARK characters ("), and finally followed by a second single U+0022 QUOTATION MARK character (").

In the following example, the name attribute is given with the double-quoted attribute value syntax:
<input name="be evil">

If an attribute using the double-quoted attribute syntax is to be followed by another attribute, then there must be a space character separating the two.

There must never be two or more attributes on the same start tag whose names are an ASCII case-insensitive match for each other.


When a foreign element has one of the namespaced attributes given by the local name and namespace of the first and second cells of a row from the following table, it must be written using the name given by the third cell from the same row.

Local name Namespace Attribute name
actuate XLink namespace xlink:actuate
arcrole XLink namespace xlink:arcrole
href XLink namespace xlink:href
role XLink namespace xlink:role
show XLink namespace xlink:show
title XLink namespace xlink:title
type XLink namespace xlink:type
base XML namespace xml:base
lang XML namespace xml:lang
space XML namespace xml:space
xmlns XMLNS namespace xmlns
xlink XMLNS namespace xmlns:xlink

No other namespaced attribute can be expressed in the HTML syntax.

Whether the attributes in the table above are conforming or not is defined by other specifications (e.g., the SVG and MathML specifications); this section only describes the syntax rules if the attributes are serialized using the HTML syntax.

8.1.2.4. Optional tags

Certain tags can be omitted.

Omitting an element’s start tag in the situations described below does not mean the element is not present; it is implied, but it is still there. For example, an HTML document always has a root html element, even if the string <html> doesn’t appear anywhere in the markup.

An html element’s start tag may be omitted if the first thing inside the html element is not a comment.

For example, in the following case it’s ok to remove the "<html>" tag:
<!DOCTYPE HTML>
<html>
<head>
  <title>Hello</title>
</head>
<body>
  <p>Welcome to this example.</p>
</body>
</html>

Doing so would make the document look like this:

<!DOCTYPE HTML>

<head>
  <title>Hello</title>
</head>
<body>
  <p>Welcome to this example.</p>
</body>
</html>

This has the exact same DOM. In particular, note that white space around the root element is ignored by the parser. The following example would also have the exact same DOM:

<!DOCTYPE HTML><head>
  <title>Hello</title>
</head>
<body>
  <p>Welcome to this example.</p>
</body>
</html>

However, in the following example, removing the start tag moves the comment to before the html element:

<!DOCTYPE HTML>
<html>
<!-- where is this comment in the DOM? -->
<head>
  <title>Hello</title>
</head>
<body>
  <p>Welcome to this example.</p>
</body>
</html>

With the tag removed, the document actually turns into the same as this:

<!DOCTYPE HTML>
<!-- where is this comment in the DOM? -->
<html>
<head>
  <title>Hello</title>
</head>
<body>
  <p>Welcome to this example.</p>
</body>
</html>

This is why the tag can only be removed if it is not followed by a comment: removing the tag when there is a comment there changes the document’s resulting parse tree. Of course, if the position of the comment does not matter, then the tag can be omitted, as if the comment had been moved to before the start tag in the first place.

An html element’s end tag may be omitted if the html element is not immediately followed by a comment.

A head element’s start tag may be omitted if the element is empty, or if the first thing inside the head element is an element.

A head element’s end tag may be omitted if the head element is not immediately followed by a space character or a comment.

A body element’s start tag may be omitted if the element is empty, or if the first thing inside the body element is not a space character or a comment, except if the first thing inside the body element is a meta, link, script, style, or template element.

A body element’s end tag may be omitted if the body element is not immediately followed by a comment.

Note that in the example above, the head element start and end tags, and the body element start tag, can’t be omitted, because they are surrounded by white space:
<!DOCTYPE HTML>
<html>
<head>
  <title>Hello</title>
</head>
<body>
  <p>Welcome to this example.</p>
</body>
</html>

(The body and html element end tags could be omitted without trouble; any spaces after those get parsed into the body element anyway.)

Usually, however, white space isn’t an issue. If we first remove the white space we don’t care about:

<!DOCTYPE HTML><html><head><title>Hello</title></head><body><p>Welcome to this example.</p></body></html>

Then we can omit a number of tags without affecting the DOM:

<!DOCTYPE HTML><title>Hello</title><p>Welcome to this example.</p>

At that point, we can also add some white space back:

<!DOCTYPE HTML>
<title>Hello</title>
<p>Welcome to this example.</p>

This would be equivalent to this document, with the omitted tags shown in their parser-implied positions; the only white space text node that results from this is the newline at the end of the head element:

<!DOCTYPE HTML>
<html><head><title>Hello</title>
</head><body><p>Welcome to this example.</p></body></html>

An li element’s end tag may be omitted if the li element is immediately followed by another li element or if there is no more content in the parent element.

A dt element’s end tag may be omitted if the dt element is immediately followed by another dt element or a dd element.

A dd element’s end tag may be omitted if the dd element is immediately followed by another dd element or a dt element, or if there is no more content in the parent element.

A p element’s end tag may be omitted if the p element is immediately followed by an address, article, aside, blockquote, details, div, dl, fieldset, figcaption, figure, footer, form, h1, h2, h3, h4, h5, h6, header, hr, main, menu, nav, ol, p, pre, section, table, or ul element, or if there is no more content in the parent element and the parent element is an HTML element that is not an a, audio, del, ins, map, noscript, or video element.

We can thus simplify the earlier example further:
<!DOCTYPE HTML><title>Hello</title><p>Welcome to this example.</p>

An rt element’s end tag may be omitted if the rt element is immediately followed by an rt or rp element, or if there is no more content in the parent element.

An rp element’s end tag may be omitted if the rp element is immediately followed by an rt or rp element, or if there is no more content in the parent element.

An optgroup element’s end tag may be omitted if the optgroup element is immediately followed by another optgroup element, or if there is no more content in the parent element.

An option element’s end tag may be omitted if the option element is immediately followed by another option element, or if it is immediately followed by an optgroup element, or if there is no more content in the parent element.

A colgroup element’s start tag may be omitted if the first thing inside the colgroup element is a col element, and if the element is not immediately preceded by another colgroup element whose end tag has been omitted. (It can’t be omitted if the element is empty.)

A colgroup element’s end tag may be omitted if the colgroup element is not immediately followed by a space character or a comment.

A caption element’s end tag may be omitted if the caption element is not immediately followed by a space character or a comment.

A thead element’s end tag may be omitted if the thead element is immediately followed by a tbody or tfoot element.

A tbody element’s start tag may be omitted if the first thing inside the tbody element is a tr element, and if the element is not immediately preceded by a tbody, thead, or tfoot element whose end tag has been omitted. (It can’t be omitted if the element is empty.)

A tbody element’s end tag may be omitted if the tbody element is immediately followed by a tbody or tfoot element, or if there is no more content in the parent element.

A tfoot element’s end tag may be omitted if the tfoot element is immediately followed by a tbody element, or if there is no more content in the parent element.

A tr element’s end tag may be omitted if the tr element is immediately followed by another tr element, or if there is no more content in the parent element.

A td element’s end tag may be omitted if the td element is immediately followed by a td or th element, or if there is no more content in the parent element.

A th element’s end tag may be omitted if the th element is immediately followed by a td or th element, or if there is no more content in the parent element.

The ability to omit all these table-related tags makes table markup much terser.

Take this example:

<table>
<caption>37547 TEE Electric Powered Rail Car Train Functions (Abbreviated)</caption>
<colgroup><col><col><col></colgroup>
<thead>
<tr>
  <th>Function</th>
  <th>Control Unit</th>
  <th>Central Station</th>
</tr>
</thead>
<tbody>
<tr>
  <td>Headlights</td>
  <td></td>
  <td></td>
</tr>
<tr>
  <td>Interior Lights</td>
  <td></td>
  <td></td>
</tr>
<tr>
  <td>Electric locomotive operating sounds</td>
  <td></td>
  <td></td>
</tr>
<tr>
  <td>Engineer’s cab lighting</td>
  <td></td>
  <td></td>
</tr>
<tr>
  <td>Station Announcements - Swiss</td>
  <td></td>
  <td></td>
</tr>
</tbody>
</table>

The exact same table, modulo some white space differences, could be marked up as follows:

<table>
<caption>37547 TEE Electric Powered Rail Car Train Functions (Abbreviated)
<colgroup><col><col><col>
<thead>
<tr>
  <th>Function
  <th>Control Unit
  <th>Central Station
<tbody>
<tr>
  <td>Headlights
  <td><td><tr>
  <td>Interior Lights
  <td><td><tr>
  <td>Electric locomotive operating sounds
  <td><td><tr>
  <td>Engineer’s cab lighting
  <td>
  <td><tr>
  <td>Station Announcements - Swiss
  <td>
  <td></table>

Since the cells take up much less room this way, this can be made even terser by having each row on one line:

<table>
<caption>37547 TEE Electric Powered Rail Car Train Functions (Abbreviated)
<colgroup><col><col><col>
<thead>
<tr> <th>Function                              <th>Control Unit     <th>Central Station
<tbody>
<tr> <td>Headlights                            <td><td><tr> <td>Interior Lights                       <td><td><tr> <td>Electric locomotive operating sounds  <td><td><tr> <td>Engineer’s cab lighting               <td>                 <td><tr> <td>Station Announcements - Swiss         <td>                 <td></table>

The only differences between these tables, at the DOM level, is with the precise position of the (in any case semantically-neutral) white space.

However, a start tag must never be omitted if it has any attributes.

Returning to the earlier example with all the white space removed and then all the optional tags removed:
<!DOCTYPE HTML><title>Hello</title><p>Welcome to this example.

If the body element in this example had to have a class attribute and the html element had to have a lang attribute, the markup would have to become:

<!DOCTYPE HTML><html lang="en"><title>Hello</title><body class="demo"><p>Welcome to this example.

This section assumes that the document is conforming, in particular, that there are no content model violations. Omitting tags in the fashion described in this section in a document that does not conform to the content models described in this specification is likely to result in unexpected DOM differences (this is, in part, what the content models are designed to avoid).

8.1.2.5. Restrictions on content models

For historical reasons, certain elements have extra restrictions beyond even the restrictions given by their content model.

A table element must not contain tr elements, even though these elements are technically allowed inside table elements according to the content models described in this specification. (If a tr element is put inside a table in the markup, it will in fact imply a tbody start tag before it.)

A single newline may be placed immediately after the start tag of pre and textarea elements. This does not affect the processing of the element. The otherwise optional newline must be included if the element’s contents themselves start with a newline (because otherwise the leading newline in the contents would be treated like the optional newline, and ignored).

The following two pre blocks are equivalent:
<pre>Hello</pre>
<pre>     
Hello</pre>
8.1.2.6. Restrictions on the contents of raw text and escapable raw text elements

The text in raw text and escapable raw text elements must not contain any occurrences of the string "</" (U+003C LESS-THAN SIGN, U+002F SOLIDUS) followed by characters that case-insensitively match the tag name of the element followed by one of U+0009 CHARACTER TABULATION (tab), U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), U+0020 SPACE, U+003E GREATER-THAN SIGN (>), or U+002F SOLIDUS (/).

8.1.3. Text

Text is allowed inside elements, attribute values, and comments. Extra constraints are placed on what is and what is not allowed in text based on where the text is to be put, as described in the other sections.

8.1.3.1. Newlines

Newlines in HTML may be represented either as U+000D CARRIAGE RETURN (CR) characters, U+000A LINE FEED (LF) characters, or pairs of U+000D CARRIAGE RETURN (CR), U+000A LINE FEED (LF) characters in that order.

Where character references are allowed, a character reference of a U+000A LINE FEED (LF) character (but not a U+000D CARRIAGE RETURN (CR) character) also represents a newline.

8.1.4. Character references

In certain cases described in other sections, text may be mixed with character references. These can be used to escape characters that couldn’t otherwise legally be included in text.

Character references must start with a U+0026 AMPERSAND character (&). Following this, there are three possible kinds of character references:

Named character references
The ampersand must be followed by one of the names given in §8.5 Named character references section, using the same case. The name must be one that is terminated by a U+003B SEMICOLON character (;).
Decimal numeric character reference
The ampersand must be followed by a U+0023 NUMBER SIGN character (#), followed by one or more ASCII digits, representing a base-ten integer that corresponds to a Unicode code point that is allowed according to the definition below. The digits must then be followed by a U+003B SEMICOLON character (;).
Hexadecimal numeric character reference
The ampersand must be followed by a U+0023 NUMBER SIGN character (#), which must be followed by either a U+0078 LATIN SMALL LETTER X character (x) or a U+0058 LATIN CAPITAL LETTER X character (X), which must then be followed by one or more ASCII hex digits, representing a hexadecimal integer that corresponds to a Unicode code point that is allowed according to the definition below. The digits must then be followed by a U+003B SEMICOLON character (;).

The numeric character reference forms described above are allowed to reference any Unicode code point other than U+0000, U+000D, permanently undefined Unicode characters (noncharacters), surrogates (U+D800–U+DFFF), and control characters other than space characters.

An ambiguous ampersand is a U+0026 AMPERSAND character (&) that is followed by one or more alphanumeric ASCII characters, followed by a U+003B SEMICOLON character (;), where these characters do not match any of the names given in the §8.5 Named character references section.

8.1.5. CDATA sections

CDATA sections must consist of the following components, in this order:

  1. The string "<![CDATA[".
  2. Optionally, text, with the additional restriction that the text must not contain the string "]]>".
  3. The string "]]>".
CDATA sections can only be used in foreign content (MathML or SVG). In this example, a CDATA section is used to escape the contents of an ms element:
<p>You can add a string to a number, but this stringifies the number:</p>
<math>
<ms><![CDATA[x<y]]></ms>
<mo>+</mo>
<mn>3</mn>
<mo>=</mo>
<ms><![CDATA[x<y3]]></ms>
</math>

8.1.6. Comments

Comments must start with the four character sequence U+003C LESS-THAN SIGN, U+0021 EXCLAMATION MARK, U+002D HYPHEN-MINUS, U+002D HYPHEN-MINUS (<!--). Following this sequence, the comment may have text, with the additional restriction that the text must not start with a single U+003E GREATER-THAN SIGN character (>), nor start with a U+002D HYPHEN-MINUS character (-) followed by a U+003E GREATER-THAN SIGN (>) character, nor contain two consecutive U+002D HYPHEN-MINUS characters (--), nor end with a U+002D HYPHEN-MINUS character (-). Finally, the comment must be ended by the three character sequence U+002D HYPHEN-MINUS, U+002D HYPHEN-MINUS, U+003E GREATER-THAN SIGN (-->).

8.2. Parsing HTML documents

This section only applies to user agents, data mining tools, and conformance checkers.

The rules for parsing XML documents into DOM trees are covered by the next section, entitled "the XHTML syntax".

User agents must use the parsing rules described in this section to generate the DOM trees from text/html resources. Together, these rules define what is referred to as the HTML parser.

While the HTML syntax described in this specification bears a close resemblance to SGML and XML, it is a separate language with its own parsing rules.

Some earlier versions of HTML (in particular from HTML 2.0 to HTML 4.01) were based on SGML and used SGML parsing rules. However, few (if any) web browsers ever implemented true SGML parsing for HTML documents; the only user agents to strictly handle HTML as an SGML application have historically been validators. The resulting confusion — with validators claiming documents to have one representation while widely deployed Web browsers interoperably implemented a different representation — has wasted decades of productivity. This version of HTML thus returns to a non-SGML basis.

Authors interested in using SGML tools in their authoring pipeline are encouraged to use XML tools and the XML serialization of HTML.

This specification defines the parsing rules for HTML documents, whether they are syntactically correct or not. Certain points in the parsing algorithm are said to be parse errors. The error handling for parse errors is well-defined (that’s the processing rules described throughout this specification), but user agents, while parsing an HTML document, may abort the parser at the first parse error that they encounter for which they do not wish to apply the rules described in this specification.

Conformance checkers must report at least one parse error condition to the user if one or more parse error conditions exist in the document and must not report parse error conditions if none exist in the document. Conformance checkers may report more than one parse error condition if more than one parse error condition exists in the document.

Parse errors are only errors with the syntax of HTML. In addition to checking for parse errors, conformance checkers will also verify that the document obeys all the other conformance requirements described in this specification.

For the purposes of conformance checkers, if a resource is determined to be in the HTML syntax, then it is an HTML document.

As stated in the terminology section, references to element types that do not explicitly specify a namespace always refer to elements in the HTML namespace. For example, if the spec talks about "a menuitem element", then that is an element with the local name "menuitem", the namespace "https://www.w3.org/1999/xhtml", and the interface HTMLMenuItemElement. Where possible, references to such elements are hyperlinked to their definition.

8.2.1. Overview of the parsing model

The input to the HTML parsing process consists of a stream of Unicode code points, which is passed through a tokenization stage followed by a tree construction stage. The output is a Document object.

Implementations that do not support scripting do not have to actually create a DOM Document object, but the DOM tree in such cases is still used as the model for the rest of the specification.

In the common case, the data handled by the tokenization stage comes from the network, but it can also come from script running in the user agent, e.g., using the document.write() API.

There is only one set of states for the tokenizer stage and the tree construction stage, but the tree construction stage is reentrant, meaning that while the tree construction stage is handling one token, the tokenizer might be resumed, causing further tokens to be emitted and processed before the first token’s processing is complete.

In the following example, the tree construction stage will be called upon to handle a "p" start tag token while handling the "script" end tag token:
...
<script>
document.write('<p>');
</script>
...

To handle these cases, parsers have a script nesting level, which must be initially set to zero, and a parser pause flag, which must be initially set to false.

8.2.2. The input byte stream

The stream of Unicode code points that comprizes the input to the tokenization stage will be initially seen by the user agent as a stream of bytes (typically coming over the network or from the local file system). The bytes encode the actual characters according to a particular character encoding, which the user agent uses to decode the bytes into characters.

For XML documents, the algorithm user agents are required to use to determine the character encoding is given by the XML specification. This section does not apply to XML documents. [XML]

Usually, the encoding sniffing algorithm defined below is used to determine the character encoding.

Given a character encoding, the bytes in the input byte stream must be converted to characters for the tokenizer’s input stream, by passing the input byte stream and character encoding to decode.

A leading Byte Order Mark (BOM) causes the character encoding argument to be ignored and will itself be skipped.

Bytes or sequences of bytes in the original byte stream that did not conform to the Encoding standard (e.g., invalid UTF-8 byte sequences in a UTF-8 input byte stream) are errors that conformance checkers are expected to report. [ENCODING]

The decoder algorithms describe how to handle invalid input; for security reasons, it is imperative that those rules be followed precisely. Differences in how invalid byte sequences are handled can result in, amongst other problems, script injection vulnerabilities ("XSS").

When the HTML parser is decoding an input byte stream, it uses a character encoding and a confidence. The confidence is either tentative, certain, or irrelevant. The encoding used, and whether the confidence in that encoding is tentative or certain, is used during the parsing to determine whether to change the encoding. If no encoding is necessary, e.g., because the parser is operating on a Unicode stream and doesn’t have to use a character encoding at all, then the confidence is irrelevant.

Some algorithms feed the parser by directly adding characters to the input stream rather than adding bytes to the input byte stream.

8.2.2.1. Parsing with a known character encoding

When the HTML parser is to operate on an input byte stream that has a known definite encoding, then the character encoding is that encoding and the confidence is certain.

8.2.2.2. Determining the character encoding

In some cases, it might be impractical to unambiguously determine the encoding before parsing the document. Because of this, this specification provides for a two-pass mechanism with an optional pre-scan. Implementations are allowed, as described below, to apply a simplified parsing algorithm to whatever bytes they have available before beginning to parse the document. Then, the real parser is started, using a tentative encoding derived from this pre-parse and other out-of-band metadata. If, while the document is being loaded, the user agent discovers a character encoding declaration that conflicts with this information, then the parser can get reinvoked to perform a parse of the document with the real encoding.

User agents must use the following algorithm, called the encoding sniffing algorithm, to determine the character encoding to use when decoding a document in the first pass. This algorithm takes as input any out-of-band metadata available to the user agent (e.g., the Content-Type metadata of the document) and all the bytes available so far, and returns a character encoding and a confidence that is either tentative or certain.

  1. If the user has explicitly instructed the user agent to override the document’s character encoding with a specific encoding, optionally return that encoding with the confidence certain and abort these steps.

    Typically, user agents remember such user requests across sessions, and in some cases apply them to documents in iframes as well.

  2. The user agent may wait for more bytes of the resource to be available, either in this step or at any later step in this algorithm. For instance, a user agent might wait 500ms or 1024 bytes, whichever came first. In general preparsing the source to find the encoding improves performance, as it reduces the need to throw away the data structures used when parsing upon finding the encoding information. However, if the user agent delays too long to obtain data to determine the encoding, then the cost of the delay could outweigh any performance improvements from the preparse.

    The authoring conformance requirements for character encoding declarations limit them to only appearing in the first 1024 bytes. User agents are therefore encouraged to use the prescan algorithm below (as invoked by these steps) on the first 1024 bytes, but not to stall beyond that.

  3. If the transport layer specifies a character encoding, and it is supported, return that encoding with the confidence certain, and abort these steps.
  4. Optionally prescan the byte stream to determine its encoding. The end condition is that the user agent decides that scanning further bytes would not be efficient. User agents are encouraged to only prescan the first 1024 bytes. User agents may decide that scanning any bytes is not efficient, in which case these substeps are entirely skipped.

    The aforementioned algorithm either aborts unsuccessfully or returns a character encoding. If it returns a character encoding, then this algorithm must be aborted, returning the same encoding, with confidence tentative.

  5. If the HTML parser for which this algorithm is being run is associated with a Document that is itself in a nested browsing context, run these substeps:

    1. Let new document be the Document with which the HTML parser is associated.
    2. Let parent document be the Document through which new document is nested (the active document of the parent browsing context of new document).
    3. If parent document’s origin is not the same origin as new document’s origin, then abort these substeps.
    4. If parent document’s character encoding is not an ASCII-compatible encoding, then abort these substeps.
    5. Return parent document’s character encoding, with the confidence tentative, and abort the encoding sniffing algorithm’s steps.
  6. Otherwise, if the user agent has information on the likely encoding for this page, e.g., based on the encoding of the page when it was last visited, then return that encoding, with the confidence tentative, and abort these steps.
  7. The user agent may attempt to autodetect the character encoding from applying frequency analysis or other algorithms to the data stream. Such algorithms may use information about the resource other than the resource’s contents, including the address of the resource. If autodetection succeeds in determining a character encoding, and that encoding is a supported encoding, then return that encoding, with the confidence tentative, and abort these steps. [UNIVCHARDET]

    User agents are generally discouraged from attempting to autodetect encodings for resources obtained over the network, since doing so involves inherently non-interoperable heuristics. Attempting to detect encodings based on an HTML document’s preamble is especially tricky since HTML markup typically uses only ASCII characters, and HTML documents tend to begin with a lot of markup rather than with text content.

    The UTF-8 encoding has a highly detectable bit pattern. Files from the local file system that contain bytes with values greater than 0x7F which match the UTF-8 pattern are very likely to be UTF-8, while documents with byte sequences that do not match it are very likely not. When a user agent can examine the whole file, rather than just the preamble, detecting for UTF-8 specifically can be especially effective. [PPUTF8] [UTF8DET]

  8. Otherwise, return an implementation-defined or user-specified default character encoding, with the confidence tentative.

    In controlled environments or in environments where the encoding of documents can be prescribed (for example, for user agents intended for dedicated use in new networks), the comprehensive UTF-8 encoding is suggested.

    In other environments, the default encoding is typically dependent on the user’s locale (an approximation of the languages, and thus often encodings, of the pages that the user is likely to frequent). The following table gives suggested defaults based on the user’s locale, for compatibility with legacy content. Locales are identified by BCP 47 language tags. [BCP47] [ENCODING]

    Locale language Suggested default encoding
    ar Arabic windows-1256
    ba Bashkir windows-1251
    be Belarusian windows-1251
    bg Bulgarian windows-1251
    cs Czech windows-1250
    el Greek ISO-8859-7
    et Estonian windows-1257
    fa Persian windows-1256
    he Hebrew windows-1255
    hr Croatian windows-1250
    hu Hungarian ISO-8859-2
    ja Japanese Shift_JIS
    kk Kazakh windows-1251
    ko Korean euc-kr
    ku Kurdish windows-1254
    ky Kyrgyz windows-1251
    lt Lithuanian windows-1257
    lv Latvian windows-1257
    mk Macedonian windows-1251
    pl Polish ISO-8859-2
    ru Russian windows-1251
    sah Yakut windows-1251
    sk Slovak windows-1250
    sl Slovenian ISO-8859-2
    sr Serbian windows-1251
    tg Tajik windows-1251
    th Thai windows-874
    tr Turkish windows-1254
    tt Tatar windows-1251
    uk Ukrainian windows-1251
    vi Vietnamese windows-1258
    zh-CN Chinese (People’s Republic of China) GB18030
    zh-TW Chinese (Taiwan) Big5
    All other locales windows-1252

    The contents of this table are derived from the intersection of Windows, Chrome, and Firefox defaults.

The document’s character encoding must immediately be set to the value returned from this algorithm, at the same time as the user agent uses the returned value to select the decoder to use for the input byte stream.


When an algorithm requires a user agent to prescan a byte stream to determine its encoding, given some defined end condition, then it must run the following steps. These steps either abort unsuccessfully or return a character encoding. If at any point during these steps (including during instances of the get an attribute algorithm invoked by this one) the user agent either runs out of bytes (meaning the position pointer created in the first step below goes beyond the end of the byte stream obtained so far) or reaches its end condition, then abort the prescan a byte stream to determine its encoding algorithm unsuccessfully.

  1. Let position be a pointer to a byte in the input byte stream, initially pointing at the first byte.

  2. Loop: If position points to:

    A sequence of bytes starting with: 0x3C 0x21 0x2D 0x2D (ASCII '<!--')

    Advance the position pointer so that it points at the first 0x3E byte which is preceded by two 0x2D bytes (i.e., at the end of an ASCII '-->' sequence) and comes after the 0x3C byte that was found. (The two 0x2D bytes can be the same as those in the '<!--' sequence.)

    A sequence of bytes starting with: 0x3C, 0x4D or 0x6D, 0x45 or 0x65, 0x54 or 0x74, 0x41 or 0x61, and one of 0x09, 0x0A, 0x0C, 0x0D, 0x20, 0x2F (case-insensitive ASCII '<meta' followed by a space or slash)
    1. Advance the position pointer so that it points at the next 0x09, 0x0A, 0x0C, 0x0D, 0x20, or 0x2F byte (the one in sequence of characters matched above).
    2. Let attribute list be an empty list of strings.
    3. Let got pragma be false.
    4. Let need pragma be null.
    5. Let charset be the null value (which, for the purposes of this algorithm, is distinct from an unrecognized encoding or the empty string).
    6. Attributes: Get an attribute and its value. If no attribute was computed, then jump to the processing step below.
    7. If the attribute’s name is already in attribute list, then return to the step labeled attributes.
    8. Add the attribute’s name to attribute list.
    9. Run the appropriate step from the following list, if one applies:

      If the attribute’s name is "http-equiv"
      If the attribute’s value is "content-type", then set got pragma to true.
      If the attribute’s name is "content"
      Apply the algorithm for extracting a character encoding from a meta element, giving the attribute’s value as the string to parse. If a character encoding is returned, and if charset is still set to null, let charset be the encoding returned, and set need pragma to true.
      If the attribute’s name is "charset"
      Let charset be the result of getting an encoding from the attribute’s value, and set need pragma to false.
    10. Return to the step labeled attributes.
    11. Processing: If need pragma is null, then jump to the step below labeled next byte.
    12. If need pragma is true but got pragma is false, then jump to the step below labeled next byte.
    13. If charset is failure, then jump to the step below labeled next byte.
    14. If charset is a UTF-16 encoding, then set charset to UTF-8.
    15. If charset is x-user-defined, then set charset to windows-1252.

    16. Abort the prescan a byte stream to determine its encoding algorithm, returning the encoding given by charset.

    A sequence of bytes starting with a 0x3C byte (ASCII <), optionally a 0x2F byte (ASCII /), and finally a byte in the range 0x41-0x5A or 0x61-0x7A (an ASCII letter)
    1. Advance the position pointer so that it points at the next 0x09 (ASCII TAB), 0x0A (ASCII LF), 0x0C (ASCII FF), 0x0D (ASCII CR), 0x20 (ASCII space), or 0x3E (ASCII >) byte.
    2. Repeatedly get an attribute until no further attributes can be found, then jump to the step below labeled next byte.
    A sequence of bytes starting with: 0x3C 0x21 (ASCII '<!')
    A sequence of bytes starting with: 0x3C 0x2F (ASCII '</')
    A sequence of bytes starting with: 0x3C 0x3F (ASCII '<?')

    Advance the position pointer so that it points at the first 0x3E byte (ASCII >) that comes after the 0x3C byte that was found.

    Any other byte

    Do nothing with that byte.

  3. Next byte: Move position so it points at the next byte in the input byte stream, and return to the step above labeled loop.

When the prescan a byte stream to determine its encoding algorithm says to get an attribute, it means doing this:

  1. If the byte at position is one of 0x09 (ASCII TAB), 0x0A (ASCII LF), 0x0C (ASCII FF), 0x0D (ASCII CR), 0x20 (ASCII space), or 0x2F (ASCII /) then advance position to the next byte and redo this step.
  2. If the byte at position is 0x3E (ASCII >), then abort the get an attribute algorithm. There isn’t one.
  3. Otherwise, the byte at position is the start of the attribute name. Let attribute name and attribute value be the empty string.
  4. Process the byte at position as follows:
    If it is 0x3D (ASCII =), and the attribute name is longer than the empty string
    Advance position to the next byte and jump to the step below labeled value.
    If it is 0x09 (ASCII TAB), 0x0A (ASCII LF), 0x0C (ASCII FF), 0x0D (ASCII CR), or 0x20 (ASCII space)
    Jump to the step below labeled spaces.
    If it is 0x2F (ASCII /) or 0x3E (ASCII >)
    Abort the get an attribute algorithm. The attribute’s name is the value of attribute name, its value is the empty string.
    If it is in the range 0x41 (ASCII A) to 0x5A (ASCII Z)
    Append the Unicode character with code point b+0x20 to attribute name (where b is the value of the byte at position). (This converts the input to lowercase.)
    Anything else
    Append the Unicode character with the same code point as the value of the byte at position to attribute name. (It doesn’t actually matter how bytes outside the ASCII range are handled here, since only ASCII characters can contribute to the detection of a character encoding.)
  5. Advance position to the next byte and return to the previous step.
  6. Spaces: If the byte at position is one of 0x09 (ASCII TAB), 0x0A (ASCII LF), 0x0C (ASCII FF), 0x0D (ASCII CR), or 0x20 (ASCII space) then advance position to the next byte, then, repeat this step.
  7. If the byte at position is not 0x3D (ASCII =), abort the get an attribute algorithm. The attribute’s name is the value of attribute name, its value is the empty string.
  8. Advance position past the 0x3D (ASCII =) byte.
  9. Value: If the byte at position is one of 0x09 (ASCII TAB), 0x0A (ASCII LF), 0x0C (ASCII FF), 0x0D (ASCII CR), or 0x20 (ASCII space) then advance position to the next byte, then, repeat this step.
  10. Process the byte at position as follows:
    If it is 0x22 (ASCII ") or 0x27 (ASCII ')
    1. Let b be the value of the byte at position.
    2. Quote loop: Advance position to the next byte.
    3. If the value of the byte at position is the value of b, then advance position to the next byte and abort the "get an attribute" algorithm. The attribute’s name is the value of attribute name, and its value is the value of attribute value.
    4. Otherwise, if the value of the byte at position is in the range 0x41 (ASCII A) to 0x5A (ASCII Z), then append a Unicode character to attribute value whose code point is 0x20 more than the value of the byte at position.
    5. Otherwise, append a Unicode character to attribute value whose code point is the same as the value of the byte at position.
    6. Return to the step above labeled quote loop.
    If it is 0x3E (ASCII >)
    Abort the get an attribute algorithm. The attribute’s name is the value of attribute name, its value is the empty string.
    If it is in the range 0x41 (ASCII A) to 0x5A (ASCII Z)
    Append the Unicode character with code point b+0x20 to attribute value (where b is the value of the byte at position). Advance position to the next byte.
    Anything else
    Append the Unicode character with the same code point as the value of the byte at position to attribute value. Advance position to the next byte.
  11. Process the byte at position as follows:
    If it is 0x09 (ASCII TAB), 0x0A (ASCII LF), 0x0C (ASCII FF), 0x0D (ASCII CR), 0x20 (ASCII space), or 0x3E (ASCII >)
    Abort the get an attribute algorithm. The attribute’s name is the value of attribute name and its value is the value of attribute value.
    If it is in the range 0x41 (ASCII A) to 0x5A (ASCII Z)
    Append the Unicode character with code point b+0x20 to attribute value (where b is the value of the byte at position).
    Anything else
    Append the Unicode character with the same code point as the value of the byte at position to attribute value.
  12. Advance position to the next byte and return to the previous step.

For the sake of interoperability, user agents should not use a pre-scan algorithm that returns different results than the one described above. (But, if you do, please at least let us know, so that we can improve this algorithm and benefit everyone...)

8.2.2.3. Character encodings

User agents must support the encodings defined in the WHATWG Encoding standard, including, but not limited to,

UTF-8, ISO-8859-2, ISO-8859-8, windows-1250, windows-1251, windows-1252, windows-1254, windows-1256, windows-1257, gb18030, Big5, ISO-2022-JP, Shift_JIS, EUC-KR, UTF-16BE, UTF-16LE, and x-user-defined. User agents must not support other encodings.

The above prohibits supporting, for example, CESU-8, UTF-7, BOCU-1, SCSU, EBCDIC, and UTF-32. This specification does not make any attempt to support prohibited encodings in its algorithms; support and use of prohibited encodings would thus lead to unexpected behavior. [CESU8] [RFC2152] [BOCU1] [SCSU]

8.2.2.4. Changing the encoding while parsing

When the parser requires the user agent to change the encoding, it must run the following steps. This might happen if the encoding sniffing algorithm described above failed to find a character encoding, or if it found a character encoding that was not the actual encoding of the file.

  1. If the encoding that is already being used to interpret the input stream is a UTF-16 encoding, then set the confidence to certain and abort these steps. The new encoding is ignored; if it was anything but the same encoding, then it would be clearly incorrect.
  2. If the new encoding is a UTF-16 encoding, then change it to UTF-8.
  3. If the new encoding is the x-user-defined encoding, then change it to Windows-1252. [ENCODING]
  4. If the new encoding is identical or equivalent to the encoding that is already being used to interpret the input stream, then set the confidence to certain and abort these steps. This happens when the encoding information found in the file matches what the encoding sniffing algorithm determined to be the encoding, and in the second pass through the parser if the first pass found that the encoding sniffing algorithm described in the earlier section failed to find the right encoding.
  5. If all the bytes up to the last byte converted by the current decoder have the same Unicode interpretations in both the current encoding and the new encoding, and if the user agent supports changing the converter on the fly, then the user agent may change to the new converter for the encoding on the fly. Set the document’s character encoding and the encoding used to convert the input stream to the new encoding, set the confidence to certain, and abort these steps.
  6. Otherwise, navigate to the document again, with replacement enabled, and using the same source browsing context, but this time skip the encoding sniffing algorithm and instead just set the encoding to the new encoding and the confidence to certain. Whenever possible, this should be done without actually contacting the network layer (the bytes should be re-parsed from memory), even if, e.g., the document is marked as not being cacheable. If this is not possible and contacting the network layer would involve repeating a request that uses a method other than GET), then instead set the confidence to certain and ignore the new encoding. The resource will be misinterpreted. User agents may notify the user of the situation, to aid in application development.

This algorithm is only invoked when a new encoding is found declared on a meta element.

8.2.2.5. Preprocessing the input stream

The input stream consists of the characters pushed into it as the input byte stream is decoded or from the various APIs that directly manipulate the input stream.

Any occurrences of any characters in the ranges U+0001 to U+0008, U+000E to U+001F, U+007F to U+009F, U+FDD0 to U+FDEF, and characters U+000B, U+FFFE, U+FFFF, U+1FFFE, U+1FFFF, U+2FFFE, U+2FFFF, U+3FFFE, U+3FFFF, U+4FFFE, U+4FFFF, U+5FFFE, U+5FFFF, U+6FFFE, U+6FFFF, U+7FFFE, U+7FFFF, U+8FFFE, U+8FFFF, U+9FFFE, U+9FFFF, U+AFFFE, U+AFFFF, U+BFFFE, U+BFFFF, U+CFFFE, U+CFFFF, U+DFFFE, U+DFFFF, U+EFFFE, U+EFFFF, U+FFFFE, U+FFFFF, U+10FFFE, and U+10FFFF are parse errors. These are all control characters or permanently undefined Unicode characters (noncharacters).

Any character that is a not a Unicode character, i.e., any isolated surrogate, is a parse error. (These can only find their way into the input stream via script APIs such as document.write().)

U+000D CARRIAGE RETURN (CR) characters and U+000A LINE FEED (LF) characters are treated specially. Any LF character that immediately follows a CR character must be ignored, and all CR characters must then be converted to LF characters. Thus, newlines in HTML DOMs are represented by LF characters, and there are never any CR characters in the input to the tokenization stage.

The next input character is the first character in the input stream that has not yet been consumed or explicitly ignored by the requirements in this section. Initially, the next input character is the first character in the input. The current input character is the last character to have been consumed.

The insertion point is the position (just before a character or just before the end of the input stream) where content inserted using document.write() is actually inserted. The insertion point is relative to the position of the character immediately after it, it is not an absolute offset into the input stream. Initially, the insertion point is undefined.

The "EOF" character in the tables below is a conceptual character representing the end of the input stream. If the parser is a script-created parser, then the end of the input stream is reached when an explicit "EOF" character (inserted by the document.close() method) is consumed. Otherwise, the "EOF" character is not a real character in the stream, but rather the lack of any further characters.

The handling of U+0000 NULL characters varies based on where the characters are found. In general, they are ignored except where doing so could plausibly introduce an attack vector. This handling is, by necessity, spread across both the tokenization stage and the tree construction stage.

8.2.3. Parse state

8.2.3.1. The insertion mode

The insertion mode is a state variable that controls the primary operation of the tree construction stage.

Initially, the insertion mode is "initial". It can change to "before html", "before head", "in head", "in head noscript", "after head", "in body", "text", "in table", "in table text", "in caption", "in column group", "in table body", "in row", "in cell", "in select", "in select in table", "in template", "after body", "in frameset", "after frameset", "after after body", and "after after frameset" during the course of the parsing, as described in the tree construction stage. The insertion mode affects how tokens are processed and whether CDATA sections are supported.

Several of these modes, namely "in head", "in body", "in table", and "in select", are special, in that the other modes defer to them at various times. When the algorithm below says that the user agent is to do something "using the rules for the m insertion mode", where m is one of these modes, the user agent must use the rules described under the m insertion mode’s section, but must leave the insertion mode unchanged unless the rules in m themselves switch the insertion mode to a new value.

When the insertion mode is switched to "text" or "in table text", the original insertion mode is also set. This is the insertion mode to which the tree construction stage will return.

Similarly, to parse nested template elements, a stack of template insertion modes is used. It is initially empty. The current template insertion mode is the insertion mode that was most recently added to the stack of template insertion modes. The algorithms in the sections below will push insertion modes onto this stack, meaning that the specified insertion mode is to be added to the stack, and pop insertion modes from the stack, which means that the most recently added insertion mode must be removed from the stack.


When the steps below require the user agent to reset the insertion mode appropriately, it means the user agent must follow these steps:

  1. Let last be false.
  2. Let node be the last node in the stack of open elements.
  3. Loop: If node is the first node in the stack of open elements, then set last to true, and, if the parser was originally created as part of the HTML fragment parsing algorithm (fragment case), set node to the context element passed to that algorithm.
  4. If node is a select element, run these substeps:

    1. If last is true, jump to the step below labeled done.
    2. Let ancestor be node.
    3. Loop: If ancestor is the first node in the stack of open elements, jump to the step below labeled done.
    4. Let ancestor be the node before ancestor in the stack of open elements.
    5. If ancestor is a template node, jump to the step below labeled done.
    6. If ancestor is a table node, switch the insertion mode to "in select in table" and abort these steps.
    7. Jump back to the step labeled loop.
    8. Done: Switch the insertion mode to "in select" and abort these steps.
  5. If node is a td or th element and last is false, then switch the insertion mode to "in cell" and abort these steps.
  6. If node is a tr element, then switch the insertion mode to "in row" and abort these steps.
  7. If node is a tbody, thead, or tfoot element, then switch the insertion mode to "in table body" and abort these steps.
  8. If node is a caption element, then switch the insertion mode to "in caption" and abort these steps.
  9. If node is a colgroup element, then switch the insertion mode to "in column group" and abort these steps.
  10. If node is a table element, then switch the insertion mode to "in table" and abort these steps.
  11. If node is a template element, then switch the insertion mode to the current template insertion mode and abort these steps.
  12. If node is a head element and last is false, then switch the insertion mode to "in head" and abort these steps.
  13. If node is a body element, then switch the insertion mode to "in body" and abort these steps.
  14. If node is a frameset element, then switch the insertion mode to "in frameset" and abort these steps. (fragment case)
  15. If node is an html element, run these substeps:

    1. If the head element pointer is null, switch the insertion mode to "before head" and abort these steps. (fragment case)
    2. Otherwise, the head element pointer is not null, switch the insertion mode to "after head" and abort these steps.
  16. If last is true, then switch the insertion mode to "in body" and abort these steps. (fragment case)
  17. Let node now be the node before node in the stack of open elements.
  18. Return to the step labeled loop.
8.2.3.2. The stack of open elements

Initially, the stack of open elements is empty. The stack grows downwards; the topmost node on the stack is the first one added to the stack, and the bottommost node of the stack is the most recently added node in the stack (notwithstanding when the stack is manipulated in a random access fashion as part of the handling for misnested tags).

The "before html" insertion mode creates the html root element node, which is then added to the stack.

In the fragment case, the stack of open elements is initialized to contain an html element that is created as part of that algorithm. (The fragment case skips the "before html" insertion mode.)

The html node, however it is created, is the topmost node of the stack. It only gets popped off the stack when the parser finishes.

The current node is the bottommost node in this stack of open elements.

The adjusted current node is the context element if the parser was created by the HTML fragment parsing algorithm and the stack of open elements has only one element in it (fragment case); otherwise, the adjusted current node is the current node.

Elements in the stack of open elements fall into the following categories:

Special
The following elements have varying levels of special parsing rules: HTML’s address, applet, area, article, aside, base, basefont, bgsound, blockquote, body, br, button, caption, center, col, colgroup, dd, details, dir, div, dl, dt, embed, fieldset, figcaption, figure, footer, form, frame, frameset, h1, h2, h3, h4, h5, h6, head, header, hr, html, iframe, img, input, li, link, listing, main, marquee, menu, menuitem, meta, nav, noembed, noframes, noscript, object, ol, p, param, plaintext, pre, script, section, select, source, style, summary, table, tbody, td, template, textarea, tfoot, th, thead, title, tr, track, ul, wbr, and xmp; MathML’s mi, mo, mn, ms, mtext, and annotation-xml; and SVG’s foreignObject, desc, and title.
Formatting
The following HTML elements are those that end up in the list of active formatting elements: a, b, big, code, em, font, i, nobr, s, small, strike, strong, tt, and u.
Ordinary
All other elements found while parsing an HTML document.

The stack of open elements is said to have an element target node in a specific scope consisting of a list of element types list when the following algorithm terminates in a match state:

  1. Initialize node to be the current node (the bottommost node of the stack).
  2. If node is the target node, terminate in a match state.
  3. Otherwise, if node is one of the element types in list, terminate in a failure state.
  4. Otherwise, set node to the previous entry in the stack of open elements and return to step 2. (This will never fail, since the loop will always terminate in the previous step if the top of the stack — an html element — is reached.)

The stack of open elements is said to have a particular element in scope when it has that element in the specific scope consisting of the following element types:

The stack of open elements is said to have a particular element in list item scope when it has that element in the specific scope consisting of the following element types:

The stack of open elements is said to have a particular element in button scope when it has that element in the specific scope consisting of the following element types:

The stack of open elements is said to have a particular element in table scope when it has that element in the specific scope consisting of the following element types:

The stack of open elements is said to have a particular element in select scope when it has that element in the specific scope consisting of all element types except the following:

Nothing happens if at any time any of the elements in the stack of open elements are moved to a new location in, or removed from, the Document tree. In particular, the stack is not changed in this situation. This can cause, amongst other strange effects, content to be appended to nodes that are no longer in the DOM.

In some cases (namely, when closing misnested formatting elements), the stack is manipulated in a random-access fashion.

8.2.3.3. The list of active formatting elements

Initially, the list of active formatting elements is empty. It is used to handle mis-nested formatting element tags.

The list contains elements in the formatting category, and markers. The markers are inserted when entering applet elements, buttons, object elements, marquees, table cells, and table captions, and are used to prevent formatting from "leaking" into applet elements, buttons, object elements, marquees, and tables.

In addition, each element in the list of active formatting elements is associated with the token for which it was created, so that further elements can be created for that token if necessary.

When the steps below require the user agent to push onto the list of active formatting elements an element element, the user agent must perform the following steps:

  1. If there are already three elements in the list of active formatting elements after the last marker, if any, or anywhere in the list if there are no markers, that have the same tag name, namespace, and attributes as element, then remove the earliest such element from the list of active formatting elements. For these purposes, the attributes must be compared as they were when the elements were created by the parser; two elements have the same attributes if all their parsed attributes can be paired such that the two attributes in each pair have identical names, namespaces, and values (the order of the attributes does not matter).

    This is the Noah’s Ark clause. But with three per family instead of two.

  2. Add element to the list of active formatting elements.

When the steps below require the user agent to reconstruct the active formatting elements, the user agent must perform the following steps:

  1. If there are no entries in the list of active formatting elements, then there is nothing to reconstruct; stop this algorithm.
  2. If the last (most recently added) entry in the list of active formatting elements is a marker, or if it is an element that is in the stack of open elements, then there is nothing to reconstruct; stop this algorithm.
  3. Let entry be the last (most recently added) element in the list of active formatting elements.
  4. Rewind: If there are no entries before entry in the list of active formatting elements, then jump to the step labeled create.
  5. Let entry be the entry one earlier than entry in the list of active formatting elements.
  6. If entry is neither a marker nor an element that is also in the stack of open elements, go to the step labeled rewind.
  7. Advance: Let entry be the element one later than entry in the list of active formatting elements.
  8. Create: Insert an HTML element for the token for which the element entry was created, to obtain new element.
  9. Replace the entry for entry in the list with an entry for new element.
  10. If the entry for new element in the list of active formatting elements is not the last entry in the list, return to the step labeled advance.

This has the effect of reopening all the formatting elements that were opened in the current body, cell, or caption (whichever is youngest) that haven’t been explicitly closed.

The way this specification is written, the list of active formatting elements always consists of elements in chronological order with the least recently added element first and the most recently added element last (except for while steps 7 to 10 of the above algorithm are being executed, of course).

When the steps below require the user agent to clear the list of active formatting elements up to the last marker, the user agent must perform the following steps:

  1. Let entry be the last (most recently added) entry in the list of active formatting elements.
  2. Remove entry from the list of active formatting elements.
  3. If entry was a marker, then stop the algorithm at this point. The list has been cleared up to the last marker.
  4. Go to step 1.
8.2.3.4. The element pointers

Initially, the head element pointer and the form element pointer are both null.

Once a head element has been parsed (whether implicitly or explicitly) the head element pointer gets set to point to this node.

The form element pointer points to the last form element that was opened and whose end tag has not yet been seen. It is used to make form controls associate with forms in the face of dramatically bad markup, for historical reasons. It is ignored inside template elements.

8.2.3.5. Other parsing state flags

The scripting flag is set to "enabled" if scripting was enabled for the Document with which the parser is associated when the parser was created, and "disabled" otherwise.

The scripting flag can be enabled even when the parser was originally created for the HTML fragment parsing algorithm, even though script elements don’t execute in that case.

The frameset-ok flag is set to "ok" when the parser is created. It is set to "not ok" after certain tokens are seen.

8.2.4. Tokenization

Implementations must act as if they used the following state machine to tokenize HTML. The state machine must start in the §8.2.4.1 Data state. Most states consume a single character, which may have various side-effects, and either switches the state machine to a new state to reconsume the same character, or switches it to a new state to consume the next character, or stays in the same state to consume the next character. Some states have more complicated behavior and can consume several characters before switching to another state. In some cases, the tokenizer state is also changed by the tree construction stage.

The exact behavior of certain states depends on the insertion mode and the stack of open elements. Certain states also use a temporary buffer to track progress.

The output of the tokenization step is a series of zero or more of the following tokens: DOCTYPE, start tag, end tag, comment, character, end-of-file. DOCTYPE tokens have a name, a public identifier, a system identifier, and a force-quirks flag. When a DOCTYPE token is created, its name, public identifier, and system identifier must be marked as missing (which is a distinct state from the empty string), and the force-quirks flag must be set to off (its other state is on). Start and end tag tokens have a tag name, a self-closing flag, and a list of attributes, each of which has a name and a value. When a start or end tag token is created, its self-closing flag must be unset (its other state is that it be set), and its attributes list must be empty. Comment and character tokens have data.

When a token is emitted, it must immediately be handled by the tree construction stage. The tree construction stage can affect the state of the tokenization stage, and can insert additional characters into the stream. (For example, the script element can result in scripts executing and using the dynamic markup insertion APIs to insert characters into the stream being tokenized.)

Creating a token and emitting it are distinct actions. It is possible for a token to be created but implicitly abandoned (never emitted), e.g., if the file ends unexpectedly while processing the characters that are being parsed into a start tag token.

When a start tag token is emitted with its self-closing flag set, if the flag is not acknowledged when it is processed by the tree construction stage, that is a parse error.

When an end tag token is emitted with attributes, that is a parse error.

When an end tag token is emitted with its self-closing flag set, that is a parse error.

An appropriate end tag token is an end tag token whose tag name matches the tag name of the last start tag to have been emitted from this tokenizer, if any. If no start tag has been emitted from this tokenizer, then no end tag token is appropriate.

Before each step of the tokenizer, the user agent must first check the parser pause flag. If it is true, then the tokenizer must abort the processing of any nested invocations of the tokenizer, yielding control back to the caller.

The tokenizer state machine consists of the states defined in the following subsections.

8.2.4.1. Data state

Consume the next input character:

U+0026 AMPERSAND (&)
Switch to the §8.2.4.2 Character reference in data state.
U+003C LESS-THAN SIGN (<)
Switch to the §8.2.4.8 Tag open state.
U+0000 NULL
parse error. Emit the current input character as a character token.
EOF
Emit an end-of-file token.
Anything else
Emit the current input character as a character token.
8.2.4.2. Character reference in data state

Switch to the §8.2.4.1 Data state.

Attempt to consume a character reference, with no additional allowed character.

If nothing is returned, emit a U+0026 AMPERSAND character (&) token.

Otherwise, emit the character tokens that were returned.

8.2.4.3. RCDATA state

Consume the next input character:

U+0026 AMPERSAND (&)
Switch to the §8.2.4.4 Character reference in RCDATA state.
U+003C LESS-THAN SIGN (<)
Switch to the §8.2.4.11 RCDATA less-than sign state.
U+0000 NULL
parse error. Emit a U+FFFD REPLACEMENT CHARACTER character token.
EOF
Emit an end-of-file token.
Anything else
Emit the current input character as a character token.
8.2.4.4. Character reference in RCDATA state

Switch to the §8.2.4.3 RCDATA state.

Attempt to consume a character reference, with no additional allowed character.

If nothing is returned, emit a U+0026 AMPERSAND character (&) token.

Otherwise, emit the character tokens that were returned.

8.2.4.5. RAWTEXT state

Consume the next input character:

U+003C LESS-THAN SIGN (<)
Switch to the §8.2.4.14 RAWTEXT less-than sign state.
U+0000 NULL
parse error. Emit a U+FFFD REPLACEMENT CHARACTER character token.
EOF
Emit an end-of-file token.
Anything else
Emit the current input character as a character token.
8.2.4.6. Script data state

Consume the next input character:

U+003C LESS-THAN SIGN (<)
Switch to the §8.2.4.17 Script data less-than sign state.
U+0000 NULL
parse error. Emit a U+FFFD REPLACEMENT CHARACTER character token.
EOF
Emit an end-of-file token.
Anything else
Emit the current input character as a character token.
8.2.4.7. PLAINTEXT state

Consume the next input character:

U+0000 NULL
parse error. Emit a U+FFFD REPLACEMENT CHARACTER character token.
EOF
Emit an end-of-file token.
Anything else
Emit the current input character as a character token.
8.2.4.8. Tag open state

Consume the next input character:

U+0021 EXCLAMATION MARK (!)
Switch to the §8.2.4.45 Markup declaration open state.
U+002F SOLIDUS (/)
Switch to the §8.2.4.9 End tag open state.
Uppercase ASCII letter
Create a new start tag token, set its tag name to the lowercase version of the current input character (add 0x0020 to the character’s code point), then switch to the §8.2.4.10 Tag name state. (Don’t emit the token yet; further details will be filled in before it is emitted.)
Lowercase ASCII letter
Create a new start tag token, set its tag name to the current input character, then switch to the §8.2.4.10 Tag name state. (Don’t emit the token yet; further details will be filled in before it is emitted.)
U+003F QUESTION MARK (?)
parse error. Switch to the §8.2.4.44 Bogus comment state.
Anything else
parse error. Switch to the §8.2.4.1 Data state. Emit a U+003C LESS-THAN SIGN character token. Reconsume the current input character.
8.2.4.9. End tag open state

Consume the next input character:

Uppercase ASCII letter
Create a new end tag token, set its tag name to the lowercase version of the current input character (add 0x0020 to the character’s code point), then switch to the §8.2.4.10 Tag name state. (Don’t emit the token yet; further details will be filled in before it is emitted.)
Lowercase ASCII letter
Create a new end tag token, set its tag name to the current input character, then switch to the §8.2.4.10 Tag name state. (Don’t emit the token yet; further details will be filled in before it is emitted.)
U+003E GREATER-THAN SIGN (>)
parse error. Switch to the §8.2.4.1 Data state.
EOF
parse error. Switch to the §8.2.4.1 Data state. Emit a U+003C LESS-THAN SIGN character token and a U+002F SOLIDUS character token. Reconsume the EOF character.
Anything else
parse error. Switch to the §8.2.4.44 Bogus comment state.
8.2.4.10. Tag name state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Switch to the §8.2.4.34 Before attribute name state.
U+002F SOLIDUS (/)
Switch to the §8.2.4.43 Self-closing start tag state.
U+003E GREATER-THAN SIGN (>)
Switch to the §8.2.4.1 Data state. Emit the current tag token.
Uppercase ASCII letter
Append the lowercase version of the current input character (add 0x0020 to the character’s code point) to the current tag token’s tag name.
U+0000 NULL
parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the current tag token’s tag name.
EOF
parse error. Switch to the §8.2.4.1 Data state. Reconsume the EOF character.
Anything else
Append the current input character to the current tag token’s tag name.
8.2.4.11. RCDATA less-than sign state

Consume the next input character:

U+002F SOLIDUS (/)
Set the temporary buffer to the empty string. Switch to the §8.2.4.12 RCDATA end tag open state.
Anything else
Switch to the §8.2.4.3 RCDATA state. Emit a U+003C LESS-THAN SIGN character token. Reconsume the current input character.
8.2.4.12. RCDATA end tag open state

Consume the next input character:

Uppercase ASCII letter
Create a new end tag token, and set its tag name to the lowercase version of the current input character (add 0x0020 to the character’s code point). Append the current input character to the temporary buffer. Finally, switch to the §8.2.4.13 RCDATA end tag name state. (Don’t emit the token yet; further details will be filled in before it is emitted.)
Lowercase ASCII letter
Create a new end tag token, and set its tag name to the current input character. Append the current input character to the temporary buffer. Finally, switch to the §8.2.4.13 RCDATA end tag name state. (Don’t emit the token yet; further details will be filled in before it is emitted.)
Anything else
Switch to the §8.2.4.3 RCDATA state. Emit a U+003C LESS-THAN SIGN character token and a U+002F SOLIDUS character token. Reconsume the current input character.
8.2.4.13. RCDATA end tag name state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
If the current end tag token is an appropriate end tag token, then switch to the §8.2.4.34 Before attribute name state. Otherwise, treat it as per the "anything else" entry below.
U+002F SOLIDUS (/)
If the current end tag token is an appropriate end tag token, then switch to the §8.2.4.43 Self-closing start tag state. Otherwise, treat it as per the "anything else" entry below.
U+003E GREATER-THAN SIGN (>)
If the current end tag token is an appropriate end tag token, then switch to the §8.2.4.1 Data state and emit the current tag token. Otherwise, treat it as per the "anything else" entry below.
Uppercase ASCII letter
Append the lowercase version of the current input character (add 0x0020 to the character’s code point) to the current tag token’s tag name. Append the current input character to the temporary buffer.
Lowercase ASCII letter
Append the current input character to the current tag token’s tag name. Append the current input character to the temporary buffer.
Anything else
Switch to the §8.2.4.3 RCDATA state. Emit a U+003C LESS-THAN SIGN character token, a U+002F SOLIDUS character token, and a character token for each of the characters in the temporary buffer (in the order they were added to the buffer). Reconsume the current input character.
8.2.4.14. RAWTEXT less-than sign state

Consume the next input character:

U+002F SOLIDUS (/)
Set the temporary buffer to the empty string. Switch to the §8.2.4.15 RAWTEXT end tag open state.
Anything else
Switch to the §8.2.4.5 RAWTEXT state. Emit a U+003C LESS-THAN SIGN character token. Reconsume the current input character.
8.2.4.15. RAWTEXT end tag open state

Consume the next input character:

Uppercase ASCII letter
Create a new end tag token, and set its tag name to the lowercase version of the current input character (add 0x0020 to the character’s code point). Append the current input character to the temporary buffer. Finally, switch to the §8.2.4.16 RAWTEXT end tag name state. (Don’t emit the token yet; further details will be filled in before it is emitted.)
Lowercase ASCII letter
Create a new end tag token, and set its tag name to the current input character. Append the current input character to the temporary buffer. Finally, switch to the §8.2.4.16 RAWTEXT end tag name state. (Don’t emit the token yet; further details will be filled in before it is emitted.)
Anything else
Switch to the §8.2.4.5 RAWTEXT state. Emit a U+003C LESS-THAN SIGN character token and a U+002F SOLIDUS character token. Reconsume the current input character.
8.2.4.16. RAWTEXT end tag name state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
If the current end tag token is an appropriate end tag token, then switch to the §8.2.4.34 Before attribute name state. Otherwise, treat it as per the "anything else" entry below.
U+002F SOLIDUS (/)
If the current end tag token is an appropriate end tag token, then switch to the §8.2.4.43 Self-closing start tag state. Otherwise, treat it as per the "anything else" entry below.
U+003E GREATER-THAN SIGN (>)
If the current end tag token is an appropriate end tag token, then switch to the §8.2.4.1 Data state and emit the current tag token. Otherwise, treat it as per the "anything else" entry below.
Uppercase ASCII letter
Append the lowercase version of the current input character (add 0x0020 to the character’s code point) to the current tag token’s tag name. Append the current input character to the temporary buffer.
Lowercase ASCII letter
Append the current input character to the current tag token’s tag name. Append the current input character to the temporary buffer.
Anything else
Switch to the §8.2.4.5 RAWTEXT state. Emit a U+003C LESS-THAN SIGN character token, a U+002F SOLIDUS character token, and a character token for each of the characters in the temporary buffer (in the order they were added to the buffer). Reconsume the current input character.
8.2.4.17. Script data less-than sign state

Consume the next input character:

U+002F SOLIDUS (/)
Set the temporary buffer to the empty string. Switch to the §8.2.4.18 Script data end tag open state.
U+0021 EXCLAMATION MARK (!)
Switch to the §8.2.4.20 Script data escape start state. Emit a U+003C LESS-THAN SIGN character token and a U+0021 EXCLAMATION MARK character token.
Anything else
Switch to the §8.2.4.6 Script data state. Emit a U+003C LESS-THAN SIGN character token. Reconsume the current input character.
8.2.4.18. Script data end tag open state

Consume the next input character:

Uppercase ASCII letter
Create a new end tag token, and set its tag name to the lowercase version of the current input character (add 0x0020 to the character’s code point). Append the current input character to the temporary buffer. Finally, switch to the §8.2.4.19 Script data end tag name state. (Don’t emit the token yet; further details will be filled in before it is emitted.)
Lowercase ASCII letter
Create a new end tag token, and set its tag name to the current input character. Append the current input character to the temporary buffer. Finally, switch to the §8.2.4.19 Script data end tag name state. (Don’t emit the token yet; further details will be filled in before it is emitted.)
Anything else
Switch to the §8.2.4.6 Script data state. Emit a U+003C LESS-THAN SIGN character token and a U+002F SOLIDUS character token. Reconsume the current input character.
8.2.4.19. Script data end tag name state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
If the current end tag token is an appropriate end tag token, then switch to the §8.2.4.34 Before attribute name state. Otherwise, treat it as per the "anything else" entry below.
U+002F SOLIDUS (/)
If the current end tag token is an appropriate end tag token, then switch to the §8.2.4.43 Self-closing start tag state. Otherwise, treat it as per the "anything else" entry below.
U+003E GREATER-THAN SIGN (>)
If the current end tag token is an appropriate end tag token, then switch to the §8.2.4.1 Data state and emit the current tag token. Otherwise, treat it as per the "anything else" entry below.
Uppercase ASCII letter
Append the lowercase version of the current input character (add 0x0020 to the character’s code point) to the current tag token’s tag name. Append the current input character to the temporary buffer.
Lowercase ASCII letter
Append the current input character to the current tag token’s tag name. Append the current input character to the temporary buffer.
Anything else
Switch to the §8.2.4.6 Script data state. Emit a U+003C LESS-THAN SIGN character token, a U+002F SOLIDUS character token, and a character token for each of the characters in the temporary buffer (in the order they were added to the buffer). Reconsume the current input character.
8.2.4.20. Script data escape start state

Consume the next input character:

U+002D HYPHEN-MINUS (-)
Switch to the §8.2.4.21 Script data escape start dash state. Emit a U+002D HYPHEN-MINUS character token.
Anything else
Switch to the §8.2.4.6 Script data state. Reconsume the current input character.
8.2.4.21. Script data escape start dash state

Consume the next input character:

U+002D HYPHEN-MINUS (-)
Switch to the §8.2.4.24 Script data escaped dash dash state. Emit a U+002D HYPHEN-MINUS character token.
Anything else
Switch to the §8.2.4.6 Script data state. Reconsume the current input character.
8.2.4.22. Script data escaped state

Consume the next input character:

U+002D HYPHEN-MINUS (-)
Switch to the §8.2.4.23 Script data escaped dash state. Emit a U+002D HYPHEN-MINUS character token.
U+003C LESS-THAN SIGN (<)
Switch to the §8.2.4.25 Script data escaped less-than sign state.
U+0000 NULL
parse error. Emit a U+FFFD REPLACEMENT CHARACTER character token.
EOF
Switch to the §8.2.4.1 Data state. parse error. Reconsume the EOF character.
Anything else
Emit the current input character as a character token.
8.2.4.23. Script data escaped dash state

Consume the next input character:

U+002D HYPHEN-MINUS (-)
Switch to the §8.2.4.24 Script data escaped dash dash state. Emit a U+002D HYPHEN-MINUS character token.
U+003C LESS-THAN SIGN (<)
Switch to the §8.2.4.25 Script data escaped less-than sign state.
U+0000 NULL
parse error. Switch to the §8.2.4.22 Script data escaped state. Emit a U+FFFD REPLACEMENT CHARACTER character token.
EOF
parse error. Switch to the §8.2.4.1 Data state. Reconsume the EOF character.
Anything else
Switch to the §8.2.4.22 Script data escaped state. Emit the current input character as a character token.
8.2.4.24. Script data escaped dash dash state

Consume the next input character:

U+002D HYPHEN-MINUS (-)
Emit a U+002D HYPHEN-MINUS character token.
U+003C LESS-THAN SIGN (<)
Switch to the §8.2.4.25 Script data escaped less-than sign state.
U+003E GREATER-THAN SIGN (>)
Switch to the §8.2.4.6 Script data state. Emit a U+003E GREATER-THAN SIGN character token.
U+0000 NULL
parse error. Switch to the §8.2.4.22 Script data escaped state. Emit a U+FFFD REPLACEMENT CHARACTER character token.
EOF
parse error. Switch to the §8.2.4.1 Data state. Reconsume the EOF character.
Anything else
Switch to the §8.2.4.22 Script data escaped state. Emit the current input character as a character token.
8.2.4.25. Script data escaped less-than sign state

Consume the next input character:

U+002F SOLIDUS (/)
Set the temporary buffer to the empty string. Switch to the §8.2.4.26 Script data escaped end tag open state.
Uppercase ASCII letter
Set the temporary buffer to the empty string. Append the lowercase version of the current input character (add 0x0020 to the character’s code point) to the temporary buffer. Switch to the §8.2.4.28 Script data double escape start state. Emit a U+003C LESS-THAN SIGN character token and the current input character as a character token.
Lowercase ASCII letter
Set the temporary buffer to the empty string. Append the current input character to the temporary buffer. Switch to the §8.2.4.28 Script data double escape start state. Emit a U+003C LESS-THAN SIGN character token and the current input character as a character token.
Anything else
Switch to the §8.2.4.22 Script data escaped state. Emit a U+003C LESS-THAN SIGN character token. Reconsume the current input character.
8.2.4.26. Script data escaped end tag open state

Consume the next input character:

Uppercase ASCII letter
Create a new end tag token, and set its tag name to the lowercase version of the current input character (add 0x0020 to the character’s code point). Append the current input character to the temporary buffer. Finally, switch to the §8.2.4.27 Script data escaped end tag name state. (Don’t emit the token yet; further details will be filled in before it is emitted.)
Lowercase ASCII letter
Create a new end tag token, and set its tag name to the current input character. Append the current input character to the temporary buffer. Finally, switch to the §8.2.4.27 Script data escaped end tag name state. (Don’t emit the token yet; further details will be filled in before it is emitted.)
Anything else
Switch to the §8.2.4.22 Script data escaped state. Emit a U+003C LESS-THAN SIGN character token and a U+002F SOLIDUS character token. Reconsume the current input character.
8.2.4.27. Script data escaped end tag name state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
If the current end tag token is an appropriate end tag token, then switch to the §8.2.4.34 Before attribute name state. Otherwise, treat it as per the "anything else" entry below.
U+002F SOLIDUS (/)
If the current end tag token is an appropriate end tag token, then switch to the §8.2.4.43 Self-closing start tag state. Otherwise, treat it as per the "anything else" entry below.
U+003E GREATER-THAN SIGN (>)
If the current end tag token is an appropriate end tag token, then switch to the §8.2.4.1 Data state and emit the current tag token. Otherwise, treat it as per the "anything else" entry below.
Uppercase ASCII letter
Append the lowercase version of the current input character (add 0x0020 to the character’s code point) to the current tag token’s tag name. Append the current input character to the temporary buffer.
Lowercase ASCII letter
Append the current input character to the current tag token’s tag name. Append the current input character to the temporary buffer.
Anything else
Switch to the §8.2.4.22 Script data escaped state. Emit a U+003C LESS-THAN SIGN character token, a U+002F SOLIDUS character token, and a character token for each of the characters in the temporary buffer (in the order they were added to the buffer). Reconsume the current input character.
8.2.4.28. Script data double escape start state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
U+002F SOLIDUS (/)
U+003E GREATER-THAN SIGN (>)
If the temporary buffer is the string "script", then switch to the §8.2.4.29 Script data double escaped state. Otherwise, switch to the §8.2.4.22 Script data escaped state. Emit the current input character as a character token.
Uppercase ASCII letter
Append the lowercase version of the current input character (add 0x0020 to the character’s code point) to the temporary buffer. Emit the current input character as a character token.
Lowercase ASCII letter
Append the current input character to the temporary buffer. Emit the current input character as a character token.
Anything else
Switch to the §8.2.4.22 Script data escaped state. Reconsume the current input character.
8.2.4.29. Script data double escaped state

Consume the next input character:

U+002D HYPHEN-MINUS (-)
Switch to the §8.2.4.30 Script data double escaped dash state. Emit a U+002D HYPHEN-MINUS character token.
U+003C LESS-THAN SIGN (<)
Switch to the §8.2.4.32 Script data double escaped less-than sign state. Emit a U+003C LESS-THAN SIGN character token.
U+0000 NULL
parse error. Emit a U+FFFD REPLACEMENT CHARACTER character token.
EOF
parse error. Switch to the §8.2.4.1 Data state. Reconsume the EOF character.
Anything else
Emit the current input character as a character token.
8.2.4.30. Script data double escaped dash state

Consume the next input character:

U+002D HYPHEN-MINUS (-)
Switch to the §8.2.4.31 Script data double escaped dash dash state. Emit a U+002D HYPHEN-MINUS character token.
U+003C LESS-THAN SIGN (<)
Switch to the §8.2.4.32 Script data double escaped less-than sign state. Emit a U+003C LESS-THAN SIGN character token.
U+0000 NULL
parse error. Switch to the §8.2.4.29 Script data double escaped state. Emit a U+FFFD REPLACEMENT CHARACTER character token.
EOF
parse error. Switch to the §8.2.4.1 Data state. Reconsume the EOF character.
Anything else
Switch to the §8.2.4.29 Script data double escaped state. Emit the current input character as a character token.
8.2.4.31. Script data double escaped dash dash state

Consume the next input character:

U+002D HYPHEN-MINUS (-)
Emit a U+002D HYPHEN-MINUS character token.
U+003C LESS-THAN SIGN (<)
Switch to the §8.2.4.32 Script data double escaped less-than sign state. Emit a U+003C LESS-THAN SIGN character token.
U+003E GREATER-THAN SIGN (>)
Switch to the §8.2.4.6 Script data state. Emit a U+003E GREATER-THAN SIGN character token.
U+0000 NULL
parse error. Switch to the §8.2.4.29 Script data double escaped state. Emit a U+FFFD REPLACEMENT CHARACTER character token.
EOF
parse error. Switch to the §8.2.4.1 Data state. Reconsume the EOF character.
Anything else
Switch to the §8.2.4.29 Script data double escaped state. Emit the current input character as a character token.
8.2.4.32. Script data double escaped less-than sign state

Consume the next input character:

U+002F SOLIDUS (/)
Set the temporary buffer to the empty string. Switch to the §8.2.4.33 Script data double escape end state. Emit a U+002F SOLIDUS character token.
Anything else
Switch to the §8.2.4.29 Script data double escaped state. Reconsume the current input character.
8.2.4.33. Script data double escape end state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
U+002F SOLIDUS (/)
U+003E GREATER-THAN SIGN (>)
If the temporary buffer is the string "script", then switch to the §8.2.4.22 Script data escaped state. Otherwise, switch to the §8.2.4.29 Script data double escaped state. Emit the current input character as a character token.
Uppercase ASCII letter
Append the lowercase version of the current input character (add 0x0020 to the character’s code point) to the temporary buffer. Emit the current input character as a character token.
Lowercase ASCII letter
Append the current input character to the temporary buffer. Emit the current input character as a character token.
Anything else
Switch to the §8.2.4.29 Script data double escaped state. Reconsume the current input character.
8.2.4.34. Before attribute name state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Ignore the character.
U+002F SOLIDUS (/)
Switch to the §8.2.4.43 Self-closing start tag state.
U+003E GREATER-THAN SIGN (>)
Switch to the §8.2.4.1 Data state. Emit the current tag token.
Uppercase ASCII letter
Start a new attribute in the current tag token. Set that attribute’s name to the lowercase version of the current input character (add 0x0020 to the character’s code point), and its value to the empty string. Switch to the §8.2.4.35 Attribute name state.
U+0000 NULL
parse error. Start a new attribute in the current tag token. Set that attribute’s name to a U+FFFD REPLACEMENT CHARACTER character, and its value to the empty string. Switch to the §8.2.4.35 Attribute name state.
U+0022 QUOTATION MARK (")
U+0027 APOSTROPHE (')
U+003C LESS-THAN SIGN (<)
U+003D EQUALS SIGN (=)
parse error. Treat it as per the "anything else" entry below.
EOF
parse error. Switch to the §8.2.4.1 Data state. Reconsume the EOF character.
Anything else
Start a new attribute in the current tag token. Set that attribute’s name to the current input character, and its value to the empty string. Switch to the §8.2.4.35 Attribute name state.
8.2.4.35. Attribute name state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Switch to the §8.2.4.36 After attribute name state.
U+002F SOLIDUS (/)
Switch to the §8.2.4.43 Self-closing start tag state.
U+003D EQUALS SIGN (=)
Switch to the §8.2.4.37 Before attribute value state.
U+003E GREATER-THAN SIGN (>)
Switch to the §8.2.4.1 Data state. Emit the current tag token.
Uppercase ASCII letter
Append the lowercase version of the current input character (add 0x0020 to the character’s code point) to the current attribute’s name.
U+0000 NULL
parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the current attribute’s name.
U+0022 QUOTATION MARK (")
U+0027 APOSTROPHE (')
U+003C LESS-THAN SIGN (<)
parse error. Treat it as per the "anything else" entry below.
EOF
parse error. Switch to the §8.2.4.1 Data state. Reconsume the EOF character.
Anything else
Append the current input character to the current attribute’s name.

When the user agent leaves the attribute name state (and before emitting the tag token, if appropriate), the complete attribute’s name must be compared to the other attributes on the same token; if there is already an attribute on the token with the exact same name, then this is a parse error and the new attribute must be removed from the token.

If an attribute is so removed from a token, it, and the value that gets associated with it, if any, are never subsequently used by the parser, and are therefore effectively discarded. Removing the attribute in this way does not change its status as the "current attribute" for the purposes of the tokenizer, however.

8.2.4.36. After attribute name state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Ignore the character.
U+002F SOLIDUS (/)
Switch to the §8.2.4.43 Self-closing start tag state.
U+003D EQUALS SIGN (=)
Switch to the §8.2.4.37 Before attribute value state.
U+003E GREATER-THAN SIGN (>)
Switch to the §8.2.4.1 Data state. Emit the current tag token.
Uppercase ASCII letter
Start a new attribute in the current tag token. Set that attribute’s name to the lowercase version of the current input character (add 0x0020 to the character’s code point), and its value to the empty string. Switch to the §8.2.4.35 Attribute name state.
U+0000 NULL
parse error. Start a new attribute in the current tag token. Set that attribute’s name to a U+FFFD REPLACEMENT CHARACTER character, and its value to the empty string. Switch to the §8.2.4.35 Attribute name state.
U+0022 QUOTATION MARK (")
U+0027 APOSTROPHE (')
U+003C LESS-THAN SIGN (<)
parse error. Treat it as per the "anything else" entry below.
EOF
parse error. Switch to the §8.2.4.1 Data state. Reconsume the EOF character.
Anything else
Start a new attribute in the current tag token. Set that attribute’s name to the current input character, and its value to the empty string. Switch to the §8.2.4.35 Attribute name state.
8.2.4.37. Before attribute value state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Ignore the character.
U+0022 QUOTATION MARK (")
Switch to the §8.2.4.38 Attribute value (double-quoted) state.
U+0026 AMPERSAND (&)
Switch to the §8.2.4.40 Attribute value (unquoted) state. Reconsume the current input character.
U+0027 APOSTROPHE (')
Switch to the §8.2.4.39 Attribute value (single-quoted) state.
U+0000 NULL
parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the current attribute’s value. Switch to the §8.2.4.40 Attribute value (unquoted) state.
U+003E GREATER-THAN SIGN (>)
parse error. Switch to the §8.2.4.1 Data state. Emit the current tag token.
U+003C LESS-THAN SIGN (<)
U+003D EQUALS SIGN (=)
U+0060 GRAVE ACCENT (`)
parse error. Treat it as per the "anything else" entry below.
EOF
parse error. Switch to the §8.2.4.1 Data state. Reconsume the EOF character.
Anything else
Append the current input character to the current attribute’s value. Switch to the §8.2.4.40 Attribute value (unquoted) state.
8.2.4.38. Attribute value (double-quoted) state

Consume the next input character:

U+0022 QUOTATION MARK (")
Switch to the §8.2.4.42 After attribute value (quoted) state.
U+0026 AMPERSAND (&)
Switch to the §8.2.4.41 Character reference in attribute value state, with the additional allowed character being U+0022 QUOTATION MARK (").
U+0000 NULL
parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the current attribute’s value.
EOF
parse error. Switch to the §8.2.4.1 Data state. Reconsume the EOF character.
Anything else
Append the current input character to the current attribute’s value.
8.2.4.39. Attribute value (single-quoted) state

Consume the next input character:

U+0027 APOSTROPHE (')
Switch to the §8.2.4.42 After attribute value (quoted) state.
U+0026 AMPERSAND (&)
Switch to the §8.2.4.41 Character reference in attribute value state, with the additional allowed character being U+0027 APOSTROPHE (').
U+0000 NULL
parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the current attribute’s value.
EOF
parse error. Switch to the §8.2.4.1 Data state. Reconsume the EOF character.
Anything else
Append the current input character to the current attribute’s value.
8.2.4.40. Attribute value (unquoted) state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Switch to the §8.2.4.34 Before attribute name state.
U+0026 AMPERSAND (&)
Switch to the §8.2.4.41 Character reference in attribute value state, with the additional allowed character being U+003E GREATER-THAN SIGN (>).
U+003E GREATER-THAN SIGN (>)
Switch to the §8.2.4.1 Data state. Emit the current tag token.
U+0000 NULL
parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the current attribute’s value.
U+0022 QUOTATION MARK (")
U+0027 APOSTROPHE (')
U+003C LESS-THAN SIGN (<)
U+003D EQUALS SIGN (=)
U+0060 GRAVE ACCENT (`)
parse error. Treat it as per the "anything else" entry below.
EOF
parse error. Switch to the §8.2.4.1 Data state. Reconsume the EOF character.
Anything else
Append the current input character to the current attribute’s value.
8.2.4.41. Character reference in attribute value state

Attempt to consume a character reference.

If nothing is returned, append a U+0026 AMPERSAND character (&) to the current attribute’s value.

Otherwise, append the returned character tokens to the current attribute’s value.

Finally, switch back to the attribute value state that switched into this state.

8.2.4.42. After attribute value (quoted) state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Switch to the §8.2.4.34 Before attribute name state.
U+002F SOLIDUS (/)
Switch to the §8.2.4.43 Self-closing start tag state.
U+003E GREATER-THAN SIGN (>)
Switch to the §8.2.4.1 Data state. Emit the current tag token.
EOF
parse error. Switch to the §8.2.4.1 Data state. Reconsume the EOF character.
Anything else
parse error. Switch to the §8.2.4.34 Before attribute name state. Reconsume the character.
8.2.4.43. Self-closing start tag state

Consume the next input character:

U+003E GREATER-THAN SIGN (>)
Set the self-closing flag of the current tag token. Switch to the §8.2.4.1 Data state. Emit the current tag token.
EOF
parse error. Switch to the §8.2.4.1 Data state. Reconsume the EOF character.
Anything else
parse error. Switch to the §8.2.4.34 Before attribute name state. Reconsume the character.
8.2.4.44. Bogus comment state

Consume every character up to and including the first U+003E GREATER-THAN SIGN character (>) or the end of the file (EOF), whichever comes first. If more than one character was consumed, then emit a comment token whose data is the concatenation of all the characters starting from and including the character that caused the state machine to switch into the bogus comment state, up to and including the character immediately before the last consumed character (i.e., up to the character just before the U+003E or EOF character), but with any U+0000 NULL characters replaced by U+FFFD REPLACEMENT CHARACTER characters. (If the comment was started by the end of the file (EOF), the token is empty. Similarly, the token is empty if it was generated by the string "<!>".)

Switch to the §8.2.4.1 Data state.

If the end of the file was reached, reconsume the EOF character.

8.2.4.45. Markup declaration open state

If the next two characters are both U+002D HYPHEN-MINUS characters (-), consume those two characters, create a comment token whose data is the empty string, and switch to the §8.2.4.46 Comment start state.

Otherwise, if the next seven characters are an ASCII case-insensitive match for the word "DOCTYPE", then consume those characters and switch to the §8.2.4.52 DOCTYPE state.

Otherwise, if there is an adjusted current node and it is not an element in the HTML namespace and the next seven characters are a case-sensitive match for the string "[CDATA[" (the five uppercase letters "CDATA" with a U+005B LEFT SQUARE BRACKET character before and after), then consume those characters and switch to the §8.2.4.68 CDATA section state.

Otherwise, this is a parse error. Switch to the §8.2.4.44 Bogus comment state. The next character that is consumed, if any, is the first character that will be in the comment.

8.2.4.46. Comment start state

Consume the next input character:

U+002D HYPHEN-MINUS (-)
Switch to the §8.2.4.47 Comment start dash state.
U+0000 NULL
parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the comment token’s data. Switch to the §8.2.4.48 Comment state.
U+003E GREATER-THAN SIGN (>)
parse error. Switch to the §8.2.4.1 Data state. Emit the comment token.
EOF
parse error. Switch to the §8.2.4.1 Data state. Emit the comment token. Reconsume the EOF character.
Anything else
Append the current input character to the comment token’s data. Switch to the §8.2.4.48 Comment state.
8.2.4.47. Comment start dash state

Consume the next input character:

U+002D HYPHEN-MINUS (-)
Switch to the §8.2.4.50 Comment end state
U+0000 NULL
parse error. Append a U+002D HYPHEN-MINUS character (-) and a U+FFFD REPLACEMENT CHARACTER character to the comment token’s data. Switch to the §8.2.4.48 Comment state.
U+003E GREATER-THAN SIGN (>)
parse error. Switch to the §8.2.4.1 Data state. Emit the comment token.
EOF
parse error. Switch to the §8.2.4.1 Data state. Emit the comment token. Reconsume the EOF character.
Anything else
Append a U+002D HYPHEN-MINUS character (-) and the current input character to the comment token’s data. Switch to the §8.2.4.48 Comment state.
8.2.4.48. Comment state

Consume the next input character:

U+002D HYPHEN-MINUS (-)
Switch to the §8.2.4.49 Comment end dash state
U+0000 NULL
parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the comment token’s data.
EOF
parse error. Switch to the §8.2.4.1 Data state. Emit the comment token. Reconsume the EOF character.
Anything else
Append the current input character to the comment token’s data.
8.2.4.49. Comment end dash state

Consume the next input character:

U+002D HYPHEN-MINUS (-)
Switch to the §8.2.4.50 Comment end state
U+0000 NULL
parse error. Append a U+002D HYPHEN-MINUS character (-) and a U+FFFD REPLACEMENT CHARACTER character to the comment token’s data. Switch to the §8.2.4.48 Comment state.
EOF
parse error. Switch to the §8.2.4.1 Data state. Emit the comment token. Reconsume the EOF character.
Anything else
Append a U+002D HYPHEN-MINUS character (-) and the current input character to the comment token’s data. Switch to the §8.2.4.48 Comment state.
8.2.4.50. Comment end state

Consume the next input character:

U+003E GREATER-THAN SIGN (>)
Switch to the §8.2.4.1 Data state. Emit the comment token.
U+0000 NULL
parse error. Append two U+002D HYPHEN-MINUS characters (-) and a U+FFFD REPLACEMENT CHARACTER character to the comment token’s data. Switch to the §8.2.4.48 Comment state.
U+0021 EXCLAMATION MARK (!)
parse error. Switch to the §8.2.4.51 Comment end bang state.
U+002D HYPHEN-MINUS (-)
parse error. Append a U+002D HYPHEN-MINUS character (-) to the comment token’s data.
EOF
parse error. Switch to the §8.2.4.1 Data state. Emit the comment token. Reconsume the EOF character.
Anything else
parse error. Append two U+002D HYPHEN-MINUS characters (-) and the current input character to the comment token’s data. Switch to the §8.2.4.48 Comment state.
8.2.4.51. Comment end bang state

Consume the next input character:

U+002D HYPHEN-MINUS (-)
Append two U+002D HYPHEN-MINUS characters (-) and a U+0021 EXCLAMATION MARK character (!) to the comment token’s data. Switch to the §8.2.4.49 Comment end dash state.
U+003E GREATER-THAN SIGN (>)
Switch to the §8.2.4.1 Data state. Emit the comment token.
U+0000 NULL
parse error. Append two U+002D HYPHEN-MINUS characters (-), a U+0021 EXCLAMATION MARK character (!), and a U+FFFD REPLACEMENT CHARACTER character to the comment token’s data. Switch to the §8.2.4.48 Comment state.
EOF
parse error. Switch to the §8.2.4.1 Data state. Emit the comment token. Reconsume the EOF character.
Anything else
Append two U+002D HYPHEN-MINUS characters (-), a U+0021 EXCLAMATION MARK character (!), and the current input character to the comment token’s data. Switch to the §8.2.4.48 Comment state.
8.2.4.52. DOCTYPE state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Switch to the §8.2.4.53 Before DOCTYPE name state.
EOF
parse error. Switch to the §8.2.4.1 Data state. Create a new DOCTYPE token. Set its force-quirks flag to on. Emit the token. Reconsume the EOF character.
Anything else
parse error. Switch to the §8.2.4.53 Before DOCTYPE name state. Reconsume the character.
8.2.4.53. Before DOCTYPE name state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Ignore the character.
Uppercase ASCII letter
Create a new DOCTYPE token. Set the token’s name to the lowercase version of the current input character (add 0x0020 to the character’s code point). Switch to the §8.2.4.54 DOCTYPE name state.
U+0000 NULL
parse error. Create a new DOCTYPE token. Set the token’s name to a U+FFFD REPLACEMENT CHARACTER character. Switch to the §8.2.4.54 DOCTYPE name state.
U+003E GREATER-THAN SIGN (>)
parse error. Create a new DOCTYPE token. Set its force-quirks flag to on. Switch to the §8.2.4.1 Data state. Emit the token.
EOF
parse error. Switch to the §8.2.4.1 Data state. Create a new DOCTYPE token. Set its force-quirks flag to on. Emit the token. Reconsume the EOF character.
Anything else
Create a new DOCTYPE token. Set the token’s name to the current input character. Switch to the §8.2.4.54 DOCTYPE name state.
8.2.4.54. DOCTYPE name state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Switch to the §8.2.4.55 After DOCTYPE name state.
U+003E GREATER-THAN SIGN (>)
Switch to the §8.2.4.1 Data state. Emit the current DOCTYPE token.
Uppercase ASCII letter
Append the lowercase version of the current input character (add 0x0020 to the character’s code point) to the current DOCTYPE token’s name.
U+0000 NULL
parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the current DOCTYPE token’s name.
EOF
parse error. Switch to the §8.2.4.1 Data state. Set the DOCTYPE token’s force-quirks flag to on. Emit that DOCTYPE token. Reconsume the EOF character.
Anything else
Append the current input character to the current DOCTYPE token’s name.
8.2.4.55. After DOCTYPE name state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Ignore the character.
U+003E GREATER-THAN SIGN (>)
Switch to the §8.2.4.1 Data state. Emit the current DOCTYPE token.
EOF
parse error. Switch to the §8.2.4.1 Data state. Set the DOCTYPE token’s force-quirks flag to on. Emit that DOCTYPE token. Reconsume the EOF character.
Anything else

If the six characters starting from the current input character are an ASCII case-insensitive match for the word "PUBLIC", then consume those characters and switch to the §8.2.4.56 After DOCTYPE public keyword state.

Otherwise, if the six characters starting from the current input character are an ASCII case-insensitive match for the word "SYSTEM", then consume those characters and switch to the §8.2.4.62 After DOCTYPE system keyword state.

Otherwise, this is a parse error. Set the DOCTYPE token’s force-quirks flag to on. Switch to the §8.2.4.67 Bogus DOCTYPE state.

8.2.4.56. After DOCTYPE public keyword state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Switch to the §8.2.4.57 Before DOCTYPE public identifier state.
U+0022 QUOTATION MARK (")
parse error. Set the DOCTYPE token’s public identifier to the empty string (not missing), then switch to the §8.2.4.58 DOCTYPE public identifier (double-quoted) state.
U+0027 APOSTROPHE (')
parse error. Set the DOCTYPE token’s public identifier to the empty string (not missing), then switch to the §8.2.4.59 DOCTYPE public identifier (single-quoted) state.
U+003E GREATER-THAN SIGN (>)
parse error. Set the DOCTYPE token’s force-quirks flag to on. Switch to the §8.2.4.1 Data state. Emit that DOCTYPE token.
EOF
parse error. Switch to the §8.2.4.1 Data state. Set the DOCTYPE token’s force-quirks flag to on. Emit that DOCTYPE token. Reconsume the EOF character.
Anything else
parse error. Set the DOCTYPE token’s force-quirks flag to on. Switch to the §8.2.4.67 Bogus DOCTYPE state.
8.2.4.57. Before DOCTYPE public identifier state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Ignore the character.
U+0022 QUOTATION MARK (")
Set the DOCTYPE token’s public identifier to the empty string (not missing), then switch to the §8.2.4.58 DOCTYPE public identifier (double-quoted) state.
U+0027 APOSTROPHE (')
Set the DOCTYPE token’s public identifier to the empty string (not missing), then switch to the §8.2.4.59 DOCTYPE public identifier (single-quoted) state.
U+003E GREATER-THAN SIGN (>)
parse error. Set the DOCTYPE token’s force-quirks flag to on. Switch to the §8.2.4.1 Data state. Emit that DOCTYPE token.
EOF
parse error. Switch to the §8.2.4.1 Data state. Set the DOCTYPE token’s force-quirks flag to on. Emit that DOCTYPE token. Reconsume the EOF character.
Anything else
parse error. Set the DOCTYPE token’s force-quirks flag to on. Switch to the §8.2.4.67 Bogus DOCTYPE state.
8.2.4.58. DOCTYPE public identifier (double-quoted) state

Consume the next input character:

U+0022 QUOTATION MARK (")
Switch to the §8.2.4.60 After DOCTYPE public identifier state.
U+0000 NULL
parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the current DOCTYPE token’s public identifier.
U+003E GREATER-THAN SIGN (>)
parse error. Set the DOCTYPE token’s force-quirks flag to on. Switch to the §8.2.4.1 Data state. Emit that DOCTYPE token.
EOF
parse error. Switch to the §8.2.4.1 Data state. Set the DOCTYPE token’s force-quirks flag to on. Emit that DOCTYPE token. Reconsume the EOF character.
Anything else
Append the current input character to the current DOCTYPE token’s public identifier.
8.2.4.59. DOCTYPE public identifier (single-quoted) state

Consume the next input character:

U+0027 APOSTROPHE (')
Switch to the §8.2.4.60 After DOCTYPE public identifier state.
U+0000 NULL
parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the current DOCTYPE token’s public identifier.
U+003E GREATER-THAN SIGN (>)
parse error. Set the DOCTYPE token’s force-quirks flag to on. Switch to the §8.2.4.1 Data state. Emit that DOCTYPE token.
EOF
parse error. Switch to the §8.2.4.1 Data state. Set the DOCTYPE token’s force-quirks flag to on. Emit that DOCTYPE token. Reconsume the EOF character.
Anything else
Append the current input character to the current DOCTYPE token’s public identifier.
8.2.4.60. After DOCTYPE public identifier state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Switch to the §8.2.4.61 Between DOCTYPE public and system identifiers state.
U+003E GREATER-THAN SIGN (>)
Switch to the §8.2.4.1 Data state. Emit the current DOCTYPE token.
U+0022 QUOTATION MARK (")
parse error. Set the DOCTYPE token’s system identifier to the empty string (not missing), then switch to the §8.2.4.64 DOCTYPE system identifier (double-quoted) state.
U+0027 APOSTROPHE (')
parse error. Set the DOCTYPE token’s system identifier to the empty string (not missing), then switch to the §8.2.4.65 DOCTYPE system identifier (single-quoted) state.
EOF
parse error. Switch to the §8.2.4.1 Data state. Set the DOCTYPE token’s force-quirks flag to on. Emit that DOCTYPE token. Reconsume the EOF character.
Anything else
parse error. Set the DOCTYPE token’s force-quirks flag to on. Switch to the §8.2.4.67 Bogus DOCTYPE state.
8.2.4.61. Between DOCTYPE public and system identifiers state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Ignore the character.
U+003E GREATER-THAN SIGN (>)
Switch to the §8.2.4.1 Data state. Emit the current DOCTYPE token.
U+0022 QUOTATION MARK (")
Set the DOCTYPE token’s system identifier to the empty string (not missing), then switch to the §8.2.4.64 DOCTYPE system identifier (double-quoted) state.
U+0027 APOSTROPHE (')
Set the DOCTYPE token’s system identifier to the empty string (not missing), then switch to the §8.2.4.65 DOCTYPE system identifier (single-quoted) state.
EOF
parse error. Switch to the §8.2.4.1 Data state. Set the DOCTYPE token’s force-quirks flag to on. Emit that DOCTYPE token. Reconsume the EOF character.
Anything else
parse error. Set the DOCTYPE token’s force-quirks flag to on. Switch to the §8.2.4.67 Bogus DOCTYPE state.
8.2.4.62. After DOCTYPE system keyword state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Switch to the §8.2.4.63 Before DOCTYPE system identifier state.
U+0022 QUOTATION MARK (")
parse error. Set the DOCTYPE token’s system identifier to the empty string (not missing), then switch to the §8.2.4.64 DOCTYPE system identifier (double-quoted) state.
U+0027 APOSTROPHE (')
parse error. Set the DOCTYPE token’s system identifier to the empty string (not missing), then switch to the §8.2.4.65 DOCTYPE system identifier (single-quoted) state.
U+003E GREATER-THAN SIGN (>)
parse error. Set the DOCTYPE token’s force-quirks flag to on. Switch to the §8.2.4.1 Data state. Emit that DOCTYPE token.
EOF
parse error. Switch to the §8.2.4.1 Data state. Set the DOCTYPE token’s force-quirks flag to on. Emit that DOCTYPE token. Reconsume the EOF character.
Anything else
parse error. Set the DOCTYPE token’s force-quirks flag to on. Switch to the §8.2.4.67 Bogus DOCTYPE state.
8.2.4.63. Before DOCTYPE system identifier state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Ignore the character.
U+0022 QUOTATION MARK (")
Set the DOCTYPE token’s system identifier to the empty string (not missing), then switch to the §8.2.4.64 DOCTYPE system identifier (double-quoted) state.
U+0027 APOSTROPHE (')
Set the DOCTYPE token’s system identifier to the empty string (not missing), then switch to the §8.2.4.65 DOCTYPE system identifier (single-quoted) state.
U+003E GREATER-THAN SIGN (>)
parse error. Set the DOCTYPE token’s force-quirks flag to on. Switch to the §8.2.4.1 Data state. Emit that DOCTYPE token.
EOF
parse error. Switch to the §8.2.4.1 Data state. Set the DOCTYPE token’s force-quirks flag to on. Emit that DOCTYPE token. Reconsume the EOF character.
Anything else
parse error. Set the DOCTYPE token’s force-quirks flag to on. Switch to the §8.2.4.67 Bogus DOCTYPE state.
8.2.4.64. DOCTYPE system identifier (double-quoted) state

Consume the next input character:

U+0022 QUOTATION MARK (")
Switch to the §8.2.4.66 After DOCTYPE system identifier state.
U+0000 NULL
parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the current DOCTYPE token’s system identifier.
U+003E GREATER-THAN SIGN (>)
parse error. Set the DOCTYPE token’s force-quirks flag to on. Switch to the §8.2.4.1 Data state. Emit that DOCTYPE token.
EOF
parse error. Switch to the §8.2.4.1 Data state. Set the DOCTYPE token’s force-quirks flag to on. Emit that DOCTYPE token. Reconsume the EOF character.
Anything else
Append the current input character to the current DOCTYPE token’s system identifier.
8.2.4.65. DOCTYPE system identifier (single-quoted) state

Consume the next input character:

U+0027 APOSTROPHE (')
Switch to the §8.2.4.66 After DOCTYPE system identifier state.
U+0000 NULL
parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the current DOCTYPE token’s system identifier.
U+003E GREATER-THAN SIGN (>)
parse error. Set the DOCTYPE token’s force-quirks flag to on. Switch to the §8.2.4.1 Data state. Emit that DOCTYPE token.
EOF
parse error. Switch to the §8.2.4.1 Data state. Set the DOCTYPE token’s force-quirks flag to on. Emit that DOCTYPE token. Reconsume the EOF character.
Anything else
Append the current input character to the current DOCTYPE token’s system identifier.
8.2.4.66. After DOCTYPE system identifier state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Ignore the character.
U+003E GREATER-THAN SIGN (>)
Switch to the §8.2.4.1 Data state. Emit the current DOCTYPE token.
EOF
parse error. Switch to the §8.2.4.1 Data state. Set the DOCTYPE token’s force-quirks flag to on. Emit that DOCTYPE token. Reconsume the EOF character.
Anything else
parse error. Switch to the §8.2.4.67 Bogus DOCTYPE state. (This does not set the DOCTYPE token’s force-quirks flag to on.)
8.2.4.67. Bogus DOCTYPE state

Consume the next input character:

U+003E GREATER-THAN SIGN (>)
Switch to the §8.2.4.1 Data state. Emit the DOCTYPE token.
EOF
Switch to the §8.2.4.1 Data state. Emit the DOCTYPE token. Reconsume the EOF character.
Anything else
Ignore the character.
8.2.4.68. CDATA section state

Switch to the §8.2.4.1 Data state.

Consume every character up to the next occurrence of the three character sequence U+005D RIGHT SQUARE BRACKET U+005D RIGHT SQUARE BRACKET U+003E GREATER-THAN SIGN (]]>), or the end of the file (EOF), whichever comes first. Emit a series of character tokens consisting of all the characters consumed except the matching three character sequence at the end (if one was found before the end of the file).

If the end of the file was reached, reconsume the EOF character.

8.2.4.69. Tokenizing character references

This section defines how to consume a character reference, optionally with an additional allowed character, which, if specified where the algorithm is invoked, adds a character to the list of characters that cause there to not be a character reference.

This definition is used when parsing character references in text and in attributes.

The behavior depends on the identity of the next character (the one immediately after the U+0026 AMPERSAND character), as follows:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
U+003C LESS-THAN SIGN
U+0026 AMPERSAND
EOF
The additional allowed character, if there is one
Not a character reference. No characters are consumed, and nothing is returned. (This is not an error, either.)
U+0023 NUMBER SIGN (#)

Consume the U+0023 NUMBER SIGN.

The behavior further depends on the character after the U+0023 NUMBER SIGN:

U+0078 LATIN SMALL LETTER X
U+0058 LATIN CAPITAL LETTER X

Consume the X.

Follow the steps below, but using ASCII hex digits.

When it comes to interpreting the number, interpret it as a hexadecimal number.

Anything else

Follow the steps below, but using ASCII digits.

When it comes to interpreting the number, interpret it as a decimal number.

Consume as many characters as match the range of characters given above (ASCII hex digits or ASCII digits).

If no characters match the range, then don’t consume any characters (and unconsume the U+0023 NUMBER SIGN character and, if appropriate, the X character). This is a parse error; nothing is returned.

Otherwise, if the next character is a U+003B SEMICOLON, consume that too. If it isn’t, there is a parse error.

If one or more characters match the range, then take them all and interpret the string of characters as a number (either hexadecimal or decimal as appropriate).

If that number is one of the numbers in the first column of the following table, then this is a parse error. Find the row with that number in the first column, and return a character token for the Unicode character given in the second column of that row.

Number Unicode character
0x00 U+FFFD REPLACEMENT CHARACTER
0x80 U+20AC EURO SIGN (€)
0x82 U+201A SINGLE LOW-9 QUOTATION MARK (‚)
0x83 U+0192 LATIN SMALL LETTER F WITH HOOK (ƒ)
0x84 U+201E DOUBLE LOW-9 QUOTATION MARK („)
0x85 U+2026 HORIZONTAL ELLIPSIS (…)
0x86 U+2020 DAGGER (†)
0x87 U+2021 DOUBLE DAGGER (‡)
0x88 U+02C6 MODIFIER LETTER CIRCUMFLEX ACCENT (ˆ)
0x89 U+2030 PER MILLE SIGN (‰)
0x8A U+0160 LATIN CAPITAL LETTER S WITH CARON (Š)
0x8B U+2039 SINGLE LEFT-POINTING ANGLE QUOTATION MARK (‹)
0x8C U+0152 LATIN CAPITAL LIGATURE OE (Œ)
0x8E U+017D LATIN CAPITAL LETTER Z WITH CARON (Ž)
0x91 U+2018 LEFT SINGLE QUOTATION MARK (‘)
0x92 U+2019 RIGHT SINGLE QUOTATION MARK (’)
0x93 U+201C LEFT DOUBLE QUOTATION MARK (“)
0x94 U+201D RIGHT DOUBLE QUOTATION MARK (”)
0x95 U+2022 BULLET (•)
0x96 U+2013 EN DASH (–)
0x97 U+2014 EM DASH (—)
0x98 U+02DC SMALL TILDE (˜)
0x99 U+2122 TRADE MARK SIGN (™)
0x9A U+0161 LATIN SMALL LETTER S WITH CARON (š)
0x9B U+203A SINGLE RIGHT-POINTING ANGLE QUOTATION MARK (›)
0x9C U+0153 LATIN SMALL LIGATURE OE (œ)
0x9E U+017E LATIN SMALL LETTER Z WITH CARON (ž)
0x9F U+0178 LATIN CAPITAL LETTER Y WITH DIAERESIS (Ÿ)

Otherwise, if the number is in the range 0xD800 to 0xDFFF or is greater than 0x10FFFF, then this is a parse error. Return a U+FFFD REPLACEMENT CHARACTER character token.

Otherwise, return a character token for the Unicode character whose code point is that number.

Additionally, if the number is in the range 0x0001 to 0x0008, 0x000D to 0x001F, 0x007F to 0x009F, 0xFDD0 to 0xFDEF, or is one of 0x000B, 0xFFFE, 0xFFFF, 0x1FFFE, 0x1FFFF, 0x2FFFE, 0x2FFFF, 0x3FFFE, 0x3FFFF, 0x4FFFE, 0x4FFFF, 0x5FFFE, 0x5FFFF, 0x6FFFE, 0x6FFFF, 0x7FFFE, 0x7FFFF, 0x8FFFE, 0x8FFFF, 0x9FFFE, 0x9FFFF, 0xAFFFE, 0xAFFFF, 0xBFFFE, 0xBFFFF, 0xCFFFE, 0xCFFFF, 0xDFFFE, 0xDFFFF, 0xEFFFE, 0xEFFFF, 0xFFFFE, 0xFFFFF, 0x10FFFE, or 0x10FFFF, then this is a parse error.

Anything else

Consume the maximum number of characters possible, with the consumed characters matching one of the identifiers in the first column of the §8.5 Named character references table (in a case-sensitive manner).

If no match can be made, then no characters are consumed, and nothing is returned. In this case, if the characters after the U+0026 AMPERSAND character (&) consist of a sequence of one or more alphanumeric ASCII characters followed by a U+003B SEMICOLON character (;), then this is a parse error.

If the character reference is being consumed as part of an attribute, and the last character matched is not a U+003B SEMICOLON character (;), and the next character is either a U+003D EQUALS SIGN character (=) or an alphanumeric ASCII character, then, for historical reasons, all the characters that were matched after the U+0026 AMPERSAND character (&) must be unconsumed, and nothing is returned.

However, if this next character is in fact a U+003D EQUALS SIGN character (=), then this is a parse error, because some legacy user agents will misinterpret the markup in those cases.

Otherwise, a character reference is parsed. If the last character matched is not a U+003B SEMICOLON character (;), there is a parse error.

Return one or two character tokens for the character(s) corresponding to the character reference name (as given by the second column of the §8.5 Named character references table).

If the markup contains (not in an attribute) the string I’m &notit; I tell you, the character reference is parsed as "not", as in, I’m ¬it; I tell you (and this is a parse error). But if the markup was I’m &notin; I tell you, the character reference would be parsed as "notin;", resulting in I’m ∉ I tell you (and no parse error).

8.2.5. Tree construction

The input to the tree construction stage is a sequence of tokens from the tokenization stage. The tree construction stage is associated with a DOM Document object when a parser is created. The "output" of this stage consists of dynamically modifying or extending that document’s DOM tree.

This specification does not define when an interactive user agent has to render the Document so that it is available to the user, or when it has to begin accepting user input.


As each token is emitted from the tokenizer, the user agent must follow the appropriate steps from the following list, known as the tree construction dispatcher:

If the stack of open elements is empty
If the adjusted current node is an element in the HTML namespace
If the adjusted current node is a MathML text integration point and the token is a start tag whose tag name is neither "mglyph" nor "malignmark"
If the adjusted current node is a MathML text integration point and the token is a character token
If the adjusted current node is an annotation-xml element in the MathML namespace and the token is a start tag whose tag name is "svg"
If the adjusted current node is an HTML integration point and the token is a start tag
If the adjusted current node is an HTML integration point and the token is a character token
If the token is an end-of-file token
Process the token according to the rules given in the section corresponding to the current insertion mode in HTML content.
Otherwise
Process the token according to the rules given in the section for parsing tokens in foreign content.

The next token is the token that is about to be processed by the tree construction dispatcher (even if the token is subsequently just ignored).

A node is a MathML text integration point if it is one of the following elements:

A node is an HTML integration point if it is one of the following elements:

If the node in question is the context element passed to the HTML fragment parsing algorithm, then the start tag token for that element is the "fake" token created during by that HTML fragment parsing algorithm.


Not all of the tag names mentioned below are conformant tag names in this specification; many are included to handle legacy content. They still form part of the algorithm that implementations are required to implement to claim conformance.

The algorithm described below places no limit on the depth of the DOM tree generated, or on the length of tag names, attribute names, attribute values, Text nodes, etc. While implementors are encouraged to avoid arbitrary limits, it is recognized that practical concerns will likely force user agents to impose nesting depth constraints.

8.2.5.1. Creating and inserting nodes

While the parser is processing a token, it can enable or disable foster parenting. This affects the following algorithm.

The appropriate place for inserting a node, optionally using a particular override target, is the position in an element returned by running the following steps:

  1. If there was an override target specified, then let target be the override target.

    Otherwise, let target be the current node.

  2. Determine the adjusted insertion location using the first matching steps from the following list:

    If foster parenting is enabled and target is a table, tbody, tfoot, thead, or tr element

    Foster parenting happens when content is misnested in tables.

    Run these substeps:

    1. Let last template be the last template element in the stack of open elements, if any.
    2. Let last table be the last table element in the stack of open elements, if any.
    3. If there is a last template and either there is no last table, or there is one, but last template is lower (more recently added) than last table in the stack of open elements, then: let adjusted insertion location be inside last template’s template contents, after its last child (if any), and abort these substeps.
    4. If there is no last table, then let adjusted insertion location be inside the first element in the stack of open elements (the html element), after its last child (if any), and abort these substeps. (fragment case)
    5. If last table has a parent node, then let adjusted insertion location be inside last table’s parent node, immediately before last table, and abort these substeps.
    6. Let previous element be the element immediately above last table in the stack of open elements.
    7. Let adjusted insertion location be inside previous element, after its last child (if any).

    These steps are involved in part because it’s possible for elements, the table element in this case in particular, to have been moved by a script around in the DOM, or indeed removed from the DOM entirely, after the element was inserted by the parser.

    Otherwise

    Let adjusted insertion location be inside target, after its last child (if any).

  3. If the adjusted insertion location is inside a template element, let it instead be inside the template element’s template contents, after its last child (if any).

  4. Return the adjusted insertion location.


When the steps below require the user agent to create an element for a token in a particular given namespace and with a particular intended parent, the user agent must run the following steps:

  1. Create a node implementing the interface appropriate for the element type corresponding to the tag name of the token in given namespace (as given in the specification that defines that element, e.g., for an a element in the HTML namespace, this specification defines it to be the HTMLAnchorElement interface), with the tag name being the name of that element, with the node being in the given namespace, and with the attributes on the node being those given in the given token.

    The interface appropriate for an element in the HTML namespace that is not defined in this specification (or other applicable specifications) is HTMLUnknownElement. Elements in other namespaces whose interface is not defined by that namespace’s specification must use the interface Element.

    The node document of the newly created element must be the node document of the intended parent.

  2. If the newly created element has an xmlns attribute in the XMLNS namespace whose value is not exactly the same as the element’s namespace, that is a parse error. Similarly, if the newly created element has an xmlns:xlink attribute in the XMLNS namespace whose value is not the XLink namespace, that is a parse error.
  3. If the newly created element is a resettable element, invoke its reset algorithm. (This initializes the element’s value and checkedness based on the element’s attributes.)
  4. If the element is a form-associated element, and the form element pointer is not null, and there is no template element on the stack of open elements, and the newly created element is either not reassociateable or doesn’t have a form attribute, and the intended parent is in the same home subtree as the element pointed to by the form element pointer, associate the newly created element with the form element pointed to by the form element pointer, and suppress the running of the reset the form owner algorithm when the parser subsequently attempts to insert the element.
  5. Return the newly created element.

When the steps below require the user agent to insert a foreign element for a token in a given namespace, the user agent must run these steps:

  1. Let the adjusted insertion location be the appropriate place for inserting a node.
  2. Create an element for the token in the given namespace, with the intended parent being the element in which the adjusted insertion location finds itself.
  3. If it is possible to insert an element at the adjusted insertion location, then insert the newly created element at the adjusted insertion location.

    If the adjusted insertion location cannot accept more elements, e.g., because it’s a Document that already has an element child, then the newly created element is dropped on the floor.

  4. Push the element onto the stack of open elements so that it is the new current node.
  5. Return the newly created element.

When the steps below require the user agent to insert an HTML element for a token, the user agent must insert a foreign element for the token, in the HTML namespace.


When the steps below require the user agent to adjust MathML attributes for a token, then, if the token has an attribute named definitionurl, change its name to definitionURL (note the case difference).

When the steps below require the user agent to adjust SVG attributes for a token, then, for each attribute on the token whose attribute name is one of the ones in the first column of the following table, change the attribute’s name to the name given in the corresponding cell in the second column. (This fixes the case of SVG attributes that are not all lowercase.)

Attribute name on token Attribute name on element
attributename attributeName
attributetype attributeType
basefrequency baseFrequency
baseprofile baseProfile
calcmode calcMode
clippathunits clipPathUnits
diffuseconstant diffuseConstant
edgemode edgeMode
filterunits filterUnits
glyphref glyphRef
gradienttransform gradientTransform
gradientunits gradientUnits
kernelmatrix kernelMatrix
kernelunitlength kernelUnitLength
keypoints keyPoints
keysplines keySplines
keytimes keyTimes
lengthadjust lengthAdjust
limitingconeangle limitingConeAngle
markerheight markerHeight
markerunits markerUnits
markerwidth markerWidth
maskcontentunits maskContentUnits
maskunits maskUnits
numoctaves numOctaves
pathlength pathLength
patterncontentunits patternContentUnits
patterntransform patternTransform
patternunits patternUnits
pointsatx pointsAtX
pointsaty pointsAtY
pointsatz pointsAtZ
preservealpha preserveAlpha
preserveaspectratio preserveAspectRatio
primitiveunits primitiveUnits
refx refX
refy refY
repeatcount repeatCount
repeatdur repeatDur
requiredextensions requiredExtensions
requiredfeatures requiredFeatures
specularconstant specularConstant
specularexponent specularExponent
spreadmethod spreadMethod
startoffset startOffset
stddeviation stdDeviation
stitchtiles stitchTiles
surfacescale surfaceScale
systemlanguage systemLanguage
tablevalues tableValues
targetx targetX
targety targetY
textlength textLength
viewbox viewBox
viewtarget viewTarget
xchannelselector xChannelSelector
ychannelselector yChannelSelector
zoomandpan zoomAndPan

When the steps below require the user agent to adjust foreign attributes for a token, then, if any of the attributes on the token match the strings given in the first column of the following table, let the attribute be a namespaced attribute, with the prefix being the string given in the corresponding cell in the second column, the local name being the string given in the corresponding cell in the third column, and the namespace being the namespace given in the corresponding cell in the fourth column. (This fixes the use of namespaced attributes, in particular lang attributes in the XML namespace.)

Attribute name Prefix Local name Namespace
xlink:actuate xlink actuate XLink namespace
xlink:arcrole xlink arcrole XLink namespace
xlink:href xlink href XLink namespace
xlink:role xlink role XLink namespace
xlink:show xlink show XLink namespace
xlink:title xlink title XLink namespace
xlink:type xlink type XLink namespace
xml:lang xml lang XML namespace
xml:space xml space XML namespace
xmlns (none) xmlns XMLNS namespace
xmlns:xlink xmlns xlink XMLNS namespace

When the steps below require the user agent to insert a character while processing a token, the user agent must run the following steps:

  1. Let data be the characters passed to the algorithm, or, if no characters were explicitly specified, the character of the character token being processed.
  2. Let the adjusted insertion location be the appropriate place for inserting a node.
  3. If the adjusted insertion location is in a Document node, then abort these steps.

    The DOM will not let Document nodes have Text node children, so they are dropped on the floor.

  4. If there is a Text node immediately before the adjusted insertion location, then append data to that Text node’s data.

    Otherwise, create a new Text node whose data is data and whose node document is the same as that of the element in which the adjusted insertion location finds itself, and insert the newly created node at the adjusted insertion location.

Here are some sample inputs to the parser and the corresponding number of Text nodes that they result in, assuming a user agent that executes scripts.
Input Number of Text nodes
  A<script>
  var script = document.getElementsByTagName('script')[0];
  document.body.removeChild(script);
  </script>B
  
One Text node in the document, containing "AB".
  A<script>
  var text = document.createTextNode('B');
  document.body.appendChild(text);
  </script>C
  
Three Text nodes; "A" before the script, the script’s contents, and "BC" after the script (the parser appends to the Text node created by the script).
  A<script>
  var text = document.getElementsByTagName('script')[0].firstChild;
  text.data = 'B';
  document.body.appendChild(text);
  </script>C
  
Two adjacent Text nodes in the document, containing "A" and "BC".
  A<table>B<tr>C</tr>D</table>
  
One Text node before the table, containing "ABCD". (This is caused by foster parenting.)
  A<table><tr> B</tr> C</table>
  
One Text node before the table, containing "A B C" (A-space-B-space-C). (This is caused by foster parenting.)
  A<table><tr> B</tr> </em>C</table>
  
One Text node before the table, containing "A BC" (A-space-B-C), and one Text node inside the table (as a child of a tbody) with a single space character. (Space characters separated from non-space characters by non-character tokens are not affected by foster parenting, even if those other tokens then get ignored.)

When the steps below require the user agent to insert a comment while processing a comment token, optionally with an explicitly insertion position position, the user agent must run the following steps:

  1. Let data be the data given in the comment token being processed.
  2. If position was specified, then let the adjusted insertion location be position. Otherwise, let adjusted insertion location be the appropriate place for inserting a node.
  3. Create a Comment node whose data attribute is set to data and whose node document is the same as that of the node in which the adjusted insertion location finds itself.
  4. Insert the newly created node at the adjusted insertion location.

DOM mutation events must not fire for changes caused by the user agent parsing the document. This includes the parsing of any content inserted using document.write() and document.writeln() calls. [UIEVENTS]

However, mutation observers do fire, as required by the DOM specification.

8.2.5.2. Parsing elements that contain only text

The generic raw text element parsing algorithm and the generic RCDATA element parsing algorithm consist of the following steps. These algorithms are always invoked in response to a start tag token.

  1. Insert an HTML element for the token.
  2. If the algorithm that was invoked is the generic raw text element parsing algorithm, switch the tokenizer to the §8.2.4.5 RAWTEXT state; otherwise the algorithm invoked was the generic RCDATA element parsing algorithm, switch the tokenizer to the §8.2.4.3 RCDATA state.
  3. Let the original insertion mode be the current insertion mode.
  4. Then, switch the insertion mode to "text".
8.2.5.3. Closing elements that have implied end tags

When the steps below require the user agent to generate implied end tags, then, while the current node is a dd element, a dt element, an li element, an option element, an optgroup element, a p element, an rb element, an rp element, an rt element, or an rtc element, the user agent must pop the current node off the stack of open elements.

If a step requires the user agent to generate implied end tags but lists an element to exclude from the process, then the user agent must perform the above steps as if that element was not in the above list.

When the steps below require the user agent to generate all implied end tags thoroughly, then, while the current node is a caption element, a colgroup element, a dd element, a dt element, an li element, an optgroup element, an option element, a p element, an rb element, an rp element, an rt element, an rtc element, a tbody element, a td element, a tfoot element, a th element, a thead element, or a tr element, the user agent must pop the current node off the stack of open elements.

8.2.5.4. The rules for parsing tokens in HTML content
8.2.5.4.1. The "initial" insertion mode

When the user agent is to apply the rules for the "initial" insertion mode, the user agent must handle the token as follows:

A character token that is one of U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), or U+0020 SPACE
Ignore the token.
A comment token
Insert a comment as the last child of the Document object.
A DOCTYPE token

If the DOCTYPE token’s name is not a case-sensitive match for the string "html", or the token’s public identifier is not missing, or the token’s system identifier is neither missing nor a case-sensitive match for the string "about:legacy-compat", and none of the sets of conditions in the following list are matched, then there is a parse error.

  • The DOCTYPE token’s name is a case-sensitive match for the string "html", the token’s public identifier is the case-sensitive string "-//W3C//DTD HTML 4.0//EN", and the token’s system identifier is either missing or the case-sensitive string "https://www.w3.org/TR/REC-html40/strict.dtd".
  • The DOCTYPE token’s name is a case-sensitive match for the string "html", the token’s public identifier is the case-sensitive string "-//W3C//DTD HTML 4.01//EN", and the token’s system identifier is either missing or the case-sensitive string "https://www.w3.org/TR/html4/strict.dtd".
  • The DOCTYPE token’s name is a case-sensitive match for the string "html", the token’s public identifier is the case-sensitive string "-//W3C//DTD XHTML 1.0 Strict//EN", and the token’s system identifier is the case-sensitive string "https://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd".
  • The DOCTYPE token’s name is a case-sensitive match for the string "html", the token’s public identifier is the case-sensitive string "-//W3C//DTD XHTML 1.1//EN", and the token’s system identifier is the case-sensitive string "https://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd".

Conformance checkers may, based on the values (including presence or lack thereof) of the DOCTYPE token’s name, public identifier, or system identifier, switch to a conformance checking mode for another language (e.g., based on the DOCTYPE token a conformance checker could recognize that the document is an HTML 4.01-era document, and defer to an HTML 4.01 conformance checker.)

Append a DocumentType node to the Document node, with the name attribute set to the name given in the DOCTYPE token, or the empty string if the name was missing; the publicId attribute set to the public identifier given in the DOCTYPE token, or the empty string if the public identifier was missing; the systemId attribute set to the system identifier given in the DOCTYPE token, or the empty string if the system identifier was missing; and the other attributes specific to DocumentType objects set to null and empty lists as appropriate. Associate the DocumentType node with the Document object so that it is returned as the value of the doctype attribute of the Document object.

Then, if the document is not an iframe srcdoc document, and the DOCTYPE token matches one of the conditions in the following list, then set the Document to quirks mode:

  • The force-quirks flag is set to on.
  • The name is set to anything other than "html" (compared case-sensitively).
  • The public identifier is set to: "-//W3O//DTD W3 HTML Strict 3.0//EN//"
  • The public identifier is set to: "-/W3C/DTD HTML 4.0 Transitional/EN"
  • The public identifier is set to: "HTML"
  • The system identifier is set to: "https://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd"
  • The public identifier starts with: "+//Silmaril//dtd html Pro v0r11 19970101//"
  • The public identifier starts with: "-//AS//DTD HTML 3.0 asWedit + extensions//"
  • The public identifier starts with: "-//AdvaSoft Ltd//DTD HTML 3.0 asWedit + extensions//"
  • The public identifier starts with: "-//IETF//DTD HTML 2.0 Level 1//"
  • The public identifier starts with: "-//IETF//DTD HTML 2.0 Level 2//"
  • The public identifier starts with: "-//IETF//DTD HTML 2.0 Strict Level 1//"
  • The public identifier starts with: "-//IETF//DTD HTML 2.0 Strict Level 2//"
  • The public identifier starts with: "-//IETF//DTD HTML 2.0 Strict//"
  • The public identifier starts with: "-//IETF//DTD HTML 2.0//"
  • The public identifier starts with: "-//IETF//DTD HTML 2.1E//"
  • The public identifier starts with: "-//IETF//DTD HTML 3.0//"
  • The public identifier starts with: "-//IETF//DTD HTML 3.2 Final//"
  • The public identifier starts with: "-//IETF//DTD HTML 3.2//"
  • The public identifier starts with: "-//IETF//DTD HTML 3//"
  • The public identifier starts with: "-//IETF//DTD HTML Level 0//"
  • The public identifier starts with: "-//IETF//DTD HTML Level 1//"
  • The public identifier starts with: "-//IETF//DTD HTML Level 2//"
  • The public identifier starts with: "-//IETF//DTD HTML Level 3//"
  • The public identifier starts with: "-//IETF//DTD HTML Strict Level 0//"
  • The public identifier starts with: "-//IETF//DTD HTML Strict Level 1//"
  • The public identifier starts with: "-//IETF//DTD HTML Strict Level 2//"
  • The public identifier starts with: "-//IETF//DTD HTML Strict Level 3//"
  • The public identifier starts with: "-//IETF//DTD HTML Strict//"
  • The public identifier starts with: "-//IETF//DTD HTML//"
  • The public identifier starts with: "-//Metrius//DTD Metrius Presentational//"
  • The public identifier starts with: "-//Microsoft//DTD Internet Explorer 2.0 HTML Strict//"
  • The public identifier starts with: "-//Microsoft//DTD Internet Explorer 2.0 HTML//"
  • The public identifier starts with: "-//Microsoft//DTD Internet Explorer 2.0 Tables//"
  • The public identifier starts with: "-//Microsoft//DTD Internet Explorer 3.0 HTML Strict//"
  • The public identifier starts with: "-//Microsoft//DTD Internet Explorer 3.0 HTML//"
  • The public identifier starts with: "-//Microsoft//DTD Internet Explorer 3.0 Tables//"
  • The public identifier starts with: "-//Netscape Comm. Corp.//DTD HTML//"
  • The public identifier starts with: "-//Netscape Comm. Corp.//DTD Strict HTML//"
  • The public identifier starts with: "-//O’Reilly and Associates//DTD HTML 2.0//"
  • The public identifier starts with: "-//O’Reilly and Associates//DTD HTML Extended 1.0//"
  • The public identifier starts with: "-//O’Reilly and Associates//DTD HTML Extended Relaxed 1.0//"
  • The public identifier starts with: "-//SQ//DTD HTML 2.0 HoTMetaL + extensions//"
  • The public identifier starts with: "-//SoftQuad Software//DTD HoTMetaL PRO 6.0::19990601::extensions to HTML 4.0//"
  • The public identifier starts with: "-//SoftQuad//DTD HoTMetaL PRO 4.0::19971010::extensions to HTML 4.0//"
  • The public identifier starts with: "-//Spyglass//DTD HTML 2.0 Extended//"
  • The public identifier starts with: "-//Sun Microsystems Corp.//DTD HotJava HTML//"
  • The public identifier starts with: "-//Sun Microsystems Corp.//DTD HotJava Strict HTML//"
  • The public identifier starts with: "-//W3C//DTD HTML 3 1995-03-24//"
  • The public identifier starts with: "-//W3C//DTD HTML 3.2 Draft//"
  • The public identifier starts with: "-//W3C//DTD HTML 3.2 Final//"
  • The public identifier starts with: "-//W3C//DTD HTML 3.2//"
  • The public identifier starts with: "-//W3C//DTD HTML 3.2S Draft//"
  • The public identifier starts with: "-//W3C//DTD HTML 4.0 Frameset//"
  • The public identifier starts with: "-//W3C//DTD HTML 4.0 Transitional//"
  • The public identifier starts with: "-//W3C//DTD HTML Experimental 19960712//"
  • The public identifier starts with: "-//W3C//DTD HTML Experimental 970421//"
  • The public identifier starts with: "-//W3C//DTD W3 HTML//"
  • The public identifier starts with: "-//W3O//DTD W3 HTML 3.0//"
  • The public identifier starts with: "-//WebTechs//DTD Mozilla HTML 2.0//"
  • The public identifier starts with: "-//WebTechs//DTD Mozilla HTML//"
  • The system identifier is missing and the public identifier starts with: "-//W3C//DTD HTML 4.01 Frameset//"
  • The system identifier is missing and the public identifier starts with: "-//W3C//DTD HTML 4.01 Transitional//"

Otherwise, if the document is not an iframe srcdoc document, and the DOCTYPE token matches one of the conditions in the following list, then set the Document to limited-quirks mode:

  • The public identifier starts with: "-//W3C//DTD XHTML 1.0 Frameset//"
  • The public identifier starts with: "-//W3C//DTD XHTML 1.0 Transitional//"
  • The system identifier is not missing and the public identifier starts with: "-//W3C//DTD HTML 4.01 Frameset//"
  • The system identifier is not missing and the public identifier starts with: "-//W3C//DTD HTML 4.01 Transitional//"

The system identifier and public identifier strings must be compared to the values given in the lists above in an ASCII case-insensitive manner. A system identifier whose value is the empty string is not considered missing for the purposes of the conditions above.

Then, switch the insertion mode to "before html".

Anything else

If the document is not an iframe srcdoc document, then this is a parse error; set the Document to quirks mode.

In any case, switch the insertion mode to "before html", then reprocess the token.

8.2.5.4.2. The "before html" insertion mode

When the user agent is to apply the rules for the "before html" insertion mode, the user agent must handle the token as follows:

A DOCTYPE token
parse error. Ignore the token.
A comment token
Insert a comment as the last child of the Document object.
A character token that is one of U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), or U+0020 SPACE
Ignore the token.
A start tag whose tag name is "html"

Create an element for the token in the HTML namespace, with the Document as the intended parent. Append it to the Document object. Put this element in the stack of open elements.

If the Document is being loaded as part of navigation of a browsing context, run these steps:

  1. If the result of running match service worker registration for the Document’s address is non-null, run the application cache selection algorithm passing the Document object with no manifest.
  2. Otherwise, run these substeps:

    1. If the newly created element has a manifest attribute whose value is not the empty string, then parse the value of that attribute, relative to the newly created element, and if that is successful, run the application cache selection algorithm passing the Document object with the result of applying the URL serializer algorithm to the resulting URL string with the exclude fragment flag set.
    2. Otherwise, run the application cache selection algorithm passing the Document object with no manifest.

Switch the insertion mode to "before head".

An end tag whose tag name is one of: "head", "body", "html", "br"
Act as described in the "anything else" entry below.
Any other end tag
parse error. Ignore the token.
Anything else

Create an html element whose node document is the Document object. Append it to the Document object. Put this element in the stack of open elements.

If the Document is being loaded as part of navigation of a browsing context, then: run the application cache selection algorithm with no manifest, passing it the Document object.

Switch the insertion mode to "before head", then reprocess the token.

The root element can end up being removed from the Document object, e.g., by scripts; nothing in particular happens in such cases, content continues being appended to the nodes as described in the next section.

8.2.5.4.3. The "before head" insertion mode

When the user agent is to apply the rules for the "before head" insertion mode, the user agent must handle the token as follows:

A character token that is one of U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), or U+0020 SPACE
Ignore the token.
A comment token
Insert a comment.
A DOCTYPE token
parse error. Ignore the token.
A start tag whose tag name is "html"
Process the token using the rules for the "in body" insertion mode.
A start tag whose tag name is "head"

Insert an HTML element for the token.

Set the head element pointer to the newly created head element.

Switch the insertion mode to "in head".

An end tag whose tag name is one of: "head", "body", "html", "br"

Act as described in the "anything else" entry below.

Any other end tag

parse error. Ignore the token.

Anything else

Insert an HTML element for a "head" start tag token with no attributes.

Set the head element pointer to the newly created head element.

Switch the insertion mode to "in head".

Reprocess the current token.

8.2.5.4.4. The "in head" insertion mode

When the user agent is to apply the rules for the "in head" insertion mode, the user agent must handle the token as follows:

A character token that is one of U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), or U+0020 SPACE
Insert the character.
A comment token
Insert a comment.
A DOCTYPE token
parse error. Ignore the token.
A start tag whose tag name is "html"
Process the token using the rules for the "in body" insertion mode.
A start tag whose tag name is one of: "base", "basefont", "bgsound", "link"

Insert an HTML element for the token. Immediately pop the current node off the stack of open elements.

Acknowledge the token’s self-closing flag, if it is set.

A start tag whose tag name is "meta"

Insert an HTML element for the token. Immediately pop the current node off the stack of open elements.

Acknowledge the token’s self-closing flag, if it is set.

If the element has a charset attribute, and getting an encoding from its value results in an encoding, and the confidence is currently tentative, then change the encoding to the resulting encoding.

Otherwise, if the element has an http-equiv attribute whose value is an ASCII case-insensitive match for the string "Content-Type", and the element has a content attribute, and applying the algorithm for extracting a character encoding from a meta element to that attribute’s value returns an encoding, and the confidence is currently tentative, then change the encoding to the extracted encoding.

A start tag whose tag name is "title"
Follow the generic RCDATA element parsing algorithm.
A start tag whose tag name is "noscript", if the scripting flag is enabled
A start tag whose tag name is one of: "noframes", "style"
Follow the generic raw text element parsing algorithm.
A start tag whose tag name is "noscript", if the scripting flag is disabled

Insert an HTML element for the token.

Switch the insertion mode to "in head noscript".

A start tag whose tag name is "script"

Run these steps:

  1. Let the adjusted insertion location be the appropriate place for inserting a node.
  2. Create an element for the token in the HTML namespace, with the intended parent being the element in which the adjusted insertion location finds itself.
  3. Mark the element as being "parser-inserted" and unset the element’s "non-blocking" flag.

    This ensures that, if the script is external, any document.write() calls in the script will execute in-line, instead of blowing the document away, as would happen in most other cases. It also prevents the script from executing until the end tag is seen.

  4. If the parser was originally created for the HTML fragment parsing algorithm, then mark the script element as "already started". (fragment case)
  5. Insert the newly created element at the adjusted insertion location.
  6. Push the element onto the stack of open elements so that it is the new current node.
  7. Switch the tokenizer to the §8.2.4.6 Script data state.
  8. Let the original insertion mode be the current insertion mode.
  9. Switch the insertion mode to "text".
An end tag whose tag name is "head"

Pop the current node (which will be the head element) off the stack of open elements.

Switch the insertion mode to "after head".

An end tag whose tag name is one of: "body", "html", "br"
Act as described in the "anything else" entry below.
A start tag whose tag name is "template"

Insert an HTML element for the token.

Insert a marker at the end of the list of active formatting elements.

Set the frameset-ok flag to "not ok".

Switch the insertion mode to "in template".

Push "in template" onto the stack of template insertion modes so that it is the new current template insertion mode.

An end tag whose tag name is "template"

If there is no template element on the stack of open elements, then this is a parse error; ignore the token.

Otherwise, run these steps:

  1. Generate all implied end tags thoroughly.
  2. If the current node is not a template element, then this is a parse error.
  3. Pop elements from the stack of open elements until a template element has been popped from the stack.
  4. Clear the list of active formatting elements up to the last marker.
  5. Pop the current template insertion mode off the stack of template insertion modes.
  6. Reset the insertion mode appropriately.
A start tag whose tag name is "head"
Any other end tag
parse error. Ignore the token.
Anything else

Pop the current node (which will be the head element) off the stack of open elements.

Switch the insertion mode to "after head".

Reprocess the token.

8.2.5.4.5. The "in head noscript" insertion mode

When the user agent is to apply the rules for the "in head noscript" insertion mode, the user agent must handle the token as follows:

A DOCTYPE token
parse error. Ignore the token.
A start tag whose tag name is "html"

Process the token using the rules for the "in body" insertion mode.

An end tag whose tag name is "noscript"

Pop the current node (which will be a noscript element) from the stack of open elements; the new current node will be a head element.

Switch the insertion mode to "in head".

A character token that is one of U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), or U+0020 SPACE
A comment token
A start tag whose tag name is one of: "basefont", "bgsound", "link", "meta", "noframes", "style"

Process the token using the rules for the "in head" insertion mode.

An end tag whose tag name is "br"
Act as described in the "anything else" entry below.
A start tag whose tag name is one of: "head", "noscript"
Any other end tag
parse error. Ignore the token.
Anything else

parse error.

Pop the current node (which will be a noscript element) from the stack of open elements; the new current node will be a head element.

Switch the insertion mode to "in head".

Reprocess the token.

8.2.5.4.6. The "after head" insertion mode

When the user agent is to apply the rules for the "after head" insertion mode, the user agent must handle the token as follows:

A character token that is one of U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), or U+0020 SPACE
Insert the character.
A comment token
Insert a comment.
A DOCTYPE token
parse error. Ignore the token.
A start tag whose tag name is "html"

Process the token using the rules for the "in body" insertion mode.

A start tag whose tag name is "body"

Insert an HTML element for the token.

Set the frameset-ok flag to "not ok".

Switch the insertion mode to "in body".

A start tag whose tag name is "frameset"

Insert an HTML element for the token.

Switch the insertion mode to "in frameset".

A start tag whose tag name is one of: "base", "basefont", "bgsound", "link", "meta", "noframes", "script", "style", "template", "title"

parse error.

Push the node pointed to by the head element pointer onto the stack of open elements.

Process the token using the rules for the "in head" insertion mode.

Remove the node pointed to by the head element pointer from the stack of open elements. (It might not be the current node at this point.)

The head element pointer cannot be null at this point.

An end tag whose tag name is "template"
Process the token using the rules for the "in head" insertion mode.
An end tag whose tag name is one of: "body", "html", "br"
Act as described in the "anything else" entry below.
A start tag whose tag name is "head"
Any other end tag
parse error. Ignore the token.
Anything else

Insert an HTML element for a "body" start tag token with no attributes.

Switch the insertion mode to "in body".

Reprocess the current token.

8.2.5.4.7. The "in body" insertion mode

When the user agent is to apply the rules for the "in body" insertion mode, the user agent must handle the token as follows:

A character token that is U+0000 NULL

parse error. Ignore the token.

A character token that is one of U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), or U+0020 SPACE

reconstruct the active formatting elements, if any.

Insert the token’s character.

Any other character token

reconstruct the active formatting elements, if any.

Insert the token’s character.

Set the frameset-ok flag to "not ok".

A comment token
Insert a comment.
A DOCTYPE token
parse error. Ignore the token.
A start tag whose tag name is "html"

parse error.

If there is a template element on the stack of open elements, then ignore the token.

Otherwise, for each attribute on the token, check to see if the attribute is already present on the top element of the stack of open elements. If it is not, add the attribute and its corresponding value to that element.

A start tag whose tag name is one of: "base", "basefont", "bgsound", "link", "meta", "noframes", "script", "style", "template", "title"
An end tag whose tag name is "template"
Process the token using the rules for the "in head" insertion mode.
A start tag whose tag name is "body"

parse error.

If the second element on the stack of open elements is not a body element, if the stack of open elements has only one node on it, or if there is a template element on the stack of open elements, then ignore the token. (fragment case)

Otherwise, set the frameset-ok flag to "not ok"; then, for each attribute on the token, check to see if the attribute is already present on the body element (the second element) on the stack of open elements, and if it is not, add the attribute and its corresponding value to that element.

A start tag whose tag name is "frameset"

parse error.

If the stack of open elements has only one node on it, or if the second element on the stack of open elements is not a body element, then ignore the token. (fragment case)

If the frameset-ok flag is set to "not ok", ignore the token.

Otherwise, run the following steps:

  1. Remove the second element on the stack of open elements from its parent node, if it has one.
  2. Pop all the nodes from the bottom of the stack of open elements, from the current node up to, but not including, the root html element.
  3. Insert an HTML element for the token.
  4. Switch the insertion mode to "in frameset".
An end-of-file token

If the stack of template insertion modes is not empty, then process the token using the rules for the "in template" insertion mode.

Otherwise, follow these steps:

  1. If there is a node in the stack of open elements that is not either a dd element, a dt element, an li element, an optgroup element, an option element, a p element, an rb element, an rp element, an rt element, an rtc element, a tbody element, a td element, a tfoot element, a th element, a thead element, a tr element, the body element, or the html element, then this is a parse error.
  2. Stop parsing.
An end tag whose tag name is "body"

If the stack of open elements does not have a body element in scope, this is a parse error; ignore the token.

Otherwise, if there is a node in the stack of open elements that is not either a dd element, a dt element, an li element, an optgroup element, an option element, a p element, an rb element, an rp element, an rt element, an rtc element, a tbody element, a td element, a tfoot element, a th element, a thead element, a tr element, the body element, or the html element, then this is a parse error.

Switch the insertion mode to "after body".

An end tag whose tag name is "html"

If the stack of open elements does not have a body element in scope, this is a parse error; ignore the token.

Otherwise, if there is a node in the stack of open elements that is not either a dd element, a dt element, an li element, an optgroup element, an option element, a p element, an rb element, an rp element, an rt element, an rtc element, a tbody element, a td element, a tfoot element, a th element, a thead element, a tr element, the body element, or the html element, then this is a parse error.

Switch the insertion mode to "after body".

Reprocess the token.

A start tag whose tag name is one of: "address", "article", "aside", "blockquote", "center", "details", "dir", "div", "dl", "fieldset", "figcaption", "figure", "footer", "header", "main", "menu", "nav", "ol", "p", "section", "summary", "ul"

If the stack of open elements has a p element in button scope, then close a p element.

Insert an HTML element for the token.

A start tag whose tag name is one of: "h1", "h2", "h3", "h4", "h5", "h6"

If the stack of open elements has a p element in button scope, then close a p element.

If the current node is an HTML element whose tag name is one of "h1", "h2", "h3", "h4", "h5", or "h6", then this is a parse error; pop the current node off the stack of open elements.

Insert an HTML element for the token.

A start tag whose tag name is one of: "pre", "listing"

If the stack of open elements has a p element in button scope, then close a p element.

Insert an HTML element for the token.

If the next token is a U+000A LINE FEED (LF) character token, then ignore that token and move on to the next one. (Newlines at the start of pre blocks are ignored as an authoring convenience.)

Set the frameset-ok flag to "not ok".

A start tag whose tag name is "form"

If the form element pointer is not null, and there is no template element on the stack of open elements, then this is a parse error; ignore the token.

Otherwise:

If the stack of open elements has a p element in button scope, then close a p element.

Insert an HTML element for the token, and, if there is no template element on the stack of open elements, set the form element pointer to point to the element created.

A start tag whose tag name is "li"

Run these steps:

  1. Set the frameset-ok flag to "not ok".
  2. Initialize node to be the current node (the bottommost node of the stack).
  3. Loop: If node is an li element, then run these substeps:

    1. Generate implied end tags, except for li elements.
    2. If the current node is not an li element, then this is a parse error.
    3. Pop elements from the stack of open elements until an li element has been popped from the stack.
    4. Jump to the step labeled done below.
  4. If node is in the special category, but is not an address, div, or p element, then jump to the step labeled done below.
  5. Otherwise, set node to the previous entry in the stack of open elements and return to the step labeled loop.
  6. Done: If the stack of open elements has a p element in button scope, then close a p element.
  7. Finally, insert an HTML element for the token.
A start tag whose tag name is one of: "dd", "dt"

Run these steps:

  1. Set the frameset-ok flag to "not ok".
  2. Initialize node to be the current node (the bottommost node of the stack).
  3. Loop: If node is a dd element, then run these substeps:

    1. Generate implied end tags, except for dd elements.
    2. If the current node is not a dd element, then this is a parse error.
    3. Pop elements from the stack of open elements until a dd element has been popped from the stack.
    4. Jump to the step labeled done below.
  4. If node is a dt element, then run these substeps:

    1. Generate implied end tags, except for dt elements.
    2. If the current node is not a dt element, then this is a parse error.
    3. Pop elements from the stack of open elements until a dt element has been popped from the stack.
    4. Jump to the step labeled done below.
  5. If node is in the special category, but is not an address, div, or p element, then jump to the step labeled done below.
  6. Otherwise, set node to the previous entry in the stack of open elements and return to the step labeled loop.
  7. Done: If the stack of open elements has a p element in button scope, then close a p element.
  8. Finally, insert an HTML element for the token.
A start tag whose tag name is "plaintext"

If the stack of open elements has a p element in button scope, then close a p element.

Insert an HTML element for the token.

Switch the tokenizer to the §8.2.4.7 PLAINTEXT state.

Once a start tag with the tag name "plaintext" has been seen, that will be the last token ever seen other than character tokens (and the end-of-file token), because there is no way to switch out of the §8.2.4.7 PLAINTEXT state.

A start tag whose tag name is "button"
  1. If the stack of open elements has a button element in scope, then run these substeps:

    1. parse error.
    2. Generate implied end tags.
    3. Pop elements from the stack of open elements until a button element has been popped from the stack.
  2. reconstruct the active formatting elements, if any.
  3. Insert an HTML element for the token.
  4. Set the frameset-ok flag to "not ok".
An end tag whose tag name is one of: "address", "article", "aside", "blockquote", "button", "center", "details", "dir", "div", "dl", "fieldset", "figcaption", "figure", "footer", "header", "listing", "main", "menu", "nav", "ol", "pre", "section", "summary", "ul"

If the stack of open elements does not have an element in scope that is an HTML element with the same tag name as that of the token, then this is a parse error; ignore the token.

Otherwise, run these steps:

  1. Generate implied end tags.
  2. If the current node is not an HTML element with the same tag name as that of the token, then this is a parse error.
  3. Pop elements from the stack of open elements until an HTML element with the same tag name as the token has been popped from the stack.
An end tag whose tag name is "form"

If there is no template element on the stack of open elements, then run these substeps:

  1. Let node be the element that the form element pointer is set to, or null if it is not set to an element.
  2. Set the form element pointer to null.
  3. If node is null or if the stack of open elements does not have node in scope, then this is a parse error; abort these steps and ignore the token.
  4. Generate implied end tags.
  5. If the current node is not node, then this is a parse error.
  6. Remove node from the stack of open elements.

If there is a template element on the stack of open elements, then run these substeps instead:

  1. If the stack of open elements does not have a form element in scope, then this is a parse error; abort these steps and ignore the token.
  2. Generate implied end tags.
  3. If the current node is not a form element, then this is a parse error.
  4. Pop elements from the stack of open elements until a form element has been popped from the stack.
An end tag whose tag name is "p"

If the stack of open elements does not have a p element in button scope, then this is a parse error; insert an HTML element for a "p" start tag token with no attributes.

Close a p element.

An end tag whose tag name is "li"

If the stack of open elements does not have an li element in list item scope, then this is a parse error; ignore the token.

Otherwise, run these steps:

  1. Generate implied end tags, except for li elements.
  2. If the current node is not an li element, then this is a parse error.
  3. Pop elements from the stack of open elements until an li element has been popped from the stack.
An end tag whose tag name is one of: "dd", "dt"

If the stack of open elements does not have an element in scope that is an HTML element with the same tag name as that of the token, then this is a parse error; ignore the token.

Otherwise, run these steps:

  1. Generate implied end tags, except for html elements with the same tag name as the token.
  2. If the current node is not an HTML element with the same tag name as that of the token, then this is a parse error.
  3. Pop elements from the stack of open elements until an HTML element with the same tag name as the token has been popped from the stack.
An end tag whose tag name is one of: "h1", "h2", "h3", "h4", "h5", "h6"

If the stack of open elements does not have an element in scope that is an HTML element and whose tag name is one of "h1", "h2", "h3", "h4", "h5", or "h6", then this is a parse error; ignore the token.

Otherwise, run these steps:

  1. Generate implied end tags.
  2. If the current node is not an HTML element with the same tag name as that of the token, then this is a parse error.
  3. Pop elements from the stack of open elements until an HTML element whose tag name is one of "h1", "h2", "h3", "h4", "h5", or "h6" has been popped from the stack.
An end tag whose tag name is "sarcasm"
Take a deep breath, then act as described in the "any other end tag" entry below.
A start tag whose tag name is "a"

If the list of active formatting elements contains an a element between the end of the list and the last marker on the list (or the start of the list if there is no marker on the list), then this is a parse error; run the adoption agency algorithm for the tag name "a", then remove that element from the list of active formatting elements and the stack of open elements if the adoption agency algorithm didn’t already remove it (it might not have if the element is not in table scope).

In the non-conforming stream <a href="a">a<table><a href="b">b</table>x, the first a element would be closed upon seeing the second one, and the "x" character would be inside a link to "b", not to "a". This is despite the fact that the outer a element is not in table scope (meaning that a regular </a> end tag at the start of the table wouldn’t close the outer a element). The result is that the two a elements are indirectly nested inside each other — non-conforming markup will often result in non-conforming DOMs when parsed.

reconstruct the active formatting elements, if any.

Insert an HTML element for the token. Push onto the list of active formatting elements that element.

A start tag whose tag name is one of: "b", "big", "code", "em", "font", "i", "s", "small", "strike", "strong", "tt", "u"

reconstruct the active formatting elements, if any.

Insert an HTML element for the token. Push onto the list of active formatting elements that element.

A start tag whose tag name is "nobr"

reconstruct the active formatting elements, if any.

If the stack of open elements has a nobr element in scope, then this is a parse error; run the adoption agency algorithm for the tag name "nobr", then once again reconstruct the active formatting elements, if any.

Insert an HTML element for the token. Push onto the list of active formatting elements that element.

An end tag whose tag name is one of: "a", "b", "big", "code", "em", "font", "i", "nobr", "s", "small", "strike", "strong", "tt", "u"

Run the adoption agency algorithm for the token’s tag name.

A start tag whose tag name is one of: "applet", "marquee", "object"

reconstruct the active formatting elements, if any.

Insert an HTML element for the token.

Insert a marker at the end of the list of active formatting elements.

Set the frameset-ok flag to "not ok".

An end tag token whose tag name is one of: "applet", "marquee", "object"

If the stack of open elements does not have an element in scope that is an HTML element with the same tag name as that of the token, then this is a parse error; ignore the token.

Otherwise, run these steps:

  1. Generate implied end tags.
  2. If the current node is not an HTML element with the same tag name as that of the token, then this is a parse error.
  3. Pop elements from the stack of open elements until an HTML element with the same tag name as the token has been popped from the stack.
  4. Clear the list of active formatting elements up to the last marker.
A start tag whose tag name is "table"

If the Document is not set to quirks mode, and the stack of open elements has a p element in button scope, then close a p element.

Insert an HTML element for the token.

Set the frameset-ok flag to "not ok".

Switch the insertion mode to "in table".

An end tag whose tag name is "br"

parse error. Drop the attributes from the token, and act as described in the next entry; i.e., act as if this was a "br" start tag token with no attributes, rather than the end tag token that it actually is.

A start tag whose tag name is one of: "area", "br", "embed", "img", "keygen", "wbr"

reconstruct the active formatting elements, if any.

Insert an HTML element for the token. Immediately pop the current node off the stack of open elements.

Acknowledge the token’s self-closing flag, if it is set.

Set the frameset-ok flag to "not ok".

A start tag whose tag name is "input"

reconstruct the active formatting elements, if any.

Insert an HTML element for the token. Immediately pop the current node off the stack of open elements.

Acknowledge the token’s self-closing flag, if it is set.

If the token does not have an attribute with the name "type", or if it does, but that attribute’s value is not an ASCII case-insensitive match for the string "hidden", then: set the frameset-ok flag to "not ok".

A start tag whose tag name is one of: "menuitem", "param", "source", "track"

Insert an HTML element for the token. Immediately pop the current node off the stack of open elements.

Acknowledge the token’s self-closing flag, if it is set.

A start tag whose tag name is "hr"

If the stack of open elements has a p element in button scope, then close a p element.

Insert an HTML element for the token. Immediately pop the current node off the stack of open elements.

Acknowledge the token’s self-closing flag, if it is set.

Set the frameset-ok flag to "not ok".

A start tag whose tag name is "image"

parse error. Change the token’s tag name to "img" and reprocess it. (Don’t ask.)

A start tag whose tag name is "textarea"

Run these steps:

  1. Insert an HTML element for the token.
  2. If the next token is a U+000A LINE FEED (LF) character token, then ignore that token and move on to the next one. (Newlines at the start of textarea elements are ignored as an authoring convenience.)
  3. Switch the tokenizer to the §8.2.4.3 RCDATA state.
  4. Let the original insertion mode be the current insertion mode.
  5. Set the frameset-ok flag to "not ok".
  6. Switch the insertion mode to "text".
A start tag whose tag name is "xmp"

If the stack of open elements has a p element in button scope, then close a p element.

reconstruct the active formatting elements, if any.

Set the frameset-ok flag to "not ok".

Follow the generic raw text element parsing algorithm.

A start tag whose tag name is "iframe"

Set the frameset-ok flag to "not ok".

Follow the generic raw text element parsing algorithm.

A start tag whose tag name is "noembed"
A start tag whose tag name is "noscript", if the scripting flag is enabled

Follow the generic raw text element parsing algorithm.

A start tag whose tag name is "select"

reconstruct the active formatting elements, if any.

Insert an HTML element for the token.

Set the frameset-ok flag to "not ok".

If the insertion mode is one of "in table", "in caption", "in table body", "in row", or "in cell", then switch the insertion mode to "in select in table". Otherwise, switch the insertion mode to "in select".

A start tag whose tag name is one of: "optgroup", "option"

If the current node is an option element, then pop the current node off the stack of open elements.

reconstruct the active formatting elements, if any.

Insert an HTML element for the token.

A start tag whose tag name is one of: "rb", "rtc"
If the stack of open elements has a ruby element in scope, then generate implied end tags. If the current node is not now a ruby element, this is a parse error.

Insert an HTML element for the token.

A start tag whose tag name is one of: "rp", "rt"

If the stack of open elements has a ruby element in scope, then generate implied end tags, except for rtc elements. If the current node is not then a ruby element or an rtc element, this is a parse error.

Insert an HTML element for the token.

A start tag whose tag name is "math"

reconstruct the active formatting elements, if any.

Adjust MathML attributes for the token. (This fixes the case of MathML attributes that are not all lowercase.)

Adjust foreign attributes for the token. (This fixes the use of namespaced attributes, in particular XLink.)

Insert a foreign element for the token, in the MathML namespace.

If the token has its self-closing flag set, pop the current node off the stack of open elements and acknowledge the token’s self-closing flag.

A start tag whose tag name is "svg"

reconstruct the active formatting elements, if any.

Adjust SVG attributes for the token. (This fixes the case of SVG attributes that are not all lowercase.)

Adjust foreign attributes for the token. (This fixes the use of namespaced attributes, in particular XLink in SVG.)

Insert a foreign element for the token, in the SVG namespace.

If the token has its self-closing flag set, pop the current node off the stack of open elements and acknowledge the token’s self-closing flag.

A start tag whose tag name is one of: "caption", "col", "colgroup", "frame", "head", "tbody", "td", "tfoot", "th", "thead", "tr"

parse error. Ignore the token.

Any other start tag

reconstruct the active formatting elements, if any.

Insert an HTML element for the token.

This element will be an ordinary element.

Any other end tag

Run these steps:

  1. Initialize node to be the current node (the bottommost node of the stack).
  2. Loop: If node is an HTML element with the same tag name as the token, then:
    1. Generate implied end tags, except for html elements with the same tag name as the token.
    2. If node is not the current node, then this is a parse error.
    3. Pop all the nodes from the current node up to node, including node, then stop these steps.
  3. Otherwise, if node is in the special category, then this is a parse error; ignore the token, and abort these steps.
  4. Set node to the previous entry in the stack of open elements.
  5. Return to the step labeled loop.

When the steps above say the user agent is to close a p element, it means that the user agent must run the following steps:

  1. Generate implied end tags, except for p elements.
  2. If the current node is not a p element, then this is a parse error.
  3. Pop elements from the stack of open elements until a p element has been popped from the stack.

The adoption agency algorithm, which takes as its only argument a tag name subject for which the algorithm is being run, consists of the following steps:

  1. If the current node is an HTML element whose tag name is subject, and the current node is not in the list of active formatting elements, then pop the current node off the stack of open elements, and abort these steps.
  2. Let outer loop counter be zero.
  3. Outer loop: If outer loop counter is greater than or equal to eight, then abort these steps.
  4. Increment outer loop counter by one.
  5. Let formatting element be the last element in the list of active formatting elements that:

    • is between the end of the list and the last marker in the list, if any, or the start of the list otherwise, and
    • has the tag name subject.

    If there is no such element, then abort these steps and instead act as described in the "any other end tag" entry above.

  6. If formatting element is not in the stack of open elements, then this is a parse error; remove the element from the list, and abort these steps.
  7. If formatting element is in the stack of open elements, but the element is not in scope, then this is a parse error; abort these steps.
  8. If formatting element is not the current node, this is a parse error. (But do not abort these steps.)
  9. Let furthest block be the topmost node in the stack of open elements that is lower in the stack than formatting element, and is an element in the special category. There might not be one.
  10. If there is no furthest block, then the user agent must first pop all the nodes from the bottom of the stack of open elements, from the current node up to and including formatting element, then remove formatting element from the list of active formatting elements, and finally abort these steps.
  11. Let common ancestor be the element immediately above formatting element in the stack of open elements.
  12. Let a bookmark note the position of formatting element in the list of active formatting elements relative to the elements on either side of it in the list.
  13. Let node and last node be furthest block. Follow these steps:

    1. Let inner loop counter be zero.
    2. Inner loop: Increment inner loop counter by one.
    3. Let node be the element immediately above node in the stack of open elements, or if node is no longer in the stack of open elements (e.g., because it got removed by this algorithm), the element that was immediately above node in the stack of open elements before node was removed.
    4. If node is formatting element, then go to the next step in the overall algorithm.
    5. If inner loop counter is greater than three and node is in the list of active formatting elements, then remove node from the list of active formatting elements.
    6. If node is not in the list of active formatting elements, then remove node from the stack of open elements and then go back to the step labeled inner loop.
    7. Create an element for the token for which the element node was created, in the HTML namespace, with common ancestor as the intended parent; replace the entry for node in the list of active formatting elements with an entry for the new element, replace the entry for node in the stack of open elements with an entry for the new element, and let node be the new element.
    8. If last node is furthest block, then move the aforementioned bookmark to be immediately after the new node in the list of active formatting elements.
    9. Insert last node into node, first removing it from its previous parent node if any.
    10. Let last node be node.
    11. Return to the step labeled inner loop.
  14. Insert whatever last node ended up being in the previous step at the appropriate place for inserting a node, but using common ancestor as the override target.
  15. Create an element for the token for which formatting element was created, in the HTML namespace, with furthest block as the intended parent.
  16. Take all of the child nodes of furthest block and append them to the element created in the last step.
  17. Append that new element to furthest block.
  18. Remove formatting element from the list of active formatting elements, and insert the new element into the list of active formatting elements at the position of the aforementioned bookmark.
  19. Remove formatting element from the stack of open elements, and insert the new element into the stack of open elements immediately below the position of furthest block in that stack.
  20. Jump back to the step labeled outer loop.

This algorithm’s name, the "adoption agency algorithm", comes from the way it causes elements to change parents, and is in contrast with other possible algorithms for dealing with misnested content, which included the "incest algorithm", the "secret affair algorithm", and the "Heizenberg algorithm".

8.2.5.4.8. The "text" insertion mode

When the user agent is to apply the rules for the "text" insertion mode, the user agent must handle the token as follows:

A character token

Insert the token’s character.

This can never be a U+0000 NULL character; the tokenizer converts those to U+FFFD REPLACEMENT CHARACTER characters.

An end-of-file token

parse error.

If the current node is a script element, mark the script element as "already started".

Pop the current node off the stack of open elements.

Switch the insertion mode to the original insertion mode and reprocess the token.

An end tag whose tag name is "script"

If the JavaScript execution context stack is empty, perform a microtask checkpoint.

Let script be the current node (which will be a script element).

Pop the current node off the stack of open elements.

Switch the insertion mode to the original insertion mode.

Let the old insertion point have the same value as the current insertion point. Let the insertion point be just before the next input character.

Increment the parser’s script nesting level by one.

Prepare the script. This might cause some script to execute, which might cause new characters to be inserted into the tokenizer, and might cause the tokenizer to output more tokens, resulting in a reentrant invocation of the parser.

Decrement the parser’s script nesting level by one. If the parser’s script nesting level is zero, then set the parser pause flag to false.

Let the insertion point have the value of the old insertion point. (In other words, restore the insertion point to its previous value. This value might be the "undefined" value.)

At this stage, if there is a pending parsing-blocking script, then:

If the script nesting level is not zero:

Set the parser pause flag to true, and abort the processing of any nested invocations of the tokenizer, yielding control back to the caller. (Tokenization will resume when the caller returns to the "outer" tree construction stage.)

The tree construction stage of this particular parser is being called reentrantly, say from a call to document.write().

Otherwise:

Run these steps:

  1. Let the script be the pending parsing-blocking script. There is no longer a pending parsing-blocking script.
  2. Block the tokenizer for this instance of the HTML parser, such that the event loop will not run tasks that invoke the tokenizer.
  3. If the parser’s Document has a style sheet that is blocking scripts or the script’s "ready to be parser-executed" flag is not set: spin the event loop until the parser’s Document has no style sheet that is blocking scripts and the script’s "ready to be parser-executed" flag is set.
  4. If this parser has been aborted in the meantime, abort these steps.

    This could happen if, e.g., while the spin the event loop algorithm is running, the browsing context gets closed, or the document.open() method gets invoked on the Document.

  5. Unblock the tokenizer for this instance of the HTML parser, such that tasks that invoke the tokenizer can again be run.
  6. Let the insertion point be just before the next input character.
  7. Increment the parser’s script nesting level by one (it should be zero before this step, so this sets it to one).
  8. Execute the script.
  9. Decrement the parser’s script nesting level by one. If the parser’s script nesting level is zero (which it always should be at this point), then set the parser pause flag to false.
  10. Let the insertion point be undefined again.
  11. If there is once again a pending parsing-blocking script, then repeat these steps from step 1.
Any other end tag

Pop the current node off the stack of open elements.

Switch the insertion mode to the original insertion mode.

8.2.5.4.9. The "in table" insertion mode

When the user agent is to apply the rules for the "in table" insertion mode, the user agent must handle the token as follows:

A character token, if the current node is table, tbody, tfoot, thead, or tr element

Let the pending table character tokens be an empty list of tokens.

Let the original insertion mode be the current insertion mode.

Switch the insertion mode to "in table text" and reprocess the token.

A comment token
Insert a comment.
A DOCTYPE token
parse error. Ignore the token.
A start tag whose tag name is "caption"

Clear the stack back to a table context. (See below.)

Insert a marker at the end of the list of active formatting elements.

Insert an HTML element for the token, then switch the insertion mode to "in caption".

A start tag whose tag name is "colgroup"

Clear the stack back to a table context. (See below.)

Insert an HTML element for the token, then switch the insertion mode to "in column group".

A start tag whose tag name is "col"

Clear the stack back to a table context. (See below.)

Insert an HTML element for a "colgroup" start tag token with no attributes, then switch the insertion mode to "in column group".

Reprocess the current token.

A start tag whose tag name is one of: "tbody", "tfoot", "thead"

Clear the stack back to a table context. (See below.)

Insert an HTML element for the token, then switch the insertion mode to "in table body".

A start tag whose tag name is one of: "td", "th", "tr"

Clear the stack back to a table context. (See below.)

Insert an HTML element for a "tbody" start tag token with no attributes, then switch the insertion mode to "in table body".

Reprocess the current token.

A start tag whose tag name is "table"

parse error.

If the stack of open elements does not have a table element in table scope, ignore the token.

Otherwise:

Pop elements from this stack until a table element has been popped from the stack.

Reset the insertion mode appropriately.

Reprocess the token.

An end tag whose tag name is "table"

If the stack of open elements does not have a table element in table scope, this is a parse error; ignore the token.

Otherwise:

Pop elements from this stack until a table element has been popped from the stack.

Reset the insertion mode appropriately.

An end tag whose tag name is one of: "body", "caption", "col", "colgroup", "html", "tbody", "td", "tfoot", "th", "thead", "tr"
parse error. Ignore the token.
A start tag whose tag name is one of: "style", "script", "template"
An end tag whose tag name is "template"

Process the token using the rules for the "in head" insertion mode.

A start tag whose tag name is "input"

If the token does not have an attribute with the name "type", or if it does, but that attribute’s value is not an ASCII case-insensitive match for the string "hidden", then: act as described in the "anything else" entry below.

Otherwise:

parse error.

Insert an HTML element for the token.

Pop that input element off the stack of open elements.

Acknowledge the token’s self-closing flag, if it is set.

A start tag whose tag name is "form"

parse error.

If there is a template element on the stack of open elements, or if the form element pointer is not null, ignore the token.

Otherwise:

Insert an HTML element for the token, and set the form element pointer to point to the element created.

Pop that form element off the stack of open elements.

An end-of-file token

Process the token using the rules for the "in body" insertion mode.

Anything else

parse error. Enable foster parenting, process the token using the rules for the "in body" insertion mode, and then disable foster parenting.

When the steps above require the user agent to clear the stack back to a table context, it means that the user agent must, while the current node is not a table, template, or html element, pop elements from the stack of open elements.

This is the same list of elements as used in the has an element in table scope steps.

The current node being an html element after this process is a fragment case.

8.2.5.4.10. The "in table text" insertion mode

When the user agent is to apply the rules for the "in table text" insertion mode, the user agent must handle the token as follows:

A character token that is U+0000 NULL

parse error. Ignore the token.

Any other character token

Append the character token to the pending table character tokens list.

Anything else

If any of the tokens in the pending table character tokens list are character tokens that are not space characters, then this is a parse error: reprocess the character tokens in the pending table character tokens list using the rules given in the "anything else" entry in the "in table" insertion mode.

Otherwise, insert the characters given by the pending table character tokens list.

Switch the insertion mode to the original insertion mode and reprocess the token.

8.2.5.4.11. The "in caption" insertion mode

When the user agent is to apply the rules for the "in caption" insertion mode, the user agent must handle the token as follows:

An end tag whose tag name is "caption"

If the stack of open elements does not have a caption element in table scope, this is a parse error; ignore the token. (fragment case)

Otherwise:

Generate implied end tags.

Now, if the current node is not a caption element, then this is a parse error.

Pop elements from this stack until a caption element has been popped from the stack.

Clear the list of active formatting elements up to the last marker.

Switch the insertion mode to "in table".

A start tag whose tag name is one of: "caption", "col", "colgroup", "tbody", "td", "tfoot", "th", "thead", "tr"
An end tag whose tag name is "table"

If the stack of open elements does not have a caption element in table scope, this is a parse error; ignore the token. (fragment case)

Otherwise:

Generate implied end tags.

Now, if the current node is not a caption element, then this is a parse error.

Pop elements from this stack until a caption element has been popped from the stack.

Clear the list of active formatting elements up to the last marker.

Switch the insertion mode to "in table".

Reprocess the token.

An end tag whose tag name is one of: "body", "col", "colgroup", "html", "tbody", "td", "tfoot", "th", "thead", "tr"
parse error. Ignore the token.
Anything else

Process the token using the rules for the "in body" insertion mode.

8.2.5.4.12. The "in column group" insertion mode

When the user agent is to apply the rules for the "in column group" insertion mode, the user agent must handle the token as follows:

A character token that is one of U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), or U+0020 SPACE
Insert the character.
A comment token
Insert a comment.
A DOCTYPE token
parse error. Ignore the token.
A start tag whose tag name is "html"

Process the token using the rules for the "in body" insertion mode.

A start tag whose tag name is "col"

Insert an HTML element for the token. Immediately pop the current node off the stack of open elements.

Acknowledge the token’s self-closing flag, if it is set.

An end tag whose tag name is "colgroup"

If the current node is not a colgroup element, then this is a parse error; ignore the token.

Otherwise, pop the current node from the stack of open elements. Switch the insertion mode to "in table".

An end tag whose tag name is "col"
parse error. Ignore the token.
A start tag whose tag name is "template"
An end tag whose tag name is "template"

Process the token using the rules for the "in head" insertion mode.

An end-of-file token

Process the token using the rules for the "in body" insertion mode.

Anything else

If the current node is not a colgroup element, then this is a parse error; ignore the token.

Otherwise, pop the current node from the stack of open elements.

Switch the insertion mode to "in table".

Reprocess the token.

8.2.5.4.13. The "in table body" insertion mode

When the user agent is to apply the rules for the "in table body" insertion mode, the user agent must handle the token as follows:

A start tag whose tag name is "tr"

Clear the stack back to a table body context. (See below.)

Insert an HTML element for the token, then switch the insertion mode to "in row".

A start tag whose tag name is one of: "th", "td"

parse error.

Clear the stack back to a table body context. (See below.)

Insert an HTML element for a "tr" start tag token with no attributes, then switch the insertion mode to "in row".

Reprocess the current token.

An end tag whose tag name is one of: "tbody", "tfoot", "thead"

If the stack of open elements does not have an element in table scope that is an HTML element with the same tag name as the token, this is a parse error; ignore the token.

Otherwise:

Clear the stack back to a table body context. (See below.)

Pop the current node from the stack of open elements. Switch the insertion mode to "in table".

A start tag whose tag name is one of: "caption", "col", "colgroup", "tbody", "tfoot", "thead"
An end tag whose tag name is "table"

If the stack of open elements does not have a tbody, thead, or tfoot element in table scope, this is a parse error; ignore the token.

Otherwise:

Clear the stack back to a table body context. (See below.)

Pop the current node from the stack of open elements. Switch the insertion mode to "in table".

Reprocess the token.

An end tag whose tag name is one of: "body", "caption", "col", "colgroup", "html", "td", "th", "tr"
parse error. Ignore the token.
Anything else
Process the token using the rules for the "in table" insertion mode.

When the steps above require the user agent to clear the stack back to a table body context, it means that the user agent must, while the current node is not a tbody, tfoot, thead, template, or html element, pop elements from the stack of open elements.

The current node being an html element after this process is a fragment case.

8.2.5.4.14. The "in row" insertion mode

When the user agent is to apply the rules for the "in row" insertion mode, the user agent must handle the token as follows:

A start tag whose tag name is one of: "th", "td"

Clear the stack back to a table row context. (See below.)

Insert an HTML element for the token, then switch the insertion mode to "in cell".

Insert a marker at the end of the list of active formatting elements.

An end tag whose tag name is "tr"

If the stack of open elements does not have a tr element in table scope, this is a parse error; ignore the token.

Otherwise:

Clear the stack back to a table row context. (See below.)

Pop the current node (which will be a tr element) from the stack of open elements. Switch the insertion mode to "in table body".

A start tag whose tag name is one of: "caption", "col", "colgroup", "tbody", "tfoot", "thead", "tr"
An end tag whose tag name is "table"

If the stack of open elements does not have a tr element in table scope, this is a parse error; ignore the token.

Otherwise:

Clear the stack back to a table row context. (See below.)

Pop the current node (which will be a tr element) from the stack of open elements. Switch the insertion mode to "in table body".

Reprocess the token.

An end tag whose tag name is one of: "tbody", "tfoot", "thead"

If the stack of open elements does not have an element in table scope that is an HTML element with the same tag name as the token, this is a parse error; ignore the token.

If the stack of open elements does not have a tr element in table scope, ignore the token.

Otherwise:

Clear the stack back to a table row context. (See below.)

Pop the current node (which will be a tr element) from the stack of open elements. Switch the insertion mode to "in table body".

Reprocess the token.

An end tag whose tag name is one of: "body", "caption", "col", "colgroup", "html", "td", "th"
parse error. Ignore the token.
Anything else

Process the token using the rules for the "in table" insertion mode.

When the steps above require the user agent to clear the stack back to a table row context, it means that the user agent must, while the current node is not a tr, template, or html element, pop elements from the stack of open elements.

The current node being an html element after this process is a fragment case.

8.2.5.4.15. The "in cell" insertion mode

When the user agent is to apply the rules for the "in cell" insertion mode, the user agent must handle the token as follows:

An end tag whose tag name is one of: "td", "th"

If the stack of open elements does not have an element in table scope that is an HTML element with the same tag name as that of the token, then this is a parse error; ignore the token.

Otherwise:

Generate implied end tags.

Now, if the current node is not an HTML element with the same tag name as the token, then this is a parse error.

Pop elements from the stack of open elements stack until an HTML element with the same tag name as the token has been popped from the stack.

Clear the list of active formatting elements up to the last marker.

Switch the insertion mode to "in row".

A start tag whose tag name is one of: "caption", "col", "colgroup", "tbody", "td", "tfoot", "th", "thead", "tr"

If the stack of open elements does not have a td or th element in table scope, then this is a parse error; ignore the token. (fragment case)

Otherwise, close the cell (see below) and reprocess the token.

An end tag whose tag name is one of: "body", "caption", "col", "colgroup", "html"
parse error. Ignore the token.
An end tag whose tag name is one of: "table", "tbody", "tfoot", "thead", "tr"

If the stack of open elements does not have an element in table scope that is an HTML element with the same tag name as that of the token, then this is a parse error; ignore the token.

Otherwise, close the cell (see below) and reprocess the token.

Anything else

Process the token using the rules for the "in body" insertion mode.

Where the steps above say to close the cell, they mean to run the following algorithm:

  1. Generate implied end tags.
  2. If the current node is not now a td element or a th element, then this is a parse error.
  3. Pop elements from the stack of open elements stack until a td element or a th element has been popped from the stack.
  4. Clear the list of active formatting elements up to the last marker.
  5. Switch the insertion mode to "in row".

The stack of open elements cannot have both a td and a th element in table scope at the same time, nor can it have neither when the close the cell algorithm is invoked.

8.2.5.4.16. The "in select" insertion mode

When the user agent is to apply the rules for the "in select" insertion mode, the user agent must handle the token as follows:

A character token that is U+0000 NULL
parse error. Ignore the token.
Any other character token

Insert the token’s character.

A comment token
Insert a comment.
A DOCTYPE token
parse error. Ignore the token.
A start tag whose tag name is "html"

Process the token using the rules for the "in body" insertion mode.

A start tag whose tag name is "option"

If the current node is an option element, pop that node from the stack of open elements.

Insert an HTML element for the token.

A start tag whose tag name is "optgroup"

If the current node is an option element, pop that node from the stack of open elements.

If the current node is an optgroup element, pop that node from the stack of open elements.

Insert an HTML element for the token.

An end tag whose tag name is "optgroup"

First, if the current node is an option element, and the node immediately before it in the stack of open elements is an optgroup element, then pop the current node from the stack of open elements.

If the current node is an optgroup element, then pop that node from the stack of open elements. Otherwise, this is a parse error; ignore the token.

An end tag whose tag name is "option"

If the current node is an option element, then pop that node from the stack of open elements. Otherwise, this is a parse error; ignore the token.

An end tag whose tag name is "select"

If the stack of open elements does not have a select element in select scope, this is a parse error; ignore the token. (fragment case)

Otherwise:

Pop elements from the stack of open elements until a select element has been popped from the stack.

Reset the insertion mode appropriately.

A start tag whose tag name is "select"

parse error.

If the stack of open elements does not have a select element in select scope, ignore the token. (fragment case)

Otherwise:

Pop elements from the stack of open elements until a select element has been popped from the stack.

Reset the insertion mode appropriately.

It just gets treated like an end tag.

A start tag whose tag name is one of: "input", "keygen", "textarea"

parse error.

If the stack of open elements does not have a select element in select scope, ignore the token. (fragment case)

Otherwise:

Pop elements from the stack of open elements until a select element has been popped from the stack.

Reset the insertion mode appropriately.

Reprocess the token.

A start tag whose tag name is one of: "script", "template"
An end tag whose tag name is "template"

Process the token using the rules for the "in head" insertion mode.

An end-of-file token

Process the token using the rules for the "in body" insertion mode.

Anything else
parse error. Ignore the token.
8.2.5.4.17. The "in select in table" insertion mode

When the user agent is to apply the rules for the "in select in table" insertion mode, the user agent must handle the token as follows:

A start tag whose tag name is one of: "caption", "table", "tbody", "tfoot", "thead", "tr", "td", "th"

parse error.

Pop elements from the stack of open elements until a select element has been popped from the stack.

Reset the insertion mode appropriately.

Reprocess the token.

An end tag whose tag name is one of: "caption", "table", "tbody", "tfoot", "thead", "tr", "td", "th"

parse error.

If the stack of open elements does not have an element in table scope that is an HTML element with the same tag name as that of the token, then ignore the token.

Otherwise:

Pop elements from the stack of open elements until a select element has been popped from the stack.

Reset the insertion mode appropriately.

Reprocess the token.

Anything else

Process the token using the rules for the "in select" insertion mode.

8.2.5.4.18. The "in template" insertion mode

When the user agent is to apply the rules for the "in template" insertion mode, the user agent must handle the token as follows:

A character token
A comment token
A DOCTYPE token

Process the token using the rules for the "in body" insertion mode.

A start tag whose tag name is one of: "base", "basefont", "bgsound", "link", "meta", "noframes", "script", "style", "template", "title"
An end tag whose tag name is "template"

Process the token using the rules for the "in head" insertion mode.

A start tag whose tag name is one of: "caption", "colgroup", "tbody", "tfoot", "thead"

Pop the current template insertion mode off the stack of template insertion modes.

Push "in table" onto the stack of template insertion modes so that it is the new current template insertion mode.

Switch the insertion mode to "in table", and reprocess the token.

A start tag whose tag name is "col"

Pop the current template insertion mode off the stack of template insertion modes.

Push "in column group" onto the stack of template insertion modes so that it is the new current template insertion mode.

Switch the insertion mode to "in column group", and reprocess the token.

A start tag whose tag name is "tr"

Pop the current template insertion mode off the stack of template insertion modes.

Push "in table body" onto the stack of template insertion modes so that it is the new current template insertion mode.

Switch the insertion mode to "in table body", and reprocess the token.

A start tag whose tag name is one of: "td", "th"

Pop the current template insertion mode off the stack of template insertion modes.

Push "in row" onto the stack of template insertion modes so that it is the new current template insertion mode.

Switch the insertion mode to "in row", and reprocess the token.

Any other start tag

Pop the current template insertion mode off the stack of template insertion modes.

Push "in body" onto the stack of template insertion modes so that it is the new current template insertion mode.

Switch the insertion mode to "in body", and reprocess the token.

Any other end tag
parse error. Ignore the token.
An end-of-file token

If there is no template element on the stack of open elements, then stop parsing. (fragment case)

Otherwise, this is a parse error.

Pop elements from the stack of open elements until a template element has been popped from the stack.

Clear the list of active formatting elements up to the last marker.

Pop the current template insertion mode off the stack of template insertion modes.

Reset the insertion mode appropriately.

Reprocess the token.

8.2.5.4.19. The "after body" insertion mode

When the user agent is to apply the rules for the "after body" insertion mode, the user agent must handle the token as follows:

A character token that is one of U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), or U+0020 SPACE

Process the token using the rules for the "in body" insertion mode.

A comment token

Insert a comment as the last child of the first element in the stack of open elements (the html element).

A DOCTYPE token
parse error. Ignore the token.
A start tag whose tag name is "html"

Process the token using the rules for the "in body" insertion mode.

An end tag whose tag name is "html"

If the parser was originally created as part of the HTML fragment parsing algorithm, this is a parse error; ignore the token. (fragment case)

Otherwise, switch the insertion mode to "after after body".

An end-of-file token
Stop parsing.
Anything else

parse error. Switch the insertion mode to "in body" and reprocess the token.

8.2.5.4.20. The "in frameset" insertion mode

When the user agent is to apply the rules for the "in frameset" insertion mode, the user agent must handle the token as follows:

A character token that is one of U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), or U+0020 SPACE
Insert the character.
A comment token
Insert a comment.
A DOCTYPE token
parse error. Ignore the token.
A start tag whose tag name is "html"

Process the token using the rules for the "in body" insertion mode.

A start tag whose tag name is "frameset"
Insert an HTML element for the token.
An end tag whose tag name is "frameset"

If the current node is the root html element, then this is a parse error; ignore the token. (fragment case)

Otherwise, pop the current node from the stack of open elements.

If the parser was not originally created as part of the HTML fragment parsing algorithm (fragment case), and the current node is no longer a frameset element, then switch the insertion mode to "after frameset".

A start tag whose tag name is "frame"

Insert an HTML element for the token. Immediately pop the current node off the stack of open elements.

Acknowledge the token’s self-closing flag, if it is set.

A start tag whose tag name is "noframes"

Process the token using the rules for the "in head" insertion mode.

An end-of-file token

If the current node is not the root html element, then this is a parse error.

The current node can only be the root html element in the fragment case.

Stop parsing.

Anything else
parse error. Ignore the token.
8.2.5.4.21. The "after frameset" insertion mode

When the user agent is to apply the rules for the "after frameset" insertion mode, the user agent must handle the token as follows:

A character token that is one of U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), or U+0020 SPACE
Insert the character.
A comment token
Insert a comment.
A DOCTYPE token
parse error. Ignore the token.
A start tag whose tag name is "html"

Process the token using the rules for the "in body" insertion mode.

An end tag whose tag name is "html"

Switch the insertion mode to "after after frameset".

A start tag whose tag name is "noframes"

Process the token using the rules for the "in head" insertion mode.

An end-of-file token
Stop parsing.
Anything else
parse error. Ignore the token.
8.2.5.4.22. The "after after body" insertion mode

When the user agent is to apply the rules for the "after after body" insertion mode, the user agent must handle the token as follows:

A comment token
Insert a comment as the last child of the Document object.
A DOCTYPE token
A character token that is one of U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), or U+0020 SPACE
A start tag whose tag name is "html"

Process the token using the rules for the "in body" insertion mode.

An end-of-file token
Stop parsing.
Anything else

parse error. Switch the insertion mode to "in body" and reprocess the token.

8.2.5.4.23. The "after after frameset" insertion mode

When the user agent is to apply the rules for the "after after frameset" insertion mode, the user agent must handle the token as follows:

A comment token
Insert a comment as the last child of the Document object.
A DOCTYPE token
A character token that is one of U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), or U+0020 SPACE
A start tag whose tag name is "html"

Process the token using the rules for the "in body" insertion mode.

An end-of-file token
Stop parsing.
A start tag whose tag name is "noframes"

Process the token using the rules for the "in head" insertion mode.

Anything else
parse error. Ignore the token.
8.2.5.5. The rules for parsing tokens in foreign content

When the user agent is to apply the rules for parsing tokens in foreign content, the user agent must handle the token as follows:

A character token that is U+0000 NULL

parse error. Insert a U+FFFD REPLACEMENT CHARACTER character.

A character token that is one of U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), or U+0020 SPACE

Insert the token’s character.

Any other character token

Insert the token’s character.

Set the frameset-ok flag to "not ok".

A comment token

Insert a comment.

A DOCTYPE token
parse error. Ignore the token.
A start tag whose tag name is one of: "b", "big", "blockquote", "body", "br", "center", "code", "dd", "div", "dl", "dt", "em", "embed", "h1", "h2", "h3", "h4", "h5", "h6", "head", "hr", "i", "img", "li", "listing", "menu", "meta", "nobr", "ol", "p", "pre", "ruby", "s", "small", "span", "strong", "strike", "sub", "sup", "table", "tt", "u", "ul", "var"
A start tag whose tag name is "font", if the token has any attributes named "color", "face", or "size"

parse error.

If the parser was originally created for the HTML fragment parsing algorithm, then act as described in the "any other start tag" entry below. (fragment case)

Otherwise:

Pop an element from the stack of open elements, and then keep popping more elements from the stack of open elements until the current node is a MathML text integration point, an HTML integration point, or an element in the HTML namespace.

Then, reprocess the token.

Any other start tag

If the adjusted current node is an element in the MathML namespace, adjust MathML attributes for the token. (This fixes the case of MathML attributes that are not all lowercase.)

If the adjusted current node is an element in the SVG namespace, and the token’s tag name is one of the ones in the first column of the following table, change the tag name to the name given in the corresponding cell in the second column. (This fixes the case of SVG elements that are not all lowercase.)

Tag name Element name
altglyph altGlyph
altglyphdef altGlyphDef
altglyphitem altGlyphItem
animatecolor animateColor
animatemotion animateMotion
animatetransform animateTransform
clippath clipPath
feblend feBlend
fecolormatrix feColorMatrix
fecomponenttransfer feComponentTransfer
fecomposite feComposite
feconvolvematrix feConvolveMatrix
fediffuselighting feDiffuseLighting
fedisplacementmap feDisplacementMap
fedistantlight feDistantLight
fedropshadow feDropShadow
feflood feFlood
fefunca feFuncA
fefuncb feFuncB
fefuncg feFuncG
fefuncr feFuncR
fegaussianblur feGaussianBlur
feimage feImage
femerge feMerge
femergenode feMergeNode
femorphology feMorphology
feoffset feOffset
fepointlight fePointLight
fespecularlighting feSpecularLighting
fespotlight feSpotLight
fetile feTile
feturbulence feTurbulence
foreignobject foreignObject
glyphref glyphRef
lineargradient linearGradient
radialgradient radialGradient
textpath textPath

If the adjusted current node is an element in the SVG namespace, adjust SVG attributes for the token. (This fixes the case of SVG attributes that are not all lowercase.)

Adjust foreign attributes for the token. (This fixes the use of namespaced attributes, in particular XLink in SVG.)

Insert a foreign element for the token, in the same namespace as the adjusted current node.

If the token has its self-closing flag set, then run the appropriate steps from the following list:

If the token’s tag name is "script", and the new current node is in the SVG namespace

Acknowledge the token’s self-closing flag, and then act as described in the steps for a "script" end tag below.

Otherwise

Pop the current node off the stack of open elements and acknowledge the token’s self-closing flag.

An end tag whose tag name is "script", if the current node is a script element in the SVG namespace

Pop the current node off the stack of open elements.

Let the old insertion point have the same value as the current insertion point. Let the insertion point be just before the next input character.

Increment the parser’s script nesting level by one. Set the parser pause flag to true.

Process the script element according to the SVG rules, if the user agent supports SVG. [SVG11]

Even if this causes new characters to be inserted into the tokenizer, the parser will not be executed reentrantly, since the parser pause flag is true.

Decrement the parser’s script nesting level by one. If the parser’s script nesting level is zero, then set the parser pause flag to false.

Let the insertion point have the value of the old insertion point. (In other words, restore the insertion point to its previous value. This value might be the "undefined" value.)

Any other end tag

Run these steps:

  1. Initialize node to be the current node (the bottommost node of the stack).
  2. If node’s tag name, converted to ASCII lowercase, is not the same as the tag name of the token, then this is a parse error.
  3. Loop: If node is the topmost element in the stack of open elements, abort these steps. (fragment case)
  4. If node’s tag name, converted to ASCII lowercase, is the same as the tag name of the token, pop elements from the stack of open elements until node has been popped from the stack, and then abort these steps.
  5. Set node to the previous entry in the stack of open elements.
  6. If node is not an element in the HTML namespace, return to the step labeled loop.
  7. Otherwise, process the token according to the rules given in the section corresponding to the current insertion mode in HTML content.

8.2.6. The end

Once the user agent stops parsing the document, the user agent must run the following steps:

  1. Set the current document readiness to "interactive" and the insertion point to undefined.
  2. Pop all the nodes off the stack of open elements.
  3. If the list of scripts that will execute when the document has finished parsing is not empty, run these substeps:
    1. Spin the event loop until the first script in the list of scripts that will execute when the document has finished parsing has its "ready to be parser-executed" flag set and the parser’s Document has no style sheet that is blocking scripts.
    2. Execute the first script in the list of scripts that will execute when the document has finished parsing.
    3. Remove the first script element from the list of scripts that will execute when the document has finished parsing (i.e., shift out the first entry in the list).
    4. If the list of scripts that will execute when the document has finished parsing is still not empty, repeat these substeps again from substep 1.
  4. Queue a task to fire a simple event that bubbles named DOMContentLoaded at the Document.
  5. Spin the event loop until the set of scripts that will execute as soon as possible and the list of scripts that will execute in order as soon as possible are empty.
  6. Spin the event loop until there is nothing that delays the load event in the Document.
  7. Queue a task to run the following substeps:

    1. Set the current document readiness to "complete".
    2. Load event: If the Document is in a browsing context, fire a simple event named load at the Document’s Window object, with target override set to the Document object.
  8. If the Document is in a browsing context, then queue a task to run the following substeps:

    1. If the Document’s page showing flag is true, then abort this task (i.e., don’t fire the event below).
    2. Set the Document’s page showing flag to true.
    3. Fire a trusted event with the name pageshow at the Window object of the Document, with target override set to the Document object, using the PageTransitionEvent interface, with the persisted attribute initialized to false. This event must not bubble, must not be cancelable, and has no default action.
  9. If the Document has any pending application cache download process tasks, then queue each such task in the order they were added to the list of pending application cache download process tasks, and then empty the list of pending application cache download process tasks. The task source for these tasks is the networking task source.
  10. If the Document’s print when loaded flag is set, then run the printing steps.
  11. The Document is now ready for post-load tasks.
  12. Queue a task to mark the Document as completely loaded.

When the user agent is to abort a parser, it must run the following steps:

  1. Throw away any pending content in the input stream, and discard any future content that would have been added to it.
  2. Set the current document readiness to "interactive".
  3. Pop all the nodes off the stack of open elements.
  4. Set the current document readiness to "complete".

Except where otherwise specified, the task source for the tasks mentioned in this section is the DOM manipulation task source.

8.2.7. Coercing an HTML DOM into an infoset

When an application uses an HTML parser in conjunction with an XML pipeline, it is possible that the constructed DOM is not compatible with the XML tool chain in certain subtle ways. For example, an XML toolchain might not be able to represent attributes with the name xmlns, since they conflict with the Namespaces in XML syntax. There is also some data that the HTML parser generates that isn’t included in the DOM itself. This section specifies some rules for handling these issues.

If the XML API being used doesn’t support DOCTYPEs, the tool may drop DOCTYPEs altogether.

If the XML API doesn’t support attributes in no namespace that are named "xmlns", attributes whose names start with "xmlns:", or attributes in the XMLNS namespace, then the tool may drop such attributes.

The tool may annotate the output with any namespace declarations required for proper operation.

If the XML API being used restricts the allowable characters in the local names of elements and attributes, then the tool may map all element and attribute local names that the API wouldn’t support to a set of names that are allowed, by replacing any character that isn’t supported with the uppercase letter U and the six digits of the character’s Unicode code point when expressed in hexadecimal, using digits 0-9 and capital letters A-F as the symbols, in increasing numeric order.

For example, the element name foo<bar, which can be output by the HTML parser, though it is neither a legal HTML element name nor a well-formed XML element name, would be converted into fooU00003Cbar, which is a well-formed XML element name (though it’s still not legal in HTML by any means).

As another example, consider the attribute xlink:href. Used on a MathML element, it becomes, after being adjusted, an attribute with a prefix "xlink" and a local name "href". However, used on an HTML element, it becomes an attribute with no prefix and the local name "xlink:href", which is not a valid NCName, and thus might not be accepted by an XML API. It could thus get converted, becoming "xlinkU00003Ahref".

The resulting names from this conversion conveniently can’t clash with any attribute generated by the HTML parser, since those are all either lowercase or those listed in the adjust foreign attributes algorithm’s table.

If the XML API restricts comments from having two consecutive U+002D HYPHEN-MINUS characters (--), the tool may insert a single U+0020 SPACE character between any such offending characters.

If the XML API restricts comments from ending in a U+002D HYPHEN-MINUS character (-), the tool may insert a single U+0020 SPACE character at the end of such comments.

If the XML API restricts allowed characters in character data, attribute values, or comments, the tool may replace any U+000C FORM FEED (FF) character with a U+0020 SPACE character, and any other literal non-XML character with a U+FFFD REPLACEMENT CHARACTER.

If the tool has no way to convey out-of-band information, then the tool may drop the following information:

  • Whether the document is set to no-quirks mode, limited-quirks mode, or quirks mode
  • The association between form controls and forms that aren’t their nearest form element ancestor (use of the form element pointer in the parser)
  • The template contents of any template elements.

The mutations allowed by this section apply after the HTML parser’s rules have been applied. For example, a <a::> start tag will be closed by a </a::> end tag, and never by a </aU00003AU00003A> end tag, even if the user agent is using the rules above to then generate an actual element in the DOM with the name aU00003AU00003A for that start tag.

8.2.8. An introduction to error handling and strange cases in the parser

This section is non-normative.

This section examines some erroneous markup and discusses how the HTML parser handles these cases.

8.2.8.1. Misnested tags: <b><i></b></i>

This section is non-normative.

The most-often discussed example of erroneous markup is as follows:

<p>1<b>2<i>3</b>4</i>5</p>

The parsing of this markup is straightforward up to the "3". At this point, the DOM looks like this:

Here, the stack of open elements has five elements on it: html, body, p, b, and i. The list of active formatting elements just has two: b and i. The insertion mode is "in body".

Upon receiving the end tag token with the tag name "b", the "adoption agency algorithm" is invoked. This is a simple case, in that the formatting element is the b element, and there is no furthest block. Thus, the stack of open elements ends up with just three elements: html, body, and p, while the list of active formatting elements has just one: i. The DOM tree is unmodified at this point.

The next token is a character ("4"), triggers the reconstruction of the active formatting elements, in this case just the i element. A new i element is thus created for the "4" Text node. After the end tag token for the "i" is also received, and the "5" Text node is inserted, the DOM looks as follows:

8.2.8.2. Misnested tags: <b><p></b></p>

This section is non-normative.

A case similar to the previous one is the following:

<b>1<p>2</b>3</p>

Up to the "2" the parsing here is straightforward:

The interesting part is when the end tag token with the tag name "b" is parsed.

Before that token is seen, the stack of open elements has four elements on it: html, body, b, and p. The list of active formatting elements just has the one: b. The insertion mode is "in body".

Upon receiving the end tag token with the tag name "b", the "adoption agency algorithm" is invoked, as in the previous example. However, in this case, there is a furthest block, namely the p element. Thus, this time the adoption agency algorithm isn’t skipped over.

The common ancestor is the body element. A conceptual "bookmark" marks the position of the b in the list of active formatting elements, but since that list has only one element in it, the bookmark won’t have much effect.

As the algorithm progresses, node ends up set to the formatting element (b), and last node ends up set to the furthest block (p).

The last node gets appended (moved) to the common ancestor, so that the DOM looks like:

A new b element is created, and the children of the p element are moved to it:

  • b
    • #text: 2

Finally, the new b element is appended to the p element, so that the DOM looks like:

The b element is removed from the list of active formatting elements and the stack of open elements, so that when the "3" is parsed, it is appended to the p element:

8.2.8.3. Unexpected markup in tables

This section is non-normative.

Error handling in tables is, for historical reasons, especially strange. For example, consider the following markup:

<table><b><tr><td>aaa</td></tr>bbb</table>ccc

The highlighted b element start tag is not allowed directly inside a table like that, and the parser handles this case by placing the element before the table. (This is called foster parenting.) This can be seen by examining the DOM tree as it stands just after the table element’s start tag has been seen:

...and then immediately after the b element start tag has been seen:

At this point, the stack of open elements has on it the elements html, body, table, and b (in that order, despite the resulting DOM tree); the list of active formatting elements just has the b element in it; and the insertion mode is "in table".

The tr start tag causes the b element to be popped off the stack and a tbody start tag to be implied; the tbody and tr elements are then handled in a rather straight-forward manner, taking the parser through the "in table body" and "in row" insertion modes, after which the DOM looks as follows:

Here, the stack of open elements has on it the elements html, body, table, tbody, and tr; the list of active formatting elements still has the b element in it; and the insertion mode is "in row".

The td element start tag token, after putting a td element on the tree, puts a marker on the list of active formatting elements (it also switches to the "in cell" insertion mode).

The marker means that when the "aaa" character tokens are seen, no b element is created to hold the resulting Text node:

The end tags are handled in a straight-forward manner; after handling them, the stack of open elements has on it the elements html, body, table, and tbody; the list of active formatting elements still has the b element in it (the marker having been removed by the "td" end tag token); and the insertion mode is "in table body".

Thus it is that the "bbb" character tokens are found. These trigger the "in table text" insertion mode to be used (with the original insertion mode set to "in table body"). The character tokens are collected, and when the next token (the table element end tag) is seen, they are processed as a group. Since they are not all spaces, they are handled as per the "anything else" rules in the "in table" insertion mode, which defer to the "in body" insertion mode but with foster parenting.

When the active formatting elements are reconstructed, a b element is created and foster parented, and then the "bbb" Text node is appended to it:

The stack of open elements has on it the elements html, body, table, tbody, and the new b (again, note that this doesn’t match the resulting tree!); the list of active formatting elements has the new b element in it; and the insertion mode is still "in table body".

Had the character tokens been only space characters instead of "bbb", then those space characters would just be appended to the tbody element.

Finally, the table is closed by a "table" end tag. This pops all the nodes from the stack of open elements up to and including the table element, but it doesn’t affect the list of active formatting elements, so the "ccc" character tokens after the table result in yet another b element being created, this time after the table:

8.2.8.4. Scripts that modify the page as it is being parsed

This section is non-normative.

Consider the following markup, which for this example we will assume is the document with URL https://example.com/inner, being rendered as the content of an iframe in another document with the URL https://example.com/outer:

<div id=a>
<script>
var div = document.getElementById("a");
parent.document.body.appendChild(div);
</script>
<script>
alert(document.URL);
</script>
</div>
<script>
alert(document.URL);
</script>

Up to the first "script" end tag, before the script is parsed, the result is relatively straightforward:

  • html
    • head
    • body
      • div id="a"
        • #text:
        • script
          • #text: var div = document.getElementById("a"); ⏎ parent.document.body.appendChild(div);

After the script is parsed, though, the div element and its child script element are gone:

They are, at this point, in the Document of the aforementioned outer browsing context. However, the stack of open elements still contains the div element.

Thus, when the second script element is parsed, it is inserted into the outer Document object.

Those parsed into different Documents than the one the parser was created for do not execute, so the first alert does not show.

Once the div element’s end tag is parsed, the div element is popped off the stack, and so the next script element is in the inner Document:

This script does execute, resulting in an alert that says "https://example.com/inner".

8.2.8.5. The execution of scripts that are moving across multiple documents

This section is non-normative.

Elaborating on the example in the previous section, consider the case where the second script element is an external script (i.e., one with a src attribute). Since the element was not in the parser’s Document when it was created, that external script is not even downloaded.

In a case where a script element with a src attribute is parsed normally into its parser’s Document, but while the external script is being downloaded, the element is moved to another document, the script continues to download, but does not execute.

In general, moving script elements between Documents is considered a bad practice.

8.2.8.6. Unclosed formatting elements

This section is non-normative.

The following markup shows how nested formatting elements (such as b) get collected and continue to be applied even as the elements they are contained in are closed, but that excessive duplicates are thrown away.

<!DOCTYPE html>
<p><b class=x><b class=x><b><b class=x><b class=x><b>X
<p>X
<p><b><b class=x><b>X
<p></b></b></b></b></b></b>X

The resulting DOM tree is as follows:

  • DOCTYPE: html
  • html
    • head
    • body
      • p
        • b class="x"
          • b class="x"
            • b
              • b class="x"
                • b class="x"
                  • b
                    • #text: X⏎
      • p
        • b class="x"
          • b
            • b class="x"
              • b class="x"
                • b
                  • #text: X⏎
      • p
        • b class="x"
          • b
            • b class="x"
              • b class="x"
                • b
                  • b
                    • b class="x"
                      • b
                        • #text: X⏎
      • p
        • #text: X⏎

Note how the second p element in the markup has no explicit b elements, but in the resulting DOM, up to three of each kind of formatting element (in this case three b elements with the class attribute, and two unadorned b elements) get reconstructed before the element’s "X".

Also note how this means that in the final paragraph only six b end tags are needed to completely clear the list of active formatting elements, even though nine b start tags have been seen up to this point.

8.3. Serializing HTML fragments

The following steps form the HTML fragment serialization algorithm. The algorithm takes as input a DOM Element, Document, or DocumentFragment referred to as the node, and either returns a string.

This algorithm serializes the children of the node being serialized, not the node itself.

  1. Let s be a string, and initialize it to the empty string.
  2. If the node is a template element, then let the node instead be the template element’s template contents (a DocumentFragment node).
  3. For each child node of the node, in tree order, run the following steps:

    1. Let current node be the child node being processed.
    2. Append the appropriate string from the following list to s:

      If current node is an Element

      If current node is an element in the HTML namespace, the MathML namespace, or the SVG namespace, then let tagname be current node’s local name. Otherwise, let tagname be current node’s qualified name.

      Append a U+003C LESS-THAN SIGN character (<), followed by tagname.

      For html elements created by the HTML parser or Document.createElement(), tagname will be lowercase.

      For each attribute that the element has, append a U+0020 SPACE character, the attribute’s serialized name as described below, a U+003D EQUALS SIGN character (=), a U+0022 QUOTATION MARK character ("), the attribute’s value, escaped as described below in attribute mode, and a second U+0022 QUOTATION MARK character (").

      An attribute’s serialized name for the purposes of the previous paragraph must be determined as follows:

      If the attribute has no namespace

      The attribute’s serialized name is the attribute’s local name.

      For attributes on html elements set by the HTML parser or by Element.setAttribute(), the local name will be lowercase.

      If the attribute is in the XML namespace
      The attribute’s serialized name is the string "xml:" followed by the attribute’s local name.
      If the attribute is in the XMLNS namespace and the attribute’s local name is xmlns
      The attribute’s serialized name is the string "xmlns".
      If the attribute is in the XMLNS namespace and the attribute’s local name is not xmlns
      The attribute’s serialized name is the string "xmlns:" followed by the attribute’s local name.
      If the attribute is in the XLink namespace
      The attribute’s serialized name is the string "xlink:" followed by the attribute’s local name.
      If the attribute is in some other namespace
      The attribute’s serialized name is the attribute’s qualified name.

      While the exact order of attributes is user agent-defined, and may depend on factors such as the order that the attributes were given in the original markup, the sort order must be stable, such that consecutive invocations of this algorithm serialize an element’s attributes in the same order.

      Append a U+003E GREATER-THAN SIGN character (>).

      If current node is an area, base, basefont, bgsound, br, col, embed, frame, hr, img, input, keygen, link, menuitem, meta, param, source, track or wbr element, then continue on to the next child node at this point.

      If current node is a pre, textarea, or listing element, and the first child node of the element, if any, is a Text node whose character data has as its first character a U+000A LINE FEED (LF) character, then append a U+000A LINE FEED (LF) character.

      Append the value of running the HTML fragment serialization algorithm on the current node element (thus recursing into this algorithm for that element), followed by a U+003C LESS-THAN SIGN character (<), a U+002F SOLIDUS character (/), tagname again, and finally a U+003E GREATER-THAN SIGN character (>).

      If current node is a Text node

      If the parent of current node is a style, script, xmp, iframe, noembed, noframes, or plaintext element, or if the parent of current node is a noscript element and scripting is enabled for the node, then append the value of current node’s data IDL attribute literally.

      Otherwise, append the value of current node’s data IDL attribute, escaped as described below.

      If current node is a Comment

      Append the literal string "<!--" (U+003C LESS-THAN SIGN, U+0021 EXCLAMATION MARK, U+002D HYPHEN-MINUS, U+002D HYPHEN-MINUS), followed by the value of current node’s data IDL attribute, followed by the literal string "-->" (U+002D HYPHEN-MINUS, U+002D HYPHEN-MINUS, U+003E GREATER-THAN SIGN).

      If current node is a ProcessingInstruction

      Append the literal string "<?" (U+003C LESS-THAN SIGN, U+003F QUESTION MARK), followed by the value of current node’s target IDL attribute, followed by a single U+0020 SPACE character, followed by the value of current node’s data IDL attribute, followed by a single U+003E GREATER-THAN SIGN character (>).

      If current node is a DocumentType

      Append the literal string "<!DOCTYPE" (U+003C LESS-THAN SIGN, U+0021 EXCLAMATION MARK, U+0044 LATIN CAPITAL LETTER D, U+004F LATIN CAPITAL LETTER O, U+0043 LATIN CAPITAL LETTER C, U+0054 LATIN CAPITAL LETTER T, U+0059 LATIN CAPITAL LETTER Y, U+0050 LATIN CAPITAL LETTER P, U+0045 LATIN CAPITAL LETTER E), followed by a space (U+0020 SPACE), followed by the value of current node’s name IDL attribute, followed by the literal string ">" (U+003E GREATER-THAN SIGN).

  4. The result of the algorithm is the string s.

It is possible that the output of this algorithm, if parsed with an HTML parser, will not return the original tree structure.

For instance, if a textarea element to which a Comment node has been appended is serialized and the output is then reparsed, the comment will end up being displayed in the text field. Similarly, if, as a result of DOM manipulation, an element contains a comment that contains the literal string "-->", then when the result of serializing the element is parsed, the comment will be truncated at that point and the rest of the comment will be interpreted as markup. More examples would be making a script element contain a Text node with the text string "</script>", or having a p element that contains a ul element (as the ul element’s start tag would imply the end tag for the p).

This can enable cross-site scripting attacks. An example of this would be a page that lets the user enter some font family names that are then inserted into a CSS style block via the DOM and which then uses the innerHTML IDL attribute to get the HTML serialization of that style element: if the user enters "</style><script>attack</script>" as a font family name, innerHTML will return markup that, if parsed in a different context, would contain a script node, even though no script node existed in the original DOM.

Escaping a string (for the purposes of the algorithm above) consists of running the following steps:

  1. Replace any occurrence of the "&" character by the string "&amp;".
  2. Replace any occurrences of the U+00A0 NO-BREAK SPACE character by the string "&nbsp;".
  3. If the algorithm was invoked in the attribute mode, replace any occurrences of the """ character by the string "&quot;".
  4. If the algorithm was not invoked in the attribute mode, replace any occurrences of the "<" character by the string "&lt;", and any occurrences of the ">" character by the string "&gt;".

8.4. Parsing HTML fragments

The following steps form the HTML fragment parsing algorithm. The algorithm takes as input an Element node, referred to as the context element, which gives the context for the parser, as well as input, a string to parse, and returns a list of zero or more nodes.

Parts marked fragment case in algorithms in the parser section are parts that only occur if the parser was created for the purposes of this algorithm. The algorithms have been annotated with such markings for informational purposes only; such markings have no normative weight. If it is possible for a condition described as a fragment case to occur even when the parser wasn’t created for the purposes of handling this algorithm, then that is an error in the specification.

  1. Create a new Document node, and mark it as being an HTML document.

  2. If the node document of the context element is in quirks mode, then let the Document be in quirks mode. Otherwise, the node document of the context element is in limited-quirks mode, then let the Document be in limited-quirks mode. Otherwise, leave the Document in no-quirks mode.

  3. Create a new HTML parser, and associate it with the just created Document node.

  4. Set the state of the HTML parser’s tokenization stage as follows:

    If it is a title or textarea element
    Switch the tokenizer to the §8.2.4.3 RCDATA state.
    If it is a style, xmp, iframe, noembed, or noframes element
    Switch the tokenizer to the §8.2.4.5 RAWTEXT state.
    If it is a script element
    Switch the tokenizer to the §8.2.4.6 Script data state.
    If it is a noscript element
    If the scripting flag is enabled, switch the tokenizer to the §8.2.4.5 RAWTEXT state. Otherwise, leave the tokenizer in the §8.2.4.1 Data state.
    If it is a plaintext element
    Switch the tokenizer to the §8.2.4.7 PLAINTEXT state.
    Otherwise
    Leave the tokenizer in the §8.2.4.1 Data state.

    For performance reasons, an implementation that does not report errors and that uses the actual state machine described in this specification directly could use the PLAINTEXT state instead of the RAWTEXT and script data states where those are mentioned in the list above. Except for rules regarding parse errors, they are equivalent, since there is no appropriate end tag token in the fragment case, yet they involve far fewer state transitions.

  5. Let root be a new html element with no attributes.

  6. Append the element root to the Document node created above.

  7. Set up the parser’s stack of open elements so that it contains just the single element root.

  8. If the context element is a template element, push "in template" onto the stack of template insertion modes so that it is the new current template insertion mode.

  9. Create a start tag token whose name is the local name of context and whose attributes are the attributes of context.

    Let this start tag token be the start tag token of the context node, e.g., for the purposes of determining if it is an HTML integration point.

  10. Reset the parser’s insertion mode appropriately.

    The parser will reference the context element as part of that algorithm.

  11. Set the parser’s form element pointer to the nearest node to the context element that is a form element (going straight up the ancestor chain, and including the element itself, if it is a form element), if any. (If there is no such form element, the form element pointer keeps its initial value, null.)

  12. Place the input into the input stream for the HTML parser just created. The encoding confidence is irrelevant.

  13. Start the parser and let it run until it has consumed all the characters just inserted into the input stream.

  14. Return the child nodes of root, in tree order.

8.5. Named character references

This table lists the character reference names that are supported by HTML, and the code points to which they refer. It is referenced by the previous sections.



Name Character(s) Glyph
Aacute; U+000C1 Á
Aacute U+000C1 Á
aacute; U+000E1 á
aacute U+000E1 á
Abreve; U+00102 Ă
abreve; U+00103 ă
ac; U+0223E
acd; U+0223F
acE; U+0223E U+00333 ∾̳
Acirc; U+000C2 Â
Acirc U+000C2 Â
acirc; U+000E2 â
acirc U+000E2 â
acute; U+000B4 ´
acute U+000B4 ´
Acy; U+00410 А
acy; U+00430 а
AElig; U+000C6 Æ
AElig U+000C6 Æ
aelig; U+000E6 æ
aelig U+000E6 æ
af; U+02061
Afr; U+1D504 𝔄
afr; U+1D51E 𝔞
Agrave; U+000C0 À
Agrave U+000C0 À
agrave; U+000E0 à
agrave U+000E0 à
alefsym; U+02135
aleph; U+02135
Alpha; U+00391 Α
alpha; U+003B1 α
Amacr; U+00100 Ā
amacr; U+00101 ā
amalg; U+02A3F ⨿
AMP; U+00026 &
AMP U+00026 &
amp; U+00026 &
amp U+00026 &
And; U+02A53
and; U+02227
andand; U+02A55
andd; U+02A5C
andslope; U+02A58
andv; U+02A5A
ang; U+02220
ange; U+029A4
angle; U+02220
angmsd; U+02221
angmsdaa; U+029A8
angmsdab; U+029A9
angmsdac; U+029AA
angmsdad; U+029AB
angmsdae; U+029AC
angmsdaf; U+029AD
angmsdag; U+029AE
angmsdah; U+029AF
angrt; U+0221F
angrtvb; U+022BE
angrtvbd; U+0299D
angsph; U+02222
angst; U+000C5 Å
angzarr; U+0237C
Aogon; U+00104 Ą
aogon; U+00105 ą
Aopf; U+1D538 𝔸
aopf; U+1D552 𝕒
ap; U+02248
apacir; U+02A6F
apE; U+02A70
ape; U+0224A
apid; U+0224B
apos; U+00027 '
ApplyFunction; U+02061
approx; U+02248
approxeq; U+0224A
Aring; U+000C5 Å
Aring U+000C5 Å
aring; U+000E5 å
aring U+000E5 å
Ascr; U+1D49C 𝒜
ascr; U+1D4B6 𝒶
Assign; U+02254
ast; U+0002A *
asymp; U+02248
asympeq; U+0224D
Atilde; U+000C3 Ã
Atilde U+000C3 Ã
atilde; U+000E3 ã
atilde U+000E3 ã
Auml; U+000C4 Ä
Auml U+000C4 Ä
auml; U+000E4 ä
auml U+000E4 ä
awconint; U+02233
awint; U+02A11
backcong; U+0224C
backepsilon; U+003F6 ϶
backprime; U+02035
backsim; U+0223D
backsimeq; U+022CD
Backslash; U+02216
Barv; U+02AE7
barvee; U+022BD
Barwed; U+02306
barwed; U+02305
barwedge; U+02305
bbrk; U+023B5
bbrktbrk; U+023B6
bcong; U+0224C
Bcy; U+00411 Б
bcy; U+00431 б
bdquo; U+0201E
becaus; U+02235
Because; U+02235
because; U+02235
bemptyv; U+029B0
bepsi; U+003F6 ϶
bernou; U+0212C
Bernoullis; U+0212C
Beta; U+00392 Β
beta; U+003B2 β
beth; U+02136
between; U+0226C
Bfr; U+1D505 𝔅
bfr; U+1D51F 𝔟
bigcap; U+022C2
bigcirc; U+025EF
bigcup; U+022C3
bigodot; U+02A00
bigoplus; U+02A01
bigotimes; U+02A02
bigsqcup; U+02A06
bigstar; U+02605
bigtriangledown; U+025BD
bigtriangleup; U+025B3
biguplus; U+02A04
bigvee; U+022C1
bigwedge; U+022C0
bkarow; U+0290D
blacklozenge; U+029EB
blacksquare; U+025AA
blacktriangle; U+025B4
blacktriangledown; U+025BE
blacktriangleleft; U+025C2
blacktriangleright; U+025B8
blank; U+02423
blk12; U+02592
blk14; U+02591
blk34; U+02593
block; U+02588
bne; U+0003D U+020E5 =⃥
bnequiv; U+02261 U+020E5 ≡⃥
bNot; U+02AED
bnot; U+02310
Bopf; U+1D539 𝔹
bopf; U+1D553 𝕓
bot; U+022A5
bottom; U+022A5
bowtie; U+022C8
boxbox; U+029C9
boxDL; U+02557
boxDl; U+02556
boxdL; U+02555
boxdl; U+02510
boxDR; U+02554
boxDr; U+02553
boxdR; U+02552
boxdr; U+0250C
boxH; U+02550
boxh; U+02500
boxHD; U+02566
boxHd; U+02564
boxhD; U+02565
boxhd; U+0252C
boxHU; U+02569
boxHu; U+02567
boxhU; U+02568
boxhu; U+02534
boxminus; U+0229F
boxplus; U+0229E
boxtimes; U+022A0
boxUL; U+0255D
boxUl; U+0255C
boxuL; U+0255B
boxul; U+02518
boxUR; U+0255A
boxUr; U+02559
boxuR; U+02558
boxur; U+02514
boxV; U+02551
boxv; U+02502
boxVH; U+0256C
boxVh; U+0256B
boxvH; U+0256A
boxvh; U+0253C
boxVL; U+02563
boxVl; U+02562
boxvL; U+02561
boxvl; U+02524
boxVR; U+02560
boxVr; U+0255F
boxvR; U+0255E
boxvr; U+0251C
bprime; U+02035
Breve; U+002D8 ˘
breve; U+002D8 ˘
brvbar; U+000A6 ¦
brvbar U+000A6 ¦
Bscr; U+0212C
bscr; U+1D4B7 𝒷
bsemi; U+0204F
bsim; U+0223D
bsime; U+022CD
bsol; U+0005C \
bsolb; U+029C5
bsolhsub; U+027C8
bull; U+02022
bullet; U+02022
bump; U+0224E
bumpE; U+02AAE
bumpe; U+0224F
Bumpeq; U+0224E
bumpeq; U+0224F
Cacute; U+00106 Ć
cacute; U+00107 ć
Cap; U+022D2
cap; U+02229
capand; U+02A44
capbrcup; U+02A49
capcap; U+02A4B
capcup; U+02A47
capdot; U+02A40
CapitalDifferentialD; U+02145
caps; U+02229 U+0FE00 ∩︀
caret; U+02041
caron; U+002C7 ˇ
Cayleys; U+0212D
ccaps; U+02A4D
Ccaron; U+0010C Č
ccaron; U+0010D č
Ccedil; U+000C7 Ç
Ccedil U+000C7 Ç
ccedil; U+000E7 ç
ccedil U+000E7 ç
Ccirc; U+00108 Ĉ
ccirc; U+00109 ĉ
Cconint; U+02230
ccups; U+02A4C
ccupssm; U+02A50
Cdot; U+0010A Ċ
cdot; U+0010B ċ
cedil; U+000B8 ¸
cedil U+000B8 ¸
Cedilla; U+000B8 ¸
cemptyv; U+029B2
cent; U+000A2 ¢
cent U+000A2 ¢
CenterDot; U+000B7 ·
centerdot; U+000B7 ·
Cfr; U+0212D
cfr; U+1D520 𝔠
CHcy; U+00427 Ч
chcy; U+00447 ч
check; U+02713
checkmark; U+02713
Chi; U+003A7 Χ
chi; U+003C7 χ
cir; U+025CB
circ; U+002C6 ˆ
circeq; U+02257
circlearrowleft; U+021BA
circlearrowright; U+021BB
circledast; U+0229B
circledcirc; U+0229A
circleddash; U+0229D
CircleDot; U+02299
circledR; U+000AE ®
circledS; U+024C8
CircleMinus; U+02296
CirclePlus; U+02295
CircleTimes; U+02297
cirE; U+029C3
cire; U+02257
cirfnint; U+02A10
cirmid; U+02AEF
cirscir; U+029C2
ClockwiseContourIntegral; U+02232
CloseCurlyDoubleQuote; U+0201D
CloseCurlyQuote; U+02019
clubs; U+02663
clubsuit; U+02663
Colon; U+02237
colon; U+0003A :
Colone; U+02A74
colone; U+02254
coloneq; U+02254
comma; U+0002C ,
commat; U+00040 @
comp; U+02201
compfn; U+02218
complement; U+02201
complexes; U+02102
cong; U+02245
congdot; U+02A6D
Congruent; U+02261
Conint; U+0222F
conint; U+0222E
ContourIntegral; U+0222E
Copf; U+02102
copf; U+1D554 𝕔
coprod; U+02210
Coproduct; U+02210
COPY; U+000A9 ©
COPY U+000A9 ©
copy; U+000A9 ©
copy U+000A9 ©
copysr; U+02117
CounterClockwiseContourIntegral; U+02233
crarr; U+021B5
Cross; U+02A2F
cross; U+02717
Cscr; U+1D49E 𝒞
cscr; U+1D4B8 𝒸
csub; U+02ACF
csube; U+02AD1
csup; U+02AD0
csupe; U+02AD2
ctdot; U+022EF
cudarrl; U+02938
cudarrr; U+02935
cuepr; U+022DE
cuesc; U+022DF
cularr; U+021B6
cularrp; U+0293D
Cup; U+022D3
cup; U+0222A
cupbrcap; U+02A48
CupCap; U+0224D
cupcap; U+02A46
cupcup; U+02A4A
cupdot; U+0228D
cupor; U+02A45
cups; U+0222A U+0FE00 ∪︀
curarr; U+021B7
curarrm; U+0293C
curlyeqprec; U+022DE
curlyeqsucc; U+022DF
curlyvee; U+022CE
curlywedge; U+022CF
curren; U+000A4 ¤
curren U+000A4 ¤
curvearrowleft; U+021B6
curvearrowright; U+021B7
cuvee; U+022CE
cuwed; U+022CF
cwconint; U+02232
cwint; U+02231
cylcty; U+0232D
Dagger; U+02021
dagger; U+02020
daleth; U+02138
Darr; U+021A1
dArr; U+021D3
darr; U+02193
dash; U+02010
Dashv; U+02AE4
dashv; U+022A3
dbkarow; U+0290F
dblac; U+002DD ˝
Dcaron; U+0010E Ď
dcaron; U+0010F ď
Dcy; U+00414 Д
dcy; U+00434 д
DD; U+02145
dd; U+02146
ddagger; U+02021
ddarr; U+021CA
DDotrahd; U+02911
ddotseq; U+02A77
deg; U+000B0 °
deg U+000B0 °
Del; U+02207
Delta; U+00394 Δ
delta; U+003B4 δ
demptyv; U+029B1
dfisht; U+0297F ⥿
Dfr; U+1D507 𝔇
dfr; U+1D521 𝔡
dHar; U+02965
dharl; U+021C3
dharr; U+021C2
DiacriticalAcute; U+000B4 ´
DiacriticalDot; U+002D9 ˙
DiacriticalDoubleAcute; U+002DD ˝
DiacriticalGrave; U+00060 `
DiacriticalTilde; U+002DC ˜
diam; U+022C4
Diamond; U+022C4
diamond; U+022C4
diamondsuit; U+02666
diams; U+02666
die; U+000A8 ¨
DifferentialD; U+02146
digamma; U+003DD ϝ
disin; U+022F2
div; U+000F7 ÷
divide; U+000F7 ÷
divide U+000F7 ÷
divideontimes; U+022C7
divonx; U+022C7
DJcy; U+00402 Ђ
djcy; U+00452 ђ
dlcorn; U+0231E
dlcrop; U+0230D
dollar; U+00024 $
Dopf; U+1D53B 𝔻
dopf; U+1D555 𝕕
Dot; U+000A8 ¨
dot; U+002D9 ˙
DotDot; U+020DC ◌⃜
doteq; U+02250
doteqdot; U+02251
DotEqual; U+02250
dotminus; U+02238
dotplus; U+02214
dotsquare; U+022A1
doublebarwedge; U+02306
DoubleContourIntegral; U+0222F
DoubleDot; U+000A8 ¨
DoubleDownArrow; U+021D3
DoubleLeftArrow; U+021D0
DoubleLeftRightArrow; U+021D4
DoubleLeftTee; U+02AE4
DoubleLongLeftArrow; U+027F8
DoubleLongLeftRightArrow; U+027FA
DoubleLongRightArrow; U+027F9
DoubleRightArrow; U+021D2
DoubleRightTee; U+022A8
DoubleUpArrow; U+021D1
DoubleUpDownArrow; U+021D5
DoubleVerticalBar; U+02225
DownArrow; U+02193
Downarrow; U+021D3
downarrow; U+02193
DownArrowBar; U+02913
DownArrowUpArrow; U+021F5
DownBreve; U+00311 ◌̑
downdownarrows; U+021CA
downharpoonleft; U+021C3
downharpoonright; U+021C2
DownLeftRightVector; U+02950
DownLeftTeeVector; U+0295E
DownLeftVector; U+021BD
DownLeftVectorBar; U+02956
DownRightTeeVector; U+0295F
DownRightVector; U+021C1
DownRightVectorBar; U+02957
DownTee; U+022A4
DownTeeArrow; U+021A7
drbkarow; U+02910
drcorn; U+0231F
drcrop; U+0230C
Dscr; U+1D49F 𝒟
dscr; U+1D4B9 𝒹
DScy; U+00405 Ѕ
dscy; U+00455 ѕ
dsol; U+029F6
Dstrok; U+00110 Đ
dstrok; U+00111 đ
dtdot; U+022F1
dtri; U+025BF
dtrif; U+025BE
duarr; U+021F5
duhar; U+0296F
dwangle; U+029A6
DZcy; U+0040F Џ
dzcy; U+0045F џ
dzigrarr; U+027FF
Eacute; U+000C9 É
Eacute U+000C9 É
eacute; U+000E9 é
eacute U+000E9 é
easter; U+02A6E
Ecaron; U+0011A Ě
ecaron; U+0011B ě
ecir; U+02256
Ecirc; U+000CA Ê
Ecirc U+000CA Ê
ecirc; U+000EA ê
ecirc U+000EA ê
ecolon; U+02255
Ecy; U+0042D Э
ecy; U+0044D э
eDDot; U+02A77
Edot; U+00116 Ė
eDot; U+02251
edot; U+00117 ė
ee; U+02147
efDot; U+02252
Efr; U+1D508 𝔈
efr; U+1D522 𝔢
eg; U+02A9A
Egrave; U+000C8 È
Egrave U+000C8 È
egrave; U+000E8 è
egrave U+000E8 è
egs; U+02A96
egsdot; U+02A98
el; U+02A99
Element; U+02208
elinters; U+023E7
ell; U+02113
els; U+02A95
elsdot; U+02A97
Emacr; U+00112 Ē
emacr; U+00113 ē
empty; U+02205
emptyset; U+02205
EmptySmallSquare; U+025FB
emptyv; U+02205
EmptyVerySmallSquare; U+025AB
emsp; U+02003
emsp13; U+02004
emsp14; U+02005
ENG; U+0014A Ŋ
eng; U+0014B ŋ
ensp; U+02002
Eogon; U+00118 Ę
eogon; U+00119 ę
Eopf; U+1D53C 𝔼
eopf; U+1D556 𝕖
epar; U+022D5
eparsl; U+029E3
eplus; U+02A71
epsi; U+003B5 ε
Epsilon; U+00395 Ε
epsilon; U+003B5 ε
epsiv; U+003F5 ϵ
eqcirc; U+02256
eqcolon; U+02255
eqsim; U+02242
eqslantgtr; U+02A96
eqslantless; U+02A95
Equal; U+02A75
equals; U+0003D =
EqualTilde; U+02242
equest; U+0225F
Equilibrium; U+021CC
equiv; U+02261
equivDD; U+02A78
eqvparsl; U+029E5
erarr; U+02971
erDot; U+02253
Escr; U+02130
escr; U+0212F
esdot; U+02250
Esim; U+02A73
esim; U+02242
Eta; U+00397 Η
eta; U+003B7 η
ETH; U+000D0 Ð
ETH U+000D0 Ð
eth; U+000F0 ð
eth U+000F0 ð
Euml; U+000CB Ë
Euml U+000CB Ë
euml; U+000EB ë
euml U+000EB ë
euro; U+020AC
excl; U+00021 !
exist; U+02203
Exists; U+02203
expectation; U+02130
ExponentialE; U+02147
exponentiale; U+02147
fallingdotseq; U+02252
Fcy; U+00424 Ф
fcy; U+00444 ф
female; U+02640
ffilig; U+0FB03
fflig; U+0FB00
ffllig; U+0FB04
Ffr; U+1D509 𝔉
ffr; U+1D523 𝔣
filig; U+0FB01
FilledSmallSquare; U+025FC
FilledVerySmallSquare; U+025AA
fjlig; U+00066 U+0006A fj
flat; U+0266D
fllig; U+0FB02
fltns; U+025B1
fnof; U+00192 ƒ
Fopf; U+1D53D 𝔽
fopf; U+1D557 𝕗
ForAll; U+02200
forall; U+02200
fork; U+022D4
forkv; U+02AD9
Fouriertrf; U+02131
fpartint; U+02A0D
frac12; U+000BD ½
frac12 U+000BD ½
frac13; U+02153
frac14; U+000BC ¼
frac14 U+000BC ¼
frac15; U+02155
frac16; U+02159
frac18; U+0215B
frac23; U+02154
frac25; U+02156
frac34; U+000BE ¾
frac34 U+000BE ¾
frac35; U+02157
frac38; U+0215C
frac45; U+02158
frac56; U+0215A
frac58; U+0215D
frac78; U+0215E
frasl; U+02044
frown; U+02322
Fscr; U+02131
fscr; U+1D4BB 𝒻
gacute; U+001F5 ǵ
Gamma; U+00393 Γ
gamma; U+003B3 γ
Gammad; U+003DC Ϝ
gammad; U+003DD ϝ
gap; U+02A86
Gbreve; U+0011E Ğ
gbreve; U+0011F ğ
Gcedil; U+00122 Ģ
Gcirc; U+0011C Ĝ
gcirc; U+0011D ĝ
Gcy; U+00413 Г
gcy; U+00433 г
Gdot; U+00120 Ġ
gdot; U+00121 ġ
gE; U+02267
ge; U+02265
gEl; U+02A8C
gel; U+022DB
geq; U+02265
geqq; U+02267
geqslant; U+02A7E
ges; U+02A7E
gescc; U+02AA9
gesdot; U+02A80
gesdoto; U+02A82
gesdotol; U+02A84
gesl; U+022DB U+0FE00 ⋛︀
gesles; U+02A94
Gfr; U+1D50A 𝔊
gfr; U+1D524 𝔤
Gg; U+022D9
gg; U+0226B
ggg; U+022D9
gimel; U+02137
GJcy; U+00403 Ѓ
gjcy; U+00453 ѓ
gl; U+02277
gla; U+02AA5
glE; U+02A92
glj; U+02AA4
gnap; U+02A8A
gnapprox; U+02A8A
gnE; U+02269
gne; U+02A88
gneq; U+02A88
gneqq; U+02269
gnsim; U+022E7
Gopf; U+1D53E 𝔾
gopf; U+1D558 𝕘
grave; U+00060 `
GreaterEqual; U+02265
GreaterEqualLess; U+022DB
GreaterFullEqual; U+02267
GreaterGreater; U+02AA2
GreaterLess; U+02277
GreaterSlantEqual; U+02A7E
GreaterTilde; U+02273
Gscr; U+1D4A2 𝒢
gscr; U+0210A
gsim; U+02273
gsime; U+02A8E
gsiml; U+02A90
GT; U+0003E >
GT U+0003E >
Gt; U+0226B
gt; U+0003E >
gt U+0003E >
gtcc; U+02AA7
gtcir; U+02A7A
gtdot; U+022D7
gtlPar; U+02995
gtquest; U+02A7C
gtrapprox; U+02A86
gtrarr; U+02978
gtrdot; U+022D7
gtreqless; U+022DB
gtreqqless; U+02A8C
gtrless; U+02277
gtrsim; U+02273
gvertneqq; U+02269 U+0FE00 ≩︀
gvnE; U+02269 U+0FE00 ≩︀
Hacek; U+002C7 ˇ
hairsp; U+0200A
half; U+000BD ½
hamilt; U+0210B
HARDcy; U+0042A Ъ
hardcy; U+0044A ъ
hArr; U+021D4
harr; U+02194
harrcir; U+02948
harrw; U+021AD
Hat; U+0005E ^
hbar; U+0210F
Hcirc; U+00124 Ĥ
hcirc; U+00125 ĥ
hearts; U+02665
heartsuit; U+02665
hellip; U+02026
hercon; U+022B9
Hfr; U+0210C
hfr; U+1D525 𝔥
HilbertSpace; U+0210B
hksearow; U+02925
hkswarow; U+02926
hoarr; U+021FF
homtht; U+0223B
hookleftarrow; U+021A9
hookrightarrow; U+021AA
Hopf; U+0210D
hopf; U+1D559 𝕙
horbar; U+02015
HorizontalLine; U+02500
Hscr; U+0210B
hscr; U+1D4BD 𝒽
hslash; U+0210F
Hstrok; U+00126 Ħ
hstrok; U+00127 ħ
HumpDownHump; U+0224E
HumpEqual; U+0224F
hybull; U+02043
hyphen; U+02010
Iacute; U+000CD Í
Iacute U+000CD Í
iacute; U+000ED í
iacute U+000ED í
ic; U+02063
Icirc; U+000CE Î
Icirc U+000CE Î
icirc; U+000EE î
icirc U+000EE î
Icy; U+00418 И
icy; U+00438 и
Idot; U+00130 İ
IEcy; U+00415 Е
iecy; U+00435 е
iexcl; U+000A1 ¡
iexcl U+000A1 ¡
iff; U+021D4
Ifr; U+02111
ifr; U+1D526 𝔦
Igrave; U+000CC Ì
Igrave U+000CC Ì
igrave; U+000EC ì
igrave U+000EC ì
ii; U+02148
iiiint; U+02A0C
iiint; U+0222D
iinfin; U+029DC
iiota; U+02129
IJlig; U+00132 IJ
ijlig; U+00133 ij
Im; U+02111
Imacr; U+0012A Ī
imacr; U+0012B ī
image; U+02111
ImaginaryI; U+02148
imagline; U+02110
imagpart; U+02111
imath; U+00131 ı
imof; U+022B7
imped; U+001B5 Ƶ
Implies; U+021D2
in; U+02208
incare; U+02105
infin; U+0221E
infintie; U+029DD
inodot; U+00131 ı
Int; U+0222C
int; U+0222B
intcal; U+022BA
integers; U+02124
Integral; U+0222B
intercal; U+022BA
Intersection; U+022C2
intlarhk; U+02A17
intprod; U+02A3C
InvisibleComma; U+02063
InvisibleTimes; U+02062
IOcy; U+00401 Ё
iocy; U+00451 ё
Iogon; U+0012E Į
iogon; U+0012F į
Iopf; U+1D540 𝕀
iopf; U+1D55A 𝕚
Iota; U+00399 Ι
iota; U+003B9 ι
iprod; U+02A3C
iquest; U+000BF ¿
iquest U+000BF ¿
Iscr; U+02110
iscr; U+1D4BE 𝒾
isin; U+02208
isindot; U+022F5
isinE; U+022F9
isins; U+022F4
isinsv; U+022F3
isinv; U+02208
it; U+02062
Itilde; U+00128 Ĩ
itilde; U+00129 ĩ
Iukcy; U+00406 І
iukcy; U+00456 і
Iuml; U+000CF Ï
Iuml U+000CF Ï
iuml; U+000EF ï
iuml U+000EF ï
Jcirc; U+00134 Ĵ
jcirc; U+00135 ĵ
Jcy; U+00419 Й
jcy; U+00439 й
Jfr; U+1D50D 𝔍
jfr; U+1D527 𝔧
jmath; U+00237 ȷ
Jopf; U+1D541 𝕁
jopf; U+1D55B 𝕛
Jscr; U+1D4A5 𝒥
jscr; U+1D4BF 𝒿
Jsercy; U+00408 Ј
jsercy; U+00458 ј
Jukcy; U+00404 Є
jukcy; U+00454 є
Kappa; U+0039A Κ
kappa; U+003BA κ
kappav; U+003F0 ϰ
Kcedil; U+00136 Ķ
kcedil; U+00137 ķ
Kcy; U+0041A К
kcy; U+0043A к
Kfr; U+1D50E 𝔎
kfr; U+1D528 𝔨
kgreen; U+00138 ĸ
KHcy; U+00425 Х
khcy; U+00445 х
KJcy; U+0040C Ќ
kjcy; U+0045C ќ
Kopf; U+1D542 𝕂
kopf; U+1D55C 𝕜
Kscr; U+1D4A6 𝒦
kscr; U+1D4C0 𝓀
lAarr; U+021DA
Lacute; U+00139 Ĺ
lacute; U+0013A ĺ
laemptyv; U+029B4
lagran; U+02112
Lambda; U+0039B Λ
lambda; U+003BB λ
Lang; U+027EA
lang; U+027E8
langd; U+02991
langle; U+027E8
lap; U+02A85
Laplacetrf; U+02112
laquo; U+000AB «
laquo U+000AB «
Larr; U+0219E
lArr; U+021D0
larr; U+02190
larrb; U+021E4
larrbfs; U+0291F
larrfs; U+0291D
larrhk; U+021A9
larrlp; U+021AB
larrpl; U+02939
larrsim; U+02973
larrtl; U+021A2
lat; U+02AAB
lAtail; U+0291B
latail; U+02919
late; U+02AAD
lates; U+02AAD U+0FE00 ⪭︀
lBarr; U+0290E
lbarr; U+0290C
lbbrk; U+02772
lbrace; U+0007B {
lbrack; U+0005B [
lbrke; U+0298B
lbrksld; U+0298F
lbrkslu; U+0298D
Lcaron; U+0013D Ľ
lcaron; U+0013E ľ
Lcedil; U+0013B Ļ
lcedil; U+0013C ļ
lceil; U+02308
lcub; U+0007B {
Lcy; U+0041B Л
lcy; U+0043B л
ldca; U+02936
ldquo; U+0201C
ldquor; U+0201E
ldrdhar; U+02967
ldrushar; U+0294B
ldsh; U+021B2
lE; U+02266
le; U+02264
LeftAngleBracket; U+027E8
LeftArrow; U+02190
Leftarrow; U+021D0
leftarrow; U+02190
LeftArrowBar; U+021E4
LeftArrowRightArrow; U+021C6
leftarrowtail; U+021A2
LeftCeiling; U+02308
LeftDoubleBracket; U+027E6
LeftDownTeeVector; U+02961
LeftDownVector; U+021C3
LeftDownVectorBar; U+02959
LeftFloor; U+0230A
leftharpoondown; U+021BD
leftharpoonup; U+021BC
leftleftarrows; U+021C7
LeftRightArrow; U+02194
Leftrightarrow; U+021D4
leftrightarrow; U+02194
leftrightarrows; U+021C6
leftrightharpoons; U+021CB
leftrightsquigarrow; U+021AD
LeftRightVector; U+0294E
LeftTee; U+022A3
LeftTeeArrow; U+021A4
LeftTeeVector; U+0295A
leftthreetimes; U+022CB
LeftTriangle; U+022B2
LeftTriangleBar; U+029CF
LeftTriangleEqual; U+022B4
LeftUpDownVector; U+02951
LeftUpTeeVector; U+02960
LeftUpVector; U+021BF
LeftUpVectorBar; U+02958
LeftVector; U+021BC
LeftVectorBar; U+02952
lEg; U+02A8B
leg; U+022DA
leq; U+02264
leqq; U+02266
leqslant; U+02A7D
les; U+02A7D
lescc; U+02AA8
lesdot; U+02A7F ⩿
lesdoto; U+02A81
lesdotor; U+02A83
lesg; U+022DA U+0FE00 ⋚︀
lesges; U+02A93
lessapprox; U+02A85
lessdot; U+022D6
lesseqgtr; U+022DA
lesseqqgtr; U+02A8B
LessEqualGreater; U+022DA
LessFullEqual; U+02266
LessGreater; U+02276
lessgtr; U+02276
LessLess; U+02AA1
lesssim; U+02272
LessSlantEqual; U+02A7D
LessTilde; U+02272
lfisht; U+0297C
lfloor; U+0230A
Lfr; U+1D50F 𝔏
lfr; U+1D529 𝔩
lg; U+02276
lgE; U+02A91
lHar; U+02962
lhard; U+021BD
lharu; U+021BC
lharul; U+0296A
lhblk; U+02584
LJcy; U+00409 Љ
ljcy; U+00459 љ
Ll; U+022D8
ll; U+0226A
llarr; U+021C7
llcorner; U+0231E
Lleftarrow; U+021DA
llhard; U+0296B
lltri; U+025FA
Lmidot; U+0013F Ŀ
lmidot; U+00140 ŀ
lmoust; U+023B0
lmoustache; U+023B0
lnap; U+02A89
lnapprox; U+02A89
lnE; U+02268
lne; U+02A87
lneq; U+02A87
lneqq; U+02268
lnsim; U+022E6
loang; U+027EC
loarr; U+021FD
lobrk; U+027E6
LongLeftArrow; U+027F5
Longleftarrow; U+027F8
longleftarrow; U+027F5
LongLeftRightArrow; U+027F7
Longleftrightarrow; U+027FA
longleftrightarrow; U+027F7
longmapsto; U+027FC
LongRightArrow; U+027F6
Longrightarrow; U+027F9
longrightarrow; U+027F6
looparrowleft; U+021AB
looparrowright; U+021AC
lopar; U+02985
Lopf; U+1D543 𝕃
lopf; U+1D55D 𝕝
loplus; U+02A2D
lotimes; U+02A34
lowast; U+02217
lowbar; U+0005F _
LowerLeftArrow; U+02199
LowerRightArrow; U+02198
loz; U+025CA
lozenge; U+025CA
lozf; U+029EB
lpar; U+00028 (
lparlt; U+02993
lrarr; U+021C6
lrcorner; U+0231F
lrhar; U+021CB
lrhard; U+0296D
lrm; U+0200E
lrtri; U+022BF
lsaquo; U+02039
Lscr; U+02112
lscr; U+1D4C1 𝓁
Lsh; U+021B0
lsh; U+021B0
lsim; U+02272
lsime; U+02A8D
lsimg; U+02A8F
lsqb; U+0005B [
lsquo; U+02018
lsquor; U+0201A
Lstrok; U+00141 Ł
lstrok; U+00142 ł
LT; U+0003C <
LT U+0003C <
Lt; U+0226A
lt; U+0003C <
lt U+0003C <
ltcc; U+02AA6
ltcir; U+02A79
ltdot; U+022D6
lthree; U+022CB
ltimes; U+022C9
ltlarr; U+02976
ltquest; U+02A7B
ltri; U+025C3
ltrie; U+022B4
ltrif; U+025C2
ltrPar; U+02996
lurdshar; U+0294A
luruhar; U+02966
lvertneqq; U+02268 U+0FE00 ≨︀
lvnE; U+02268 U+0FE00 ≨︀
macr; U+000AF ¯
macr U+000AF ¯
male; U+02642
malt; U+02720
maltese; U+02720
Map; U+02905
map; U+021A6
mapsto; U+021A6
mapstodown; U+021A7
mapstoleft; U+021A4
mapstoup; U+021A5
marker; U+025AE
mcomma; U+02A29
Mcy; U+0041C М
mcy; U+0043C м
mdash; U+02014
mDDot; U+0223A
measuredangle; U+02221
MediumSpace; U+0205F
Mellintrf; U+02133
Mfr; U+1D510 𝔐
mfr; U+1D52A 𝔪
mho; U+02127
micro; U+000B5 µ
micro U+000B5 µ
mid; U+02223
midast; U+0002A *
midcir; U+02AF0
middot; U+000B7 ·
middot U+000B7 ·
minus; U+02212
minusb; U+0229F
minusd; U+02238
minusdu; U+02A2A
MinusPlus; U+02213
mlcp; U+02ADB
mldr; U+02026
mnplus; U+02213
models; U+022A7
Mopf; U+1D544 𝕄
mopf; U+1D55E 𝕞
mp; U+02213
Mscr; U+02133
mscr; U+1D4C2 𝓂
mstpos; U+0223E
Mu; U+0039C Μ
mu; U+003BC μ
multimap; U+022B8
mumap; U+022B8
nabla; U+02207
Nacute; U+00143 Ń
nacute; U+00144 ń
nang; U+02220 U+020D2 ∠⃒
nap; U+02249
napE; U+02A70 U+00338 ⩰̸
napid; U+0224B U+00338 ≋̸
napos; U+00149 ʼn
napprox; U+02249
natur; U+0266E
natural; U+0266E
naturals; U+02115
nbsp; U+000A0  
nbsp U+000A0  
nbump; U+0224E U+00338 ≎̸
nbumpe; U+0224F U+00338 ≏̸
ncap; U+02A43
Ncaron; U+00147 Ň
ncaron; U+00148 ň
Ncedil; U+00145 Ņ
ncedil; U+00146 ņ
ncong; U+02247
ncongdot; U+02A6D U+00338 ⩭̸
ncup; U+02A42
Ncy; U+0041D Н
ncy; U+0043D н
ndash; U+02013
ne; U+02260
nearhk; U+02924
neArr; U+021D7
nearr; U+02197
nearrow; U+02197
nedot; U+02250 U+00338 ≐̸
NegativeMediumSpace; U+0200B
NegativeThickSpace; U+0200B
NegativeThinSpace; U+0200B
NegativeVeryThinSpace; U+0200B
nequiv; U+02262
nesear; U+02928
nesim; U+02242 U+00338 ≂̸
NestedGreaterGreater; U+0226B
NestedLessLess; U+0226A
NewLine; U+0000A
nexist; U+02204
nexists; U+02204
Nfr; U+1D511 𝔑
nfr; U+1D52B 𝔫
ngE; U+02267 U+00338 ≧̸
nge; U+02271
ngeq; U+02271
ngeqq; U+02267 U+00338 ≧̸
ngeqslant; U+02A7E U+00338 ⩾̸
nges; U+02A7E U+00338 ⩾̸
nGg; U+022D9 U+00338 ⋙̸
ngsim; U+02275
nGt; U+0226B U+020D2 ≫⃒
ngt; U+0226F
ngtr; U+0226F
nGtv; U+0226B U+00338 ≫̸
nhArr; U+021CE
nharr; U+021AE
nhpar; U+02AF2
ni; U+0220B
nis; U+022FC
nisd; U+022FA
niv; U+0220B
NJcy; U+0040A Њ
njcy; U+0045A њ
nlArr; U+021CD
nlarr; U+0219A
nldr; U+02025
nlE; U+02266 U+00338 ≦̸
nle; U+02270
nLeftarrow; U+021CD
nleftarrow; U+0219A
nLeftrightarrow; U+021CE
nleftrightarrow; U+021AE
nleq; U+02270
nleqq; U+02266 U+00338 ≦̸
nleqslant; U+02A7D U+00338 ⩽̸
nles; U+02A7D U+00338 ⩽̸
nless; U+0226E
nLl; U+022D8 U+00338 ⋘̸
nlsim; U+02274
nLt; U+0226A U+020D2 ≪⃒
nlt; U+0226E
nltri; U+022EA
nltrie; U+022EC
nLtv; U+0226A U+00338 ≪̸
nmid; U+02224
NoBreak; U+02060
NonBreakingSpace; U+000A0  
Nopf; U+02115
nopf; U+1D55F 𝕟
Not; U+02AEC
not; U+000AC ¬
not U+000AC ¬
NotCongruent; U+02262
NotCupCap; U+0226D
NotDoubleVerticalBar; U+02226
NotElement; U+02209
NotEqual; U+02260
NotEqualTilde; U+02242 U+00338 ≂̸
NotExists; U+02204
NotGreater; U+0226F
NotGreaterEqual; U+02271
NotGreaterFullEqual; U+02267 U+00338 ≧̸
NotGreaterGreater; U+0226B U+00338 ≫̸
NotGreaterLess; U+02279
NotGreaterSlantEqual; U+02A7E U+00338 ⩾̸
NotGreaterTilde; U+02275
NotHumpDownHump; U+0224E U+00338 ≎̸
NotHumpEqual; U+0224F U+00338 ≏̸
notin; U+02209
notindot; U+022F5 U+00338 ⋵̸
notinE; U+022F9 U+00338 ⋹̸
notinva; U+02209
notinvb; U+022F7
notinvc; U+022F6
NotLeftTriangle; U+022EA
NotLeftTriangleBar; U+029CF U+00338 ⧏̸
NotLeftTriangleEqual; U+022EC
NotLess; U+0226E
NotLessEqual; U+02270
NotLessGreater; U+02278
NotLessLess; U+0226A U+00338 ≪̸
NotLessSlantEqual; U+02A7D U+00338 ⩽̸
NotLessTilde; U+02274
NotNestedGreaterGreater; U+02AA2 U+00338 ⪢̸
NotNestedLessLess; U+02AA1 U+00338 ⪡̸
notni; U+0220C
notniva; U+0220C
notnivb; U+022FE
notnivc; U+022FD
NotPrecedes; U+02280
NotPrecedesEqual; U+02AAF U+00338 ⪯̸
NotPrecedesSlantEqual; U+022E0
NotReverseElement; U+0220C
NotRightTriangle; U+022EB
NotRightTriangleBar; U+029D0 U+00338 ⧐̸
NotRightTriangleEqual; U+022ED
NotSquareSubset; U+0228F U+00338 ⊏̸
NotSquareSubsetEqual; U+022E2
NotSquareSuperset; U+02290 U+00338 ⊐̸
NotSquareSupersetEqual; U+022E3
NotSubset; U+02282 U+020D2 ⊂⃒
NotSubsetEqual; U+02288
NotSucceeds; U+02281
NotSucceedsEqual; U+02AB0 U+00338 ⪰̸
NotSucceedsSlantEqual; U+022E1
NotSucceedsTilde; U+0227F U+00338 ≿̸
NotSuperset; U+02283 U+020D2 ⊃⃒
NotSupersetEqual; U+02289
NotTilde; U+02241
NotTildeEqual; U+02244
NotTildeFullEqual; U+02247
NotTildeTilde; U+02249
NotVerticalBar; U+02224
npar; U+02226
nparallel; U+02226
nparsl; U+02AFD U+020E5 ⫽⃥
npart; U+02202 U+00338 ∂̸
npolint; U+02A14
npr; U+02280
nprcue; U+022E0
npre; U+02AAF U+00338 ⪯̸
nprec; U+02280
npreceq; U+02AAF U+00338 ⪯̸
nrArr; U+021CF
nrarr; U+0219B
nrarrc; U+02933 U+00338 ⤳̸
nrarrw; U+0219D U+00338 ↝̸
nRightarrow; U+021CF
nrightarrow; U+0219B
nrtri; U+022EB
nrtrie; U+022ED
nsc; U+02281
nsccue; U+022E1
nsce; U+02AB0 U+00338 ⪰̸
Nscr; U+1D4A9 𝒩
nscr; U+1D4C3 𝓃
nshortmid; U+02224
nshortparallel; U+02226
nsim; U+02241
nsime; U+02244
nsimeq; U+02244
nsmid; U+02224
nspar; U+02226
nsqsube; U+022E2
nsqsupe; U+022E3
nsub; U+02284
nsubE; U+02AC5 U+00338 ⫅̸
nsube; U+02288
nsubset; U+02282 U+020D2 ⊂⃒
nsubseteq; U+02288
nsubseteqq; U+02AC5 U+00338 ⫅̸
nsucc; U+02281
nsucceq; U+02AB0 U+00338 ⪰̸
nsup; U+02285
nsupE; U+02AC6 U+00338 ⫆̸
nsupe; U+02289
nsupset; U+02283 U+020D2 ⊃⃒
nsupseteq; U+02289
nsupseteqq; U+02AC6 U+00338 ⫆̸
ntgl; U+02279
Ntilde; U+000D1 Ñ
Ntilde U+000D1 Ñ
ntilde; U+000F1 ñ
ntilde U+000F1 ñ
ntlg; U+02278
ntriangleleft; U+022EA
ntrianglelefteq; U+022EC
ntriangleright; U+022EB
ntrianglerighteq; U+022ED
Nu; U+0039D Ν
nu; U+003BD ν
num; U+00023 #
numero; U+02116
numsp; U+02007
nvap; U+0224D U+020D2 ≍⃒
nVDash; U+022AF
nVdash; U+022AE
nvDash; U+022AD
nvdash; U+022AC
nvge; U+02265 U+020D2 ≥⃒
nvgt; U+0003E U+020D2 >⃒
nvHarr; U+02904
nvinfin; U+029DE
nvlArr; U+02902
nvle; U+02264 U+020D2 ≤⃒
nvlt; U+0003C U+020D2 <⃒
nvltrie; U+022B4 U+020D2 ⊴⃒
nvrArr; U+02903
nvrtrie; U+022B5 U+020D2 ⊵⃒
nvsim; U+0223C U+020D2 ∼⃒
nwarhk; U+02923
nwArr; U+021D6
nwarr; U+02196
nwarrow; U+02196
nwnear; U+02927
Oacute; U+000D3 Ó
Oacute U+000D3 Ó
oacute; U+000F3 ó
oacute U+000F3 ó
oast; U+0229B
ocir; U+0229A
Ocirc; U+000D4 Ô
Ocirc U+000D4 Ô
ocirc; U+000F4 ô
ocirc U+000F4 ô
Ocy; U+0041E О
ocy; U+0043E о
odash; U+0229D
Odblac; U+00150 Ő
odblac; U+00151 ő
odiv; U+02A38
odot; U+02299
odsold; U+029BC
OElig; U+00152 Œ
oelig; U+00153 œ
ofcir; U+029BF ⦿
Ofr; U+1D512 𝔒
ofr; U+1D52C 𝔬
ogon; U+002DB ˛
Ograve; U+000D2 Ò
Ograve U+000D2 Ò
ograve; U+000F2 ò
ograve U+000F2 ò
ogt; U+029C1
ohbar; U+029B5
ohm; U+003A9 Ω
oint; U+0222E
olarr; U+021BA
olcir; U+029BE
olcross; U+029BB
oline; U+0203E
olt; U+029C0
Omacr; U+0014C Ō
omacr; U+0014D ō
Omega; U+003A9 Ω
omega; U+003C9 ω
Omicron; U+0039F Ο
omicron; U+003BF ο
omid; U+029B6
ominus; U+02296
Oopf; U+1D546 𝕆
oopf; U+1D560 𝕠
opar; U+029B7
OpenCurlyDoubleQuote; U+0201C
OpenCurlyQuote; U+02018
operp; U+029B9
oplus; U+02295
Or; U+02A54
or; U+02228
orarr; U+021BB
ord; U+02A5D
order; U+02134
orderof; U+02134
ordf; U+000AA ª
ordf U+000AA ª
ordm; U+000BA º
ordm U+000BA º
origof; U+022B6
oror; U+02A56
orslope; U+02A57
orv; U+02A5B
oS; U+024C8
Oscr; U+1D4AA 𝒪
oscr; U+02134
Oslash; U+000D8 Ø
Oslash U+000D8 Ø
oslash; U+000F8 ø
oslash U+000F8 ø
osol; U+02298
Otilde; U+000D5 Õ
Otilde U+000D5 Õ
otilde; U+000F5 õ
otilde U+000F5 õ
Otimes; U+02A37
otimes; U+02297
otimesas; U+02A36
Ouml; U+000D6 Ö
Ouml U+000D6 Ö
ouml; U+000F6 ö
ouml U+000F6 ö
ovbar; U+0233D
OverBar; U+0203E
OverBrace; U+023DE
OverBracket; U+023B4
OverParenthesis; U+023DC
par; U+02225
para; U+000B6
para U+000B6
parallel; U+02225
parsim; U+02AF3
parsl; U+02AFD
part; U+02202
PartialD; U+02202
Pcy; U+0041F П
pcy; U+0043F п
percnt; U+00025 %
period; U+0002E .
permil; U+02030
perp; U+022A5
pertenk; U+02031
Pfr; U+1D513 𝔓
pfr; U+1D52D 𝔭
Phi; U+003A6 Φ
phi; U+003C6 φ
phiv; U+003D5 ϕ
phmmat; U+02133
phone; U+0260E
Pi; U+003A0 Π
pi; U+003C0 π
pitchfork; U+022D4
piv; U+003D6 ϖ
planck; U+0210F
planckh; U+0210E
plankv; U+0210F
plus; U+0002B +
plusacir; U+02A23
plusb; U+0229E
pluscir; U+02A22
plusdo; U+02214
plusdu; U+02A25
pluse; U+02A72
PlusMinus; U+000B1 ±
plusmn; U+000B1 ±
plusmn U+000B1 ±
plussim; U+02A26
plustwo; U+02A27
pm; U+000B1 ±
Poincareplane; U+0210C
pointint; U+02A15
Popf; U+02119
popf; U+1D561 𝕡
pound; U+000A3 £
pound U+000A3 £
Pr; U+02ABB
pr; U+0227A
prap; U+02AB7
prcue; U+0227C
prE; U+02AB3
pre; U+02AAF
prec; U+0227A
precapprox; U+02AB7
preccurlyeq; U+0227C
Precedes; U+0227A
PrecedesEqual; U+02AAF
PrecedesSlantEqual; U+0227C
PrecedesTilde; U+0227E
preceq; U+02AAF
precnapprox; U+02AB9
precneqq; U+02AB5
precnsim; U+022E8
precsim; U+0227E
Prime; U+02033
prime; U+02032
primes; U+02119
prnap; U+02AB9
prnE; U+02AB5
prnsim; U+022E8
prod; U+0220F
Product; U+0220F
profalar; U+0232E
profline; U+02312
profsurf; U+02313
prop; U+0221D
Proportion; U+02237
Proportional; U+0221D
propto; U+0221D
prsim; U+0227E
prurel; U+022B0
Pscr; U+1D4AB 𝒫
pscr; U+1D4C5 𝓅
Psi; U+003A8 Ψ
psi; U+003C8 ψ
puncsp; U+02008
Qfr; U+1D514 𝔔
qfr; U+1D52E 𝔮
qint; U+02A0C
Qopf; U+0211A
qopf; U+1D562 𝕢
qprime; U+02057
Qscr; U+1D4AC 𝒬
qscr; U+1D4C6 𝓆
quaternions; U+0210D
quatint; U+02A16
quest; U+0003F ?
questeq; U+0225F
QUOT; U+00022 "
QUOT U+00022 "
quot; U+00022 "
quot U+00022 "
rAarr; U+021DB
race; U+0223D U+00331 ∽̱
Racute; U+00154 Ŕ
racute; U+00155 ŕ
radic; U+0221A
raemptyv; U+029B3
Rang; U+027EB
rang; U+027E9
rangd; U+02992
range; U+029A5
rangle; U+027E9
raquo; U+000BB »
raquo U+000BB »
Rarr; U+021A0
rArr; U+021D2
rarr; U+02192
rarrap; U+02975
rarrb; U+021E5
rarrbfs; U+02920
rarrc; U+02933
rarrfs; U+0291E
rarrhk; U+021AA
rarrlp; U+021AC
rarrpl; U+02945
rarrsim; U+02974
Rarrtl; U+02916
rarrtl; U+021A3
rarrw; U+0219D
rAtail; U+0291C
ratail; U+0291A
ratio; U+02236
rationals; U+0211A
RBarr; U+02910
rBarr; U+0290F
rbarr; U+0290D
rbbrk; U+02773
rbrace; U+0007D }
rbrack; U+0005D ]
rbrke; U+0298C
rbrksld; U+0298E
rbrkslu; U+02990
Rcaron; U+00158 Ř
rcaron; U+00159 ř
Rcedil; U+00156 Ŗ
rcedil; U+00157 ŗ
rceil; U+02309
rcub; U+0007D }
Rcy; U+00420 Р
rcy; U+00440 р
rdca; U+02937
rdldhar; U+02969
rdquo; U+0201D
rdquor; U+0201D
rdsh; U+021B3
Re; U+0211C
real; U+0211C
realine; U+0211B
realpart; U+0211C
reals; U+0211D
rect; U+025AD
REG; U+000AE ®
REG U+000AE ®
reg; U+000AE ®
reg U+000AE ®
ReverseElement; U+0220B
ReverseEquilibrium; U+021CB
ReverseUpEquilibrium; U+0296F
rfisht; U+0297D
rfloor; U+0230B
Rfr; U+0211C
rfr; U+1D52F 𝔯
rHar; U+02964
rhard; U+021C1
rharu; U+021C0
rharul; U+0296C
Rho; U+003A1 Ρ
rho; U+003C1 ρ
rhov; U+003F1 ϱ
RightAngleBracket; U+027E9
RightArrow; U+02192
Rightarrow; U+021D2
rightarrow; U+02192
RightArrowBar; U+021E5
RightArrowLeftArrow; U+021C4
rightarrowtail; U+021A3
RightCeiling; U+02309
RightDoubleBracket; U+027E7
RightDownTeeVector; U+0295D
RightDownVector; U+021C2
RightDownVectorBar; U+02955
RightFloor; U+0230B
rightharpoondown; U+021C1
rightharpoonup; U+021C0
rightleftarrows; U+021C4
rightleftharpoons; U+021CC
rightrightarrows; U+021C9
rightsquigarrow; U+0219D
RightTee; U+022A2
RightTeeArrow; U+021A6
RightTeeVector; U+0295B
rightthreetimes; U+022CC
RightTriangle; U+022B3
RightTriangleBar; U+029D0
RightTriangleEqual; U+022B5
RightUpDownVector; U+0294F
RightUpTeeVector; U+0295C
RightUpVector; U+021BE
RightUpVectorBar; U+02954
RightVector; U+021C0
RightVectorBar; U+02953
ring; U+002DA ˚
risingdotseq; U+02253
rlarr; U+021C4
rlhar; U+021CC
rlm; U+0200F
rmoust; U+023B1
rmoustache; U+023B1
rnmid; U+02AEE
roang; U+027ED
roarr; U+021FE
robrk; U+027E7
ropar; U+02986
Ropf; U+0211D
ropf; U+1D563 𝕣
roplus; U+02A2E
rotimes; U+02A35
RoundImplies; U+02970
rpar; U+00029 )
rpargt; U+02994
rppolint; U+02A12
rrarr; U+021C9
Rrightarrow; U+021DB
rsaquo; U+0203A
Rscr; U+0211B
rscr; U+1D4C7 𝓇
Rsh; U+021B1
rsh; U+021B1
rsqb; U+0005D ]
rsquo; U+02019
rsquor; U+02019
rthree; U+022CC
rtimes; U+022CA
rtri; U+025B9
rtrie; U+022B5
rtrif; U+025B8
rtriltri; U+029CE
RuleDelayed; U+029F4
ruluhar; U+02968
rx; U+0211E
Sacute; U+0015A Ś
sacute; U+0015B ś
sbquo; U+0201A
Sc; U+02ABC
sc; U+0227B
scap; U+02AB8
Scaron; U+00160 Š
scaron; U+00161 š
sccue; U+0227D
scE; U+02AB4
sce; U+02AB0
Scedil; U+0015E Ş
scedil; U+0015F ş
Scirc; U+0015C Ŝ
scirc; U+0015D ŝ
scnap; U+02ABA
scnE; U+02AB6
scnsim; U+022E9
scpolint; U+02A13
scsim; U+0227F
Scy; U+00421 С
scy; U+00441 с
sdot; U+022C5
sdotb; U+022A1
sdote; U+02A66
searhk; U+02925
seArr; U+021D8
searr; U+02198
searrow; U+02198
sect; U+000A7 §
sect U+000A7 §
semi; U+0003B ;
seswar; U+02929
setminus; U+02216
setmn; U+02216
sext; U+02736
Sfr; U+1D516 𝔖
sfr; U+1D530 𝔰
sfrown; U+02322
sharp; U+0266F
SHCHcy; U+00429 Щ
shchcy; U+00449 щ
SHcy; U+00428 Ш
shcy; U+00448 ш
ShortDownArrow; U+02193
ShortLeftArrow; U+02190
shortmid; U+02223
shortparallel; U+02225
ShortRightArrow; U+02192
ShortUpArrow; U+02191
shy; U+000AD ­
shy U+000AD ­
Sigma; U+003A3 Σ
sigma; U+003C3 σ
sigmaf; U+003C2 ς
sigmav; U+003C2 ς
sim; U+0223C
simdot; U+02A6A
sime; U+02243
simeq; U+02243
simg; U+02A9E
simgE; U+02AA0
siml; U+02A9D
simlE; U+02A9F
simne; U+02246
simplus; U+02A24
simrarr; U+02972
slarr; U+02190
SmallCircle; U+02218
smallsetminus; U+02216
smashp; U+02A33
smeparsl; U+029E4
smid; U+02223
smile; U+02323
smt; U+02AAA
smte; U+02AAC
smtes; U+02AAC U+0FE00 ⪬︀
SOFTcy; U+0042C Ь
softcy; U+0044C ь
sol; U+0002F /
solb; U+029C4
solbar; U+0233F
Sopf; U+1D54A 𝕊
sopf; U+1D564 𝕤
spades; U+02660
spadesuit; U+02660
spar; U+02225
sqcap; U+02293
sqcaps; U+02293 U+0FE00 ⊓︀
sqcup; U+02294
sqcups; U+02294 U+0FE00 ⊔︀
Sqrt; U+0221A
sqsub; U+0228F
sqsube; U+02291
sqsubset; U+0228F
sqsubseteq; U+02291
sqsup; U+02290
sqsupe; U+02292
sqsupset; U+02290
sqsupseteq; U+02292
squ; U+025A1
Square; U+025A1
square; U+025A1
SquareIntersection; U+02293
SquareSubset; U+0228F
SquareSubsetEqual; U+02291
SquareSuperset; U+02290
SquareSupersetEqual; U+02292
SquareUnion; U+02294
squarf; U+025AA
squf; U+025AA
srarr; U+02192
Sscr; U+1D4AE 𝒮
sscr; U+1D4C8 𝓈
ssetmn; U+02216
ssmile; U+02323
sstarf; U+022C6
Star; U+022C6
star; U+02606
starf; U+02605
straightepsilon; U+003F5 ϵ
straightphi; U+003D5 ϕ
strns; U+000AF ¯
Sub; U+022D0
sub; U+02282
subdot; U+02ABD
subE; U+02AC5
sube; U+02286
subedot; U+02AC3
submult; U+02AC1
subnE; U+02ACB
subne; U+0228A
subplus; U+02ABF ⪿
subrarr; U+02979
Subset; U+022D0
subset; U+02282
subseteq; U+02286
subseteqq; U+02AC5
SubsetEqual; U+02286
subsetneq; U+0228A
subsetneqq; U+02ACB
subsim; U+02AC7
subsub; U+02AD5
subsup; U+02AD3
succ; U+0227B
succapprox; U+02AB8
succcurlyeq; U+0227D
Succeeds; U+0227B
SucceedsEqual; U+02AB0
SucceedsSlantEqual; U+0227D
SucceedsTilde; U+0227F
succeq; U+02AB0
succnapprox; U+02ABA
succneqq; U+02AB6
succnsim; U+022E9
succsim; U+0227F
SuchThat; U+0220B
Sum; U+02211
sum; U+02211
sung; U+0266A
Sup; U+022D1
sup; U+02283
sup1; U+000B9 ¹
sup1 U+000B9 ¹
sup2; U+000B2 ²
sup2 U+000B2 ²
sup3; U+000B3 ³
sup3 U+000B3 ³
supdot; U+02ABE
supdsub; U+02AD8
supE; U+02AC6
supe; U+02287
supedot; U+02AC4
Superset; U+02283
SupersetEqual; U+02287
suphsol; U+027C9
suphsub; U+02AD7
suplarr; U+0297B
supmult; U+02AC2
supnE; U+02ACC
supne; U+0228B
supplus; U+02AC0
Supset; U+022D1
supset; U+02283
supseteq; U+02287
supseteqq; U+02AC6
supsetneq; U+0228B
supsetneqq; U+02ACC
supsim; U+02AC8
supsub; U+02AD4
supsup; U+02AD6
swarhk; U+02926
swArr; U+021D9
swarr; U+02199
swarrow; U+02199
swnwar; U+0292A
szlig; U+000DF ß
szlig U+000DF ß
Tab; U+00009
target; U+02316
Tau; U+003A4 Τ
tau; U+003C4 τ
tbrk; U+023B4
Tcaron; U+00164 Ť
tcaron; U+00165 ť
Tcedil; U+00162 Ţ
tcedil; U+00163 ţ
Tcy; U+00422 Т
tcy; U+00442 т
tdot; U+020DB ◌⃛
telrec; U+02315
Tfr; U+1D517 𝔗
tfr; U+1D531 𝔱
there4; U+02234
Therefore; U+02234
therefore; U+02234
Theta; U+00398 Θ
theta; U+003B8 θ
thetasym; U+003D1 ϑ
thetav; U+003D1 ϑ
thickapprox; U+02248
thicksim; U+0223C
ThickSpace; U+0205F U+0200A   
thinsp; U+02009
ThinSpace; U+02009
thkap; U+02248
thksim; U+0223C
THORN; U+000DE Þ
THORN U+000DE Þ
thorn; U+000FE þ
thorn U+000FE þ
Tilde; U+0223C
tilde; U+002DC ˜
TildeEqual; U+02243
TildeFullEqual; U+02245
TildeTilde; U+02248
times; U+000D7 ×
times U+000D7 ×
timesb; U+022A0
timesbar; U+02A31
timesd; U+02A30
tint; U+0222D
toea; U+02928
top; U+022A4
topbot; U+02336
topcir; U+02AF1
Topf; U+1D54B 𝕋
topf; U+1D565 𝕥
topfork; U+02ADA
tosa; U+02929
tprime; U+02034
TRADE; U+02122
trade; U+02122
triangle; U+025B5
triangledown; U+025BF
triangleleft; U+025C3
trianglelefteq; U+022B4
triangleq; U+0225C
triangleright; U+025B9
trianglerighteq; U+022B5
tridot; U+025EC
trie; U+0225C
triminus; U+02A3A
TripleDot; U+020DB ◌⃛
triplus; U+02A39
trisb; U+029CD
tritime; U+02A3B
trpezium; U+023E2
Tscr; U+1D4AF 𝒯
tscr; U+1D4C9 𝓉
TScy; U+00426 Ц
tscy; U+00446 ц
TSHcy; U+0040B Ћ
tshcy; U+0045B ћ
Tstrok; U+00166 Ŧ
tstrok; U+00167 ŧ
twixt; U+0226C
twoheadleftarrow; U+0219E
twoheadrightarrow; U+021A0
Uacute; U+000DA Ú
Uacute U+000DA Ú
uacute; U+000FA ú
uacute U+000FA ú
Uarr; U+0219F
uArr; U+021D1
uarr; U+02191
Uarrocir; U+02949
Ubrcy; U+0040E Ў
ubrcy; U+0045E ў
Ubreve; U+0016C Ŭ
ubreve; U+0016D ŭ
Ucirc; U+000DB Û
Ucirc U+000DB Û
ucirc; U+000FB û
ucirc U+000FB û
Ucy; U+00423 У
ucy; U+00443 у
udarr; U+021C5
Udblac; U+00170 Ű
udblac; U+00171 ű
udhar; U+0296E
ufisht; U+0297E
Ufr; U+1D518 𝔘
ufr; U+1D532 𝔲
Ugrave; U+000D9 Ù
Ugrave U+000D9 Ù
ugrave; U+000F9 ù
ugrave U+000F9 ù
uHar; U+02963
uharl; U+021BF
uharr; U+021BE
uhblk; U+02580
ulcorn; U+0231C
ulcorner; U+0231C
ulcrop; U+0230F
ultri; U+025F8
Umacr; U+0016A Ū
umacr; U+0016B ū
uml; U+000A8 ¨
uml U+000A8 ¨
UnderBar; U+0005F _
UnderBrace; U+023DF
UnderBracket; U+023B5
UnderParenthesis; U+023DD
Union; U+022C3
UnionPlus; U+0228E
Uogon; U+00172 Ų
uogon; U+00173 ų
Uopf; U+1D54C 𝕌
uopf; U+1D566 𝕦
UpArrow; U+02191
Uparrow; U+021D1
uparrow; U+02191
UpArrowBar; U+02912
UpArrowDownArrow; U+021C5
UpDownArrow; U+02195
Updownarrow; U+021D5
updownarrow; U+02195
UpEquilibrium; U+0296E
upharpoonleft; U+021BF
upharpoonright; U+021BE
uplus; U+0228E
UpperLeftArrow; U+02196
UpperRightArrow; U+02197
Upsi; U+003D2 ϒ
upsi; U+003C5 υ
upsih; U+003D2 ϒ
Upsilon; U+003A5 Υ
upsilon; U+003C5 υ
UpTee; U+022A5
UpTeeArrow; U+021A5
upuparrows; U+021C8
urcorn; U+0231D
urcorner; U+0231D
urcrop; U+0230E
Uring; U+0016E Ů
uring; U+0016F ů
urtri; U+025F9
Uscr; U+1D4B0 𝒰
uscr; U+1D4CA 𝓊
utdot; U+022F0
Utilde; U+00168 Ũ
utilde; U+00169 ũ
utri; U+025B5
utrif; U+025B4
uuarr; U+021C8
Uuml; U+000DC Ü
Uuml U+000DC Ü
uuml; U+000FC ü
uuml U+000FC ü
uwangle; U+029A7
vangrt; U+0299C
varepsilon; U+003F5 ϵ
varkappa; U+003F0 ϰ
varnothing; U+02205
varphi; U+003D5 ϕ
varpi; U+003D6 ϖ
varpropto; U+0221D
vArr; U+021D5
varr; U+02195
varrho; U+003F1 ϱ
varsigma; U+003C2 ς
varsubsetneq; U+0228A U+0FE00 ⊊︀
varsubsetneqq; U+02ACB U+0FE00 ⫋︀
varsupsetneq; U+0228B U+0FE00 ⊋︀
varsupsetneqq; U+02ACC U+0FE00 ⫌︀
vartheta; U+003D1 ϑ
vartriangleleft; U+022B2
vartriangleright; U+022B3
Vbar; U+02AEB
vBar; U+02AE8
vBarv; U+02AE9
Vcy; U+00412 В
vcy; U+00432 в
VDash; U+022AB
Vdash; U+022A9
vDash; U+022A8
vdash; U+022A2
Vdashl; U+02AE6
Vee; U+022C1
vee; U+02228
veebar; U+022BB
veeeq; U+0225A
vellip; U+022EE
Verbar; U+02016
verbar; U+0007C |
Vert; U+02016
vert; U+0007C |
VerticalBar; U+02223
VerticalLine; U+0007C |
VerticalSeparator; U+02758
VerticalTilde; U+02240
VeryThinSpace; U+0200A
Vfr; U+1D519 𝔙
vfr; U+1D533 𝔳
vltri; U+022B2
vnsub; U+02282 U+020D2 ⊂⃒
vnsup; U+02283 U+020D2 ⊃⃒
Vopf; U+1D54D 𝕍
vopf; U+1D567 𝕧
vprop; U+0221D
vrtri; U+022B3
Vscr; U+1D4B1 𝒱
vscr; U+1D4CB 𝓋
vsubnE; U+02ACB U+0FE00 ⫋︀
vsubne; U+0228A U+0FE00 ⊊︀
vsupnE; U+02ACC U+0FE00 ⫌︀
vsupne; U+0228B U+0FE00 ⊋︀
Vvdash; U+022AA
vzigzag; U+0299A
Wcirc; U+00174 Ŵ
wcirc; U+00175 ŵ
wedbar; U+02A5F
Wedge; U+022C0
wedge; U+02227
wedgeq; U+02259
weierp; U+02118
Wfr; U+1D51A 𝔚
wfr; U+1D534 𝔴
Wopf; U+1D54E 𝕎
wopf; U+1D568 𝕨
wp; U+02118
wr; U+02240
wreath; U+02240
Wscr; U+1D4B2 𝒲
wscr; U+1D4CC 𝓌
xcap; U+022C2
xcirc; U+025EF
xcup; U+022C3
xdtri; U+025BD
Xfr; U+1D51B 𝔛
xfr; U+1D535 𝔵
xhArr; U+027FA
xharr; U+027F7
Xi; U+0039E Ξ
xi; U+003BE ξ
xlArr; U+027F8
xlarr; U+027F5
xmap; U+027FC
xnis; U+022FB
xodot; U+02A00
Xopf; U+1D54F 𝕏
xopf; U+1D569 𝕩
xoplus; U+02A01
xotime; U+02A02
xrArr; U+027F9
xrarr; U+027F6
Xscr; U+1D4B3 𝒳
xscr; U+1D4CD 𝓍
xsqcup; U+02A06
xuplus; U+02A04
xutri; U+025B3
xvee; U+022C1
xwedge; U+022C0
Yacute; U+000DD Ý
Yacute U+000DD Ý
yacute; U+000FD ý
yacute U+000FD ý
YAcy; U+0042F Я
yacy; U+0044F я
Ycirc; U+00176 Ŷ
ycirc; U+00177 ŷ
Ycy; U+0042B Ы
ycy; U+0044B ы
yen; U+000A5 ¥
yen U+000A5 ¥
Yfr; U+1D51C 𝔜
yfr; U+1D536 𝔶
YIcy; U+00407 Ї
yicy; U+00457 ї
Yopf; U+1D550 𝕐
yopf; U+1D56A 𝕪
Yscr; U+1D4B4 𝒴
yscr; U+1D4CE 𝓎
YUcy; U+0042E Ю
yucy; U+0044E ю
Yuml; U+00178 Ÿ
yuml; U+000FF ÿ
yuml U+000FF ÿ
Zacute; U+00179 Ź
zacute; U+0017A ź
Zcaron; U+0017D Ž
zcaron; U+0017E ž
Zcy; U+00417 З
zcy; U+00437 з
Zdot; U+0017B Ż
zdot; U+0017C ż
zeetrf; U+02128
ZeroWidthSpace; U+0200B
Zeta; U+00396 Ζ
zeta; U+003B6 ζ
Zfr; U+02128
zfr; U+1D537 𝔷
ZHcy; U+00416 Ж
zhcy; U+00436 ж
zigrarr; U+021DD
Zopf; U+02124
zopf; U+1D56B 𝕫
Zscr; U+1D4B5 𝒵
zscr; U+1D4CF 𝓏
zwj; U+0200D
zwnj; U+0200C

This data is also available as a JSON file.

The glyphs displayed above are non-normative. Refer to the Unicode specifications for formal definitions of the characters listed above.

The character reference names originate from the XML Entity Definitions for Characters specification, though only the above is considered normative. [[XML-ENTITY-NAMES]]

9. The XHTML syntax

This section only describes the rules for XML resources. Rules for text/html resources are discussed in the section above entitled "The HTML syntax".

9.1. Writing XHTML documents

The syntax for using HTML with XML, whether in XHTML documents or embedded in other XML documents, is defined in the XML and Namespaces in XML specifications. [XML] [XML-NAMES]

This specification does not define any syntax-level requirements beyond those defined for XML proper.

XML documents may contain a DOCTYPE if desired, but this is not required to conform to this specification. This specification does not define a public or system identifier, nor provide a formal DTD.

According to the XML specification, XML processors are not guaranteed to process the external DTD subset referenced in the DOCTYPE. This means, for example, that using entity references for characters in XHTML documents is unsafe if they are defined in an external file (except for &lt;, &gt;, &amp;, &quot; and &apos;).

9.2. Parsing XHTML documents

This section describes the relationship between XML and the DOM, with a particular emphasis on how this interacts with HTML.

An XML parser, for the purposes of this specification, is a construct that follows the rules given in the XML specification to map a string of bytes or characters into a Document object.

At the time of writing, no such rules actually exist.

An XML parser is either associated with a Document object when it is created, or creates one implicitly.

This Document must then be populated with DOM nodes that represent the tree structure of the input passed to the parser, as defined by the XML specification, the Namespaces in XML specification, and the DOM specification. DOM mutation events must not fire for the operations that the XML parser performs on the Document’s tree, but the user agent must act as if elements and attributes were individually appended and set respectively so as to trigger rules in this specification regarding what happens when an element is inserted into a document or has its attributes set, and the DOM specification’s requirements regarding mutation observers mean that mutation observers are fired (unlike mutation events). [XML] [XML-NAMES] [DOM] [UIEVENTS]

Between the time an element’s start tag is parsed and the time either the element’s end tag is parsed or the parser detects a well-formedness error, the user agent must act as if the element was in a stack of open elements.

This is used, e.g., by the object element to avoid instantiating plugins before the param element children have been parsed.

This specification provides the following additional information that user agents should use when retrieving an external entity: the public identifiers given in the following list all correspond to the URL given by this link. (This URL is a DTD containing the entity declarations for the names listed in the §8.5 Named character references section.) [XML]

  • -//W3C//DTD XHTML 1.0 Transitional//EN
  • -//W3C//DTD XHTML 1.1//EN
  • -//W3C//DTD XHTML 1.0 Strict//EN
  • -//W3C//DTD XHTML 1.0 Frameset//EN
  • -//W3C//DTD XHTML Basic 1.0//EN
  • -//W3C//DTD XHTML 1.1 plus MathML 2.0//EN
  • -//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN
  • -//W3C//DTD MathML 2.0//EN
  • -//WAPFORUM//DTD XHTML Mobile 1.0//EN

Furthermore, user agents should attempt to retrieve the above external entity’s content when one of the above public identifiers is used, and should not attempt to retrieve any other external entity’s content.

This is not strictly a violation of the XML specification, but it does contradict the spirit of the XML specification’s requirements. This is motivated by a desire for user agents to all handle entities in an interoperable fashion without requiring any network access for handling external subsets. [XML]

XML parsers can be invoked with XML scripting support enabled or disabled. Except where otherwise specified, XML parsers are invoked with XML scripting support enabled.

When an XML parser with XML scripting support enabled creates a script element, it must be marked as being "parser-inserted" and its "non-blocking" flag must be unset. If the parser was originally created for the XML fragment parsing algorithm, then the element must be marked as "already started" also. When the element’s end tag is subsequently parsed, the user agent must perform a microtask checkpoint, and then prepare the script element. If this causes there to be a pending parsing-blocking script, then the user agent must run the following steps:

  1. Block this instance of the XML parser, such that the event loop will not run tasks that invoke it.
  2. Spin the event loop until the parser’s Document has no style sheet that is blocking scripts and the pending parsing-blocking script’s "ready to be parser-executed" flag is set.
  3. Unblock this instance of the XML parser, such that tasks that invoke it can again be run.
  4. Execute the pending parsing-blocking script.
  5. There is no longer a pending parsing-blocking script.

Since the document.write() API is not available for XML documents, much of the complexity in the HTML parser is not needed in the XML parser.

When the XML parser has XML scripting support disabled, none of this happens.

When an XML parser would append a node to a template element, it must instead append it to the template element’s template contents (a DocumentFragment node).

This is a willful violation of the XML specification; unfortunately, XML is not formally extensible in the manner that is needed for template processing. [XML]

When an XML parser creates a Node object, its node document must be set to the node document of the node into which the newly created node is to be inserted.

Certain algorithms in this specification spoon-feed the parser characters one string at a time. In such cases, the XML parser must act as it would have if faced with a single string consisting of the concatenation of all those characters.

When an XML parser reaches the end of its input, it must stop parsing, following the same rules as the HTML parser. An XML parser can also be aborted, which must again be done in the same way as for an HTML parser.

For the purposes of conformance checkers, if a resource is determined to be in the XHTML syntax, then it is an XML document.

9.3. Serializing XHTML fragments

The XML fragment serialization algorithm for a Document or Element node either returns a fragment of XML that represents that node or throws an exception.

For Documents, the algorithm must return a string in the form of a document entity, if none of the error cases below apply.

For Elements, the algorithm must return a string in the form of an internal general parsed entity, if none of the error cases below apply.

In both cases, the string returned must be XML namespace-well-formed and must be an isomorphic serialization of all of that node’s relevant child nodes, in tree order. User agents may adjust prefixes and namespace declarations in the serialization (and indeed might be forced to do so in some cases to obtain namespace-well-formed XML). User agents may use a combination of regular text and character references to represent Text nodes in the DOM.

A node’s relevant child nodes are those that apply given the following rules:

For template elements
The relevant child nodes are the child nodes of the template element’s template contents, if any.
For all other nodes
The relevant child nodes are the child nodes of node itself, if any.

For Elements, if any of the elements in the serialization are in no namespace, the default namespace in scope for those elements must be explicitly declared as the empty string. (This doesn’t apply in the Document case.) [XML] [XML-NAMES]

For the purposes of this section, an internal general parsed entity is considered XML namespace-well-formed if a document consisting of an element with no namespace declarations whose contents are the internal general parsed entity would itself be XML namespace-well-formed.

If any of the following error cases are found in the DOM subtree being serialized, then the algorithm must throw an InvalidStateError exception instead of returning a string:

  • A Document node with no child element nodes.
  • A DocumentType node that has an external subset public identifier that contains characters that are not matched by the XML PubidChar production. [XML]
  • A DocumentType node that has an external subset system identifier that contains both a U+0022 QUOTATION MARK (") and a U+0027 APOSTROPHE (') or that contains characters that are not matched by the XML Char production. [XML]
  • A node with a local name containing a U+003A COLON (:).
  • A node with a local name that does not match the XML Name production. [XML]
  • An Attr node with no namespace whose local name is the lowercase string "xmlns". [XML-NAMES]
  • An Element node with two or more attributes with the same local name and namespace.
  • An Attr node, Text node, Comment node, or ProcessingInstruction node whose data contains characters that are not matched by the XML Char production. [XML]
  • A Comment node whose data contains two adjacent U+002D HYPHEN-MINUS characters (-) or ends with such a character.
  • A ProcessingInstruction node whose target name is an ASCII case-insensitive match for the string "xml".
  • A ProcessingInstruction node whose target name contains a U+003A COLON (:).
  • A ProcessingInstruction node whose data contains the string "?>".

These are the only ways to make a DOM unserialisable. The DOM enforces all the other XML constraints; for example, trying to append two elements to a Document node will throw a HierarchyRequestError exception.

9.4. Parsing XHTML fragments

The XML fragment parsing algorithm either returns a Document or throws a "SyntaxError" DOMException. Given a string input and a context element context, the algorithm is as follows:

  1. Create a new XML parser.

  2. Feed the parser just created the string corresponding to the start tag of the context element, declaring all the namespace prefixes that are in scope on that element in the DOM, as well as declaring the default namespace (if any) that is in scope on that element in the DOM.

    A namespace prefix is in scope if the DOM lookupNamespaceURI() method on the element would return a non-null value for that prefix.

    The default namespace is the namespace for which the DOM isDefaultNamespace() method on the element would return true.

    No DOCTYPE is passed to the parser, and therefore no external subset is referenced, and therefore no entities will be recognized.

  3. Feed the parser just created the string input.

  4. Feed the parser just created the string corresponding to the end tag of the context element.

  5. If there is an XML well-formedness or XML namespace well-formedness error, then throw a "SyntaxError" DOMException and abort these steps.

  6. If the root element of the resulting Document has any sibling nodes, then throw a "SyntaxError" DOMException and abort these steps.

  7. Return the child nodes of the root element of the resulting Document, in tree order.

10. Rendering

User agents are not required to present HTML documents in any particular way. However, this section provides a set of suggestions for rendering HTML documents that, if followed, are likely to lead to a user experience that closely resembles the experience intended by the documents' authors. So as to avoid confusion regarding the normativity of this section, RFC2119 terms have not been used. Instead, the term "expected" is used to indicate behavior that will lead to this experience. For the purposes of conformance for user agents designated as supporting the suggested default rendering, the term "expected" in this section has the same conformance implications as the RFC2119-defined term "must".

10.1. Introduction

In general, user agents are expected to support CSS, and many of the suggestions in this section are expressed in CSS terms. User agents that use other presentation mechanisms can derive their expected behavior by translating from the CSS rules given in this section.

In the absence of style-layer rules to the contrary (e.g., author style sheets), user agents are expected to render an element so that it conveys to the user the meaning that the element represents, as described by this specification.

The suggestions in this section generally assume a visual output medium with a resolution of 96dpi or greater, but HTML is intended to apply to multiple media (it is a media-independent language). User agent implementors are encouraged to adapt the suggestions in this section to their target media.


An element is being rendered if it has any associated CSS layout boxes, SVG layout boxes, or some equivalent in other styling languages.

Just being off-screen does not mean the element is not being rendered. The presence of the hidden attribute normally means the element is not being rendered, though this might be overridden by the style sheets.


User agents that do not honor author-level CSS style sheets are nonetheless expected to act as if they applied the CSS rules given in these sections in a manner consistent with this specification and the relevant CSS and Unicode specifications. [CSS-2015] [UNICODE] [BIDI]

This is especially important for issues relating to the display, unicode-bidi, and direction properties.

10.2. The CSS user agent style sheet and presentational hints

The CSS rules given in these subsections are, except where otherwise specified, expected to be used as part of the user-agent level style sheet defaults for all documents that contain html elements.

Some rules are intended for the author-level zero-specificity presentational hints part of the CSS cascade; these are explicitly called out as presentational hints.

Some of the rules regarding left and right margins are given here as appropriate for elements whose direction property is ltr, and are expected to be flipped around on elements whose direction property is rtl. These are marked "LTR-specific".

These markings only affect the handling of attribute values, not attribute names or element names.


When the text below says that an attribute attribute on an element element maps to the pixel length property (or properties) properties, it means that if element has an attribute attribute set, and parsing that attribute’s value using the rules for parsing non-negative integers doesn’t generate an error, then the user agent is expected to use the parsed value as a pixel length for a presentational hint for properties.

When the text below says that an attribute attribute on an element element maps to the dimension property (or properties) properties, it means that if element has an attribute attribute set, and parsing that attribute’s value using the rules for parsing dimension values doesn’t generate an error, then the user agent is expected to use the parsed dimension as the value for a presentational hint for properties, with the value given as a pixel length if the dimension was a length, and with the value given as a percentage if the dimension was a percentage.

When the text below says that an attribute attribute on an element element maps to the dimension property (ignoring zero) (or properties) properties, it means that if element has an attribute attribute set, and parsing that attribute’s value using the rules for parsing non-zero dimension values doesn’t generate an error, then the user agent is expected to use the parsed dimension as the value for a presentational hint for properties, with the value given as a pixel length if the dimension was a length, and with the value given as a percentage if the dimension was a percentage.

When a user agent is to align descendants of a node, the user agent is expected to align only those descendants that have both their margin-left and margin-right properties computing to a value other than auto, that are over-constrained and that have one of those two margins with a used value forced to a greater value, and that do not themselves have an applicable align attribute. When multiple elements are to align a particular descendant, the most deeply nested such element is expected to override the others. Aligned elements are expected to be aligned by having the used values of their left and right margins be set accordingly.

10.3. Non-replaced elements

10.3.1. Hidden elements

@namespace url(http://www.w3.org/1999/xhtml);

[hidden], area, base, basefont, datalist, head, link, menu[type=context i], meta,
noembed, noframes, param, rp, script, source, style, template, track, title {
  display: none;
}

embed[hidden] { display: inline; height: 0; width: 0; }

input[type=hidden i] { display none ! important; }

@media (scripting) {
  noscript { display: none !important; }
}

10.3.2. The page

@namespace url(http://www.w3.org/1999/xhtml);

html, body { display: block; }

For each property in the table below, given a body element, the first attribute that exists maps to the pixel length property on the body element. If none of the attributes for a property are found, or if the value of the attribute that was found cannot be parsed successfully, then, then a default value of 8px is expected to be used for that property instead.

Property Source
margin-top body element’s marginheight attribute
The body element’s container frame element’s marginheight attribute
body element’s topmargin attribute
margin-right body element’s marginwidth attribute
The body element’s container frame element’s marginwidth attribute
body element’s rightmargin attribute
margin-bottom body element’s marginheight attribute
The body element’s container frame element’s marginheight attribute
body element’s bottommargin attribute
margin-left body element’s marginwidth attribute
The body element’s container frame element’s marginwidth attribute
body element’s leftmargin attribute

If the body element’s node document’s browsing context is a nested browsing context, and the browsing context container of that nested browsing context is a frame or iframe element, then the container frame element of the body element is that frame or iframe element. Otherwise, there is no container frame element.

The above requirements imply that a page can change the margins of another page (including one from another origin) using, for example, an iframe. This is potentially a security risk, as it might in some cases allow an attack to contrive a situation in which a page is rendered not as the author intended, possibly for the purposes of phishing or otherwise misleading the user.


If a Document is in a nested browsing context, it is expected to be positioned and sized to fit inside the content box of its browsing context container. If a browsing context is not being rendered, it is expected to have a viewport with zero width and zero height.

If the Document is in a nested browsing context, and the browsing context container of that nested browsing context is a frame or iframe element, and that element has a scrolling attribute, and that attribute’s value is an ASCII case-insensitive match for the string "off", "noscroll", or "no", then the user agent is expected to prevent any scroll bars from being shown for the viewport of the nested browsing context, regardless of the overflow property that applies to that viewport.


When a body element has a background attribute set to a non-empty value, the new value is expected to be parsed relative to the element’s node document, and if this is successful, the user agent is expected to treat the attribute as a presentational hint setting the element’s background-image property to the resulting URL string.

When a body element has a bgcolor attribute set, the new value is expected to be parsed using the rules for parsing a legacy color value, and if that does not return an error, the user agent is expected to treat the attribute as a presentational hint setting the element’s background-color property to the resulting color.

When a body element has a text attribute, its value is expected to be parsed using the rules for parsing a legacy color value, and if that does not return an error, the user agent is expected to treat the attribute as a presentational hint setting the element’s color property to the resulting color.

When a body element has a link attribute, its value is expected to be parsed using the rules for parsing a legacy color value, and if that does not return an error, the user agent is expected to treat the attribute as a presentational hint setting the color property of any element in the Document matching the ':link' pseudo-class to the resulting color.

When a body element has a vlink attribute, its value is expected to be parsed using the rules for parsing a legacy color value, and if that does not return an error, the user agent is expected to treat the attribute as a presentational hint setting the color property of any element in the Document matching the ':visited' pseudo-class to the resulting color.

When a body element has an alink attribute, its value is expected to be parsed using the rules for parsing a legacy color value, and if that does not return an error, the user agent is expected to treat the attribute as a presentational hint setting the color property of any element in the Document matching the ':active' pseudo-class and either the ':link' pseudo-class or the ':visited' pseudo-class to the resulting color.

10.3.3. Flow content

@namespace url(http://www.w3.org/1999/xhtml);

address, blockquote, center, div, figure, figcaption, footer, form, header, hr,
legend, listing, main, p, plaintext, pre, summary, xmp {
  display: block;
}

blockquote, figure, listing, p, plaintext, pre, xmp {
  margin-top: 1em; margin-bottom: 1em;
}

blockquote, figure { margin-left: 40px; margin-right: 40px; }

address { font-style: italic; }
listing, plaintext, pre, xmp {
  font-family: monospace; white-space: pre;
}

The following rules are also expected to apply, as presentational hints:

@namespace url(http://www.w3.org/1999/xhtml);

pre[wrap] { white-space: pre-wrap; }

In quirks mode, the following rules are also expected to apply:

@namespace url(http://www.w3.org/1999/xhtml);

form { margin-bottom: 1em; }

The center element, and the div element when it has an align attribute whose value is an ASCII case-insensitive match for either the string "center" or the string "middle", are expected to center text within themselves, as if they had their text-align property set to center in a presentational hint, and to align descendants to the center.

The div element, when it has an align attribute whose value is an ASCII case-insensitive match for the string "left", is expected to left-align text within itself, as if it had its text-align property set to left in a presentational hint, and to align descendants to the left.

The div element, when it has an align attribute whose value is an ASCII case-insensitive match for the string "right", is expected to right-align text within itself, as if it had its text-align property set to right in a presentational hint, and to align descendants to the right.

The div element, when it has an align attribute whose value is an ASCII case-insensitive match for the string "justify", is expected to full-justify text within itself, as if it had its text-align property set to justify in a presentational hint, and to align descendants to the left.

10.3.4. Phrasing content

@namespace url(http://www.w3.org/1999/xhtml);

  cite, dfn, em, i, var { font-style: italic; }
  b, strong { font-weight: bolder; }
  code, kbd, samp, tt { font-family: monospace; }
  big { font-size: larger; }
  small { font-size: smaller; }

  sub { vertical-align: sub; }
  sup { vertical-align: super; }
  sub, sup { line-height: normal; font-size: smaller; }

  ruby { display: ruby; }
  rb   { display: ruby-base; white-space: nowrap; }
  rt   {
    display: ruby-text;
    white-space: nowrap;
    font-size: 50%;
    font-variant-east-asian: ruby;
    text-emphasis: none;
  }
  rbc  { display: ruby-base-container; }
  rtc  { display: ruby-text-container; }
  ruby, rb, rt, rbc, rtc { unicode-bidi: isolate; }

  :link { color: #0000EE; }
  :visited { color: #551A8B; }
  :link:active, :visited:active { color: #FF0000; }
  :link, :visited { text-decoration: underline; cursor: pointer; }
  a:link[rel~=help], a:visited[rel~=help],
  area:link[rel~=help], area:visited[rel~=help] { cursor: help; }

  :focus { outline: auto; }

  mark { background: yellow; color: black; } /* this color is just a suggestion and can be changed based on implementation feedback */

  abbr[title], acronym[title] { text-decoration: dotted underline; }
  ins, u { text-decoration: underline; }
  del, s, strike { text-decoration: line-through; }
  blink { text-decoration: blink; }

  q::before { content: open-quote; }
  q::after { content: close-quote; }

  br { display-outside: newline; } /* this also has bidi implications */
  nobr { white-space: nowrap; }
  wbr { display-outside: break-opportunity; } /* this also has bidi implications */
  nobr wbr { white-space: normal; }

The following rules are also expected to apply, as presentational hints:

@namespace url(http://www.w3.org/1999/xhtml);

  br[clear=left i] { clear: left; }
  br[clear=right i] { clear: right; }
  br[clear=all i], br[clear=both i] { clear: both; }

User agents that do not support correct ruby rendering are expected to render parentheses around the text of rt elements in the absence of rp elements. [CSS3-RUBY]


User agents are expected to support the clear property on inline elements (in order to render br elements with clear attributes) in the manner described in the non-normative note to this effect in CSS2.1.

The initial value for the color property is expected to be black. The initial value for the background-color property is expected to be transparent. The canvas' background is expected to be white.


When a font element has a color attribute, its value is expected to be parsed using the rules for parsing a legacy color value, and if that does not return an error, the user agent is expected to treat the attribute as a presentational hint setting the element’s color property to the resulting color.

The font element is expected to override the color of any text decoration that spans the text of the element to the used value of the element’s color property.

When a font element has a face attribute, the user agent is expected to treat the attribute as a presentational hint setting the element’s font-family property to the attribute’s value.

When a font element has a size attribute, the user agent is expected to use the following steps, known as the rules for parsing a legacy font size, to treat the attribute as a presentational hint setting the element’s font-size property:

  1. Let input be the attribute’s value.
  2. Let position be a pointer into input, initially pointing at the start of the string.
  3. Skip whitespace.
  4. If position is past the end of input, there is no presentational hint. Abort these steps.
  5. If the character at position is a U+002B PLUS SIGN character (+), then let mode be relative-plus, and advance position to the next character. Otherwise, if the character at position is a U+002D HYPHEN-MINUS character (-), then let mode be relative-minus, and advance position to the next character. Otherwise, let mode be absolute.
  6. Collect a sequence of characters that are ASCII digits, and let the resulting sequence be digits.
  7. If digits is the empty string, there is no presentational hint. Abort these steps.
  8. Interpret digits as a base-ten integer. Let value be the resulting number.
  9. If mode is relative-plus, then increment value by 3. If mode is relative-minus, then let value be the result of subtracting value from 3.

  10. If value is greater than 7, let it be 7.
  11. If value is less than 1, let it be 1.
  12. Set font-size to the keyword corresponding to the value of value according to the following table:

    value font-size keyword Notes
    1 x-small
    2 small
    3 medium
    4 large
    5 x-large
    6 xx-large
    7 xxx-large see below

    The "xxx-large" value is a non-CSS value used here to indicate a font size 50% larger than "xx-large".

10.3.5. Bidirectional text

@namespace url(http://www.w3.org/1999/xhtml);

[dir]:dir(ltr), bdi:dir(ltr), input[type=tel i]:dir(ltr) { direction: ltr; }
[dir]:dir(rtl), bdi:dir(rtl) { direction: rtl; }

address, blockquote, center, div, figure, figcaption, footer, form, header, hr,
legend, listing, main, p, plaintext, pre, summary, xmp, article, aside, h1, h2,
h3, h4, h5, h6, nav, section, table, caption, colgroup, col, thead,
tbody, tfoot, tr, td, th, dir, dd, dl, dt, menu, ol, ul, li, bdi, output,
[dir=ltr i], [dir=rtl i], [dir=auto i] {
  unicode-bidi: isolate;
}

bdo, bdo[dir] { unicode-bidi: isolate-override; }

input[dir=auto i]:matches([type=search i], [type=tel i], [type=url i],
[type=email i]), textarea[dir=auto i], pre[dir=auto i] {
  unicode-bidi: plaintext;
}
/* see prose for input elements whose type attribute is in the Text state */

/* the rules setting the 'content' property on br and wbr elements also has bidi implications */

When an input element’s dir attribute is in the auto state and its type attribute is in the Text state, then the user agent is expected to act as if it had a user-agent-level style sheet rule setting the unicode-bidi property to plaintext.

Input fields (i.e., textarea elements, and input elements when their type attribute is in the Text, Search, Telephone, URL, or E-mail state) are expected to present an editing user interface with a directionality that matches the element’s direction property.

When the document’s character encoding is ISO-8859-8, the following rules are additionally expected to apply, following those above: [ENCODING]

@namespace url(http://www.w3.org/1999/xhtml);

address, blockquote, center, div, figure, figcaption, footer, form, header, hr,
legend, listing, main, p, plaintext, pre, summary, xmp, article, aside, h1, h2,
h3, h4, h5, h6, nav, section, table, caption, colgroup, col, thead,
tbody, tfoot, tr, td, th, dir, dd, dl, dt, menu, ol, ul, li, [dir=ltr i],
[dir=rtl i], [dir=auto i], *|* {
  unicode-bidi: bidi-override;
}
input:not([type=submit i]):not([type=reset i]):not([type=button i]),
textarea, keygen {
  unicode-bidi: normal;
}

10.3.6. Quotes

This block is automatically generated from the Unicode Common Locale Data Repository. [CLDR]

User agents are expected to use either the block below (which will be regularly updated) or to automatically generate their own copy directly from the source material. The language codes are derived from the CLDR file names. The quotes are derived from the delimiter blocks, with fallback handled as specified in the CLDR documentation.



@namespace url(http://www.w3.org/1999/xhtml);

:root                                                         { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(af),       :not(:lang(af)) > :lang(af)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(agq),      :not(:lang(agq)) > :lang(agq)           { quotes: '\201e' '\201d' '\201a' '\2019' } /*     */
:root:lang(ak),       :not(:lang(ak)) > :lang(ak)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(am),       :not(:lang(am)) > :lang(am)             { quotes: '\00ab' '\00bb' '\2039' '\203a' } /* « »   */
:root:lang(ar),       :not(:lang(ar)) > :lang(ar)             { quotes: '\201d' '\201c' '\2019' '\2018' } /*     */
:root:lang(asa),      :not(:lang(asa)) > :lang(asa)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(az-Cyrl),  :not(:lang(az-Cyrl)) > :lang(az-Cyrl)   { quotes: '\00ab' '\00bb' '\2039' '\203a' } /* « »   */
:root:lang(bas),      :not(:lang(bas)) > :lang(bas)           { quotes: '\00ab' '\00bb' '\201e' '\201c' } /* « »   */
:root:lang(bem),      :not(:lang(bem)) > :lang(bem)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(bez),      :not(:lang(bez)) > :lang(bez)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(bg),       :not(:lang(bg)) > :lang(bg)             { quotes: '\201e' '\201c' '\201a' '\2018' } /*     */
:root:lang(bm),       :not(:lang(bm)) > :lang(bm)             { quotes: '\00ab' '\00bb' '\201c' '\201d' } /* « »   */
:root:lang(bn),       :not(:lang(bn)) > :lang(bn)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(br),       :not(:lang(br)) > :lang(br)             { quotes: '\00ab' '\00bb' '\2039' '\203a' } /* « »   */
:root:lang(brx),      :not(:lang(brx)) > :lang(brx)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(bs-Cyrl),  :not(:lang(bs-Cyrl)) > :lang(bs-Cyrl)   { quotes: '\201e' '\201c' '\201a' '\2018' } /*     */
:root:lang(ca),       :not(:lang(ca)) > :lang(ca)             { quotes: '\201c' '\201d' '\00ab' '\00bb' } /*   « » */
:root:lang(cgg),      :not(:lang(cgg)) > :lang(cgg)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(chr),      :not(:lang(chr)) > :lang(chr)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(cs),       :not(:lang(cs)) > :lang(cs)             { quotes: '\201e' '\201c' '\201a' '\2018' } /*     */
:root:lang(da),       :not(:lang(da)) > :lang(da)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(dav),      :not(:lang(dav)) > :lang(dav)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(de),       :not(:lang(de)) > :lang(de)             { quotes: '\201e' '\201c' '\201a' '\2018' } /*     */
:root:lang(de-CH),    :not(:lang(de-CH)) > :lang(de-CH)       { quotes: '\00ab' '\00bb' '\2039' '\203a' } /* « »   */
:root:lang(dje),      :not(:lang(dje)) > :lang(dje)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(dua),      :not(:lang(dua)) > :lang(dua)           { quotes: '\00ab' '\00bb' '\2018' '\2019' } /* « »   */
:root:lang(dyo),      :not(:lang(dyo)) > :lang(dyo)           { quotes: '\00ab' '\00bb' '\201c' '\201d' } /* « »   */
:root:lang(dz),       :not(:lang(dz)) > :lang(dz)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(ebu),      :not(:lang(ebu)) > :lang(ebu)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(ee),       :not(:lang(ee)) > :lang(ee)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(el),       :not(:lang(el)) > :lang(el)             { quotes: '\00ab' '\00bb' '\201c' '\201d' } /* « »   */
:root:lang(en),       :not(:lang(en)) > :lang(en)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(es),       :not(:lang(es)) > :lang(es)             { quotes: '\201c' '\201d' '\00ab' '\00bb' } /*   « » */
:root:lang(et),       :not(:lang(et)) > :lang(et)             { quotes: '\201e' '\201c' '\201a' '\2018' } /*     */
:root:lang(eu),       :not(:lang(eu)) > :lang(eu)             { quotes: '\201c' '\201d' '\00ab' '\00bb' } /*   « » */
:root:lang(ewo),      :not(:lang(ewo)) > :lang(ewo)           { quotes: '\00ab' '\00bb' '\201c' '\201d' } /* « »   */
:root:lang(fa),       :not(:lang(fa)) > :lang(fa)             { quotes: '\00ab' '\00bb' '\2039' '\203a' } /* « »   */
:root:lang(ff),       :not(:lang(ff)) > :lang(ff)             { quotes: '\201e' '\201d' '\201a' '\2019' } /*     */
:root:lang(fi),       :not(:lang(fi)) > :lang(fi)             { quotes: '\201d' '\201d' '\2019' '\2019' } /*     */
:root:lang(fr),       :not(:lang(fr)) > :lang(fr)             { quotes: '\00ab' '\00bb' '\00ab' '\00bb' } /* « » « » */
:root:lang(fr-CA),    :not(:lang(fr-CA)) > :lang(fr-CA)       { quotes: '\00ab' '\00bb' '\2039' '\203a' } /* « »   */
:root:lang(fr-CH),    :not(:lang(fr-CH)) > :lang(fr-CH)       { quotes: '\00ab' '\00bb' '\2039' '\203a' } /* « »   */
:root:lang(gsw),      :not(:lang(gsw)) > :lang(gsw)           { quotes: '\00ab' '\00bb' '\2039' '\203a' } /* « »   */
:root:lang(gu),       :not(:lang(gu)) > :lang(gu)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(guz),      :not(:lang(guz)) > :lang(guz)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(ha),       :not(:lang(ha)) > :lang(ha)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(he),       :not(:lang(he)) > :lang(he)             { quotes: '\0022' '\0022' '\0027' '\0027' } /* " " ' ' */
:root:lang(hi),       :not(:lang(hi)) > :lang(hi)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(hr),       :not(:lang(hr)) > :lang(hr)             { quotes: '\201e' '\201c' '\201a' '\2018' } /*     */
:root:lang(hu),       :not(:lang(hu)) > :lang(hu)             { quotes: '\201e' '\201d' '\00bb' '\00ab' } /*   » « */
:root:lang(id),       :not(:lang(id)) > :lang(id)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(ig),       :not(:lang(ig)) > :lang(ig)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(it),       :not(:lang(it)) > :lang(it)             { quotes: '\00ab' '\00bb' '\201c' '\201d' } /* « »   */
:root:lang(ja),       :not(:lang(ja)) > :lang(ja)             { quotes: '\300c' '\300d' '\300e' '\300f' } /*     */
:root:lang(jgo),      :not(:lang(jgo)) > :lang(jgo)           { quotes: '\00ab' '\00bb' '\2039' '\203a' } /* « »   */
:root:lang(jmc),      :not(:lang(jmc)) > :lang(jmc)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(kab),      :not(:lang(kab)) > :lang(kab)           { quotes: '\00ab' '\00bb' '\201c' '\201d' } /* « »   */
:root:lang(kam),      :not(:lang(kam)) > :lang(kam)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(kde),      :not(:lang(kde)) > :lang(kde)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(kea),      :not(:lang(kea)) > :lang(kea)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(khq),      :not(:lang(khq)) > :lang(khq)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(ki),       :not(:lang(ki)) > :lang(ki)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(kkj),      :not(:lang(kkj)) > :lang(kkj)           { quotes: '\00ab' '\00bb' '\2039' '\203a' } /* « »   */
:root:lang(kln),      :not(:lang(kln)) > :lang(kln)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(km),       :not(:lang(km)) > :lang(km)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(kn),       :not(:lang(kn)) > :lang(kn)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(ko),       :not(:lang(ko)) > :lang(ko)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(ksb),      :not(:lang(ksb)) > :lang(ksb)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(ksf),      :not(:lang(ksf)) > :lang(ksf)           { quotes: '\00ab' '\00bb' '\2018' '\2019' } /* « »   */
:root:lang(lag),      :not(:lang(lag)) > :lang(lag)           { quotes: '\201d' '\201d' '\2019' '\2019' } /*     */
:root:lang(lg),       :not(:lang(lg)) > :lang(lg)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(ln),       :not(:lang(ln)) > :lang(ln)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(lo),       :not(:lang(lo)) > :lang(lo)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(lt),       :not(:lang(lt)) > :lang(lt)             { quotes: '\201e' '\201c' '\201e' '\201c' } /*     */
:root:lang(lu),       :not(:lang(lu)) > :lang(lu)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(luo),      :not(:lang(luo)) > :lang(luo)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(luy),      :not(:lang(luy)) > :lang(luy)           { quotes: '\201e' '\201c' '\201a' '\2018' } /*     */
:root:lang(lv),       :not(:lang(lv)) > :lang(lv)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(mas),      :not(:lang(mas)) > :lang(mas)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(mer),      :not(:lang(mer)) > :lang(mer)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(mfe),      :not(:lang(mfe)) > :lang(mfe)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(mg),       :not(:lang(mg)) > :lang(mg)             { quotes: '\00ab' '\00bb' '\201c' '\201d' } /* « »   */
:root:lang(mgo),      :not(:lang(mgo)) > :lang(mgo)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(mk),       :not(:lang(mk)) > :lang(mk)             { quotes: '\201e' '\201c' '\201a' '\2018' } /*     */
:root:lang(ml),       :not(:lang(ml)) > :lang(ml)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(mr),       :not(:lang(mr)) > :lang(mr)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(ms),       :not(:lang(ms)) > :lang(ms)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(mua),      :not(:lang(mua)) > :lang(mua)           { quotes: '\00ab' '\00bb' '\201c' '\201d' } /* « »   */
:root:lang(my),       :not(:lang(my)) > :lang(my)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(naq),      :not(:lang(naq)) > :lang(naq)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(nb),       :not(:lang(nb)) > :lang(nb)             { quotes: '\00ab' '\00bb' '\2018' '\2019' } /* « »   */
:root:lang(nd),       :not(:lang(nd)) > :lang(nd)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(nl),       :not(:lang(nl)) > :lang(nl)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(nmg),      :not(:lang(nmg)) > :lang(nmg)           { quotes: '\201e' '\201d' '\00ab' '\00bb' } /*   « » */
:root:lang(nn),       :not(:lang(nn)) > :lang(nn)             { quotes: '\00ab' '\00bb' '\2018' '\2019' } /* « »   */
:root:lang(nnh),      :not(:lang(nnh)) > :lang(nnh)           { quotes: '\00ab' '\00bb' '\201c' '\201d' } /* « »   */
:root:lang(nus),      :not(:lang(nus)) > :lang(nus)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(nyn),      :not(:lang(nyn)) > :lang(nyn)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(pl),       :not(:lang(pl)) > :lang(pl)             { quotes: '\201e' '\201d' '\00ab' '\00bb' } /*   « » */
:root:lang(pt),       :not(:lang(pt)) > :lang(pt)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(pt-PT),    :not(:lang(pt-PT)) > :lang(pt-PT)       { quotes: '\00ab' '\00bb' '\201c' '\201d' } /* « »   */
:root:lang(rn),       :not(:lang(rn)) > :lang(rn)             { quotes: '\201d' '\201d' '\2019' '\2019' } /*     */
:root:lang(ro),       :not(:lang(ro)) > :lang(ro)             { quotes: '\201e' '\201d' '\00ab' '\00bb' } /*   « » */
:root:lang(rof),      :not(:lang(rof)) > :lang(rof)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(ru),       :not(:lang(ru)) > :lang(ru)             { quotes: '\00ab' '\00bb' '\201e' '\201c' } /* « »   */
:root:lang(rw),       :not(:lang(rw)) > :lang(rw)             { quotes: '\00ab' '\00bb' '\2018' '\2019' } /* « »   */
:root:lang(rwk),      :not(:lang(rwk)) > :lang(rwk)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(saq),      :not(:lang(saq)) > :lang(saq)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(sbp),      :not(:lang(sbp)) > :lang(sbp)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(seh),      :not(:lang(seh)) > :lang(seh)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(ses),      :not(:lang(ses)) > :lang(ses)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(sg),       :not(:lang(sg)) > :lang(sg)             { quotes: '\00ab' '\00bb' '\201c' '\201d' } /* « »   */
:root:lang(shi),      :not(:lang(shi)) > :lang(shi)           { quotes: '\00ab' '\00bb' '\201e' '\201d' } /* « »   */
:root:lang(shi-Latn), :not(:lang(shi-Latn)) > :lang(shi-Latn) { quotes: '\00ab' '\00bb' '\201e' '\201d' } /* « »   */
:root:lang(si),       :not(:lang(si)) > :lang(si)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(sk),       :not(:lang(sk)) > :lang(sk)             { quotes: '\201e' '\201c' '\201a' '\2018' } /*     */
:root:lang(sl),       :not(:lang(sl)) > :lang(sl)             { quotes: '\201e' '\201c' '\201a' '\2018' } /*     */
:root:lang(sn),       :not(:lang(sn)) > :lang(sn)             { quotes: '\201d' '\201d' '\2019' '\2019' } /*     */
:root:lang(so),       :not(:lang(so)) > :lang(so)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(sq),       :not(:lang(sq)) > :lang(sq)             { quotes: '\201e' '\201c' '\201a' '\2018' } /*     */
:root:lang(sr),       :not(:lang(sr)) > :lang(sr)             { quotes: '\201e' '\201c' '\201a' '\2018' } /*     */
:root:lang(sr-Latn),  :not(:lang(sr-Latn)) > :lang(sr-Latn)   { quotes: '\201e' '\201c' '\201a' '\2018' } /*     */
:root:lang(sv),       :not(:lang(sv)) > :lang(sv)             { quotes: '\201d' '\201d' '\2019' '\2019' } /*     */
:root:lang(sw),       :not(:lang(sw)) > :lang(sw)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(swc),      :not(:lang(swc)) > :lang(swc)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(ta),       :not(:lang(ta)) > :lang(ta)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(te),       :not(:lang(te)) > :lang(te)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(teo),      :not(:lang(teo)) > :lang(teo)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(th),       :not(:lang(th)) > :lang(th)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(ti-ER),    :not(:lang(ti-ER)) > :lang(ti-ER)       { quotes: '\2018' '\2019' '\201c' '\201d' } /*     */
:root:lang(to),       :not(:lang(to)) > :lang(to)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(tr),       :not(:lang(tr)) > :lang(tr)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(twq),      :not(:lang(twq)) > :lang(twq)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(tzm),      :not(:lang(tzm)) > :lang(tzm)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(uk),       :not(:lang(uk)) > :lang(uk)             { quotes: '\00ab' '\00bb' '\201e' '\201c' } /* « »   */
:root:lang(ur),       :not(:lang(ur)) > :lang(ur)             { quotes: '\201d' '\201c' '\2019' '\2018' } /*     */
:root:lang(vai),      :not(:lang(vai)) > :lang(vai)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(vai-Latn), :not(:lang(vai-Latn)) > :lang(vai-Latn) { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(vi),       :not(:lang(vi)) > :lang(vi)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(vun),      :not(:lang(vun)) > :lang(vun)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(xh),       :not(:lang(xh)) > :lang(xh)             { quotes: '\2018' '\2019' '\201c' '\201d' } /*     */
:root:lang(xog),      :not(:lang(xog)) > :lang(xog)           { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(yav),      :not(:lang(yav)) > :lang(yav)           { quotes: '\00ab' '\00bb' '\00ab' '\00bb' } /* « » « » */
:root:lang(yo),       :not(:lang(yo)) > :lang(yo)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(zh),       :not(:lang(zh)) > :lang(zh)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */
:root:lang(zh-Hant),  :not(:lang(zh-Hant)) > :lang(zh-Hant)   { quotes: '\300c' '\300d' '\300e' '\300f' } /*     */
:root:lang(zu),       :not(:lang(zu)) > :lang(zu)             { quotes: '\201c' '\201d' '\2018' '\2019' } /*     */

10.3.7. Sections and headings

@namespace url(http://www.w3.org/1999/xhtml);

article, aside, h1, h2, h3, h4, h5, h6, nav, section {
  display: block;
}

h1 { margin-top: 0.67em; margin-bottom: 0.67em; font-size: 2.00em; font-weight: bold; }
h2 { margin-top: 0.83em; margin-bottom: 0.83em; font-size: 1.50em; font-weight: bold; }
h3 { margin-top: 1.00em; margin-bottom: 1.00em; font-size: 1.17em; font-weight: bold; }
h4 { margin-top: 1.33em; margin-bottom: 1.33em; font-size: 1.00em; font-weight: bold; }
h5 { margin-top: 1.67em; margin-bottom: 1.67em; font-size: 0.83em; font-weight: bold; }
h6 { margin-top: 2.33em; margin-bottom: 2.33em; font-size: 0.67em; font-weight: bold; }

In the following CSS block, x is shorthand for the following selector: :matches(article, aside, nav, section)

@namespace url(http://www.w3.org/1999/xhtml);

x h1 { margin-top: 0.83em; margin-bottom: 0.83em; font-size: 1.50em; }
x x h1 { margin-top: 1.00em; margin-bottom: 1.00em; font-size: 1.17em; }
x x x h1 { margin-top: 1.33em; margin-bottom: 1.33em; font-size: 1.00em; }
x x x x h1 { margin-top: 1.67em; margin-bottom: 1.67em; font-size: 0.83em; }
x x x x x h1 { margin-top: 2.33em; margin-bottom: 2.33em; font-size: 0.67em; }

The shorthand is used to keep this block at least mildly readable.

10.3.8. Lists

@namespace url(http://www.w3.org/1999/xhtml);

dir, dd, dl, dt, menu, ol, ul { display: block; }
li { display: list-item; }

dir, dl, menu, ol, ul { margin-top: 1em; margin-bottom: 1em; }

:matches(dir, dl, menu, ol, ul) :matches(dir, dl, menu, ol, ul) {
  margin-top: 0; margin-bottom: 0;
}

dd { margin-left: 40px; } /* LTR-specific: use 'margin-right' for rtl elements */
dir, menu, ol, ul { padding-left: 40px; } /* LTR-specific: use 'padding-right' for rtl elements */

ol { list-style-type: decimal; }

dir, menu, ul {
  list-style-type: disc;
}
:matches(dir, menu, ol, ul) :matches(dir, menu, ul) {
  list-style-type: circle;
}
:matches(dir, menu, ol, ul) :matches(dir, menu, ol, ul) :matches(dir, menu, ul) {
  list-style-type: square;
}

The following rules are also expected to apply, as presentational hints:

@namespace url(http://www.w3.org/1999/xhtml);

ol[type=1], li[type=1] { list-style-type: decimal; }
ol[type=a], li[type=a] { list-style-type: lower-alpha; }
ol[type=A], li[type=A] { list-style-type: upper-alpha; }
ol[type=i], li[type=i] { list-style-type: lower-roman; }
ol[type=I], li[type=I] { list-style-type: upper-roman; }
ul[type=none i], li[type=none i] { list-style-type: none; }
ul[type=disc i], li[type=disc i] { list-style-type: disc; }
ul[type=circle i], li[type=circle i] { list-style-type: circle; }
ul[type=square i], li[type=square i] { list-style-type: square; }

In the above stylesheet, the attribute selectors for the ol and li elements are expected to be treated as case-sensitive.

When rendering li elements, non-CSS user agents are expected to use the ordinal value of the li element to render the counter in the list item marker.

This specification does not yet define the CSS-specific rules for rendering li elements, because CSS doesn’t yet provide sufficient hooks for this purpose.

10.3.9. Tables

@namespace url(http://www.w3.org/1999/xhtml);

table { display: table; }
caption { display: table-caption; }
colgroup, colgroup[hidden] { display: table-column-group; }
col, col[hidden] { display: table-column; }
thead, thead[hidden] { display: table-header-group; }
tbody, tbody[hidden] { display: table-row-group; }
tfoot, tfoot[hidden] { display: table-footer-group; }
tr, tr[hidden] { display: table-row; }
td, th, td[hidden], th[hidden] { display: table-cell; }

colgroup[hidden], col[hidden], thead[hidden], tbody[hidden],
tfoot[hidden], tr[hidden], td[hidden], th[hidden] {
  visibility: collapse;
}

table {
  box-sizing: border-box;
  border-spacing: 2px;
  border-collapse: separate;
  text-indent: initial;
}
td, th { padding: 1px; }
th { font-weight: bold; }

thead, tbody, tfoot, table > tr { vertical-align: middle; }
tr, td, th { vertical-align: inherit; }

table, td, th { border-color: gray; }
thead, tbody, tfoot, tr { border-color: inherit; }
table[rules=none i], table[rules=groups i], table[rules=rows i],
table[rules=cols i], table[rules=all i], table[frame=void i],
table[frame=above i], table[frame=below i], table[frame=hsides i],
table[frame=lhs i], table[frame=rhs i], table[frame=vsides i],
table[frame=box i], table[frame=border i],
table[rules=none i] > tr > td, table[rules=none i] > tr > th,
table[rules=groups i] > tr > td, table[rules=groups i] > tr > th,
table[rules=rows i] > tr > td, table[rules=rows i] > tr > th,
table[rules=cols i] > tr > td, table[rules=cols i] > tr > th,
table[rules=all i] > tr > td, table[rules=all i] > tr > th,
table[rules=none i] > thead > tr > td, table[rules=none i] > thead > tr > th,
table[rules=groups i] > thead > tr > td, table[rules=groups i] > thead > tr > th,
table[rules=rows i] > thead > tr > td, table[rules=rows i] > thead > tr > th,
table[rules=cols i] > thead > tr > td, table[rules=cols i] > thead > tr > th,
table[rules=all i] > thead > tr > td, table[rules=all i] > thead > tr > th,
table[rules=none i] > tbody > tr > td, table[rules=none i] > tbody > tr > th,
table[rules=groups i] > tbody > tr > td, table[rules=groups i] > tbody > tr > th,
table[rules=rows i] > tbody > tr > td, table[rules=rows i] > tbody > tr > th,
table[rules=cols i] > tbody > tr > td, table[rules=cols i] > tbody > tr > th,
table[rules=all i] > tbody > tr > td, table[rules=all i] > tbody > tr > th,
table[rules=none i] > tfoot > tr > td, table[rules=none i] > tfoot > tr > th,
table[rules=groups i] > tfoot > tr > td, table[rules=groups i] > tfoot > tr > th,
table[rules=rows i] > tfoot > tr > td, table[rules=rows i] > tfoot > tr > th,
table[rules=cols i] > tfoot > tr > td, table[rules=cols i] > tfoot > tr > th,
table[rules=all i] > tfoot > tr > td, table[rules=all i] > tfoot > tr > th {
  border-color: black;
}

The following rules are also expected to apply, as presentational hints:

@namespace url(http://www.w3.org/1999/xhtml);

table[align=left i] { float: left; }
table[align=right i] { float: right; }
table[align=center i] { margin-left: auto; margin-right: auto; }
thead[align=absmiddle i], tbody[align=absmiddle i], tfoot[align=absmiddle i],
tr[align=absmiddle i], td[align=absmiddle i], th[align=absmiddle i] {
  text-align: center;
}

caption[align=bottom i] { caption-side: bottom; }
p[align=left i], h1[align=left i], h2[align=left i], h3[align=left i],
h4[align=left i], h5[align=left i], h6[align=left i] {
  text-align: left;
}
p[align=right i], h1[align=right i], h2[align=right i], h3[align=right i],
h4[align=right i], h5[align=right i], h6[align=right i] {
  text-align: right;
}
p[align=center i], h1[align=center i], h2[align=center i], h3[align=center i],
h4[align=center i], h5[align=center i], h6[align=center i] {
  text-align: center;
}
p[align=justify i], h1[align=justify i], h2[align=justify i], h3[align=justify i],
h4[align=justify i], h5[align=justify i], h6[align=justify i] {
  text-align: justify;
}
thead[valign=top i], tbody[valign=top i], tfoot[valign=top i],
tr[valign=top i], td[valign=top i], th[valign=top i] {
  vertical-align: top;
}
thead[valign=middle i], tbody[valign=middle i], tfoot[valign=middle i],
tr[valign=middle i], td[valign=middle i], th[valign=middle i] {
  vertical-align: middle;
}
thead[valign=bottom i], tbody[valign=bottom i], tfoot[valign=bottom i],
tr[valign=bottom i], td[valign=bottom i], th[valign=bottom i] {
  vertical-align: bottom;
}
thead[valign=baseline i], tbody[valign=baseline i], tfoot[valign=baseline i],
tr[valign=baseline i], td[valign=baseline i], th[valign=baseline i] {
  vertical-align: baseline;
}

td[nowrap], th[nowrap] { white-space: nowrap; }

table[rules=none i], table[rules=groups i], table[rules=rows i],
table[rules=cols i], table[rules=all i] {
border-style: hidden;
  border-collapse: collapse;
}
table[border] { border-style: outset; } /* only if border is not equivalent to zero */
table[frame=void i] { border-style: hidden; }
table[frame=above i] { border-style: outset hidden hidden hidden; }
table[frame=below i] { border-style: hidden hidden outset hidden; }
table[frame=hsides i] { border-style: outset hidden outset hidden; }
table[frame=lhs i] { border-style: hidden hidden hidden outset; }
table[frame=rhs i] { border-style: hidden outset hidden hidden; }
table[frame=vsides i] { border-style: hidden outset; }
table[frame=box i], table[frame=border i] { border-style: outset; }

table[border] > tr > td, table[border] > tr > th,
table[border] > thead > tr > td, table[border] > thead > tr > th,
table[border] > tbody > tr > td, table[border] > tbody > tr > th,
table[border] > tfoot > tr > td, table[border] > tfoot > tr > th {
/* only if border is not equivalent to zero */
  border-width: 1px;
  border-style: inset;
}
table[rules=none i] > tr > td, table[rules=none i] > tr > th,
table[rules=none i] > thead > tr > td, table[rules=none i] > thead > tr > th,
table[rules=none i] > tbody > tr > td, table[rules=none i] > tbody > tr > th,
table[rules=none i] > tfoot > tr > td, table[rules=none i] > tfoot > tr > th,
table[rules=groups i] > tr > td, table[rules=groups i] > tr > th,
table[rules=groups i] > thead > tr > td, table[rules=groups i] > thead > tr > th,
table[rules=groups i] > tbody > tr > td, table[rules=groups i] > tbody > tr > th,
table[rules=groups i] > tfoot > tr > td, table[rules=groups i] > tfoot > tr > th,
table[rules=rows i] > tr > td, table[rules=rows i] > tr > th,
table[rules=rows i] > thead > tr > td, table[rules=rows i] > thead > tr > th,
table[rules=rows i] > tbody > tr > td, table[rules=rows i] > tbody > tr > th,
table[rules=rows i] > tfoot > tr > td, table[rules=rows i] > tfoot > tr > th {
  border-width: 1px;
  border-style: none;
}
table[rules=cols i] > tr > td, table[rules=cols i] > tr > th,
table[rules=cols i] > thead > tr > td, table[rules=cols i] > thead > tr > th,
table[rules=cols i] > tbody > tr > td, table[rules=cols i] > tbody > tr > th,
table[rules=cols i] > tfoot > tr > td, table[rules=cols i] > tfoot > tr > th {
  border-width: 1px;
  border-style: none solid;
}
table[rules=all i] > tr > td, table[rules=all i] > tr > th,
table[rules=all i] > thead > tr > td, table[rules=all i] > thead > tr > th,
table[rules=all i] > tbody > tr > td, table[rules=all i] > tbody > tr > th,
table[rules=all i] > tfoot > tr > td, table[rules=all i] > tfoot > tr > th {
  border-width: 1px;
  border-style: solid;
}

table[rules=groups i] > colgroup {
  border-left-width: 1px;
  border-left-style: solid;
  border-right-width: 1px;
  border-right-style: solid;
}
table[rules=groups i] > thead,
table[rules=groups i] > tbody,
table[rules=groups i] > tfoot {
  border-top-width: 1px;
  border-top-style: solid;
  border-bottom-width: 1px;
  border-bottom-style: solid;
}

table[rules=rows i] > tr, table[rules=rows i] > thead > tr,
table[rules=rows i] > tbody > tr, table[rules=rows i] > tfoot > tr {
  border-top-width: 1px;
  border-top-style: solid;
  border-bottom-width: 1px;
  border-bottom-style: solid;
}

In quirks mode, the following rules are also expected to apply:

@namespace url(http://www.w3.org/1999/xhtml);

table {
  font-weight: initial;
  font-style: initial;
  font-variant: initial;
  font-size: initial;
  line-height: initial;
  white-space: initial;
  text-align: initial;
}

For the purposes of the CSS table model, the col element is expected to be treated as if it was present as many times as its span attribute specifies.

For the purposes of the CSS table model, the colgroup element, if it contains no col element, is expected to be treated as if it had as many such children as its span attribute specifies.

For the purposes of the CSS table model, the colspan and rowspan attributes on td and th elements are expected to provide the special knowledge regarding cells spanning rows and columns.

In HTML documents, the following rules are also expected to apply:

@namespace url(http://www.w3.org/1999/xhtml);

:matches(table, thead, tbody, tfoot, tr) > form {  display: none !important; }

The table element’s cellspacing attribute maps to the pixel length property border-spacing on the element.

The table element’s cellpadding attribute maps to the pixel length properties padding-top, padding-right, padding-bottom, and padding-left of any td and th elements that have corresponding cells in the table corresponding to the table element.

The table element’s hspace attribute maps to the dimension properties margin-left and margin-right on the table element.

The table element’s vspace attribute maps to the dimension properties margin-top and margin-bottom on the table element.

The table element’s height attribute maps to the dimension property (ignoring zero) height on the table element.

The table element’s width attribute maps to the dimension property (ignoring zero) width on the table element.

The col element’s width attribute maps to the dimension property (ignoring zero) width on the col element.

The tr element’s height attribute maps to the dimension property (ignoring zero) height on the tr element.

The td and th elements' height attributes map to the dimension property (ignoring zero) height on the element.

The td and th elements' width attributes map to the dimension property (ignoring zero) width on the element.


The caption element unless specified otherwise below, and the thead, tbody, tfoot, tr, td, and th elements when they have an align attribute whose value is an ASCII case-insensitive match for either the string "center" or the string "middle", are expected to center text within themselves, as if they had their text-align property set to center in a presentational hint, and to align descendants to the center.

The caption, thead, tbody, tfoot, tr, td, and th elements, when they have an align attribute whose value is an ASCII case-insensitive match for the string "left", are expected to left-align text within themselves, as if they had their text-align property set to left in a presentational hint, and to align descendants to the left.

The caption, thead, tbody, tfoot, tr, td, and th elements, when they have an align attribute whose value is an ASCII case-insensitive match for the string "right", are expected to right-align text within themselves, as if they had their text-align property set to right in a presentational hint, and to align descendants to the right.

The caption, thead, tbody, tfoot, tr, td, and th elements, when they have an align attribute whose value is an ASCII case-insensitive match for the string "justify", are expected to full-justify text within themselves, as if they had their text-align property set to justify in a presentational hint, and to align descendants to the left.

User agents are expected to have a rule in their user agent stylesheet that matches th elements that have a parent node whose computed value for the text-align property is its initial value, whose declaration block consists of just a single declaration that sets the text-align property to the value center.


When a table, thead, tbody, tfoot, tr, td, or th element has a background attribute set to a non-empty value, the new value is expected to be parsed relative to the element’s node document, and if this is successful, the user agent is expected to treat the attribute as a presentational hint setting the element’s background-image property to the resulting URL string.

When a table, thead, tbody, tfoot, tr, td, or th element has a bgcolor attribute set, the new value is expected to be parsed using the rules for parsing a legacy color value, and if that does not return an error, the user agent is expected to treat the attribute as a presentational hint setting the element’s background-color property to the resulting color.

When a table element has a bordercolor attribute, its value is expected to be parsed using the rules for parsing a legacy color value, and if that does not return an error, the user agent is expected to treat the attribute as a presentational hint setting the element’s border-top-color, border-right-color, border-bottom-color, and border-left-color properties to the resulting color.


The table element’s border attribute maps to the pixel length properties border-top-width, border-right-width, border-bottom-width, border-left-width on the element. If the attribute is present but parsing the attribute’s value using the rules for parsing non-negative integers generates an error, a default value of 1px is expected to be used for that property instead.

Rules marked "only if border is not equivalent to zero" in the CSS block above is expected to only be applied if the border attribute mentioned in the selectors for the rule is not only present but, when parsed using the rules for parsing non-negative integers, is also found to have a value other than zero or to generate an error.


In quirks mode, a td element or a th element that has a nowrap attribute but also has a width attribute whose value, when parsed using the rules for parsing non-zero dimension values, is found to be a length (not an error or a number classified as a percentage), is expected to have a presentational hint setting the element’s white-space property to normal, overriding the rule in the CSS block above that sets it to nowrap.

10.3.10. Margin collapsing quirks

A node is substantial if it is a text node that is not inter-element whitespace, or if it is an element node.

A node is blank if it is an element that contains no substantial nodes.

The elements with default margins are the following elements: blockquote, dir, dl, h1, h2, h3, h4, h5, h6, listing, menu, ol, p, plaintext, pre, ul, xmp

In quirks mode, any element with default margins that is the child of a body, td, or th element and has no substantial previous siblings is expected to have a user-agent level style sheet rule that sets its margin-top property to zero.

In quirks mode, any element with default margins that is the child of a body, td, or th element, has no substantial previous siblings, and is blank, is expected to have a user-agent level style sheet rule that sets its margin-bottom property to zero also.

In quirks mode, any element with default margins that is the child of a td or th element, has no substantial following siblings, and is blank, is expected to have a user-agent level style sheet rule that sets its margin-top property to zero.

In quirks mode, any p element that is the child of a td or th element and has no substantial following siblings, is expected to have a user-agent level style sheet rule that sets its margin-bottom property to zero.

10.3.11. Form controls

@namespace url(http://www.w3.org/1999/xhtml);

  input, select, option, optgroup, button, textarea, keygen {
  text-indent: initial;
  }

  input:matches([type=radio i], [type=checkbox i], [type=reset i], [type=button i],
  [type=submit i], [type=search i]), select, button {
  box-sizing: border-box;
  }

In quirks mode, the following rules are also expected to apply:

@namespace url(http://www.w3.org/1999/xhtml);

  input:not([type=image i]), textarea { box-sizing: border-box; }

Each kind of form control is also given a specific default binding, as described in subsequent sections, which implements the look and feel of the control.

10.3.12. The hr element

@namespace url(http://www.w3.org/1999/xhtml);

  hr { color: gray; border-style: inset; border-width: 1px; margin: 0.5em auto; }

The following rules are also expected to apply, as presentational hints:

@namespace url(http://www.w3.org/1999/xhtml);

  hr[align=left] { margin-left: 0; margin-right: auto; }
  hr[align=right] { margin-left: auto; margin-right: 0; }
  hr[align=center] { margin-left: auto; margin-right: auto; }
  hr[color], hr[noshade] { border-style: solid; }

If an hr element has either a color attribute or a noshade attribute, and furthermore also has a size attribute, and parsing that attribute’s value using the rules for parsing non-negative integers doesn’t generate an error, then the user agent is expected to use the parsed value divided by two as a pixel length for presentational hints for the properties border-top-width, border-right-width, border-bottom-width, and border-left-width on the element.

Otherwise, if an hr element has neither a color attribute nor a noshade attribute, but does have a size attribute, and parsing that attribute’s value using the rules for parsing non-negative integers doesn’t generate an error, then: if the parsed value is one, then the user agent is expected to use the attribute as a presentational hint setting the element’s border-bottom-width to 0; otherwise, if the parsed value is greater than one, then the user agent is expected to use the parsed value minus two as a pixel length for presentational hints for the height property on the element.

The width attribute on an hr element maps to the dimension property width on the element.

When an hr element has a color attribute, its value is expected to be parsed using the rules for parsing a legacy color value, and if that does not return an error, the user agent is expected to treat the attribute as a presentational hint setting the element’s color property to the resulting color.

10.3.13. The fieldset and legend elements

@namespace url(http://www.w3.org/1999/xhtml);

  fieldset {
  display: block;
  margin-left: 2px; margin-right: 2px;
  border: groove 2px ThreeDFace;
  padding: 0.35em 0.625em 0.75em;
  min-width: min-content;
  }

  legend {
  padding-left: 2px; padding-right: 2px;
  }

The fieldset element is expected to establish a new block formatting context.

If the fieldset element has a child that matches the conditions in the list below, then the first such child is the fieldset element’s rendered legend:

A fieldset element’s rendered legend, if any, is expected to be rendered over the top border edge of the fieldset element as a block box (overriding any explicit display value). In the absence of an explicit width, the box should shrink-wrap. If the legend element in question has an align attribute, and its value is an ASCII case-insensitive match for one of the strings in the first column of the following table, then the legend is expected to be rendered horizontally aligned over the border edge in the position given in the corresponding cell on the same row in the second column. If the attribute is absent or has a value that doesn’t match any of the cases in the table, then the position is expected to be on the right if the direction property on this element has a computed value of rtl, and on the left otherwise.

Attribute value Alignment position
left On the left
right On the right
center In the middle

10.4. Replaced elements

10.4.1. Embedded content

The embed, iframe, and video elements are expected to be treated as replaced elements.

A canvas element that represents embedded content is expected to be treated as a replaced element; the contents of such elements are the element’s bitmap, if any, or else a transparent black bitmap with the same intrinsic dimensions as the element. Other canvas elements are expected to be treated as ordinary elements in the rendering model.

An object element that represents an image, plugin, or nested browsing context is expected to be treated as a replaced element. Other object elements are expected to be treated as ordinary elements in the rendering model.

An applet element that represents a plugin is expected to be treated as a replaced element. Other applet elements are expected to be treated as ordinary elements in the rendering model.

The audio element, when it is exposing a user interface, is expected to be treated as a replaced element about one line high, as wide as is necessary to expose the user agent’s user interface features. When an audio element is not exposing a user interface, the user agent is expected to force its display property to compute to none, irrespective of CSS rules.

Whether a video element is exposing a user interface is not expected to affect the size of the rendering; controls are expected to be overlaid above the page content without causing any layout changes, and are expected to disappear when the user does not need them.

When a video element represents a poster frame or frame of video, the poster frame or frame of video is expected to be rendered at the largest size that maintains the aspect ratio of that poster frame or frame of video without being taller or wider than the video element itself, and is expected to be centered in the video element.

Any subtitles or captions are expected to be overlayed directly on top of their video element, as defined by the relevant rendering rules; for WebVTT, those are the rules for updating the display of WebVTT text tracks. [WEBVTT]

When the user agent starts exposing a user interface for a video element, the user agent should run the rules for updating the text track rendering of each of the text tracks in the video element’s list of text tracks that are showing and whose text track kind is one of subtitles or captions (e.g., for text tracks based on WebVTT, the rules for updating the display of WebVTT text tracks). [WEBVTT]

Resizing video and canvas elements does not interrupt video playback or clear the canvas.


The following CSS rules are expected to apply:

@namespace url(http://www.w3.org/1999/xhtml);

video { object-fit: contain; }

10.4.2. Images

User agents are expected to render img elements and input elements whose type attributes are in the image button state, according to the first applicable rules from the following list:

If the element represents an image
The user agent is expected to treat the element as a replaced element and render the image according to the rules for doing so defined in CSS.

If the element does not represent an image, but the element already has intrinsic dimensions (e.g., from the dimension attributes or CSS rules), and either:

  • the user agent has reason to believe that the image will become available and be rendered in due course, or
  • the element has no alt attribute, or
  • the Document is in quirks mode
The user agent is expected to treat the element as a replaced element whose content is the text that the element represents, if any, optionally alongside an icon indicating that the image is being obtained (if applicable). For input elements, the element is expected to appear button-like to indicate that the element is a button.
If the element is an img element that represents some text and the user agent does not expect this to change
The user agent is expected to treat the element as a non-replaced phrasing element whose content is the text, optionally with an icon indicating that an image is missing, so that the user can request the image be displayed or investigate why it is not rendering. In non-graphical contexts, such an icon should be omitted.
If the element is an img element that represents nothing and the user agent does not expect this to change
The user agent is expected to treat the element as an empty inline element. (In the absence of further styles, this will cause the element to essentially not be rendered.)
If the element is an input element that does not represent an image and the user agent does not expect this to change
The user agent is expected to treat the element as a replaced element consisting of a button whose content is the element’s alternative text. The intrinsic dimensions of the button are expected to be about one line in height and whatever width is necessary to render the text on one line.

The icons mentioned above are expected to be relatively small so as not to disrupt most text but be easily clickable. In a visual environment, for instance, icons could be 16 pixels by 16 pixels square, or 1em by 1em if the images are scalable. In an audio environment, the icon could be a short bleep. The icons are intended to indicate to the user that they can be used to get to whatever options the user agent provides for images, and, where appropriate, are expected to provide access to the context menu that would have come up if the user interacted with the actual image.


All animated images with the same absolute URL and the same image data are expected to be rendered synchronized to the same timeline as a group, with the timeline starting at the time of the least recent addition to the group.

In other words, when a second image with the same absolute URL and animated image data is inserted into a document, it jumps to the point in the animation cycle that is currently being displayed by the first image.

When a user agent is to restart the animation for an img element showing an animated image, all animated images with the same absolute URL and the same image data in that img element’s node document are expected to restart their animation from the beginning.


The following CSS rules are expected to apply when the Document is in quirks mode:

@namespace url(http://www.w3.org/1999/xhtml);

img[align=left i] { margin-right: 3px; }
img[align=right i] { margin-left: 3px; }

10.4.3. Attributes for embedded content and images

The following CSS rules are expected to apply as presentational hints:

@namespace url(http://www.w3.org/1999/xhtml);

iframe[frameborder=0], iframe[frameborder=no i] { border: none; }

applet[align=left i], embed[align=left i], iframe[align=left i],
img[align=left i], input[type=image i][align=left i], object[align=left i] {
  float: left;
}

applet[align=right i], embed[align=right i], iframe[align=right i],
img[align=right i], input[type=image i][align=right i], object[align=right i] {
  float: right;
}

applet[align=top i], embed[align=top i], iframe[align=top i],
img[align=top i], input[type=image i][align=top i], object[align=top i] {
  vertical-align: top;
}

applet[align=baseline i], embed[align=baseline i], iframe[align=baseline i],
img[align=baseline i], input[type=image i][align=baseline i], object[align=baseline i] {
  vertical-align: baseline;
}

applet[align=texttop i], embed[align=texttop i], iframe[align=texttop i],
img[align=texttop i], input[type=image i][align=texttop i], object[align=texttop i] {
  vertical-align: text-top;
}

applet[align=absmiddle i], embed[align=absmiddle i], iframe[align=absmiddle i],
img[align=absmiddle i], input[type=image i][align=absmiddle i], object[align=absmiddle i],
applet[align=abscenter i], embed[align=abscenter i], iframe[align=abscenter i],
img[align=abscenter i], input[type=image i][align=abscenter i], object[align=abscenter i] {
  vertical-align: middle;
}

applet[align=bottom i], embed[align=bottom i], iframe[align=bottom i],
img[align=bottom i], input[type=image i][align=bottom i],
object[align=bottom i] {
  vertical-align: bottom;
}

When an applet, embed, iframe, img, or object element, or an input element whose type attribute is in the image button state, has an align attribute whose value is an ASCII case-insensitive match for the string "center" or the string "middle", the user agent is expected to act as if the element’s vertical-align property was set to a value that aligns the vertical middle of the element with the parent element’s baseline.

The hspace attribute of applet, embed, iframe, img, or object elements, and input elements with a type attribute in the image button state, maps to the dimension properties margin-left and margin-right on the element.

The vspace attribute of applet, embed, iframe, img, or object elements, and input elements with a type attribute in the image button state, maps to the dimension properties margin-top and margin-bottom on the element.

When an img element, object element, or input element with a type attribute in the image button state has a border attribute whose value, when parsed using the rules for parsing non-negative integers, is found to be a number greater than zero, the user agent is expected to use the parsed value for eight presentational hints: four setting the parsed value as a pixel length for the element’s border-top-width, border-right-width, border-bottom-width, and border-left-width properties, and four setting the element’s border-top-style, border-right-style, border-bottom-style, and border-left-style properties to the value solid.

The width and height attributes on applet, embed, iframe, img, object or video elements, and input elements with a type attribute in the image button state and that either represents an image or that the user expects will eventually represent an image, map to the dimension properties width and height on the element respectively.

10.4.4. Image maps

Shapes on an image map are expected to act, for the purpose of the CSS cascade, as elements independent of the original area element that happen to match the same style rules but inherit from the img or object element.

For the purposes of the rendering, only the cursor property is expected to have any effect on the shape.

Thus, for example, if an area element has a style attribute that sets the cursor property to help, then when the user designates that shape, the cursor would change to a Help cursor.

Similarly, if an area element had a CSS rule that set its cursor property to inherit (or if no rule setting the cursor property matched the element at all), the shape’s cursor would be inherited from the img or object element of the image map, not from the parent of the area element.

10.5. Bindings

10.5.1. Introduction

Exactly how the bindings are implemented is not specified by this specification. User agents are encouraged to make their bindings set the appearance CSS property appropriately to achieve platform-native appearances for widgets, and are expected to implement any relevant animations, etc, that are appropriate for the platform. [CSS-UI-3]

10.5.2. The button element

When the button binding applies to a button element, the element is expected to render as an inline-block box rendered as a button whose contents are the contents of the element.

When the button element’s type attribute is in the Menu state, the user agent is expected to indicate that activating the element will display a menu, e.g., by displaying a down-pointing triangle after the button’s label.

10.5.3. The details element

When the details binding applies to a details element, the element is expected to render as a block box with its padding-left property set to "40px" for left-to-right elements (LTR-specific) and with its padding-right property set to "40px" for right-to-left elements. The element’s shadow tree is expected to take the element’s first child summary element, if any, and place it in a first block box container, and then take the element’s remaining descendants, if any, and place them in a second block box container.

The first container is expected to contain at least one line box, and that line box is expected to contain a disclosure widget (typically a triangle), horizontally positioned within the left padding of the details element. That widget is expected to allow the user to request that the details be shown or hidden.

The second container is expected to have its overflow property set to hidden. When the details element does not have an open attribute, this second container is expected to be removed from the rendering.

10.5.4. The input element as a text entry widget

When the input-textfield binding applies to an input element whose type attribute is in the Text, Search, Telephone, URL, or E-mail state, the element is expected to render as an inline-block box rendered as a text field.

When the input-password binding applies to an input element whose type attribute is in the Password state, the element is expected to render as an inline-block box rendered as a text field whose contents are obscured.

If these text fields provide a text selection, then, when the user changes the current selection in such a binding, the user agent is expected to queue a task to fire a simple event that bubbles named select at the element, using the user interaction task source as the task source.

If an input element whose type attribute is in one of the above states has a size attribute, and parsing that attribute’s value using the rules for parsing non-negative integers doesn’t generate an error, then the user agent is expected to use the attribute as a presentational hint for the width property on the element, with the value obtained from applying the converting a character width to pixels algorithm to the value of the attribute.

If an input element whose type attribute is in one of the above states does not have a size attribute, then the user agent is expected to act as if it had a user-agent-level style sheet rule setting the width property on the element to the value obtained from applying the converting a character width to pixels algorithm to the number 20.

The converting a character width to pixels algorithm returns (size-1)×avg + max, where size is the character width to convert, avg is the average character width of the primary font for the element for which the algorithm is being run, in pixels, and max is the maximum character width of that same font, also in pixels. (The element’s letter-spacing property does not affect the result.)

When the input-textfield binding applies to an element, the line-height property, if it has a computed value equivalent to a value that is less than 1.0, must have a used value of 1.0.

10.5.5. The input element as domain-specific widgets

When the input-date binding applies to an input element whose type attribute is in the Date state, the element is expected to render as an inline-block box depicting a Date control.

When the input-month binding applies to an input element whose type attribute is in the Month state, the element is expected to render as an inline-block box depicting a Month control.

When the input-week binding applies to an input element whose type attribute is in the Week state, the element is expected to render as an inline-block box depicting a Week control.

When the input-time binding applies to an input element whose type attribute is in the Time state, the element is expected to render as an inline-block box depicting a Time control.

When the input-datetime-local binding applies to an input element whose type attribute is in the Local Date and Time state, the element is expected to render as an inline-block box depicting a Local Date and Time control.

When the input-number binding applies to an input element whose type attribute is in the Number state, the element is expected to render as an inline-block box depicting a Number control.

These controls are all expected to be about one line high, and about as wide as necessary to show the widest possible value.

10.5.6. The input element as a range control

When the input-range binding applies to an input element whose type attribute is in the Range state, the element is expected to render as an inline-block box depicting a slider control.

When the control is wider than it is tall (or square), the control is expected to be a horizontal slider, with the lowest value on the right if the direction property on this element has a computed value of rtl, and on the left otherwise. When the control is taller than it is wide, it is expected to be a vertical slider, with the lowest value on the bottom.

Predefined suggested values (provided by the list attribute) are expected to be shown as tick marks on the slider, which the slider can snap to.

User agents are expected to use the used value of the direction property on the element to determine the direction in which the slider operates. Typically, a left-to-right (ltr) horizontal control would have the lowest value on the left and the highest value on the right, and vice versa.

10.5.7. The input element as a color well

When the input-color binding applies to an input element whose type attribute is in the Color state, the element is expected to render as an inline-block box depicting a color well, which, when activated, provides the user with a color picker (e.g., a color wheel or color palette) from which the color can be changed.

Predefined suggested values (provided by the list attribute) are expected to be shown in the color picker interface, not on the color well itself.

10.5.8. The input element as a checkbox and radio button widgets

When the input-checkbox binding applies to an input element whose type attribute is in the Checkbox state, the element is expected to render as an inline-block box containing a single checkbox control, with no label.

When the input-radio binding applies to an input element whose type attribute is in the Radio Button state, the element is expected to render as an inline-block box containing a single radio button control, with no label.

10.5.9. The input element as a file upload control

When the input-file binding applies to an input element whose type attribute is in the File Upload state, the element is expected to render as an inline-block box containing a span of text giving the file name(s) of the selected files, if any, followed by a button that, when activated, provides the user with a file picker from which the selection can be changed.

10.5.10. The input element as a button

When the input-button binding applies to an input element whose type attribute is in the submit button, Reset Button, or Button state, the element is expected to render as an inline-block box rendered as a button, about one line high, containing the contents of the element’s value attribute, if any, or text derived from the element’s type attribute in a user-agent-defined (and probably locale-specific) fashion, if not.

10.5.11. The marquee element

When the marquee binding applies to a marquee element, while the element is turned on, the element is expected to render in an animated fashion according to its attributes as follows:

If the element’s behavior attribute is in the scroll state

Slide the contents of the element in the direction described by the direction attribute as defined below, such that it begins off the start side of the marquee, and ends flush with the inner end side.

For example, if the direction attribute is left (the default), then the contents would start such that their left edge are off the side of the right edge of the marquee’s content area, and the contents would then slide up to the point where the left edge of the contents are flush with the left inner edge of the marquee’s content area.

Once the animation has ended, the user agent is expected to increment the marquee current loop index. If the element is still turned on after this, then the user agent is expected to restart the animation.

If the element’s behavior attribute is in the slide state

Slide the contents of the element in the direction described by the direction attribute as defined below, such that it begins off the start side of the marquee, and ends off the end side of the marquee.

For example, if the direction attribute is left (the default), then the contents would start such that their left edge are off the side of the right edge of the marquee's content area, and the contents would then slide up to the point where the right edge of the contents are flush with the left inner edge of the marquee's content area.

Once the animation has ended, the user agent is expected to increment the marquee current loop index. If the element is still turned on after this, then the user agent is expected to restart the animation.

If the element’s behavior attribute is in the alternate state

When the marquee current loop index is even (or zero), slide the contents of the element in the direction described by the direction attribute as defined below, such that it begins flush with the start side of the marquee, and ends flush with the end side of the marquee.

When the marquee current loop index is odd, slide the contents of the element in the opposite direction than that described by the direction attribute as defined below, such that it begins flush with the end side of the marquee, and ends flush with the start side of the marquee.

For example, if the direction attribute is left (the default), then the contents would with their right edge flush with the right inner edge of the marquee’s content area, and the contents would then slide up to the point where the left edge of the contents are flush with the left inner edge of the marquee’s content area.

Once the animation has ended, the user agent is expected to increment the marquee current loop index. If the element is still turned on after this, then the user agent is expected to continue the animation.

The direction attribute has the meanings described in the following table:

direction attribute state Direction of animation Start edge End edge Opposite direction
left ← Right to left Right Left → Left to Right
right → Left to Right Left Right ← Right to left
up ↑ Up (Bottom to Top) Bottom Top ↓ Down (Top to Bottom)
down ↓ Down (Top to Bottom) Top Bottom ↑ Up (Bottom to Top)

In any case, the animation should proceed such that there is a delay given by the marquee scroll interval between each frame, and such that the content moves at most the distance given by the marquee scroll distance with each frame.

When a marquee element has a bgcolor attribute set, the value is expected to be parsed using the rules for parsing a legacy color value, and if that does not return an error, the user agent is expected to treat the attribute as a presentational hint setting the element’s background-color property to the resulting color.

The width and height attributes on a marquee element map to the dimension properties width and height on the element respectively.

The intrinsic height of a marquee element with its direction attribute in the up or down states is 200 CSS pixels.

The vspace attribute of a marquee element maps to the dimension properties margin-top and margin-bottom on the element. The hspace attribute of a marquee element maps to the dimension properties margin-left and margin-right on the element.

The overflow property on the marquee element is expected to be ignored; overflow is expected to always be hidden.

10.5.12. The meter element

When the meter binding applies to a meter element, the element is expected to render as an inline-block box with a height of "1em" and a width of "5em", a vertical-align of "-0.2em", and with its contents depicting a gauge.

When the element is wider than it is tall (or square), the depiction is expected to be of a horizontal gauge, with the minimum value on the right if the direction property on this element has a computed value of rtl, and on the left otherwise. When the element is taller than it is wide, it is expected to depict a vertical gauge, with the minimum value on the bottom.

User agents are expected to use a presentation consistent with platform conventions for gauges, if any.

Requirements for what must be depicted in the gauge are included in the definition of the meter element.

10.5.13. The progress element

When the progress binding applies to a progress element, the element is expected to render as an inline-block box with a height of "1em" and a width of "10em", and a vertical-align of "-0.2em".

When the element is wider than it is tall, the element is expected to be depicted as a horizontal progress bar, with the start on the right and the end on the left if the direction property on this element has a computed value of rtl, and with the start on the left and the end on the right otherwise. When the element is taller than it is wide, it is expected to be depicted as a vertical progress bar, with the lowest value on the bottom. When the element is square, it is expected to be depicted as a direction-independent progress widget (e.g., a circular progress ring).

User agents are expected to use a presentation consistent with platform conventions for progress bars. In particular, user agents are expected to use different presentations for determinate and indeterminate progress bars. User agents are also expected to vary the presentation based on the dimensions of the element.

For example, on some platforms for showing indeterminate progress there is a "spinner" progress indicator with square dimensions, which could be used when the element is square, and an indeterminate progress bar, which could be used when the element is wide.

Requirements for how to determine if the progress bar is determinate or indeterminate, and what progress a determinate progress bar is to show, are included in the definition of the progress element.

10.5.14. The select element

When the select binding applies to a select element whose multiple attribute is present, the element is expected to render as a multi-select list box.

When the select binding applies to a select element whose multiple attribute is absent, and the element’s display size is greater than 1, the element is expected to render as a single-select list box.

When the element renders as a list box, it is expected to render as an inline-block box whose height is the height necessary to contain as many rows for items as given by the element’s display size, or four rows if the attribute is absent, and whose width is the width of the select’s labels plus the width of a scrollbar.

When the select binding applies to a select element whose multiple attribute is absent, and the element’s display size is 1, the element is expected to render as a one-line drop down box whose width is the width of the select’s labels.

In either case (list box or drop-down box), the element’s items are expected to be the element’s list of options, with the element’s optgroup element children providing headers for groups of options where applicable.

An optgroup element is expected to be rendered by displaying the element’s label attribute.

An option element is expected to be rendered by displaying the element’s label, indented under its optgroup element if it has one.

The width of the select’s labels is the wider of the width necessary to render the widest optgroup, and the width necessary to render the widest option element in the element’s list of options (including its indent, if any).

If a select element contains a placeholder label option, the user agent is expected to render that option in a manner that conveys that it is a label, rather than a valid option of the control. This can include preventing the placeholder label option from being explicitly selected by the user. When the placeholder label option’s selectedness is true, the control is expected to be displayed in a fashion that indicates that no valid option is currently selected.

User agents are expected to render the labels in a select in such a manner that any alignment remains consistent whether the label is being displayed as part of the page or in a menu control.

10.5.15. The textarea element

@namespace url(http://www.w3.org/1999/xhtml);

textarea { white-space: pre-wrap; }

When the textarea binding applies to a textarea element, the element is expected to render as an inline-block box rendered as a multiline text field. If this text field provides a selection, then, when the user changes the current selection in such a binding, the user agent is expected to queue a task to fire a simple event that bubbles named select at the element, using the user interaction task source as the task source.

If the element has a cols attribute, and parsing that attribute’s value using the rules for parsing non-negative integers doesn’t generate an error, then the user agent is expected to use the attribute as a presentational hint for the width property on the element, with the value being the textarea effective width (as defined below). Otherwise, the user agent is expected to act as if it had a user-agent-level style sheet rule setting the width property on the element to the textarea effective width.

The textarea effective width of a textarea element is size×avg + sbw, where size is the element’s character width, avg is the average character width of the primary font of the element, in CSS pixels, and sbw is the width of a scroll bar, in CSS pixels. (The element’s letter-spacing property does not affect the result.)

If the element has a rows attribute, and parsing that attribute’s value using the rules for parsing non-negative integers doesn’t generate an error, then the user agent is expected to use the attribute as a presentational hint for the height property on the element, with the value being the textarea effective height (as defined below). Otherwise, the user agent is expected to act as if it had a user-agent-level style sheet rule setting the height property on the element to the textarea effective height.

The textarea effective height of a textarea element is the height in CSS pixels of the number of lines specified the element’s character height, plus the height of a scrollbar in CSS pixels.

User agents are expected to apply the white-space CSS property to textarea elements. For historical reasons, if the element has a wrap attribute whose value is an ASCII case-insensitive match for the string "off", then the user agent is expected to treat the attribute as a presentational hint setting the element’s white-space property to pre.

10.5.16. The keygen element

When the keygen binding applies to a keygen element, the element is expected to render as an inline-block box containing a user interface to configure the key pair to be generated.

10.6. Frames and framesets

User agent are expected to render frameset elements as a box with the height and width of the viewport, with a surface rendered according to the following layout algorithm:

  1. The cols and rows variables are lists of zero or more pairs consisting of a number and a unit, the unit being one of percentage, relative, and absolute.

    Use the rules for parsing a list of dimensions to parse the value of the element’s cols attribute, if there is one. Let cols be the result, or an empty list if there is no such attribute.

    Use the rules for parsing a list of dimensions to parse the value of the element’s rows attribute, if there is one. Let rows be the result, or an empty list if there is no such attribute.

  2. For any of the entries in cols or rows that have the number zero and the unit relative, change the entry’s number to one.

  3. If cols has no entries, then add a single entry consisting of the value 1 and the unit relative to cols.

    If rows has no entries, then add a single entry consisting of the value 1 and the unit relative to rows.

  4. Invoke the algorithm defined below to convert a list of dimensions to a list of pixel values using cols as the input list, and the width of the surface that the frameset is being rendered into, in CSS pixels, as the input dimension. Let sized cols be the resulting list.

    Invoke the algorithm defined below to convert a list of dimensions to a list of pixel values using rows as the input list, and the height of the surface that the frameset is being rendered into, in CSS pixels, as the input dimension. Let sized rows be the resulting list.

  5. Split the surface into a grid of w×h rectangles, where w is the number of entries in sized cols and h is the number of entries in sized rows.

    Size the columns so that each column in the grid is as many CSS pixels wide as the corresponding entry in the sized cols list.

    Size the rows so that each row in the grid is as many CSS pixels high as the corresponding entry in the sized rows list.

  6. Let children be the list of frame and frameset elements that are children of the frameset element for which the algorithm was invoked.

  7. For each row of the grid of rectangles created in the previous step, from top to bottom, run these substeps:

    1. For each rectangle in the row, from left to right, run these substeps:

      1. If there are any elements left in children, take the first element in the list, and assign it to the rectangle.

        If this is a frameset element, then recurse the entire frameset layout algorithm for that frameset element, with the rectangle as the surface.

        Otherwise, it is a frame element; render its nested browsing context, positioned and sized to fit the rectangle.

      2. If there are any elements left in children, remove the first element from children.

  8. If the frameset element has a border, draw an outer set of borders around the rectangles, using the element’s frame border color.

    For each rectangle, if there is an element assigned to that rectangle, and that element has a border, draw an inner set of borders around that rectangle, using the element’s frame border color.

    For each (visible) border that does not abut a rectangle that is assigned a frame element with a noresize attribute (including rectangles in further nested frameset elements), the user agent is expected to allow the user to move the border, resizing the rectangles within, keeping the proportions of any nested frameset grids.

    A frameset or frame element has a border if the following algorithm returns true:

    1. If the element has a frameborder attribute whose value is not the empty string and whose first character is either a U+0031 DIGIT ONE (1) character, a U+0079 LATIN SMALL LETTER Y character (y), or a U+0059 LATIN CAPITAL LETTER Y character (Y), then return true.
    2. Otherwise, if the element has a frameborder attribute, return false.
    3. Otherwise, if the element has a parent element that is a frameset element, then return true if that element has a border, and false if it does not.
    4. Otherwise, return true.

    The frame border color of a frameset or frame element is the color obtained from the following algorithm:

    1. If the element has a bordercolor attribute, and applying the rules for parsing a legacy color value to that attribute’s value does not result in an error, then return the color so obtained.
    2. Otherwise, if the element has a parent element that is a frameset element, then return the frame border color of that element.
    3. Otherwise, return gray.

The algorithm to convert a list of dimensions to a list of pixel values consists of the following steps:

  1. Let input list be the list of numbers and units passed to the algorithm.

    Let output list be a list of numbers the same length as input list, all zero.

    Entries in output list correspond to the entries in input list that have the same position.

  2. Let input dimension be the size passed to the algorithm.
  3. Let count percentage be the number of entries in input list whose unit is percentage.

    Let total percentage be the sum of all the numbers in input list whose unit is percentage.

    Let count relative be the number of entries in input list whose unit is relative.

    Let total relative be the sum of all the numbers in input list whose unit is relative.

    Let count absolute be the number of entries in input list whose unit is absolute.

    Let total absolute be the sum of all the numbers in input list whose unit is absolute.

    Let remaining space be the value of input dimension.

  4. If total absolute is greater than remaining space, then for each entry in input list whose unit is absolute, set the corresponding value in output list to the number of the entry in input list multiplied by remaining space and divided by total absolute. Then, set remaining space to zero.

    Otherwise, for each entry in input list whose unit is absolute, set the corresponding value in output list to the number of the entry in input list. Then, decrement remaining space by total absolute.

  5. If total percentage multiplied by the input dimension and divided by 100 is greater than remaining space, then for each entry in input list whose unit is percentage, set the corresponding value in output list to the number of the entry in input list multiplied by remaining space and divided by total percentage. Then, set remaining space to zero.

    Otherwise, for each entry in input list whose unit is percentage, set the corresponding value in output list to the number of the entry in input list multiplied by the input dimension and divided by 100. Then, decrement remaining space by total percentage multiplied by the input dimension and divided by 100.

  6. For each entry in input list whose unit is relative, set the corresponding value in output list to the number of the entry in input list multiplied by remaining space and divided by total relative.

  7. Return output list.

User agents working with integer values for frame widths (as opposed to user agents that can lay frames out with subpixel accuracy) are expected to distribute the remainder first to the last entry whose unit is relative, then equally (not proportionally) to each entry whose unit is percentage, then equally (not proportionally) to each entry whose unit is absolute, and finally, failing all else, to the last entry.


The contents of a frame element that does not have a frameset parent are expected to be rendered as transparent black; the user agent is expected to not render the nested browsing context in this case, and that nested browsing context is expected to have a viewport with zero width and zero height.

10.7. Interactive media

User agents are expected to allow the user to control aspects of hyperlink activation and §4.10.22 Form submission, such as which browsing context is to be used for the subsequent navigation.

User agents are expected to allow users to discover the destination of hyperlinks and of forms before triggering their navigation.

User agents may allow users to navigate browsing contexts to the URLs indicated by the cite attributes on q, blockquote, ins, and del elements.

User agents may surface hyperlinks created by link elements in their user interface.

While link elements that create hyperlinks will match the ':link' or ':visited' pseudo-classes, will react to clicks if visible, and so forth, this does not extend to any browser interface constructs that expose those same links. Activating a link through the browser’s interface, rather than in the page itself, does not trigger click events and the like.

10.7.2. The title attribute

User agents are expected to expose the advisory information of elements upon user request, and to make the user aware of the presence of such information.

On interactive graphical systems where the user can use a pointing device, this could take the form of a tooltip. When the user is unable to use a pointing device, then the user agent is expected to make the content available in some other fashion, e.g., by making the element a focusable area and always displaying the advisory information of the currently focused element, or by showing the advisory information of the elements under the user’s finger on a touch device as the user pans around the screen.

U+000A LINE FEED (LF) characters are expected to cause line breaks in the tooltip; U+0009 CHARACTER TABULATION (tab) characters are expected to render as a non-zero horizontal shift that lines up the next glyph with the next tab stop, with tab stops occurring at points that are multiples of 8 times the width of a U+0020 SPACE character.

For example, a visual user agent could make elements with a title attribute focusable, and could make any focused element with a title attribute show its tooltip under the element while the element has focus. This would allow a user to tab around the document to find all the advisory text.
As another example, a screen reader could provide an audio cue when reading an element with a tooltip, with an associated key to read the last tooltip for which a cue was played.

10.7.3. Editing hosts

The current text editing caret (i.e., the active range, if it is empty and in an editing host), if any, is expected to act like an inline replaced element with the vertical dimensions of the caret and with zero width for the purposes of the CSS rendering model.

This means that even an empty block can have the caret inside it, and that when the caret is in such an element, it prevents margins from collapsing through the element.

10.7.4. Text rendered in native user interfaces

User agents are expected to honor the Unicode semantics of text that is exposed in user interfaces, for example supporting the bidirectional algorithm in text shown in dialogs, title bars, pop-up menus, and tooltips. Text from the contents of elements is expected to be rendered in a manner that honors the directionality of the element from which the text was obtained. Text from attributes is expected to be rendered in a manner that honours the directionality of the attribute.

Consider the following markup, which has Hebrew text asking for a programming language, the languages being text for which a left-to-right direction is important given the punctuation in some of their names:
<p dir="rtl" lang="he">
<label>
בחר שפת תכנות:
<select>
  <option dir="ltr">C++</option>
  <option dir="ltr">C#</option>
  <option dir="ltr">FreePascal</option>
  <option dir="ltr">F#</option>
</select>
</label>
</p>

If the select element was rendered as a drop down box, a correct rendering would ensure that the punctuation was the same both in the drop down, and in the box showing the current selection.

The directionality of attributes depends on the attribute and on the element’s dir attribute, as the following example demonstrates. Consider this markup:
<table>
<tr>
<th abbr="(א" dir=ltr>A
<th abbr="(א" dir=rtl>A
<th abbr="(א" dir=auto>A
</table>

If the abbr attributes are rendered, e.g., in a tooltip or other user interface, the first will have a left parenthesis (because the direction is ltr), the second will have a right parenthesis (because the direction is rtl), and the third will have a right parenthesis (because the direction is determined from the attribute value to be rtl).

However, if instead the attribute was not a directionality-capable attribute, the results would be different:

<table>
<tr>
<th>A
<th>A
<th>A
</table>

In this case, if the user agent were to expose the data-abbr attribute in the user interface (e.g., in a debugging environment), the last case would be rendered with a left parenthesis, because the direction would be determined from the element’s contents.

A string provided by a script (e.g., the argument to window.alert()) is expected to be treated as an independent set of one or more bidirectional algorithm paragraphs when displayed, as defined by the bidirectional algorithm, including, for instance, supporting the paragraph-breaking behavior of U+000A LINE FEED (LF) characters. For the purposes of determining the paragraph level of such text in the bidirectional algorithm, this specification does not provide a higher-level override of rules P2 and P3. [BIDI]

When necessary, authors can enforce a particular direction for a given paragraph by starting it with the Unicode U+200E LEFT-TO-RIGHT MARK or U+200F RIGHT-TO-LEFT MARK characters.

Thus, the following script:
alert('\u05DC\u05DE\u05D3 HTML \u05D4\u05D9\u05D5\u05DD!')

...would always result in a message reading "למד LMTH היום!" (not "דמל HTML םויה!"), regardless of the language of the user agent interface or the direction of the page or any of its elements.

For a more complex example, consider the following script:
/* Warning: this script does not handle right-to-left scripts correctly */
var s;
if (s = prompt('What is your name?')) {
  alert(s + '! Ok, Fred, ' + s + ', and Wilma will get the car.');
}

When the user enters "Kitty", the user agent would alert "Kitty! Ok, Fred, Kitty, and Wilma will get the car.". However, if the user enters "لا أفهم", then the bidirectional algorithm will determine that the direction of the paragraph is right-to-left, and so the output will be the following unintended mess: "لا أفهم! derF ,kO, لا أفهم, rac eht teg lliw amliW dna."

To force an alert that starts with user-provided text (or other text of unknown directionality) to render left-to-right, the string can be prefixed with a U+200E LEFT-TO-RIGHT MARK character:

var s;
if (s = prompt('What is your name?')) {
  alert('\u200E' + s + '! Ok, Fred, ' + s + ', and Wilma will get the car.');
}

User agents are expected to allow the user to request the opportunity to obtain a physical form (or a representation of a physical form) of a Document. For example, selecting the option to print a page or convert it to PDF format. [PDF]

When the user actually obtains a physical form (or a representation of a physical form) of a Document, the user agent is expected to create a new rendering of the Document for the print media.

10.9. Unstyled XML documents

HTML user agents may, in certain circumstances, find themselves rendering non-HTML documents that use vocabularies for which they lack any built-in knowledge. This section provides for a way for user agents to handle such documents in a somewhat useful manner.

While a Document is an unstyled document, the user agent is expected to render an unstyled document view.

A Document is an unstyled document while it matches the following conditions:

An unstyled document view is one where the DOM is not rendered according to CSS (which would, since there are no applicable styles in this context, just result in a wall of text), but is instead rendered in a manner that is useful for a developer. This could consist of just showing the Document object’s source, maybe with syntax highlighting, or it could consist of displaying just the DOM tree, or simply a message saying that the page is not a styled document.

If a Document stops being an unstyled document, then the conditions above stop applying, and thus a user agent following these requirements will switch to using the regular CSS rendering.

11. Obsolete features

11.1. Obsolete but conforming features

Features listed in this section will trigger warnings in conformance checkers.

Authors should not specify a border attribute on an img element. If the attribute is present, its value must be the string "0". CSS should be used instead.

Authors should not specify a language attribute on a script element. If the attribute is present, its value must be an ASCII case-insensitive match for the string "JavaScript" and either the type attribute must be omitted or its value must be an ASCII case-insensitive match for the string "text/javascript". The attribute should be entirely omitted instead (with the value "JavaScript", it has no effect), or replaced with use of the type attribute.

Authors should not specify the name attribute on a elements. If the attribute is present, its value must not be the empty string and must neither be equal to the value of any of the IDs in the element’s home subtree other than the element’s own id, if any, nor be equal to the value of any of the other name attributes on a elements in the element’s home subtree. If this attribute is present and the element has an id, then the attribute’s value must be equal to the element’s id. In earlier versions of the language, this attribute was intended as a way to specify possible targets for fragment identifiers in URLs. The id attribute should be used instead.

Authors should not, but may despite requirements to the contrary elsewhere in this specification, specify the maxlength and size attributes on input elements whose type attributes are in the Number state. One valid reason for using these attributes regardless is to help legacy user agents that do not support input elements with type="number" to still render the text field with a useful width.

In the HTML syntax, specifying a DOCTYPE that is an obsolete permitted DOCTYPE will also trigger a warning.

11.1.1. Warnings for obsolete but conforming features

To ease the transition from HTML Transitional documents to the language defined in this specification, and to discourage certain features that are only allowed in very few circumstances, conformance checkers must warn the user when the following features are used in a document. These are generally old obsolete features that have no effect, and are allowed only to distinguish between likely mistakes (regular conformance errors) and mere vestigial markup or unusual and discouraged practices (these warnings).

The following features must be categorized as described above:

Conformance checkers must distinguish between pages that have no conformance errors and have none of these obsolete features, and pages that have no conformance errors but do have some of these obsolete features.

For example, a validator could report some pages as "Valid HTML" and others as "Valid HTML with warnings".

11.2. Non-conforming features

Elements in the following list are entirely obsolete, and must not be used by authors:

applet

Use embed or object instead.

acronym

Use abbr instead.

bgsound

Use audio instead.

dir

Use ul instead.

frame

frameset

noframes

Either use iframe and CSS instead, or use server-side includes to generate complete pages with the various invariant parts merged in.

isindex

Use an explicit form and text field combination instead.

listing

Use pre and code instead.

nextid

Use GUIDs instead.

noembed

Use object instead of embed when fallback is necessary.

plaintext

Use the "text/plain" MIME type instead.

strike

Use del instead if the element is marking an edit, otherwise use s instead.

xmp

Use pre and code instead, and escape "<" and "&" characters as "&lt;" and "&amp;" respectively.

basefont

big

blink

center

font

marquee

multicol

nobr

spacer

tt

Use appropriate elements or CSS instead.

Where the tt element would have been used for marking up keyboard input, consider the kbd element; for variables, consider the var element; for computer code, consider the code element; and for computer output, consider the samp element.

Similarly, if the big element is being used to denote a heading, consider using the h1 element; if it is being used for marking up important passages, consider the strong element; and if it is being used for highlighting text for reference purposes, consider the mark element.

See also the text-level semantics usage summary for more suggestions with examples.


The following attributes are obsolete (though the elements are still part of the language), and must not be used by authors:

charset on a elements

charset on link elements

Use an HTTP Content-Type header on the linked resource instead.

coords on a elements

shape on a elements

Use area instead of a for image maps.

methods on a elements

methods on link elements

Use the HTTP OPTIONS feature instead.

name on a elements (except as noted in the previous section)

name on embed elements

name on img elements

name on option elements

Use the id attribute instead.

urn on a elements

urn on link elements

Specify the preferred persistent identifier using the href attribute instead.

accept on form elements

Use the accept attribute directly on the input elements instead.

type on area elements

These attributes do not do anything useful, and for historical reasons there are no corresponding IDL attributes on area elements. Omit them altogether.

nohref on area elements

Omitting the href attribute is sufficient; the nohref attribute is unnecessary. Omit it altogether.

profile on head elements

When used for declaring which meta terms are used in the document, unnecessary; omit it altogether, and register the names.

When used for triggering specific user agent behaviors: use a link element instead.

version on html elements

Unnecessary. Omit it altogether.

manifest on html elements

The use of application caches is not recommended. Alternative mechanisms to support offline applications include the use of [WEBSTORAGE], [IndexedDB], and [SERVICE-WORKERS].

ismap on input elements

Unnecessary. Omit it altogether. All input elements with a type attribute in the image button state are processed as server-side image maps.

usemap on input elements

Use img instead of input for image maps.

lowsrc on img elements

Use a progressive JPEG image (given in the src attribute), instead of using two separate images.

target on link elements

Unnecessary. Omit it altogether.

scheme on meta elements

Use only one scheme per field, or make the scheme declaration part of the value.

archive on object elements

classid on object elements

code on object elements

codebase on object elements

codetype on object elements

Use the data and type attributes to invoke plugins. To set parameters with these names in particular, the param element can be used.

declare on object elements

Repeat the object element completely each time the resource is to be reused.

standby on object elements

Optimize the linked resource so that it loads quickly or, at least, incrementally.

usemap on object elements

Use img instead of object for image maps.

type on param elements

valuetype on param elements

Use the name and value attributes without declaring value types.

language on script elements (except as noted in the previous section)

Use the type attribute instead.

event on script elements

for on script elements

Use DOM events mechanisms to register event listeners. [DOM]

media on source elements

Use script to select the media resource(s) to use.

datapagesize on table elements

Unnecessary. Omit it altogether.

summary on table elements

Use one of the §4.9.1.1 Techniques for describing tables given in the table section instead.

abbr on td elements

Use text that begins in an unambiguous and terse manner, and include any more elaborate text after that. The title attribute can also be useful in including more detailed text, so that the cell’s contents can be made terse. If it’s a heading, use th (which has an abbr attribute).

axis on td and th elements

Use the scope attribute on the relevant th.

scope on td elements

Use th elements for heading cells.

datasrc on a, applet, button, div, frame, iframe, img, input, label, legend, marquee, object, option, select, span, table, and textarea elements

datafld on a, applet, button, div, fieldset, frame, iframe, img, input, label, legend, marquee, object, param, select, span, and textarea elements

dataformatas on button, div, input, label, legend, marquee, object, option, select, span, and table elements

Use script and a mechanism such as XMLHttpRequest to populate the page dynamically. [XHR]

alink on body elements

bgcolor on body elements

bottommargin on body elements

leftmargin on body elements

link on body elements

marginheight on body elements

marginwidth on body elements

rightmargin on body elements

text on body elements

margintop on body elements

vlink on body elements

clear on br elements

align on caption elements

align on col elements

char on col elements

charoff on col elements

valign on col elements

width on col elements

align on div elements

compact on dl elements

align on embed elements

hspace on embed elements

vspace on embed elements

align on hr elements

color on hr elements

noshade on hr elements

size on hr elements

width on hr elements

align on h1h6 elements

align on iframe elements

allowtransparency on iframe elements

frameborder on iframe elements

framespacing on iframe elements

hspace on iframe elements

marginheight on iframe elements

marginwidth on iframe elements

scrolling on iframe elements

vspace on iframe elements

align on input elements

border on input elements

hspace on input elements

vspace on input elements

align on img elements

border on img elements (except as noted in the previous section)

hspace on img elements

vspace on img elements

align on legend elements

type on li elements

compact on menu elements

align on object elements

border on object elements

hspace on object elements

vspace on object elements

compact on ol elements

align on p elements

width on pre elements

align on table elements

bgcolor on table elements

border on table elements

bordercolor on table elements

cellpadding on table elements

cellspacing on table elements

frame on table elements

height on table elements

rules on table elements

width on table elements

align on tbody, thead, and tfoot elements

char on tbody, thead, and tfoot elements

charoff on tbody, thead, and tfoot elements

valign on tbody, thead, and tfoot elements

align on td and th elements

bgcolor on td and th elements

char on td and th elements

charoff on td and th elements

height on td and th elements

nowrap on td and th elements

valign on td and th elements

width on td and th elements

align on tr elements

bgcolor on tr elements

char on tr elements

charoff on tr elements

height on tr elements

valign on tr elements

compact on ul elements

type on ul elements

background on body, table, thead, tbody, tfoot, tr, td, and th elements

Use CSS instead.


The border attribute on the table element can be used to provide basic fallback styling for the purpose of making tables legible in browsing environments where CSS support is limited or absent, such as text-based browsers, WYSIWYG editors, and in situations where CSS support is disabled or the style sheet is lost. Only the empty string and the value "1" may be used as border values for this purpose. Other values are considered obsolete. To regulate the thickness of such borders, authors should instead use CSS.

11.3. Requirements for implementations

11.3.1. The applet element

This feature is in the process of being removed from the Web platform. (This is a long process that takes many years.) Using the applet element at this time is highly discouraged.

The applet element is a Java-specific variant of the embed element. The applet element is now obsoleted so that all extension frameworks (Java, .NET, Flash, etc) are handled in a consistent manner.

When the element matches any of the following conditions, it represents its contents:

Otherwise, the user agent should instantiate a Java Language runtime plugin, and should pass the names and values of all the attributes on the element, in the order they were added to the element, with the attributes added by the parser being ordered in source order, and then a parameter named "PARAM" whose value is null, and then all the names and values of parameters given by param elements that are children of the applet element, in tree order, to the plugin used. If the plugin supports a scriptable interface, the HTMLAppletElement object representing the element should expose that interface. The applet element represents the plugin.

The applet element is unaffected by the CSS display property. The Java Language runtime is instantiated even if the element is hidden with a 'display:none' CSS style.

The applet element must implement the HTMLAppletElement interface.

interface HTMLAppletElement : HTMLElement {
  attribute DOMString align;
  attribute DOMString alt;
  attribute DOMString archive;
  attribute DOMString code;
  attribute DOMString codeBase;
  attribute DOMString height;
  attribute unsigned long hspace;
  attribute DOMString name;
  attribute DOMString _object; // the underscore is not part of the identifier
  attribute unsigned long vspace;
  attribute DOMString width;
};

The align, alt, archive, code, height, hspace, name, object, vspace, and width IDL attributes must reflect the respective content attributes of the same name. For the purposes of reflection, the applet element’s object content attribute is defined as containing a URL.

The codeBase IDL attribute must reflect the codebase content attribute, which for the purposes of reflection is defined as containing a URL.

11.3.2. The marquee element

The marquee element is a presentational element that animates content. CSS transitions and animations are a more appropriate mechanism. [CSS3-ANIMATIONS] [CSS3-TRANSITIONS]

The task source for tasks mentioned in this section is the DOM manipulation task source.

The marquee element must implement the HTMLMarqueeElement interface.

interface HTMLMarqueeElement : HTMLElement {
  attribute DOMString behavior;
  attribute DOMString bgColor;
  attribute DOMString direction;
  attribute DOMString height;
  attribute unsigned long hspace;
  attribute long loop;
  attribute unsigned long scrollAmount;
  attribute unsigned long scrollDelay;
  attribute boolean trueSpeed;
  attribute unsigned long vspace;
  attribute DOMString width;

  attribute EventHandler onbounce;
  attribute EventHandler onfinish;
  attribute EventHandler onstart;

  void start();
  void stop();
};

A marquee element can be turned on or turned off. When it is created, it is turned on.

When the start() method is called, the marquee element must be turned on.

When the stop() method is called, the marquee element must be turned off.

When a marquee element is created, the user agent must queue a task to fire a simple event named start at the element.


The behavior content attribute on marquee elements is an enumerated attribute with the following keywords (all non-conforming):

Keyword State
scroll scroll
slide slide
alternate alternate

The missing value default is the scroll state.


The direction content attribute on marquee elements is an enumerated attribute with the following keywords (all non-conforming):

Keyword State
left left
right right
up up
down down

The missing value default is the left state.


The truespeed content attribute on marquee elements is a boolean attribute.


A marquee element has a marquee scroll interval, which is obtained as follows:

  1. If the element has a scrolldelay content attribute, and parsing its value using the rules for parsing non-negative integers does not return an error, then let delay be the parsed value. Otherwise, let delay be 85.

  2. If the element does not have a truespeed attribute, and the delay value is less than 60, then let delay be 60 instead.

  3. The marquee scroll interval is delay, interpreted in milliseconds.


A marquee element has a marquee scroll distance, which, if the element has a scrollamount content attribute, and parsing its value using the rules for parsing non-negative integers does not return an error, is the parsed value interpreted in CSS pixels, and otherwise is 6 CSS pixels.


A marquee element has a marquee loop count, which, if the element has a loop content attribute, and parsing its value using the rules for parsing integers does not return an error or a number less than 1, is the parsed value, and otherwise is -1.

The loop IDL attribute, on getting, must return the element’s marquee loop count; and on setting, if the new value is different than the element’s marquee loop count and either greater than zero or equal to -1, must set the element’s loop content attribute (adding it if necessary) to the valid integer that represents the new value. (Other values are ignored.)

A marquee element also has a marquee current loop index, which is zero when the element is created.

The rendering layer will occasionally increment the marquee current loop index, which must cause the following steps to be run:

  1. If the marquee loop count is -1, then abort these steps.

  2. Increment the marquee current loop index by one.

  3. If the marquee current loop index is now equal to or greater than the element’s marquee loop count, turn off the marquee element and queue a task to fire a simple event named finish at the marquee element.

    Otherwise, if the behavior attribute is in the alternate state, then queue a task to fire a simple event named bounce at the marquee element.

    Otherwise, queue a task to fire a simple event named start at the marquee element.


The following are the event handlers (and their corresponding event handler event types) that must be supported, as event handler content attributes and event handler IDL attributes, by marquee elements:

Event handler Event handler event type
onbounce bounce
onfinish finish
onstart start

The behavior, direction, height, hspace, vspace, and width IDL attributes must reflect the respective content attributes of the same name.

The bgColor IDL attribute must reflect the bgcolor content attribute.

The scrollAmount IDL attribute must reflect the scrollamount content attribute. The default value is 6.

The scrollDelay IDL attribute must reflect the scrolldelay content attribute. The default value is 85.

The trueSpeed IDL attribute must reflect the truespeed content attribute.

11.3.3. Frames

The frameset element acts as the body element in documents that use frames.

The frameset element must implement the HTMLFrameSetElement interface.

interface HTMLFrameSetElement : HTMLElement {
  attribute DOMString cols;
  attribute DOMString rows;
};
HTMLFrameSetElement implements WindowEventHandlers;

The cols and rows IDL attributes of the frameset element must reflect the respective content attributes of the same name.

The frameset element exposes as event handler content attributes a number of the event handlers of the Window object. It also mirrors their event handler IDL attributes.

The onblur, onerror, onfocus, onload, onresize, and onscroll event handlers of the Window object, exposed on the frameset element, replace the generic event handlers with the same names normally supported by html elements.


The frame element defines a nested browsing context similar to the iframe element, but rendered within a frameset element.

A frame element is said to be an active frame element when it is in a Document.

When a frame element is created as an active frame element, or becomes an active frame element after not having been one, the user agent must create a nested browsing context, and then process the frame attributes for the first time.

When a frame element stops being an active frame element, the user agent must discard the nested browsing context.

Whenever a frame element with a nested browsing context has its src attribute set, changed, or removed, the user agent must process the frame attributes.

When the user agent is to process the frame attributes, it must run the first appropriate steps from the following list:

If the element has no src attribute specified, and the user agent is processing the frame's attributes for the first time
Queue a task to fire a simple event named load at the frame element.
Otherwise
  1. If the value of the src attribute is the empty string, let url be the string "about:blank".

    Otherwise, resolve the value of the src attribute, relative to the frame element.

    If that is not successful, then let url be the string "about:blank". Otherwise, let url be the resulting absolute URL.

  2. Navigate the element’s child browsing contextto url.

Furthermore, if the active document of the element’s child browsing context before such a navigation was not completely loaded at the time of the new navigation, then the navigation must be completed with replacement enabled.

Similarly, if the child browsing context’s session history contained only one Document when the process the frame attributes algorithm was invoked, and that was the about:blank Document created when the child browsing context was created, then any navigation required of the user agent in that algorithm must be completed with replacement enabled.

When a Document in a frame is marked as completely loaded, the user agent must queue a task to fire a simple event named load at the frame element.

The task source for the tasks above is the DOM manipulation task source.

When a frame element’s nested browsing context’s active document is not ready for post-load tasks, and when anything is delaying the load event of the frame element’s browsing context’s active document, and when the frame element’s browsing context is in the delaying load events mode, the frame must delay the load event of its document.

When the browsing context is created, if a name content attribute is present, the browsing context name must be set to the value of this attribute; otherwise, the browsing context name must be set to the empty string.

Whenever the name attribute is set, the nested browsing context’s name must be changed to the new value. If the attribute is removed, the browsing context name must be set to the empty string.

The frame element must implement the HTMLFrameElement interface.

interface HTMLFrameElement : HTMLElement {
  attribute DOMString name;
  attribute DOMString scrolling;
  attribute DOMString src;
  attribute DOMString frameBorder;
  attribute boolean noResize;
  readonly attribute Document? contentDocument;
  readonly attribute WindowProxy? contentWindow;

  [TreatNullAs=EmptyString] attribute DOMString marginHeight;
  [TreatNullAs=EmptyString] attribute DOMString marginWidth;
};

The name, scrolling, and src IDL attributes of the frame element must reflect the respective content attributes of the same name. For the purposes of reflection, the frame element’s src content attribute is defined as containing a URL.

The frameBorder IDL attribute of the frame element must reflect the element’s frameborder content attribute.

The noResize IDL attribute of the frame element must reflect the element’s noresize content attribute.

The contentDocument IDL attribute of the frame element must return the Document object of the active document of the frame element’s nested browsing context, if any and if its origin is the same origin-domain as the origin specified by the incumbent settings object, or null otherwise.

The contentWindow IDL attribute must return the WindowProxy object of the frame element’s nested browsing context.

The marginHeight IDL attribute of the frame element must reflect the element’s marginheight content attribute.

The marginWidth IDL attribute of the frame element must reflect the element’s marginwidth content attribute.

11.3.4. Application caches

An application cache is a set of cached resources consisting of:

Each application cache has a completeness flag, which is either complete or incomplete.


An application cache group is a group of application caches, identified by the absolute URL of a resource manifest which is used to populate the caches in the group.

An application cache is newer than another if it was created after the other (in other words, application caches in an application cache group have a chronological order).

Only the newest application cache in an application cache group can have its completeness flag set to incomplete; the others are always all complete.

Each application cache group has an update status, which is one of the following: idle, checking, downloading.

A relevant application cache is an application cache that is the newest in its group to be complete.

Each application cache group has a list of pending master entries. Each entry in this list consists of a resource and a corresponding Document object. It is used during the application cache download process to ensure that new master entries are cached even if the application cache download process was already running for their application cache group when they were loaded.

An application cache group can be marked as obsolete, meaning that it must be ignored when looking at what application cache groups exist.


A cache host is a Document or a SharedWorkerGlobalScope object. A cache host can be associated with an application cache.

[WEBWORKERS]

A Document initially is not associated with an application cache, but can become associated with one early during the page load process, when steps in the parser and in the navigation sections cause cache selection to occur.

A SharedWorkerGlobalScope can be associated with an application cache when it is created.

[WEBWORKERS]

Each cache host has an associated ApplicationCache object.


Multiple application caches in different application cache groups can contain the same resource, e.g., if the manifests all reference that resource. If the user agent is to select an application cache from a list of relevant application caches that contain a resource, the user agent must use the application cache that the user most likely wants to see the resource from, taking into account the following:


A URL matches a fallback namespace if there exists a relevant application cache whose manifest’s URL has the same origin as the URL in question, and that has a fallback namespace that is a prefix match for the URL being examined. If multiple fallback namespaces match the same URL, the longest one is the one that matches. A URL looking for a fallback namespace can match more than one application cache at a time, but only matches one namespace in each cache.

11.3.4.1. Parsing cache manifests

When a user agent is to parse a manifest, it means that the user agent must run the following steps:

  1. UTF-8 decode the byte stream corresponding with the manifest to be parsed.

    The UTF-8 decode algorithm strips a leading BOM, if any.

  2. Let base URL be the absolute URL representing the manifest.
  3. Apply the URL parser to base URL, and let manifest path be the path component thus obtained.
  4. Remove all the characters in manifest path after the last U+002F SOLIDUS character (/), if any. (The first character and the last character in manifest path after this step will both be slashes, the URL path separator character.)
  5. Apply the URL parser steps to the base URL, so that the components from its URL record can be used by the subsequent steps of this algorithm.
  6. Let explicit URLs be an initially empty list of absolute URLs for explicit entries.
  7. Let fallback URLs be an initially empty mapping of fallback namespaces to absolute URLs for fallback entries.
  8. Let online safelist namespaces be an initially empty list of absolute URLs for an online safelist.
  9. Let online safelist wildcard flag be blocking.
  10. Let cache mode flag be fast.
  11. Let input be the decoded text of the manifest’s byte stream.
  12. Let position be a pointer into input, initially pointing at the first character.
  13. If the characters starting from position are "CACHE", followed by a U+0020 SPACE character, followed by "MANIFEST", then advance position to the next character after those. Otherwise, this isn’t a cache manifest; abort this algorithm with a failure while checking for the magic signature.
  14. If the character at position is neither a U+0020 SPACE character, a U+0009 CHARACTER TABULATION (tab) character, U+000A LINE FEED (LF) character, nor a U+000D CARRIAGE RETURN (CR) character, then this isn’t a cache manifest; abort this algorithm with a failure while checking for the magic signature.
  15. This is a cache manifest. The algorithm cannot fail beyond this point (though bogus lines can get ignored).
  16. Collect a sequence of characters that are not U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters, and ignore those characters. (Extra text on the first line, after the signature, is ignored.)
  17. Let mode be "explicit".
  18. Start of line: If position is past the end of input, then jump to the last step. Otherwise, collect a sequence of characters that are U+000A LINE FEED (LF), U+000D CARRIAGE RETURN (CR), U+0020 SPACE, or U+0009 CHARACTER TABULATION (tab) characters.
  19. Now, collect a sequence of characters that are not U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters, and let the result be line.
  20. Drop any trailing U+0020 SPACE and U+0009 CHARACTER TABULATION (tab) characters at the end of line.
  21. If line is the empty string, then jump back to the step labeled start of line.
  22. If the first character in line is a U+0023 NUMBER SIGN character (#), then jump back to the step labeled Start of line.
  23. If line equals "CACHE:" (the word "CACHE" followed by a U+003A COLON character (:)), then set mode to "explicit" and jump back to the step labeled Start of line.
  24. If line equals "FALLBACK:" (the word "FALLBACK" followed by a U+003A COLON character (:)), then set mode to "fallback" and jump back to the step labeled Start of line.
  25. If line equals "NETWORK:" (the word "NETWORK" followed by a U+003A COLON character (:)), then set mode to "online safelist" and jump back to the step labeled Start of line.
  26. If line equals "SETTINGS:" (the word "SETTINGS" followed by a U+003A COLON character (:)), then set mode to "settings" and jump back to the step labeled Start of line.
  27. If line ends with a U+003A COLON character (:), then set mode to "unknown" and jump back to the step labeled Start of line.
  28. This is either a data line or it is syntactically incorrect.
  29. Let position be a pointer into line, initially pointing at the start of the string.
  30. Let tokens be a list of strings, initially empty.
  31. While position doesn’t point past the end of line:

    1. Let current token be an empty string.
    2. While position doesn’t point past the end of line and the character at position is neither a U+0020 SPACE nor a U+0009 CHARACTER TABULATION (tab) character, add the character at position to current token and advance position to the next character in input.
    3. Add current token to the tokens list.
    4. While position doesn’t point past the end of line and the character at position is either a U+0020 SPACE or a U+0009 CHARACTER TABULATION (tab) character, advance position to the next character in input.
  32. Process tokens as follows:

    If mode is "explicit"

    Let urlRecord be the result of parsing the first item in tokens, with base URL; ignore the rest.

    If urlRecord is failure, then jump back to the step labeled Start of line.

    If urlRecord has a different scheme component than base URL (the manifest’s URL), then jump back to the step labeled Start of line.

    Let new URL be the result of applying the URL serializer algorithm to urlRecord, with the exclude fragment flag set.

    Add new URL to the explicit URLs.

    If mode is "fallback"
    Let part one be the first token in tokens, and let part two be the second token in tokens.

    Let urlRecordOne be the result of parsing part one with base URL.

    Let urlRecordTwo be the result of parsing part two with base URL.

    If either urlRecordOne or urlRecordTwo is failure, then jump back to the step labeled Start of line.

    If the origin of either urlRecordOne or urlRecordTwo is not same origin with the manifest’s URL origin, then jump back to the step labeled Start of line.

    Let part one path be the path component of urlRecordOne.

    If manifest path is not a prefix match for part one path, then jump back to the step labeled Start of line.

    Let part one be the result of applying the URL serializer algorithm to urlRecordOne, with the exclude fragment flag set.

    Let part two be the result of applying the URL serializer algorithm to urlRecordTwo, with the exclude fragment flag set.

    If part one is already in the fallback URLs mapping as a fallback namespace, then jump back to the step labeled Start of line.

    Otherwise, add part one to the fallback URLs mapping as a fallback namespace, mapped to part two as the fallback entry.

    If mode is "online safelist"

    If the first item in tokens is a U+002A ASTERISK character (*), then set online safelist wildcard flag to open and jump back to the step labeled Start of line.

    Otherwise, let urlRecord be the result of parsing the first item in tokens with base URL.

    If urlRecord is failure, then jump back to the step labeled Start of line.

    If urlRecord has a different scheme component than base URL (the manifest’s URL), then jump back to the step labeled Start of line.

    Let new URL be the result of applying the URL serializer algorithm to urlRecord, with the exclude fragment flag set.

    Add new URL to the online safelist namespaces.

    If mode is "settings"

    If tokens contains a single token, and that token is a case-sensitive match for the string "prefer-online", then set cache mode flag to prefer-online and jump back to the step labeled Start of line.

    Otherwise, the line is an unsupported setting: do nothing; the line is ignored.

    If mode is "unknown"

    Do nothing. The line is ignored.

  33. Jump back to the step labeled Start of line. (That step jumps to the next, and last, step when the end of the file is reached.)
  34. Return the explicit URLs list, the fallback URLs mapping, the online safelist namespaces, the online safelist wildcard flag, and the cache mode flag.
11.3.4.2. Downloading or updating an application cache

When the user agent is required (by other parts of this specification) to start the application cache download process for an absolute URL purported to identify a manifest, or for an application cache group, potentially given a particular cache host, and potentially given a master resource, the user agent must run the steps below. These steps are always run in parallel with the event loop tasks.

Some of these steps have requirements that only apply if the user agent shows caching progress. Support for this is optional. Certain events fired during the application cache download process allow the script to override the display of such an interface. (Such events are delayed until after the load event has fired.)

User agents are encouraged not to show prominent update progress notifications for applications that cancel the relevant events.

The application cache download process steps are as follows:

  1. Optionally, wait until the permission to start the application cache download process has been obtained from the user and until the user agent is confident that the network is available. This could include doing nothing until the user explicitly opts-in to caching the site, or could involve prompting the user for permission. The algorithm might never get past this point. (This step is particularly intended to be used by user agents running on severely space-constrained devices or in highly privacy-sensitive environments).
  2. Atomically, so as to avoid race conditions, perform the following substeps:

    1. Pick the appropriate substeps:

      If these steps were invoked with an absolute URL purported to identify a manifest

      Let manifest URL be that absolute URL.

      If there is no application cache group identified by manifest URL, then create a new application cache group identified by manifest URL. Initially, it has no application caches. One will be created later in this algorithm.

      If these steps were invoked with an application cache group

      Let manifest URL be the absolute URL of the manifest used to identify the application cache group to be updated.

      If that application cache group is obsolete, then abort this instance of the application cache download process. This can happen if another instance of this algorithm found the manifest to be 404 or 410 while this algorithm was waiting in the first step above.

    2. Let cache group be the application cache group identified by manifest URL.
    3. If these steps were invoked with a master resource, then add the resource, along with the resource’s Document, to cache group’s list of pending master entries.
    4. If these steps were invoked with a cache host, and the status of cache group is checking or downloading, then queue a post-load task to fire a simple event named checking that is cancelable at the ApplicationCache singleton of that cache host. The default action of this event must be, if the user agent shows caching progress, the display of some sort of user interface indicating to the user that the user agent is checking to see if it can download the application.
    5. If these steps were invoked with a cache host, and the status of cache group is downloading, then also queue a post-load task to fire a simple event named downloading that is cancelable at the ApplicationCache singleton of that cache host. The default action of this event must be, if the user agent shows caching progress, the display of some sort of user interface indicating to the user the application is being downloaded.
    6. If the status of the cache group is either checking or downloading, then abort this instance of the application cache download process, as an update is already in progress.
    7. Set the status of cache group to checking.
    8. For each cache host associated with an application cache in cache group, queue a post-load task to fire a simple event that is cancelable named checking at the ApplicationCache singleton of the cache host. The default action of these events must be, if the user agent shows caching progress, the display of some sort of user interface indicating to the user that the user agent is checking for the availability of updates.

    The remainder of the steps run in parallel.

    If cache group already has an application cache in it, then this is an upgrade attempt. Otherwise, this is a cache attempt.

  3. If this is a cache attempt, then this algorithm was invoked with a cache host; queue a post-load task to fire a simple event named checking that is cancelable at the ApplicationCache singleton of that cache host. The default action of this event must be, if the user agent shows caching progress, the display of some sort of user interface indicating to the user that the user agent is checking for the availability of updates.
  4. Let request be a new request whose URL is manifest URL, client is null, destination is "subresource", omit-Origin-header flag is set, referrer is "no-referrer", synchronous flag is set, credentials mode is "include", and whose use-URL-credentials flag is set.
  5. Fetching the manifest: Let manifest be the result of fetching request. HTTP caching semantics should be honored for this request.

    Parse manifest’s body according to the rules for parsing manifests, obtaining a list of explicit entries, fallback entries and the fallback namespaces that map to them, entries for the online safelist, and values for the online safelist wildcard flag and the cache mode flag.

    The MIME type of the resource is ignored — it is assumed to be text/cache-manifest. In the future, if new manifest formats are supported, the different types will probably be distinguished on the basis of the file signatures (for the current format, that is the "CACHE MANIFEST" string at the top of the file).

  6. If fetching the manifest fails due to a 404 or 410 response status, then run these substeps:

    1. Mark cache group as obsolete. This cache group no longer exists for any purpose other than the processing of Document objects already associated with an application cache in the cache group.
    2. Let task list be an empty list of tasks.
    3. For each cache host associated with an application cache in cache group, create a task to fire a simple event named obsolete that is cancelable at the ApplicationCache singleton of the cache host, and append it to task list. The default action of these events must be, if the user agent shows caching progress, the display of some sort of user interface indicating to the user that the application is no longer available for offline use.
    4. For each entry in cache group’s list of pending master entries, create a task to fire a simple event that is cancelable named error (not obsolete!) at the ApplicationCache singleton of the Document for this entry, if there still is one, and append it to task list. The default action of this event must be, if the user agent shows caching progress, the display of some sort of user interface indicating to the user that the user agent failed to save the application for offline use.
    5. If cache group has an application cache whose completeness flag is incomplete, then discard that application cache.
    6. If appropriate, remove any user interface indicating that an update for this cache is in progress.
    7. Let the status of cache group be idle.
    8. For each task in task list, queue that task as a post-load task.
    9. Abort the application cache download process.
  7. Otherwise, if fetching the manifest fails in some other way (e.g., the server returns another 4xx or 5xx response, or there is a DNS error, or the connection times out, or the user cancels the download, or the parser for manifests fails when checking the magic signature), or if the server returned a redirect, then run the cache failure steps. [HTTP]

  8. If this is an upgrade attempt and the newly downloaded manifest is byte-for-byte identical to the manifest found in the newest application cache in cache group, or the response status is 304, then run these substeps:

    1. Let cache be the newest application cache in cache group.
    2. Let task list be an empty list of tasks.
    3. For each entry in cache group’s list of pending master entries, wait for the resource for this entry to have either completely downloaded or failed.

      If the download failed (e.g., the server returns a 4xx or 5xx response, or there is a DNS error, the connection times out, or the user cancels the download), or if the resource is labeled with the "no-store" cache directive, then create a task to fire a simple event that is cancelable named error at the ApplicationCache singleton of the Document for this entry, if there still is one, and append it to task list. The default action of this event must be, if the user agent shows caching progress, the display of some sort of user interface indicating to the user that the user agent failed to save the application for offline use.

      Otherwise, associate the Document for this entry with cache; store the resource for this entry in cache, if it isn’t already there, and categorize its entry as a master entry. If applying the URL parser algorithm to the resource’s URL results in a resulting URL record that has a non-null fragment component, the URL used for the entry in cache must instead be the absolute URL obtained from applying the URL serializer algorithm to the resulting URL record with the exclude fragment flag set (application caches never include fragment identifiers).

    4. For each cache host associated with an application cache in cache group, create a task to fire a simple event that is cancelable named noupdate at the ApplicationCache singleton of the cache host, and append it to task list. The default action of these events must be, if the user agent shows caching progress, the display of some sort of user interface indicating to the user that the application is up to date.
    5. Empty cache group’s list of pending master entries.
    6. If appropriate, remove any user interface indicating that an update for this cache is in progress.
    7. Let the status of cache group be idle.
    8. For each task in task list, queue that task as a post-load task.
    9. Abort the application cache download process.
  9. Let new cache be a newly created application cache in cache group. Set its completeness flag to incomplete.
  10. For each entry in cache group’s list of pending master entries, associate the Document for this entry with new cache.
  11. Set the status of cache group to downloading.
  12. For each cache host associated with an application cache in cache group, queue a post-load task to fire a simple event that is cancelable named downloading at the ApplicationCache singleton of the cache host. The default action of these events must be, if the user agent shows caching progress, the display of some sort of user interface indicating to the user that a new version is being downloaded.
  13. Let file list be an empty list of URLs with flags.
  14. Add all the URLs in the list of explicit entries obtained by parsing manifest to file list, each flagged with "explicit entry".
  15. Add all the URLs in the list of fallback entries obtained by parsing manifest to file list, each flagged with "fallback entry".
  16. If this is an upgrade attempt, then add all the URLs of master entries in the newest application cache in cache group whose completeness flag is complete to file list, each flagged with "master entry".
  17. If any URL is in file list more than once, then merge the entries into one entry for that URL, that entry having all the flags that the original entries had.
  18. For each URL in file list, run the following steps. These steps may be run in parallel for two or more of the URLs at a time. If, while running these steps, the ApplicationCache object’s abort() method sends a signal to this instance of the application cache download process algorithm, then run the cache failure steps instead.

    1. If the resource URL being processed was flagged as neither an "explicit entry" nor or a "fallback entry", then the user agent may skip this URL.

      This is intended to allow user agents to expire resources not listed in the manifest from the cache. Generally, implementors are urged to use an approach that expires lesser-used resources first.

    2. For each cache host associated with an application cache in cache group, queue a progress post-load task to fire a trusted event with the name progress, which does not bubble, which is cancelable, and which uses the ProgressEvent interface, at the ApplicationCache singleton of the cache host. The lengthComputable attribute must be set to true, the total attribute must be set to the number of files in file list, and the loaded attribute must be set to the number of files in file list that have been either downloaded or skipped so far. The default action of these events must be, if the user agent shows caching progress, the display of some sort of user interface indicating to the user that a file is being downloaded in preparation for updating the application. [XHR]
    3. Let request be a new request whose URL is URL, client is null, destination is "subresource", origin is manifest URL’s origin, referrer is "no-referrer", synchronous flag is set, credentials mode is "include", use-URL-credentials flag is set, and redirect mode is "manual".
    4. Fetch request. If this is an upgrade attempt, then use the newest application cache in cache group as an HTTP cache, and honor HTTP caching semantics (such as expiration, ETags, and so forth) with respect to that cache. User agents may also have other caches in place that are also honored.
    5. If the previous step fails (e.g., the server returns a 4xx or 5xx response, or there is a DNS error, or the connection times out, or the user cancels the download), or if the server returned a redirect, or if the resource is labeled with the "no-store" cache directive, then run the first appropriate step from the following list: [HTTP]

      If the URL being processed was flagged as an "explicit entry" or a "fallback entry"

      If these steps are being run in parallel for any other URLs in file list, then abort these steps for those other URLs. Run the cache failure steps.

      Redirects are fatal because they are either indicative of a network problem (e.g., a captive portal); or would allow resources to be added to the cache under URLs that differ from any URL that the networking model will allow access to, leaving orphan entries; or would allow resources to be stored under URLs different than their true URLs. All of these situations are bad.

      If the error was a 404 or 410 HTTP response
      If the resource was labeled with the "no-store" cache directive

      Skip this resource. It is dropped from the cache.

      Otherwise

      Copy the resource and its metadata from the newest application cache in cache group whose completeness flag is complete, and act as if that was the fetched resource, ignoring the resource obtained from the network.

      These rules make errors for resources listed in the manifest fatal, while making it possible for other resources to be removed from caches when they are removed from the server, without errors, and making non-manifest resources survive server-side errors.

      Except for the "no-store" directive, HTTP caching rules that would cause a file to be expired or otherwise not cached are ignored for the purposes of the application cache download process.

    6. Otherwise, the fetching succeeded. Store the resource in the new cache.

      If the user agent is not able to store the resource (e.g., because of quota restrictions), the user agent may prompt the user or try to resolve the problem in some other manner (e.g., automatically pruning content in other caches). If the problem cannot be resolved, the user agent must run the cache failure steps.

    7. If the URL being processed was flagged as an "explicit entry" in file list, then categorize the entry as an explicit entry.
    8. If the URL being processed was flagged as a "fallback entry" in file list, then categorize the entry as a fallback entry.
    9. If the URL being processed was flagged as an "master entry" in file list, then categorize the entry as a master entry.
    10. As an optimization, if the resource is an HTML or XML file whose root element is an html element with a manifest attribute whose value doesn’t match the manifest URL of the application cache being processed, then the user agent should mark the entry as being foreign.
  19. For each cache host associated with an application cache in cache group, queue a progress post-load task to fire a trusted event with the name progress, which does not bubble, which is cancelable, and which uses the ProgressEvent interface, at the ApplicationCache singleton of the cache host. The lengthComputable attribute must be set to true, the total and the loaded attributes must be set to the number of files in file list. The default action of these events must be, if the user agent shows caching progress, the display of some sort of user interface indicating to the user that all the files have been downloaded. [XHR]
  20. Store the list of fallback namespaces, and the URLs of the fallback entries that they map to, in new cache.
  21. Store the URLs that form the new online safelist in new cache.
  22. Store the value of the new online safelist wildcard flag in new cache.
  23. Store the value of the new cache mode flag in new cache.
  24. For each entry in cache group’s list of pending master entries, wait for the resource for this entry to have either completely downloaded or failed.

    If the download failed (e.g., the server returns a 4xx or 5xx response, or there is a DNS error, the connection times out, or the user cancels the download), or if the resource is labeled with the "no-store" cache directive, then run these substeps:

    1. Unassociate the Document for this entry from new cache.
    2. Queue a post-load task to fire a simple event that is cancelable named error at the ApplicationCache singleton of the Document for this entry, if there still is one. The default action of this event must be, if the user agent shows caching progress, the display of some sort of user interface indicating to the user that the user agent failed to save the application for offline use.
    3. If this is a cache attempt and this entry is the last entry in cache group’s list of pending master entries, then run these further substeps:

      1. Discard cache group and its only application cache, new cache.
      2. If appropriate, remove any user interface indicating that an update for this cache is in progress.
      3. Abort the application cache download process.
    4. Otherwise, remove this entry from cache group’s list of pending master entries.

    Otherwise, store the resource for this entry in new cache, if it isn’t already there, and categorize its entry as a master entry.

  25. Let request be a new request whose URL is manifest URL, client is null, destination is "subresource", referrer is "no-referrer", synchronous flag is set, credentials mode is "include", and whose use-URL-credentials flag is set.
  26. Let second manifest be the result of fetching request. HTTP caching semantics should again be honored for this request.

  27. If the previous step failed for any reason, or if the fetching attempt involved a redirect, or if second manifest and manifest are not byte-for-byte identical, then schedule a rerun of the entire algorithm with the same parameters after a short delay, and run the cache failure steps.

  28. Otherwise, store manifest in new cache, if it’s not there already, and categorize its entry as the manifest.

  29. Set the completeness flag of new cache to complete.
  30. Let task list be an empty list of tasks.
  31. If this is a cache attempt, then for each cache host associated with an application cache in cache group, create a task to fire a simple event that is cancelable named cached at the ApplicationCache singleton of the cache host, and append it to task list. The default action of these events must be, if the user agent shows caching progress, the display of some sort of user interface indicating to the user that the application has been cached and that they can now use it offline.

    Otherwise, it is an upgrade attempt. For each cache host associated with an application cache in cache group, create a task to fire a simple event that is cancelable named updateready at the ApplicationCache singleton of the cache host, and append it to task list. The default action of these events must be, if the user agent shows caching progress, the display of some sort of user interface indicating to the user that a new version is available and that they can activate it by reloading the page.

  32. If appropriate, remove any user interface indicating that an update for this cache is in progress.
  33. Set the update status of cache group to idle.
  34. For each task in task list, queue that task as a post-load task.

The cache failure steps are as follows:

  1. Let task list be an empty list of tasks.
  2. For each entry in cache group’s list of pending master entries, run the following further substeps. These steps may be run in parallel for two or more entries at a time.

    1. Wait for the resource for this entry to have either completely downloaded or failed.
    2. Unassociate the Document for this entry from its application cache, if it has one.
    3. Create a task to fire a simple event that is cancelable named error at the ApplicationCache singleton of the Document for this entry, if there still is one, and append it to task list. The default action of these events must be, if the user agent shows caching progress, the display of some sort of user interface indicating to the user that the user agent failed to save the application for offline use.
  3. For each cache host still associated with an application cache in cache group, create a task to fire a simple event that is cancelable named error at the ApplicationCache singleton of the cache host, and append it to task list. The default action of these events must be, if the user agent shows caching progress, the display of some sort of user interface indicating to the user that the user agent failed to save the application for offline use.
  4. Empty cache group’s list of pending master entries.
  5. If cache group has an application cache whose completeness flag is incomplete, then discard that application cache.
  6. If appropriate, remove any user interface indicating that an update for this cache is in progress.
  7. Let the status of cache group be idle.
  8. If this was a cache attempt, discard cache group altogether.
  9. For each task in task list, queue that task as a post-load task.
  10. Abort the application cache download process.

Attempts to fetch resources as part of the application cache download process may be done with cache-defeating semantics, to avoid problems with stale or inconsistent intermediary caches.


User agents may invoke the application cache download process, in the background, for any application cache group, at any time (with no cache host). This allows user agents to keep caches primed and to update caches even before the user visits a site.


Each Document has a list of pending application cache download process tasks that is used to delay events fired by the algorithm above until the document’s load event has fired. When the Document is created, the list must be empty.

When the steps above say to queue a post-load task task, where task is a task that dispatches an event on a target ApplicationCache object target, the user agent must run the appropriate steps from the following list:

If target’s node document is ready for post-load tasks
Queue the task task.
Otherwise
Add task to target’s node document’s list of pending application cache download process tasks.

When the steps above say to queue a progress post-load task task, where task is a task that dispatches an event on a target ApplicationCache object target, the user agent must run the following steps:

  1. If there is a task in target’s node document’s list of pending application cache download process tasks that is labeled as a progress task, then remove that task from the list.
  2. Label task as a progress task.
  3. Queue a post-load task task.

The task source for these tasks is the networking task source.

11.3.4.3. The application cache selection algorithm

When the application cache selection algorithm algorithm is invoked with a Document document and optionally a manifest URL manifest URL, the user agent must run the first applicable set of steps from the following list:

If there is a manifest URL, and document was loaded from an application cache, and the URL of the manifest of that cache’s application cache group is not the same as manifest URL

Mark the entry for the resource from which document was taken in the application cache from which it was loaded as foreign.

Restart the current navigation from the top of the navigation algorithm, undoing any changes that were made as part of the initial load (changes can be avoided by ensuring that the step to update the session history with the new page is only ever completed after this application cache selection algorithm is run, though this is not required).

If document was loaded from an application cache, and that application cache still exists (it is not now obsolete)

Associate document with the application cache from which it was loaded. Invoke, in the background, the application cache download process for that application cache’s application cache group, with document as the cache host.

If document was loaded using GET, and, there is a manifest URL, and manifest URL has the same origin as document

Invoke, in the background, the application cache download process for manifest URL, with document as the cache host and with the resource from which document was parsed as the master resource.

If there are relevant application caches that are identified by a URL with the same origin as the URL of document, and that have this URL as one of their entries, excluding entries marked as foreign, then the user agent should use the most appropriate application cache of those that match as an HTTP cache for any subresource loads. User agents may also have other caches in place that are also honored.

Otherwise

The Document is not associated with any application cache.

If there was a manifest URL, the user agent may report to the user that it was ignored, to aid in application development.

11.3.4.4. Changes to the networking model

When a cache host is associated with an application cache whose completeness flag is complete, any and all loads for resources related to that cache host other than those for child browsing contexts must go through the following steps instead of immediately invoking the mechanisms appropriate to that resource’s scheme:

  1. If the resource is not to be fetched using the GET method, or if applying the URL parser algorithm to both its URL and the application cache’s manifest’s URL results in two URL records with different scheme components, then fetch the resource normally and abort these steps.
  2. If the resource’s URL is a master entry, the manifest, an explicit entry, or a fallback entry in the application cache, then get the resource from the cache (instead of fetching it), and abort these steps.
  3. If there is an entry in the application cache’s online safelist that has the same origin as the resource’s URL and that is a prefix match for the resource’s URL, then fetch the resource normally and abort these steps.
  4. If the resource’s URL has the same origin as the manifest’s URL, and there is a fallback namespace f in the application cache that is a prefix match for the resource’s URL, then:

    Fetch the resource normally. If this results in a redirect to a resource with another origin (indicative of a captive portal), or a 4xx or 5xx status code, or if there were network errors (but not if the user canceled the download), then instead get, from the cache, the resource of the fallback entry corresponding to the fallback namespace f. Abort these steps.

  5. If the application cache’s online safelist wildcard flag is open, then fetch the resource normally and abort these steps.
  6. Fail the resource load as if there had been a generic network error.

The above algorithm ensures that so long as the online safelist wildcard flag is blocking, resources that are not present in the manifest will always fail to load (at least, after the application cache has been primed the first time), making the testing of offline applications simpler.

11.3.4.5. Expiring application caches

As a general rule, user agents should not expire application caches, except on request from the user, or after having been left unused for an extended period of time.

Application caches and cookies have similar implications with respect to privacy (e.g., if the site can identify the user when providing the cache, it can store data in the cache that can be used for cookie resurrection). Implementors are therefore encouraged to expose application caches in a manner related to HTTP cookies, allowing caches to be expunged together with cookies and other origin-specific data.

11.3.4.6. Disk space

User agents should consider applying constraints on disk usage of application caches, and care should be taken to ensure that the restrictions cannot be easily worked around using subdomains.

User agents should allow users to see how much space each domain is using, and may offer the user the ability to delete specific application caches.

11.3.4.7. Security concerns with offline applications caches

This section is non-normative.

The main risk introduced by offline application caches is that an injection attack can be elevated into persistent site-wide page replacement. This attack involves using an injection vulnerability to upload two files to the victim site. The first file is an application cache manifest consisting of just a fallback entry pointing to the second file, which is an HTML page whose manifest is declared as that first file. Once the user has been directed to that second file, all subsequent accesses to any file covered by the given fallback namespace while either the user or the site is offline will instead show that second file. Targeted denial-of-service attacks or cookie bombing attacks (where the client is made to send so many cookies that the server refuses to process the request) can be used to ensure that the site appears offline.

To mitigate this, manifests can only specify fallbacks that are in the same path as the manifest itself. This means that a content injection upload vulnerability in a particular directory on a server can only be escalated to a take-over of that directory and its subdirectories. If there is no way to inject a file into the root directory, the entire site cannot be taken over.

If a site has been attacked in this way, simply removing the offending manifest might eventually clear the problem, since the next time the manifest is updated, a 404 error will be seen, and the user agent will clear the cache. "Eventually" is the key word here, however; while the attack on the user or server is ongoing, such that connections from an affected user to the affected site are blocked, the user agent will simply assume that the user is offline and will continue to use the hostile manifest. Unfortunately, if a cookie bombing attack has also been used, merely removing the manifest is insufficient; in addition, the server has to be configured to return a 404 or 410 response instead of the 413 "Request Entity Too Large" response.

TLS does not inherently protect a site from this attack, since the attack relies on content being served from the server itself. Not using application caches also does not prevent this attack, since the attack relies on an attacker-provided manifest.

11.3.4.8. Application cache API
[Exposed=(Window, SharedWorker)]
interface ApplicationCache : EventTarget {
  // update status
  const unsigned short UNCACHED = 0;
  const unsigned short IDLE = 1;
  const unsigned short CHECKING = 2;
  const unsigned short DOWNLOADING = 3;
  const unsigned short UPDATEREADY = 4;
  const unsigned short OBSOLETE = 5;
  readonly attribute unsigned short status;

  // updates
  void update();
  void abort();
  void swapCache();

  // events
  attribute EventHandler onchecking;
  attribute EventHandler onerror;
  attribute EventHandler onnoupdate;
  attribute EventHandler ondownloading;
  attribute EventHandler onprogress;
  attribute EventHandler onupdateready;
  attribute EventHandler oncached;
  attribute EventHandler onobsolete;
};
cache = window . applicationCache

(In a window.) Returns the ApplicationCache object that applies to the active document of that Window.

cache = self . applicationCache

(In a shared worker.) Returns the ApplicationCache object that applies to the current shared worker.

cache . status

Returns the current status of the application cache, as given by the constants defined below.

cache . update()

Invokes the application cache download process.

Throws an InvalidStateError exception if there is no application cache to update.

cache . abort()

Cancels the application cache download process.

cache . swapCache()

Switches to the most recent application cache, if there is a newer one. If there isn’t, throws an InvalidStateError exception.

There is a one-to-one mapping from cache hosts to ApplicationCache objects. The applicationCache attribute on Window objects must return the ApplicationCache object associated with the Window object’s active document. The applicationCache attribute on SharedWorkerGlobalScope objects must return the ApplicationCache object associated with the worker.

A Window or SharedWorkerGlobalScope object has an associated ApplicationCache object even if that cache host has no actual application cache.


The status attribute, on getting, must return the current state of the application cache that the ApplicationCache object’s cache host is associated with, if any. This must be the appropriate value from the following list:

UNCACHED (numeric value 0)
The ApplicationCache object’s cache host is not associated with an application cache at this time.
IDLE (numeric value 1)
The ApplicationCache object’s cache host is associated with an application cache whose application cache group’s update status is idle, and that application cache is the newest cache in its application cache group, and the application cache group is not marked as obsolete.
CHECKING (numeric value 2)
The ApplicationCache object’s cache host is associated with an application cache whose application cache group’s update status is checking.
DOWNLOADING (numeric value 3)
The ApplicationCache object’s cache host is associated with an application cache whose application cache group’s update status is downloading.
UPDATEREADY (numeric value 4)
The ApplicationCache object’s cache host is associated with an application cache whose application cache group’s update status is idle, and whose application cache group is not marked as obsolete, but that application cache is not the newest cache in its group.
OBSOLETE (numeric value 5)
The ApplicationCache object’s cache host is associated with an application cache whose application cache group is marked as obsolete.

If the update() method is invoked, the user agent must invoke the application cache download process, in the background, for the application cache group of the application cache with which the ApplicationCache object’s cache host is associated, but without giving that cache host to the algorithm. If there is no such application cache, or if its application cache group is marked as obsolete, then the method must throw an InvalidStateError exception instead.

If the abort() method is invoked, the user agent must send a signal to the current application cache download process for the application cache group of the application cache with which the ApplicationCache object’s cache host is associated, if any. If there is no such application cache, or it does not have a current application cache download process, then do nothing.

If the swapCache() method is invoked, the user agent must run the following steps:

  1. Check that ApplicationCache object’s cache host is associated with an application cache. If it is not, then throw an InvalidStateError exception and abort these steps.
  2. Let cache be the application cache with which the ApplicationCache object’s cache host is associated. (By definition, this is the same as the one that was found in the previous step.)
  3. If cache’s application cache group is marked as obsolete, then unassociate the ApplicationCache object’s cache host from cache and abort these steps. (Resources will now load from the network instead of the cache.)
  4. Check that there is an application cache in the same application cache group as cache whose completeness flag is complete and that is newer than cache. If there is not, then throw an InvalidStateError exception and abort these steps.
  5. Let new cache be the newest application cache in the same application cache group as cache whose completeness flag is complete.
  6. Unassociate the ApplicationCache object’s cache host from cache and instead associate it with new cache.

The following are the event handlers (and their corresponding event handler event types) that must be supported, as event handler IDL attributes, by all objects implementing the ApplicationCache interface:

Event handler Event handler event type
onchecking checking
onerror error
onnoupdate noupdate
ondownloading downloading
onprogress progress
onupdateready updateready
oncached cached
onobsolete obsolete

11.3.5. Other elements, attributes and APIs

User agents must treat acronym elements in a manner equivalent to abbr elements in terms of semantics and for purposes of rendering.


partial interface HTMLAnchorElement {
  attribute DOMString coords;
  attribute DOMString charset;
  attribute DOMString name;
  attribute DOMString shape;
};

The coords, charset, name, and shape IDL attributes of the th element must reflect the respective content attributes of the same name.


partial interface HTMLAreaElement {
  attribute boolean noHref;
};

The noHref IDL attribute of the area element must reflect the element’s nohref content attribute.


partial interface HTMLBodyElement {
  [TreatNullAs=EmptyString] attribute DOMString text;
  [TreatNullAs=EmptyString] attribute DOMString link;
  [TreatNullAs=EmptyString] attribute DOMString vLink;
  [TreatNullAs=EmptyString] attribute DOMString aLink;
  [TreatNullAs=EmptyString] attribute DOMString bgColor;
  attribute DOMString background;
};

The text IDL attribute of the body element must reflect the element’s text content attribute.

The link IDL attribute of the body element must reflect the element’s link content attribute.

The aLink IDL attribute of the body element must reflect the element’s alink content attribute.

The vLink IDL attribute of the body element must reflect the element’s vlink content attribute.

The bgColor IDL attribute of the body element must reflect the element’s bgcolor content attribute.

The background IDL attribute of the body element must reflect the element’s background content attribute. (The background content is not defined to contain a URL, despite rules regarding its handling in §10 Rendering above.)


partial interface HTMLBRElement {
  attribute DOMString clear;
};

The clear IDL attribute of the br element must reflect the content attribute of the same name.


partial interface HTMLTableCaptionElement {
  attribute DOMString align;
};

The align IDL attribute of the caption element must reflect the content attribute of the same name.


partial interface HTMLTableColElement {
  attribute DOMString align;
  attribute DOMString ch;
  attribute DOMString chOff;
  attribute DOMString vAlign;
  attribute DOMString width;
};

The align and width IDL attributes of the col element must reflect the respective content attributes of the same name.

The ch IDL attribute of the col element must reflect the element’s char content attribute.

The chOff IDL attribute of the col element must reflect the element’s charoff content attribute.

The vAlign IDL attribute of the col element must reflect the element’s valign content attribute.


User agents must treat dir elements in a manner equivalent to ul elements in terms of semantics and for purposes of rendering.

The dir element must implement the HTMLDirectoryElement interface.

interface HTMLDirectoryElement : HTMLElement {
  attribute boolean compact;
};

The compact IDL attribute of the dir element must reflect the content attribute of the same name.


partial interface HTMLDivElement {
  attribute DOMString align;
};

The align IDL attribute of the div element must reflect the content attribute of the same name.


partial interface HTMLDListElement {
  attribute boolean compact;
};

The compact IDL attribute of the dl element must reflect the content attribute of the same name.


partial interface HTMLEmbedElement {
  attribute DOMString align;
  attribute DOMString name;
};

The name and align IDL attributes of the embed element must reflect the respective content attributes of the same name.


The font element must implement the HTMLFontElement interface.

interface HTMLFontElement : HTMLElement {
  [TreatNullAs=EmptyString] attribute DOMString color;
  attribute DOMString face;
  attribute DOMString size;
};

The color, face, and size IDL attributes of the font element must reflect the respective content attributes of the same name.


partial interface HTMLHeadingElement {
  attribute DOMString align;
};

The align IDL attribute of the h1h6 elements must reflect the content attribute of the same name.


The profile IDL attribute on head elements (with the HTMLHeadElement interface) is intentionally omitted. Unless so required by another applicable specification, implementations would therefore not support this attribute. (It is mentioned here as it was defined in a previous version of the DOM specifications.)


partial interface HTMLHRElement {
  attribute DOMString align;
  attribute DOMString color;
  attribute boolean noShade;
  attribute DOMString size;
  attribute DOMString width;
};

The align, color, size, and width IDL attributes of the hr element must reflect the respective content attributes of the same name.

The noShade IDL attribute of the hr element must reflect the element’s noshade content attribute.


partial interface HTMLHtmlElement {
  attribute DOMString version;
};

The version IDL attribute of the html element must reflect the content attribute of the same name.


partial interface HTMLIFrameElement {
  attribute DOMString align;
  attribute DOMString scrolling;
  attribute DOMString frameBorder;

  [TreatNullAs=EmptyString] attribute DOMString marginHeight;
  [TreatNullAs=EmptyString] attribute DOMString marginWidth;
};

The align and scrolling IDL attributes of the iframe element must reflect the respective content attributes of the same name.

The frameBorder IDL attribute of the iframe element must reflect the element’s frameborder content attribute.

The marginHeight IDL attribute of the iframe element must reflect the element’s marginheight content attribute.

The marginWidth IDL attribute of the iframe element must reflect the element’s marginwidth content attribute.


partial interface HTMLImageElement {
  attribute DOMString name;
  attribute DOMString lowsrc;
  attribute DOMString align;
  attribute unsigned long hspace;
  attribute unsigned long vspace;

  [TreatNullAs=EmptyString] attribute DOMString border;
};

The name, align, border, hspace, and vspace IDL attributes of the img element must reflect the respective content attributes of the same name.

The lowsrc IDL attribute of the img element must reflect the element’s lowsrc content attribute, which for the purposes of reflection is defined as containing a URL.


partial interface HTMLInputElement {
  attribute DOMString align;
  attribute DOMString useMap;
};

The align IDL attribute of the input element must reflect the content attribute of the same name.

The useMap IDL attribute of the input element must reflect the element’s usemap content attribute.


partial interface HTMLLegendElement {
  attribute DOMString align;
};

The align IDL attribute of the legend element must reflect the content attribute of the same name.


partial interface HTMLLIElement {
  attribute DOMString type;
};

The type IDL attribute of the li element must reflect the content attribute of the same name.


partial interface HTMLLinkElement {
  attribute DOMString charset;
  attribute DOMString target;
};

The charset and target IDL attributes of the link element must reflect the respective content attributes of the same name.


User agents must treat listing elements in a manner equivalent to pre elements in terms of semantics and for purposes of rendering.


partial interface HTMLMenuElement {
  attribute boolean compact;
};

The compact IDL attribute of the menu element must reflect the content attribute of the same name.


partial interface HTMLMetaElement {
  attribute DOMString scheme;
};

User agents may treat the scheme content attribute on the meta element as an extension of the element’s name content attribute when processing a meta element with a name attribute whose value is one that the user agent recognizes as supporting the scheme attribute.

User agents are encouraged to ignore the scheme attribute and instead process the value given to the metadata name as if it had been specified for each expected value of the scheme attribute.

For example, if the user agent acts on meta elements with name attributes having the value "eGMS.subject.keyword", and knows that the scheme attribute is used with this metadata name, then it could take the scheme attribute into account, acting as if it was an extension of the name attribute. Thus the following two meta elements could be treated as two elements giving values for two different metadata names, one consisting of a combination of "eGMS.subject.keyword" and "LGCL", and the other consisting of a combination of "eGMS.subject.keyword" and "ORLY":
<!-- this markup is invalid -->
<meta name="eGMS.subject.keyword" scheme="LGCL" content="Abandoned vehicles">
<meta name="eGMS.subject.keyword" scheme="ORLY" content="Mah car: kthxbye">

The suggested processing of this markup, however, would be equivalent to the following:

<meta name="eGMS.subject.keyword" content="Abandoned vehicles">
<meta name="eGMS.subject.keyword" content="Mah car: kthxbye">

The scheme IDL attribute of the meta element must reflect the content attribute of the same name.


partial interface HTMLObjectElement {
  attribute DOMString align;
  attribute DOMString archive;
  attribute DOMString code;
  attribute boolean declare;
  attribute unsigned long hspace;
  attribute DOMString standby;
  attribute unsigned long vspace;
  attribute DOMString codeBase;
  attribute DOMString codeType;
  attribute DOMString useMap;

  [TreatNullAs=EmptyString] attribute DOMString border;
};

The align, archive, border, code, declare, hspace, standby, and vspace IDL attributes of the object element must reflect the respective content attributes of the same name.

The codeBase IDL attribute of the object element must reflect the element’s codebase content attribute, which for the purposes of reflection is defined as containing a URL.

The codeType IDL attribute of the object element must reflect the element’s codetype content attribute.

The useMap IDL attribute of the object element must reflect the element’s usemap content attribute.


partial interface HTMLOListElement {
  attribute boolean compact;
};

The compact IDL attribute of the ol element must reflect the content attribute of the same name.


partial interface HTMLParagraphElement {
  attribute DOMString align;
};

The align IDL attribute of the p element must reflect the content attribute of the same name.


partial interface HTMLParamElement {
  attribute DOMString type;
  attribute DOMString valueType;
};

The type IDL attribute of the param element must reflect the content attribute of the same name.

The valueType IDL attribute of the param element must reflect the element’s valuetype content attribute.


User agents must treat plaintext elements in a manner equivalent to pre elements in terms of semantics and for purposes of rendering. (The parser has special behavior for this element, though.)


partial interface HTMLPreElement {
  attribute long width;
};

The width IDL attribute of the pre element must reflect the content attribute of the same name.


partial interface HTMLScriptElement {
  attribute DOMString event;
  attribute DOMString htmlFor;
};

The event IDL attribute of the script element must reflect the element’s event content attribute.

The htmlFor IDL attribute of the script element must reflect the element’s for content attribute.


partial interface HTMLTableElement {
  attribute DOMString align;
  attribute DOMString border;
  attribute DOMString frame;
  attribute DOMString rules;
  attribute DOMString summary;
  attribute DOMString width;

  [TreatNullAs=EmptyString] attribute DOMString bgColor;
  [TreatNullAs=EmptyString] attribute DOMString cellPadding;
  [TreatNullAs=EmptyString] attribute DOMString cellSpacing;
};

The align, border, frame, summary, rules, and width, IDL attributes of the table element must reflect the respective content attributes of the same name.

The bgColor IDL attribute of the table element must reflect the element’s bgcolor content attribute.

The cellPadding IDL attribute of the table element must reflect the element’s cellpadding content attribute.

The cellSpacing IDL attribute of the table element must reflect the element’s cellspacing content attribute.


partial interface HTMLTableSectionElement {
  attribute DOMString align;
  attribute DOMString ch;
  attribute DOMString chOff;
  attribute DOMString vAlign;
};

The align IDL attribute of the tbody, thead, and tfoot elements must reflect the content attribute of the same name.

The ch IDL attribute of the tbody, thead, and tfoot elements must reflect the elements' char content attributes.

The chOff IDL attribute of the tbody, thead, and tfoot elements must reflect the elements' charoff content attributes.

The vAlign IDL attribute of the tbody, thead, and tfoot element must reflect the elements' valign content attributes.


partial interface HTMLTableCellElement {
  attribute DOMString align;
  attribute DOMString axis;
  attribute DOMString height;
  attribute DOMString width;

  attribute DOMString ch;
  attribute DOMString chOff;
  attribute boolean noWrap;
  attribute DOMString vAlign;

  [TreatNullAs=EmptyString] attribute DOMString bgColor;
};

The align, axis, height, and width IDL attributes of the td and th elements must reflect the respective content attributes of the same name.

The ch IDL attribute of the td and th elements must reflect the elements' char content attributes.

The chOff IDL attribute of the td and th elements must reflect the elements' charoff content attributes.

The noWrap IDL attribute of the td and th elements must reflect the elements' nowrap content attributes.

The vAlign IDL attribute of the td and th element must reflect the elements' valign content attributes.

The bgColor IDL attribute of the td and th elements must reflect the elements' bgcolor content attributes.


partial interface HTMLTableDataCellElement {
  attribute DOMString abbr;
};

The abbr IDL attribute of the td element must reflect the respective content attributes of the same name.


partial interface HTMLTableRowElement {
  attribute DOMString align;
  attribute DOMString ch;
  attribute DOMString chOff;
  attribute DOMString vAlign;

  [TreatNullAs=EmptyString] attribute DOMString bgColor;
};

The align IDL attribute of the tr element must reflect the content attribute of the same name.

The ch IDL attribute of the tr element must reflect the element’s char content attribute.

The chOff IDL attribute of the tr element must reflect the element’s charoff content attribute.

The vAlign IDL attribute of the tr element must reflect the element’s valign content attribute.

The bgColor IDL attribute of the tr element must reflect the element’s bgcolor content attribute.


partial interface HTMLUListElement {
  attribute boolean compact;
  attribute DOMString type;
};

The compact and type IDL attributes of the ul element must reflect the respective content attributes of the same name.


User agents must treat xmp elements in a manner equivalent to pre elements in terms of semantics and for purposes of rendering. (The parser has special behavior for this element though.)


The blink, bgsound, isindex, multicol, nextid, and spacer elements must use the HTMLUnknownElement interface.


partial interface Document {
  [TreatNullAs=EmptyString] attribute DOMString fgColor;
  [TreatNullAs=EmptyString] attribute DOMString linkColor;
  [TreatNullAs=EmptyString] attribute DOMString vlinkColor;
  [TreatNullAs=EmptyString] attribute DOMString alinkColor;
  [TreatNullAs=EmptyString] attribute DOMString bgColor;

  [SameObject] readonly attribute HTMLCollection anchors;
  [SameObject] readonly attribute HTMLCollection applets;

  void clear();
  void captureEvents();
  void releaseEvents();

  [SameObject] readonly attribute HTMLAllCollection all;
};

The attributes of the Document object listed in the first column of the following table must reflect the content attribute on the body element with the name given in the corresponding cell in the second column on the same row, if the body element is a body element (as opposed to a frameset element). When there is no body element or if it is a frameset element, the attributes must instead return the empty string on getting and do nothing on setting.

IDL attribute Content attribute
fgColor text
linkColor link
vlinkColor vlink
alinkColor alink
bgColor bgcolor

The anchors attribute must return an HTMLCollection rooted at the Document node, whose filter matches only a elements with name attributes.

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

The clear(), captureEvents(), and releaseEvents() methods must do nothing.


The all attribute must return an HTMLAllCollection rooted at the Document node, whose filter matches all elements.

The object returned for all has several unusual behaviors:

These requirements are a willful violation of the JavaScript specification current at the time of writing (ECMAScript edition 6). The JavaScript specification requires that the ToBoolean() operator convert all objects to the true value, and does not have provisions for objects acting as if they were undefined for the purposes of certain operators. This violation is motivated by a desire for compatibility with two classes of legacy content: one that uses the presence of document.all as a way to detect legacy user agents, and one that only supports those legacy user agents and uses the document.all object without testing for its presence first. [ECMA-262]


partial interface Window {
  void captureEvents();
  void releaseEvents();

  [Replaceable, SameObject] readonly attribute External external;
};

The captureEvents() and releaseEvents() methods must do nothing.

The external attribute of the Window interface must return an instance of the External interface:

[NoInterfaceObject]
interface External {
  void AddSearchProvider();
  void IsSearchProviderInstalled();
};

The AddSearchProvider() and IsSearchProviderInstalled() methods must do nothing.

12. IANA considerations

12.1. text/html

This registration is for community review and will be submitted to the IESG for review, approval, and registration with IANA.

Type name:

text

Subtype name:

html

Required parameters:

No required parameters

Optional parameters:

charset

The charset parameter may be provided to specify the document’s character encoding, overriding any character encoding declarations in the document other than a Byte Order Mark (BOM). The parameter’s value must be one of the labels of the character encoding used to serialize the file. [ENCODING]

Encoding considerations:

8bit (see the section on character encoding declarations)

Security considerations:

Entire novels have been written about the security considerations that apply to HTML documents. Many are listed in this document, to which the reader is referred for more details. Some general concerns bear mentioning here, however:

HTML is scripted language, and has a large number of APIs (some of which are described in this document). Script can expose the user to potential risks of information leakage, credential leakage, cross-site scripting attacks, cross-site request forgeries, and a host of other problems. While the designs in this specification are intended to be safe if implemented correctly, a full implementation is a massive undertaking and, as with any software, user agents are likely to have security bugs.

Even without scripting, there are specific features in HTML which, for historical reasons, are required for broad compatibility with legacy content but that expose the user to unfortunate security problems. In particular, the img element can be used in conjunction with some other features as a way to effect a port scan from the user’s location on the Internet. This can expose local network topologies that the attacker would otherwise not be able to determine.

HTML relies on a compartmentalization scheme sometimes known as the same-origin policy. An origin in most cases consists of all the pages served from the same host, on the same port, using the same protocol.

It is critical, therefore, to ensure that any untrusted content that forms part of a site be hosted on a different origin than any sensitive content on that site. Untrusted content can easily spoof any other page on the same origin, read data from that origin, cause scripts in that origin to execute, submit forms to and from that origin even if they are protected from cross-site request forgery attacks by unique tokens, and make use of any third-party resources exposed to or rights granted to that origin.

Interoperability considerations:

Rules for processing both conforming and non-conforming content are defined in this specification.

Published specification:

This document is the relevant specification. Labeling a resource with the text/html type asserts that the resource is an HTML document using the HTML syntax.

Applications that use this media type:

Web browsers, tools for processing Web content, HTML authoring tools, search engines, validators.

Additional information:

Magic number(s):

No sequence of bytes can uniquely identify an HTML document. More information on detecting HTML documents is available in the MIME Sniffing specification. [MIMESNIFF]

File extension(s):

"html" and "htm" are commonly, but certainly not exclusively, used as the extension for HTML documents.

Macintosh file type code(s):

TEXT

Person & email address to contact for further information:

Ian Hickson <ian@hixie.ch>

Intended usage:

Common

Restrictions on usage:

No restrictions apply.

Author:

Ian Hickson <ian@hixie.ch>

Change controller:

W3C

Fragment identifiers used with text/html resources either refer to the indicated part of the document or provide state information for in-page scripts.

12.2. multipart/x-mixed-replace

This registration is for community review and will be submitted to the IESG for review, approval, and registration with IANA.

Type name:

multipart

Subtype name:

x-mixed-replace

Required parameters:

Optional parameters:

No optional parameters.

Encoding considerations:

binary

Security considerations:

Subresources of a multipart/x-mixed-replace resource can be of any type, including types with non-trivial security implications such as text/html.

Interoperability considerations:

None.

Published specification:

This specification describes processing rules for Web browsers. Conformance requirements for generating resources with this type are the same as for multipart/mixed. [RFC2046]

Applications that use this media type:

This type is intended to be used in resources generated by Web servers, for consumption by Web browsers.

Additional information:

Magic number(s):

No sequence of bytes can uniquely identify a multipart/x-mixed-replace resource.

File extension(s):

No specific file extensions are recommended for this type.

Macintosh file type code(s):

No specific Macintosh file type codes are recommended for this type.

Person & email address to contact for further information:

Ian Hickson <ian@hixie.ch>

Intended usage:

Common

Restrictions on usage:

No restrictions apply.

Author:

Ian Hickson <ian@hixie.ch>

Change controller:

W3C

Fragment identifiers used with multipart/x-mixed-replace resources apply to each body part as defined by the type used by that body part.

12.3. application/xhtml+xml

This registration is for community review and will be submitted to the IESG for review, approval, and registration with IANA.

Type name:

application

Subtype name:

xhtml+xml

Required parameters:

Same as for application/xml [RFC7303]

Optional parameters:

Same as for application/xml [RFC7303]

Encoding considerations:

Same as for application/xml [RFC7303]

Security considerations:

Same as for application/xml [RFC7303]

Interoperability considerations:

Same as for application/xml [RFC7303]

Published specification:

Labeling a resource with the application/xhtml+xml type asserts that the resource is an XML document that likely has a root element from the HTML namespace. Thus, the relevant specifications are the XML specification, the Namespaces in XML specification, and this specification. [XML] [XPTR-XMLNS]

Applications that use this media type:

Same as for application/xml [RFC7303]

Additional information:

Magic number(s):

Same as for application/xml [RFC7303]

File extension(s):

"xhtml" and "xht" are sometimes used as extensions for XML resources that have a root element from the HTML namespace.

Macintosh file type code(s):

TEXT

Person & email address to contact for further information:

Ian Hickson <ian@hixie.ch>

Intended usage:

Common

Restrictions on usage:

No restrictions apply.

Author:

Ian Hickson <ian@hixie.ch>

Change controller:

W3C

Fragment identifiers used with application/xhtml+xml resources have the same semantics as with any XML MIME type. [RFC7303]

12.4. web+ scheme prefix

This section describes a convention for use with the IANA URI scheme registry. It does not itself register a specific scheme. [RFC7595]

Scheme name:

Schemes starting with the four characters "web+" followed by one or more letters in the range a-z.

Status:

Permanent

Scheme syntax:

Scheme-specific.

Scheme semantics:

Scheme-specific.

Encoding considerations:

All "web+" schemes should use UTF-8 encodings where relevant.

Applications/protocols that use this scheme name:

Scheme-specific.

Interoperability considerations:

The scheme is expected to be used in the context of Web applications.

Security considerations:

Any Web page is able to register a handler for all "web+" schemes. As such, these schemes must not be used for features intended to be core platform features (e.g., network transfer protocols like HTTP or FTP). Similarly, such schemes must not store confidential information in their URLs, such as usernames, passwords, personal information, or confidential project names.

Contact:

Ian Hickson <ian@hixie.ch>

Change controller:

Ian Hickson <ian@hixie.ch>

References:

Custom scheme and content handlers, HTML Living Standard: https://html.spec.whatwg.org/#custom-handlers

Index

Terms defined by this specification

Terms defined by reference

Elements

This section is non-normative.

List of elements
Element Description Categories Parents† Children Attributes Interface
a Hyperlink flow; phrasing*; interactive phrasing transparent* globals; href; target; download; rel; hreflang; type HTMLAnchorElement
abbr Abbreviation flow; phrasing phrasing phrasing globals HTMLElement
address Contact information for a page or article element flow flow flow* globals HTMLElement
area Hyperlink or dead area on an image map flow; phrasing phrasing* empty globals; alt; coords; shape; href; target; download; rel; hreflang; type HTMLAreaElement
article Self-contained syndicatable or reusable composition flow; sectioning flow flow globals HTMLElement
aside Sidebar for tangentially related content flow; sectioning flow flow globals HTMLElement
audio Audio player flow; phrasing; embedded; interactive phrasing source*; transparent* globals; src; crossorigin; preload; autoplay; loop; muted; controls HTMLAudioElement
b Keywords flow; phrasing phrasing phrasing globals HTMLElement
base Base URL and default target browsing context for hyperlinks and forms metadata head; template empty globals; href; target HTMLBaseElement
bdi Text directionality isolation flow; phrasing phrasing phrasing globals HTMLElement
bdo Text directionality formatting flow; phrasing phrasing phrasing globals HTMLElement
blockquote A section quoted from another source flow; sectioning root flow flow globals; cite HTMLQuoteElement
body Document body sectioning root html flow globals; onafterprint; onbeforeprint; onbeforeunload; onhashchange; onlanguagechange; onmessage; onoffline; ononline; onpagehide; onpageshow; onpopstate; onstorage; onunload HTMLBodyElement
br Line break, e.g., in poem or postal address flow; phrasing phrasing empty globals HTMLBRElement
button Button control flow; phrasing; interactive; listed; labelable; submittable; reassociateable; form-associated phrasing phrasing* globals; autofocus; disabled; form; formaction; formenctype; formmethod; formnovalidate; formtarget; menu; name; type; value HTMLButtonElement
canvas Scriptable bitmap canvas flow; phrasing; embedded phrasing transparent globals; width; height HTMLCanvasElement
caption Table caption none table; template flow* globals HTMLTableCaptionElement
cite Title of a work flow; phrasing phrasing phrasing globals HTMLElement
code Computer code flow; phrasing phrasing phrasing globals HTMLElement
col Table column none colgroup; template empty globals; span HTMLTableColElement
colgroup Group of columns in a table none table; template col*; template* globals; span HTMLTableColElement
data Machine-readable equivalent flow; phrasing phrasing phrasing globals; value HTMLDataElement
datalist Container for options for combo box control flow; phrasing phrasing phrasing; option globals HTMLDataListElement
dd Content for corresponding dt element(s) none dl; template flow globals HTMLElement
del A removal from the document flow; phrasing* phrasing transparent globals; cite; datetime HTMLModElement
details Disclosure control for hiding details flow; sectioning root; interactive flow summary*; flow globals; open HTMLDetailsElement
dfn Defining instance flow; phrasing phrasing phrasing* globals HTMLElement
div Generic flow container flow flow flow globals HTMLDivElement
dl Association list consisting of zero or more name-value groups flow flow dt*; dd*; script-supporting elements globals HTMLDListElement
dt Legend for corresponding dd element(s) none dl; template flow* globals HTMLElement
em Stress emphasis flow; phrasing phrasing phrasing globals HTMLElement
embed Plugin flow; phrasing; embedded; interactive phrasing empty globals; src; type; width; height; any* HTMLEmbedElement
fieldset Group of form controls flow; sectioning root; listed; reassociateable; form-associated flow legend*; flow globals; disabled; form; name HTMLFieldSetElement
figcaption Caption for figure none figure; template flow globals HTMLElement
figure Figure with optional caption flow; sectioning root flow figcaption*; flow globals HTMLElement
footer Footer for a page or section flow flow flow* globals HTMLElement
form User-submittable form flow flow flow* globals; accept-charset; action; autocomplete; enctype; method; name; novalidate; target HTMLFormElement
h1, h2, h3, h4, h5, h6 Section heading flow; heading flow phrasing globals HTMLHeadingElement
head Container for document metadata none html metadata content* globals HTMLHeadElement
header Introductory or navigational aids for a page or section flow flow flow* globals HTMLElement
hr Thematic break flow flow empty globals HTMLHRElement
html Root element none none* head*; body* globals HTMLHtmlElement
i Alternate voice flow; phrasing phrasing phrasing globals HTMLElement
iframe Nested browsing context flow; phrasing; embedded; interactive phrasing text* globals; src; srcdoc; name; sandbox; allowfullscreen; width; height HTMLIFrameElement
img Image flow; phrasing; embedded; interactive*; form-associated phrasing empty globals; alt; src; srcset; crossorigin; usemap; ismap; width; height HTMLImageElement
input Form control flow; phrasing; interactive*; listed; labelable; submittable; resettable; reassociateable; form-associated phrasing empty globals; accept; alt; autocomplete; autofocus; checked; dirname; disabled; form; formaction; formenctype; formmethod; formnovalidate; formtarget; height; inputmode; list; max; maxlength; min; minlength; multiple; name; pattern; placeholder; readonly; required; size; src; step; type; value; width HTMLInputElement
ins An addition to the document flow; phrasing* phrasing transparent globals; cite; datetime HTMLModElement
kbd User input flow; phrasing phrasing phrasing globals HTMLElement
keygen Cryptographic key-pair generator form control flow; phrasing; interactive; listed; labelable; submittable; resettable; reassociateable; form-associated phrasing empty globals; autofocus; challenge; disabled; form; keytype; name HTMLKeygenElement
label Caption for a form control flow; phrasing; interactive; reassociateable; form-associated phrasing phrasing* globals; for HTMLLabelElement
legend Caption for fieldset none fieldset; template phrasing globals HTMLLegendElement
li List item none ol; ul; menu*; template flow globals; value* HTMLLIElement
link Link metadata metadata; flow*; phrasing* head; template; noscript*; phrasing* empty globals; href; crossorigin; rel; media; hreflang; type; sizes HTMLLinkElement
main Main content of a document flow flow flow* globals HTMLElement
map Image map flow; phrasing* phrasing transparent; area* globals; name HTMLMapElement
mark Highlight flow; phrasing phrasing phrasing globals HTMLElement
menu Menu of commands flow flow; menu* li*; flow*; menuitem*; hr*; menu*; script-supporting elements* globals; type; label HTMLMenuElement
menuitem Menu command none menu; template empty globals; type; label; icon; disabled; checked; radiogroup; default HTMLMenuItemElement
meta Text metadata metadata; flow*; phrasing* head; template; noscript*; phrasing* empty globals; name; http-equiv; content; charset HTMLMetaElement
meter Gauge flow; phrasing; labelable phrasing phrasing* globals; value; min; max; low; high; optimum HTMLMeterElement
nav Section with navigational links flow; sectioning flow flow globals HTMLElement
noscript Fallback content for script metadata; flow; phrasing head*; template*; phrasing* varies* globals HTMLElement
object Image, nested browsing context, or plugin flow; phrasing; embedded; interactive*; listed; submittable; reassociateable; form-associated phrasing param*; transparent globals; data; type; typemustmatch; name; form; width; height HTMLObjectElement
ol Ordered list flow flow li; script-supporting elements globals; reversed; start; type HTMLOListElement
optgroup Group of options in a list box none select; template option; script-supporting elements globals; disabled; label HTMLOptGroupElement
option Option in a list box or combo box control none select; datalist; optgroup; template text* globals; disabled; label; selected; value HTMLOptionElement
output Calculated output value flow; phrasing; listed; labelable; resettable; reassociateable; form-associated phrasing phrasing globals; for; form; name HTMLOutputElement
p Paragraph flow flow phrasing globals HTMLParagraphElement
param Parameter for object none object; template empty globals; name; value HTMLParamElement
picture Image flow; phrasing; embedded phrasing source*; one img; script-supporting elements globals HTMLPictureElement
pre Block of preformatted text flow flow phrasing globals HTMLPreElement
progress Progress bar flow; phrasing; labelable phrasing phrasing* globals; value; max HTMLProgressElement
q Quotation flow; phrasing phrasing phrasing globals; cite HTMLQuoteElement
rb Ruby base none ruby; template phrasing globals HTMLElement
rp Parenthesis for ruby annotation text none ruby; rtc; template phrasing globals HTMLElement
rt Ruby annotation text none ruby; rtc; template phrasing globals HTMLElement
rtc Ruby annotation text container none ruby; template phrasing globals HTMLElement
ruby Ruby annotation(s) flow; phrasing phrasing phrasing; rp; rt; rb; rtc* globals HTMLElement
s Inaccurate text flow; phrasing phrasing phrasing globals HTMLElement
samp Computer output flow; phrasing phrasing phrasing globals HTMLElement
script Embedded script metadata; flow; phrasing; script-supporting elements head; phrasing; script-supporting elements script, data, or script documentation* globals; src; type; charset; async; defer; crossorigin nonce HTMLScriptElement
section Generic document or application section flow; sectioning flow flow globals HTMLElement
select List box control flow; phrasing; interactive; listed; labelable; submittable; resettable; reassociateable; form-associated phrasing option; optgroup; script-supporting elements globals; autocomplete; autofocus; disabled; form; multiple; name; required; size HTMLSelectElement
small Side comment flow; phrasing phrasing phrasing globals HTMLElement
source Media source for video or audio none video; audio; template empty globals; src; type HTMLSourceElement
source Image source for img none picture empty globals; srcset; sizes; media; type HTMLSourceElement
span Generic phrasing container flow; phrasing phrasing phrasing globals HTMLSpanElement
strong Importance flow; phrasing phrasing phrasing globals HTMLElement
style Embedded styling information metadata; flow* head; noscript*; flow* varies* globals; media; nonce; type HTMLStyleElement
sub Subscript flow; phrasing phrasing phrasing globals HTMLElement
summary Caption for details none details phrasing globals HTMLElement
sup Superscript flow; phrasing phrasing phrasing globals HTMLElement
table Table flow flow caption*; colgroup*; thead*; tbody*; tfoot*; tr*; script-supporting elements globals; border HTMLTableElement
tbody Group of rows in a table none table; template tr; script-supporting elements globals HTMLTableSectionElement
td Table cell sectioning root tr; template flow globals; colspan; rowspan; headers HTMLTableDataCellElement
template Template metadata; flow; phrasing; script-supporting elements metadata; phrasing; script-supporting elements; colgroup* it’s complicated* globals HTMLTemplateElement
textarea Multiline text field flow; phrasing; interactive; listed; labelable; submittable; resettable; reassociateable; form-associated phrasing text globals; autofocus; cols; dirname; disabled; form; inputmode; maxlength; minlength; name; placeholder; readonly; required; rows; wrap HTMLTextAreaElement
tfoot Group of footer rows in a table none table; template tr; script-supporting elements globals HTMLTableSectionElement
th Table header cell interactive* tr; template flow* globals; colspan; rowspan; headers; scope; abbr HTMLTableHeaderCellElement
thead Group of heading rows in a table none table; template tr; script-supporting elements globals HTMLTableSectionElement
time Machine-readable equivalent of date- or time-related data flow; phrasing phrasing phrasing globals; datetime HTMLTimeElement
title Document title metadata head; template text* globals HTMLTitleElement
tr Table row none table; thead; tbody; tfoot; template th*; td; script-supporting elements globals HTMLTableRowElement
track Timed text track none audio; video; template empty globals; default; kind; label; src; srclang HTMLTrackElement
u Keywords flow; phrasing phrasing phrasing globals HTMLElement
ul List flow flow li; script-supporting elements globals HTMLUListElement
var Variable flow; phrasing phrasing phrasing globals HTMLElement
video Video player flow; phrasing; embedded; interactive phrasing source*; transparent* globals; src; crossorigin; poster; preload; autoplay; loop; muted; controls; width; height HTMLVideoElement
wbr Line breaking opportunity flow; phrasing phrasing empty globals HTMLElement

An asterisk (*) in a cell indicates that the actual rules are more complicated than indicated in the table above.

† Categories in the "Parents" column refer to parents that list the given categories in their content model, not to elements that themselves are in those categories. For example, the a element’s "Parents" column says "phrasing", so any element whose content model contains the "phrasing" category could be a parent of an a element. Since the "flow" category includes all the "phrasing" elements, that means the th element could be a parent to an a element.

Element content categories

This section is non-normative.

List of element content categories
Category Elements Elements with exceptions
Metadata content base; link; meta; noscript; script; style; template; title
Flow content a; abbr; address; article; aside; audio; b; bdi; bdo; blockquote; br; button; canvas; cite; code; data; datalist; del; details; dfn; div; dl; em; embed; fieldset; figure; footer; form; h1; h2; h3; h4; h5; h6; header; hr; i; iframe; img; input; ins; kbd; keygen; label; main; map; mark; math; menu; meter; nav; noscript; object; ol; output; p; pre; progress; q; ruby; s; samp; script; section; select; small; span; strong; sub; sup; svg; table; template; textarea; time; u; ul; var; video; wbr; Text area (if it is a descendant of a map element)
Sectioning content article; aside; nav; section
Heading content h1; h2; h3; h4; h5; h6;
Phrasing content a; abbr; audio; b; bdi; bdo; br; button; canvas; cite; code; data; datalist; del; dfn; em; embed; i; iframe; img; input; ins; kbd; keygen; label; map; mark; math; meter; noscript; object; output; progress; q; ruby; s; samp; script; select; small; span; strong; sub; sup; svg; template; textarea; time; u; var; video; wbr; Text area (if it is a descendant of a map element);
Embedded content audio; canvas; embed; iframe; img; math; object; svg; video
Interactive content* button; details; embed; iframe; keygen; label; select; textarea a (if the href attribute is present); audio (if the controls attribute is present); img (if the usemap attribute is present); input (if the type attribute is not in the Hidden state); video (if the controls attribute is present)
Sectioning roots blockquote; body; details; fieldset; figure; td
Form-associated elements button; fieldset; input; keygen; label; object; output; select; textarea; img
Listed elements button; fieldset; input; keygen; object; output; select; textarea
Submittable elements button; input; keygen; object; select; textarea
Resettable elements input; keygen; output; select; textarea
Labelable elements button; input; keygen; meter; output; progress; select; textarea
Reassociateable elements button; fieldset; input; keygen; label; object; output; select; textarea
Palpable content a; abbr; address; article; aside; b; bdi; bdo; blockquote; button; canvas; cite; code; data; details; dfn; div; em; embed; fieldset; figure; footer; form; h1; h2; h3; h4; h5; h6; header; i; iframe; img; ins; kbd; keygen; label; main; map; mark; math; meter; nav; object; output; p; pre; progress; q; ruby; s; samp; section; select; small; span; strong; sub; sup; svg; table; textarea; time; u; var; video audio (if the controls attribute is present); dl (if the element’s children include at least one name-value group); input (if the type attribute is not in the Hidden state); ol (if the element’s children include at least one li element); ul (if the element’s children include at least one li element); Text that is not inter-element whitespace
Script-supporting elements script; template

* The tabindex attribute can also make any element into interactive content.

Attributes

This section is non-normative.

List of attributes (excluding event handler content attributes)
Attribute Element(s) Description Value
abbr th Alternative label to use for the header cell when referencing the cell in other contexts Text*
accept input Hint for expected file type in file upload controls Set of comma-separated tokens* consisting of valid MIME types with no parameters or audio/*, video/*, or image/*
accept-charset form Character encodings to use for form submission Ordered set of unique space-separated tokens, ASCII case-insensitive, consisting of labels of ASCII-compatible encodings*
accesskey HTML elements Keyboard shortcut to activate or focus element Ordered set of unique space-separated tokens, case-sensitive, consisting of one Unicode code point in length
action form URL to use for form submission Valid non-empty URL potentially surrounded by spaces
allowfullscreen iframe Whether to allow the iframe's contents to use requestFullscreen() Boolean attribute
alt area; img; input Replacement text for use when images are not available Text*
async script Execute script asynchronously Boolean attribute
autocomplete form Default setting for autofill feature for controls in the form "on"; "off"
autocomplete input; select; textarea Hint for form autofill feature Autofill field name and related tokens*
autofocus button; input; keygen; select; textarea Automatically focus the form control when the page is loaded Boolean attribute
autoplay audio; video Hint that the media resource can be started automatically when the page is loaded Boolean attribute
border table Explicit indication that the table element is not being used for layout purposes The empty string, or "1"
challenge keygen String to package with the generated and signed public key Text
charset meta Character encoding declaration Encoding label*
charset script Character encoding of the external script resource Encoding label*
checked menuitem; input Whether the command or control is checked Boolean attribute
cite blockquote; del; ins; q Link to the source of the quotation or more information about the edit Valid URL potentially surrounded by spaces
class HTML elements Classes to which the element belongs Set of space-separated tokens
cols textarea Maximum number of characters per line Valid non-negative integer greater than zero
colspan td; th Number of columns that the cell is to span Valid non-negative integer greater than zero
command menuitem Command definition ID*
content meta Value of the element Text*
contenteditable HTML elements Whether the element is editable "true"; "false"
contextmenu HTML elements The element’s context menu ID*
controls audio; video Show user agent controls Boolean attribute
coords area Coordinates for the shape to be created in an image map Valid list of floating-point numbers*
crossorigin audio; img; link; script; video How the element handles crossorigin requests "anonymous"; "use-credentials"
data object Address of the resource Valid non-empty URL potentially surrounded by spaces
datetime del; ins Date and (optionally) time of the change Valid date string with optional time
datetime time Machine-readable value Valid month string, valid date string, valid yearless date string, valid time string, valid floating date and time string, valid time-zone offset string, valid global date and time string, valid week string, valid non-negative integer, or valid duration string
default menuitem Mark the command as being a default command Boolean attribute
default track Enable the track if no other text track is more suitable Boolean attribute
defer script Defer script execution Boolean attribute
dir HTML elements The text directionality of the element "ltr"; "rtl"; "auto"
dir bdo The text directionality of the element "ltr"; "rtl"
dirname input; textarea Name of form field to use for sending the element’s directionality in form submission Text*
disabled button; menuitem; fieldset; input; keygen; optgroup; option; select; textarea Whether the form control is disabled Boolean attribute
download a; area Whether to download the resource instead of navigating to it, and its file name if so Text
draggable HTML elements Whether the element is draggable "true"; "false"
dropzone HTML elements Accepted item types for drag-and-drop Unordered set of unique space-separated tokens, ASCII case-insensitive, consisting of accepted types and drag feedback*
enctype form Form data set encoding type to use for form submission "application/x-www-form-urlencoded"; "multipart/form-data"; "text/plain"
for label Associate the label with form control ID*
for output Specifies controls from which the output was calculated Unordered set of unique space-separated tokens, case-sensitive, consisting of IDs*
form button; fieldset; input; keygen; label; object; output; select; textarea Associates the control with a form element ID*
formaction button; input URL to use for form submission Valid non-empty URL potentially surrounded by spaces
formenctype button; input Form data set encoding type to use for form submission "application/x-www-form-urlencoded"; "multipart/form-data"; "text/plain"
formmethod button; input HTTP method to use for form submission "GET"; "POST"
formnovalidate button; input Bypass form control validation for form submission Boolean attribute
formtarget button; input Browsing context for form submission Valid browsing context name or keyword
headers td; th The header cells for this cell Unordered set of unique space-separated tokens, case-sensitive, consisting of IDs*
height canvas; embed; iframe; img; input; object; video Vertical dimension Valid non-negative integer
hidden HTML elements Whether the element is relevant Boolean attribute
high meter Low limit of high range Valid floating-point number*
href a; area Address of the hyperlink Valid URL potentially surrounded by spaces
href link Address of the hyperlink Valid non-empty URL potentially surrounded by spaces
href base Document base URL Valid URL potentially surrounded by spaces
hreflang a; area; link Language of the linked resource Valid BCP 47 language tag
http-equiv meta Pragma directive Text*
icon menuitem Icon for the command Valid non-empty URL potentially surrounded by spaces
id HTML elements The element’s ID Text*
inputmode input; textarea Hint for selecting an input modality "verbatim"; "latin"; "latin-name"; "latin-prose"; "full-width-latin"; "kana"; "kana-name"; "katakana"; "numeric"; "tel"; "email"; "url"
ismap img Whether the image is a server-side image map Boolean attribute
keytype keygen The type of cryptographic key to generate Text*
kind track The type of text track "subtitles"; "captions"; "descriptions"; "chapters"; "metadata"
label menuitem; menu; optgroup; option; track User-visible label Text
lang HTML elements Language of the element Valid BCP 47 language tag or the empty string
list input List of autocomplete options ID*
loop audio; video Whether to loop the media resource Boolean attribute
low meter High limit of low range Valid floating-point number*
max input Maximum value Varies*
max meter; progress Upper bound of range Valid floating-point number*
maxlength input; textarea Maximum length of value Valid non-negative integer
media link; style Applicable media Valid media query list
menu button Specifies the element’s designated pop-up menu ID*
method form HTTP method to use for form submission "get"; "post"
min input Minimum value Varies*
min meter Lower bound of range Valid floating-point number*
minlength input; textarea Minimum length of value Valid non-negative integer
multiple input; select Whether to allow multiple values Boolean attribute
muted audio; video Whether to mute the media resource by default Boolean attribute
name button; fieldset; input; keygen; output; select; textarea Name of form control to use for form submission and in the form.elements API Text*
name form Name of form to use in the document.forms API Text*
name iframe; object Name of nested browsing context Valid browsing context name or keyword
name map Name of image map to reference from the usemap attribute Text*
name meta Metadata name Text*
name param Name of parameter Text
nonce script; style Cryptographic nonce used in Content Security Policy checks [CSP3] Text
novalidate form Bypass form control validation for form submission Boolean attribute
open details Whether the details are visible Boolean attribute
optimum meter Optimum value in gauge Valid floating-point number*
pattern input Pattern to be matched by the form control’s value Regular expression matching the JavaScript Pattern production
placeholder input; textarea User-visible label to be placed within the form control Text*
poster video Poster frame to show prior to video playback Valid non-empty URL potentially surrounded by spaces
preload audio; video Hints how much buffering the media resource will likely need "none"; "metadata"; "auto"
radiogroup menuitem Name of group of commands to treat as a radio button group Text
readonly input; textarea Whether to allow the value to be edited by the user Boolean attribute
rel a; area; link Relationship of this document (or subsection/topic) to the destination resource Set of space-separated tokens*
required input; select; textarea Whether the control is required for form submission Boolean attribute
rev a; link Reverse link relationship of the destination resource to this document (or subsection/topic) Set of space-separated tokens
reversed ol Number the list backwards Boolean attribute
rows textarea Number of lines to show Valid non-negative integer greater than zero
rowspan td; th Number of rows that the cell is to span Valid non-negative integer
sandbox iframe Security rules for nested content Unordered set of unique space-separated tokens, ASCII case-insensitive, consisting of "allow-forms", "allow-pointer-lock", "allow-popups", "allow-same-origin", "allow-scripts and "allow-top-navigation"
spellcheck HTML elements Whether the element is to have its spelling and grammar checked "true"; "false"
scope th Specifies which cells the header cell applies to "row"; "col"; "rowgroup"; "colgroup"
selected option Whether the option is selected by default Boolean attribute
shape area The kind of shape to be created in an image map "circle"; "default"; "poly"; "rect"
size input; select Size of the control Valid non-negative integer greater than zero
sizes link Sizes of the icons (for rel="icon") Unordered set of unique space-separated tokens, ASCII case-insensitive, consisting of sizes*
sizes img; source Image sizes for different page layouts Valid source size list
span col; colgroup Number of columns spanned by the element Valid non-negative integer greater than zero
src audio; embed; iframe; img; input; script; source; track; video Address of the resource Valid non-empty URL potentially surrounded by spaces
srcdoc iframe A document to render in the iframe The source of an iframe srcdoc document*
srclang track Language of the text track Valid BCP 47 language tag
srcset img; source Images to use in different situations (e.g., high-resolution displays, small monitors, etc) Comma-separated list of image candidate strings
start ol Ordinal value of the first item Valid integer
step input Granularity to be matched by the form control’s value Valid floating-point number greater than zero, or "any"
style HTML elements Presentational and formatting instructions CSS declarations*
tabindex HTML elements Whether the element is focusable, and the relative order of the element for the purposes of sequential focus navigation Valid integer
target a; area Browsing context for hyperlink navigation Valid browsing context name or keyword
target base Default browsing context for hyperlink navigation and form submission Valid browsing context name or keyword
target form Browsing context for form submission Valid browsing context name or keyword
title HTML elements Advisory information for the element Text
title abbr; dfn Full term or expansion of abbreviation Text
title input Description of pattern (when used with pattern attribute) Text
title menuitem Hint describing the command Text
title link Title of the link Text
title link; style Alternative style sheet set name Text
translate HTML elements Whether the element is to be translated when the page is localized "yes"; "no"
type a; area; link Hint for the type of the referenced resource Valid MIME type
type button Type of button "submit"; "reset"; "button"; "menu"
type embed; object; script; source; style Type of embedded resource Valid MIME type
type input Type of form control input type keyword
type menu Type of menu "context";
type menuitem Type of command "command"; "checkbox"; "radio"
type ol Kind of list marker "1"; "a"; "A"; "i"; "I"
typemustmatch object Whether the type attribute and the Content-Type value need to match for the resource to be used Boolean attribute
usemap img Name of image map to use Valid hash-name reference*
value button; option Value to be used for form submission Text
value data Machine-readable value Text*
value input Value of the form control Varies*
value li Ordinal value of the list item Valid integer
value meter; progress Current value of the element Valid floating-point number
value param Value of parameter Text
width canvas; embed; iframe; img; input; object; video Horizontal dimension Valid non-negative integer
wrap textarea How the value of the form control is to be wrapped for form submission "soft"; "hard"

An asterisk (*) in a cell indicates that the actual rules are more complicated than indicated in the table above.


List of event handler content attributes
Attribute Element(s) Description Value
onabort HTML elements abort event handler Event handler content attribute
onafterprint body afterprint event handler for Window object Event handler content attribute
onbeforeprint body beforeprint event handler for Window object Event handler content attribute
onbeforeunload body beforeunload event handler for Window object Event handler content attribute
onblur HTML elements blur event handler Event handler content attribute
oncanplay HTML elements canplay event handler Event handler content attribute
oncanplaythrough HTML elements canplaythrough event handler Event handler content attribute
onchange HTML elements change event handler Event handler content attribute
onclick HTML elements click event handler Event handler content attribute
oncontextmenu HTML elements contextmenu event handler Event handler content attribute
oncopy HTML elements copy event handler Event handler content attribute
oncuechange HTML elements cuechange event handler Event handler content attribute
oncut HTML elements cut event handler Event handler content attribute
ondblclick HTML elements dblclick event handler Event handler content attribute
ondrag HTML elements drag event handler Event handler content attribute
ondragend HTML elements dragend event handler Event handler content attribute
ondragenter HTML elements dragenter event handler Event handler content attribute
ondragexit HTML elements dragexit event handler Event handler content attribute
ondragleave HTML elements dragleave event handler Event handler content attribute
ondragover HTML elements dragover event handler Event handler content attribute
ondragstart HTML elements dragstart event handler Event handler content attribute
ondrop HTML elements drop event handler Event handler content attribute
ondurationchange HTML elements durationchange event handler Event handler content attribute
onended HTML elements ended event handler Event handler content attribute
onerror HTML elements error event handler Event handler content attribute
onfocus HTML elements focus event handler Event handler content attribute
onhashchange body hashchange event handler for Window object Event handler content attribute
oninput HTML elements input event handler Event handler content attribute
oninvalid HTML elements invalid event handler Event handler content attribute
onkeydown HTML elements keydown event handler Event handler content attribute
onkeypress HTML elements keypress event handler Event handler content attribute
onkeyup HTML elements keyup event handler Event handler content attribute
onlanguagechange body languagechange event handler for Window object Event handler content attribute
onload HTML elements load event handler Event handler content attribute
onloadeddata HTML elements loadeddata event handler Event handler content attribute
onloadedmetadata HTML elements loadedmetadata event handler Event handler content attribute
onloadstart HTML elements loadstart event handler Event handler content attribute
onmessage body message event handler for Window object Event handler content attribute
onmousedown HTML elements mousedown event handler Event handler content attribute
onmouseenter HTML elements mouseenter event handler Event handler content attribute
onmouseleave HTML elements mouseleave event handler Event handler content attribute
onmousemove HTML elements mousemove event handler Event handler content attribute
onmouseout HTML elements mouseout event handler Event handler content attribute
onmouseover HTML elements mouseover event handler Event handler content attribute
onmouseup HTML elements mouseup event handler Event handler content attribute
onwheel HTML elements wheel event handler Event handler content attribute
onoffline body offline event handler for Window object Event handler content attribute
ononline body online event handler for Window object Event handler content attribute
onpagehide body pagehide event handler for Window object Event handler content attribute
onpageshow body pageshow event handler for Window object Event handler content attribute
onpaste HTML elements paste event handler Event handler content attribute
onpause HTML elements pause event handler Event handler content attribute
onplay HTML elements play event handler Event handler content attribute
onplaying HTML elements playing event handler Event handler content attribute
onpopstate body popstate event handler for Window object Event handler content attribute
onprogress HTML elements progress event handler Event handler content attribute
onratechange HTML elements ratechange event handler Event handler content attribute
onreset HTML elements reset event handler Event handler content attribute
onresize HTML elements resize event handler Event handler content attribute
onscroll HTML elements scroll event handler Event handler content attribute
onseeked HTML elements seeked event handler Event handler content attribute
onseeking HTML elements seeking event handler Event handler content attribute
onselect HTML elements select event handler Event handler content attribute
onshow HTML elements show event handler Event handler content attribute
onstalled HTML elements stalled event handler Event handler content attribute
onstorage body storage event handler for Window object Event handler content attribute
onsubmit HTML elements submit event handler Event handler content attribute
onsuspend HTML elements suspend event handler Event handler content attribute
ontimeupdate HTML elements timeupdate event handler Event handler content attribute
ontoggle HTML elements toggle event handler Event handler content attribute
onunload body unload event handler for Window object Event handler content attribute
onvolumechange HTML elements volumechange event handler Event handler content attribute
onwaiting HTML elements waiting event handler Event handler content attribute

Element Interfaces

This section is non-normative.

List of interfaces for elements
Element(s) Interface(s)
a HTMLAnchorElement : HTMLElement
abbr HTMLElement
address HTMLElement
area HTMLAreaElement : HTMLElement
article HTMLElement
aside HTMLElement
audio HTMLAudioElement : HTMLMediaElement : HTMLElement
b HTMLElement
base HTMLBaseElement : HTMLElement
bdi HTMLElement
bdo HTMLElement
blockquote HTMLQuoteElement : HTMLElement
body HTMLBodyElement : HTMLElement
br HTMLBRElement : HTMLElement
button HTMLButtonElement : HTMLElement
canvas HTMLCanvasElement : HTMLElement
caption HTMLTableCaptionElement : HTMLElement
cite HTMLElement
code HTMLElement
col HTMLTableColElement : HTMLElement
colgroup HTMLTableColElement : HTMLElement
menuitem HTMLMenuItemElement : HTMLElement
data HTMLDataElement : HTMLElement
datalist HTMLDataListElement : HTMLElement
dd HTMLElement
del HTMLModElement : HTMLElement
details HTMLDetailsElement : HTMLElement
dfn HTMLElement
div HTMLDivElement : HTMLElement
dl HTMLDListElement : HTMLElement
dt HTMLElement
em HTMLElement
embed HTMLEmbedElement : HTMLElement
fieldset HTMLFieldSetElement : HTMLElement
figcaption HTMLElement
figure HTMLElement
footer HTMLElement
form HTMLFormElement : HTMLElement
h1 HTMLHeadingElement : HTMLElement
h2 HTMLHeadingElement : HTMLElement
h3 HTMLHeadingElement : HTMLElement
h4 HTMLHeadingElement : HTMLElement
h5 HTMLHeadingElement : HTMLElement
h6 HTMLHeadingElement : HTMLElement
head HTMLHeadElement : HTMLElement
header HTMLElement
hr HTMLHRElement : HTMLElement
html HTMLHtmlElement : HTMLElement
i HTMLElement
iframe HTMLIFrameElement : HTMLElement
img HTMLImageElement : HTMLElement
input HTMLInputElement : HTMLElement
ins HTMLModElement : HTMLElement
kbd HTMLElement
keygen HTMLKeygenElement : HTMLElement
label HTMLLabelElement : HTMLElement
legend HTMLLegendElement : HTMLElement
li HTMLLIElement : HTMLElement
link HTMLLinkElement : HTMLElement
main HTMLElement
map HTMLMapElement : HTMLElement
mark HTMLElement
menu HTMLMenuElement : HTMLElement
meta HTMLMetaElement : HTMLElement
meter HTMLMeterElement : HTMLElement
nav HTMLElement
noscript HTMLElement
object HTMLObjectElement : HTMLElement
ol HTMLOListElement : HTMLElement
optgroup HTMLOptGroupElement : HTMLElement
option HTMLOptionElement : HTMLElement
output HTMLOutputElement : HTMLElement
p HTMLParagraphElement : HTMLElement
param HTMLParamElement : HTMLElement
picture HTMLPictureElement : HTMLElement
pre HTMLPreElement : HTMLElement
progress HTMLProgressElement : HTMLElement
q HTMLQuoteElement : HTMLElement
rb HTMLElement
rp HTMLElement
rt HTMLElement
rtc HTMLElement
ruby HTMLElement
s HTMLElement
samp HTMLElement
script HTMLScriptElement : HTMLElement
section HTMLElement
select HTMLSelectElement : HTMLElement
small HTMLElement
source HTMLSourceElement : HTMLElement
source HTMLSourceElement : HTMLElement
span HTMLSpanElement : HTMLElement
strong HTMLElement
style HTMLStyleElement : HTMLElement
sub HTMLElement
summary HTMLElement
sup HTMLElement
table HTMLTableElement : HTMLElement
tbody HTMLTableSectionElement : HTMLElement
td HTMLTableDataCellElement : HTMLTableCellElement : HTMLElement
template HTMLTemplateElement : HTMLElement
textarea HTMLTextAreaElement : HTMLElement
tfoot HTMLTableSectionElement : HTMLElement
th HTMLTableHeaderCellElement : HTMLTableCellElement : HTMLElement
thead HTMLTableSectionElement : HTMLElement
time HTMLTimeElement : HTMLElement
title HTMLTitleElement : HTMLElement
tr HTMLTableRowElement : HTMLElement
track HTMLTrackElement : HTMLElement
u HTMLElement
ul HTMLUListElement : HTMLElement
var HTMLElement
video HTMLVideoElement : HTMLMediaElement : HTMLElement
wbr HTMLElement

Events

This section is non-normative.

List of events
Event Interface Interesting targets Description
abort Event Window Fired at the Window when the download was aborted by the user
DOMContentLoaded Event Document Fired at the Document once the parser has finished
afterprint Event Window Fired at the Window after printing
afterscriptexecute Event script elements Fired at script elements after the script runs (just before the corresponding load event)
beforeprint Event Window Fired at the Window before printing
beforescriptexecute Event script elements Fired at script elements just before the script runs; canceling the event cancels the running of the script
beforeunload BeforeUnloadEvent Window Fired at the Window when the page is about to be unloaded, in case the page would like to show a warning prompt
blur Event Window, elements Fired at nodes losing focus
change Event Form controls Fired at controls when the user commits a value change (see also the change event of input elements)
click MouseEvent Elements Normally a mouse event; also synthetically fired at an element before its activation behavior is run, when an element is activated from a non-pointer input device (e.g., a keyboard)
contextmenu Event Elements Fired at elements when the user requests their context menu
copy Event Elements Fired at elements when the user copies data to the clipboard
cut Event Elements Fired at elements when the user copies the selected data on the clipboard and removes the selection from the document
error Event Global scope objects, Worker objects, elements, networking-related objects Fired when unexpected errors occur (e.g., networking errors, script errors, decoding errors)
focus Event Window, elements Fired at nodes gaining focus
hashchange HashChangeEvent Window Fired at the Window when the fragment identifier part of the document’s address changes
input Event Form controls Fired at controls when the user changes the value (see also the change event of input elements)
invalid Event Form controls Fired at controls during form validation if they do not satisfy their constraints
languagechange Event Global scope objects Fired at the global scope object when the user’s preferred languages change
load Event Window, elements Fired at the Window when the document has finished loading; fired at an element containing a resource (e.g., img, embed) when its resource has finished loading
loadend Event or ProgressEvent img elements Fired at img elements after a successful load (see also media element events)
loadstart ProgressEvent img elements Fired at img elements when a load begins (see also media element events)
message MessageEvent Window, EventSource, WebSocket, MessagePort, DedicatedWorkerGlobalScope, Worker Fired at an object when it receives a message
offline Event Global scope objects Fired at the global scope object when the network connections fails
online Event Global scope objects Fired at the global scope object when the network connections returns
open Event EventSource, WebSocket Fired at networking-related objects when a connection is established
pagehide PageTransitionEvent Window Fired at the Window when the page’s entry in the session history stops being the current entry
pageshow PageTransitionEvent Window Fired at the Window when the page’s entry in the session history becomes the current entry
paste Event Elements Fired at elements when the user will insert the clipboard data in the most suitable format (if any) supported for the given context
popstate PopStateEvent Window Fired at the Window when the user navigates the session history
progress ProgressEvent img elements Fired at img elements during a CORS-same-origin image load (see also media element events)
readystatechange Event Document Fired at the Document when it finishes parsing and again when all its subresources have finished loading
reset Event form elements Fired at a form element when it is reset
select Event Form controls Fired at form controls when their text selection is adjusted (whether by an API or by the user)
show RelatedEvent menu elements Fired at a menu element when it is shown as a context menu
storage StorageEvent Window Fired at Window event when the corresponding localStorage or sessionStorage storage areas change
submit Event form elements Fired at a form element when it is submitted
toggle Event details element Fired at details elements when they open or close
unload Event Window Fired at the Window object when the page is going away

See also media element events, application cache events, and drag-and-drop events.

IDL Index

[LegacyUnenumerableNamedProperties]
interface HTMLAllCollection {
  readonly attribute unsigned long length;
  getter Element? (unsigned long index);
  getter (HTMLCollection or Element)? namedItem(DOMString name);
  legacycaller (HTMLCollection or Element)? item(optional DOMString nameOrItem);
};

interface HTMLFormControlsCollection : HTMLCollection {
  // inherits length and item()
  getter (RadioNodeList or Element)? namedItem(DOMString name); // shadows inherited namedItem()
};

interface RadioNodeList : NodeList {
  attribute DOMString value;
};

interface HTMLOptionsCollection : HTMLCollection {
  // inherits item(), namedItem()
  attribute unsigned long length; // shadows inherited length
  setter void (unsigned long index, HTMLOptionElement? option);
  void add((HTMLOptionElement or HTMLOptGroupElement) element, optional (HTMLElement or long)? before = null);
  void remove(long index);
  attribute long selectedIndex;
};

[OverrideBuiltins]
interface DOMStringMap {
  getter DOMString (DOMString name);
  setter void (DOMString name, DOMString value);
  deleter void (DOMString name);
};

interface DOMElementMap {
  getter Element (DOMString name);
  setter creator void (DOMString name, Element value);
  deleter void (DOMString name);
};

enum DocumentReadyState { "loading", "interactive", "complete" };

[OverrideBuiltins]
partial /*sealed*/ interface Document {
  // resource metadata management
  [PutForwards=href, Unforgeable] readonly attribute Location? location;
  attribute DOMString domain;
  readonly attribute DOMString referrer;
  attribute DOMString cookie;
  readonly attribute DOMString lastModified;
  readonly attribute DocumentReadyState readyState;

  // DOM tree accessors
  getter object (DOMString name);
  attribute DOMString title;
  attribute DOMString dir;
  attribute HTMLElement? body;
  readonly attribute HTMLHeadElement? head;
  [SameObject] readonly attribute HTMLCollection images;
  [SameObject] readonly attribute HTMLCollection embeds;
  [SameObject] readonly attribute HTMLCollection plugins;
  [SameObject] readonly attribute HTMLCollection links;
  [SameObject] readonly attribute HTMLCollection forms;
  [SameObject] readonly attribute HTMLCollection scripts;
  NodeList getElementsByName(DOMString elementName);
  readonly attribute HTMLScriptElement? currentScript;

  // dynamic markup insertion
  Document open(optional DOMString type = "text/html", optional DOMString replace = "");
  WindowProxy open(DOMString url, DOMString name, DOMString features, optional boolean replace = false);
  void close();
  void write(DOMString... text);
  void writeln(DOMString... text);

  // user interaction
  readonly attribute WindowProxy? defaultView;
  readonly attribute Element? activeElement;
  boolean hasFocus();
  attribute DOMString designMode;
  boolean execCommand(DOMString commandId, optional boolean showUI = false, optional DOMString value = "");
  boolean queryCommandEnabled(DOMString commandId);
  boolean queryCommandIndeterm(DOMString commandId);
  boolean queryCommandState(DOMString commandId);
  boolean queryCommandSupported(DOMString commandId);
  DOMString queryCommandValue(DOMString commandId);

  // special event handler IDL attributes that only apply to Document objects
  [LenientThis] attribute EventHandler onreadystatechange;
};
Document implements GlobalEventHandlers;
Document implements DocumentAndElementEventHandlers;

partial interface XMLDocument {
  boolean load(DOMString url);
};

interface HTMLElement : Element {
  // metadata attributes
  attribute DOMString title;
  attribute DOMString lang;
  attribute boolean translate;
  attribute DOMString dir;
  [SameObject] readonly attribute DOMStringMap dataset;

  // user interaction
  attribute boolean hidden;
  void click();
  attribute long tabIndex;
  void focus();
  void blur();
  attribute DOMString accessKey;
  attribute boolean draggable;
  [PutForwards=value] readonly attribute DOMTokenList dropzone;
  attribute HTMLMenuElement? contextMenu;
  attribute boolean spellcheck;
  void forceSpellCheck();
};
HTMLElement implements GlobalEventHandlers;
HTMLElement implements DocumentAndElementEventHandlers;
HTMLElement implements ElementContentEditable;

interface HTMLUnknownElement : HTMLElement { };

interface HTMLHtmlElement : HTMLElement {};

interface HTMLHeadElement : HTMLElement {};

interface HTMLTitleElement : HTMLElement {
  attribute DOMString text;
};

interface HTMLBaseElement : HTMLElement {
  attribute DOMString href;
  attribute DOMString target;
};

interface HTMLLinkElement : HTMLElement {
  attribute DOMString href;
  attribute DOMString? crossOrigin;
  attribute DOMString rel;
  attribute DOMString rev;
  [SameObject, PutForwards=value]readonly attribute DOMTokenList relList;
  attribute DOMString media;
  attribute DOMString hreflang;
  attribute DOMString type;
  [SameObject, PutForwards=value] readonly attribute DOMTokenList sizes;
};
HTMLLinkElement implements LinkStyle;

interface HTMLMetaElement : HTMLElement {
  attribute DOMString name;
  attribute DOMString httpEquiv;
  attribute DOMString content;
};

interface HTMLStyleElement : HTMLElement {
  attribute DOMString media;
  attribute DOMString nonce;
  attribute DOMString type;
};
HTMLStyleElement implements LinkStyle;

interface HTMLBodyElement : HTMLElement {
};
HTMLBodyElement implements WindowEventHandlers;

interface HTMLHeadingElement : HTMLElement {};

interface HTMLParagraphElement : HTMLElement {};

interface HTMLHRElement : HTMLElement {};

interface HTMLPreElement : HTMLElement {};

interface HTMLQuoteElement : HTMLElement {
  attribute DOMString cite;
};

interface HTMLOListElement : HTMLElement {
  attribute boolean reversed;
  attribute long start;
  attribute DOMString type;
};

interface HTMLUListElement : HTMLElement {};

interface HTMLLIElement : HTMLElement {
  attribute long value;
};

interface HTMLDListElement : HTMLElement {};

interface HTMLDivElement : HTMLElement {};

interface HTMLAnchorElement : HTMLElement {
  attribute DOMString target;
  attribute DOMString download;
  attribute DOMString rel;
  attribute DOMString rev;
  [SameObject, PutForwards=value] readonly attribute DOMTokenList relList;
  attribute DOMString hreflang;
  attribute DOMString type;
  attribute DOMString text;
};
HTMLAnchorElement implements HTMLHyperlinkElementUtils;

interface HTMLDataElement : HTMLElement {
  attribute DOMString value;
};

interface HTMLTimeElement : HTMLElement {
  attribute DOMString dateTime;
};

interface HTMLSpanElement : HTMLElement {};

interface HTMLBRElement : HTMLElement {};

interface HTMLModElement : HTMLElement {
  attribute DOMString cite;
  attribute DOMString dateTime;
};

interface HTMLPictureElement : HTMLElement {};

partial interface HTMLSourceElement {
  attribute DOMString srcset;
  attribute DOMString sizes;
  attribute DOMString media;
};

[NamedConstructor=Image(선택적으로 부호 없는 너비 길이, 선택적으로 부호 없는 높이 길이)]
interface HTMLImageElement : HTMLElement {
  attribute DOMString alt;
  attribute DOMString src;
  attribute DOMString srcset;
  attribute DOMString sizes;
  attribute DOMString? crossOrigin;
  attribute DOMString useMap;
  attribute boolean isMap;
  attribute unsigned long width;
  attribute unsigned long height;
  readonly attribute unsigned long naturalWidth;
  readonly attribute unsigned long naturalHeight;
  readonly attribute boolean complete;
  readonly attribute DOMString currentSrc;
};

interface HTMLIFrameElement : HTMLElement {
  attribute DOMString src;
  attribute DOMString srcdoc;
  attribute DOMString name;
  [PutForwards=value] readonly attribute DOMTokenList sandbox;
  attribute boolean allowFullscreen;
  attribute DOMString width;
  attribute DOMString height;
  readonly attribute Document? contentDocument;
  readonly attribute WindowProxy? contentWindow;
};

interface HTMLEmbedElement : HTMLElement {
  attribute DOMString src;
  attribute DOMString type;
  attribute DOMString width;
  attribute DOMString height;
  legacycaller any (any... arguments);
};

interface HTMLObjectElement : HTMLElement {
  attribute DOMString data;
  attribute DOMString type;
  attribute boolean typeMustMatch;
  attribute DOMString name;
  readonly attribute HTMLFormElement? form;
  attribute DOMString width;
  attribute DOMString height;
  readonly attribute Document? contentDocument;
  readonly attribute WindowProxy? contentWindow;

  readonly attribute boolean willValidate;
  readonly attribute ValidityState validity;
  readonly attribute DOMString validationMessage;
  boolean checkValidity();
  boolean reportValidity();
  void setCustomValidity(DOMString error);

  legacycaller any (any... arguments);
};

interface HTMLParamElement : HTMLElement {
  attribute DOMString name;
  attribute DOMString value;
};

interface HTMLVideoElement : HTMLMediaElement {
  attribute unsigned long width;
  attribute unsigned long height;
  readonly attribute unsigned long videoWidth;
  readonly attribute unsigned long videoHeight;
  attribute DOMString poster;
};

[NamedConstructor=Audio(optional DOMString src)]
interface HTMLAudioElement : HTMLMediaElement {};

interface HTMLSourceElement : HTMLElement {
  attribute DOMString src;
  attribute DOMString type;
};

interface HTMLTrackElement : HTMLElement {
  attribute DOMString kind;
  attribute DOMString src;
  attribute DOMString srclang;
  attribute DOMString label;
  attribute boolean default;

  const unsigned short NONE = 0;
  const unsigned short LOADING = 1;
  const unsigned short LOADED = 2;
  const unsigned short ERROR = 3;
  readonly attribute unsigned short readyState;

  readonly attribute TextTrack track;
};

enum CanPlayTypeResult { "" /* empty string */, "maybe", "probably" };

typedef (MediaStream or MediaSource or Blob) MediaProvider;

interface HTMLMediaElement : HTMLElement {

  // error state
  readonly attribute MediaError? error;

  // network state
  attribute DOMString src;
  attribute MediaProvider? srcObject;
  readonly attribute DOMString currentSrc;
  attribute DOMString? crossOrigin;
  const unsigned short NETWORK_EMPTY = 0;
  const unsigned short NETWORK_IDLE = 1;
  const unsigned short NETWORK_LOADING = 2;
  const unsigned short NETWORK_NO_SOURCE = 3;
  readonly attribute unsigned short networkState;
  attribute DOMString preload;
  readonly attribute TimeRanges buffered;
  void load();
  CanPlayTypeResult canPlayType(DOMString type);

  // ready state
  const unsigned short HAVE_NOTHING = 0;
  const unsigned short HAVE_METADATA = 1;
  const unsigned short HAVE_CURRENT_DATA = 2;
  const unsigned short HAVE_FUTURE_DATA = 3;
  const unsigned short HAVE_ENOUGH_DATA = 4;
  readonly attribute unsigned short readyState;
  readonly attribute boolean seeking;

  // playback state
  attribute double currentTime;
  void fastSeek(double time);
  readonly attribute unrestricted double duration;
  object getStartDate();
  readonly attribute boolean paused;
  attribute double defaultPlaybackRate;
  attribute double playbackRate;
  readonly attribute TimeRanges played;
  readonly attribute TimeRanges seekable;
  readonly attribute boolean ended;
  attribute boolean autoplay;
  attribute boolean loop;
  void play();
  void pause();

  // controls
  attribute boolean controls;
  attribute double volume;
  attribute boolean muted;
  attribute boolean defaultMuted;

  // tracks
  [SameObject] readonly attribute AudioTrackList audioTracks;
  [SameObject] readonly attribute VideoTrackList videoTracks;
  [SameObject] readonly attribute TextTrackList textTracks;
  TextTrack addTextTrack(TextTrackKind kind, optional DOMString label = "", optional DOMString language = "");
};

interface MediaError {
  const unsigned short MEDIA_ERR_ABORTED = 1;
  const unsigned short MEDIA_ERR_NETWORK = 2;
  const unsigned short MEDIA_ERR_DECODE = 3;
  const unsigned short MEDIA_ERR_SRC_NOT_SUPPORTED = 4;
  readonly attribute unsigned short code;
};

interface AudioTrackList : EventTarget {
  readonly attribute unsigned long length;
  getter AudioTrack (unsigned long index);
  AudioTrack? getTrackById(DOMString id);

  attribute EventHandler onchange;
  attribute EventHandler onaddtrack;
  attribute EventHandler onremovetrack;
};

interface AudioTrack {
  readonly attribute DOMString id;
  readonly attribute DOMString kind;
  readonly attribute DOMString label;
  readonly attribute DOMString language;
  attribute boolean enabled;
};

interface VideoTrackList : EventTarget {
  readonly attribute unsigned long length;
  getter VideoTrack (unsigned long index);
  VideoTrack? getTrackById(DOMString id);
  readonly attribute long selectedIndex;

  attribute EventHandler onchange;
  attribute EventHandler onaddtrack;
  attribute EventHandler onremovetrack;
};

interface VideoTrack {
  readonly attribute DOMString id;
  readonly attribute DOMString kind;
  readonly attribute DOMString label;
  readonly attribute DOMString language;
  attribute boolean selected;
};

interface TextTrackList : EventTarget {
  readonly attribute unsigned long length;
  getter TextTrack (unsigned long index);
  TextTrack? getTrackById(DOMString id);

  attribute EventHandler onchange;
  attribute EventHandler onaddtrack;
  attribute EventHandler onremovetrack;
};

enum TextTrackMode { "disabled",  "hidden",  "showing" };

enum TextTrackKind { "subtitles",  "captions",  "descriptions",  "chapters",  "metadata" };

interface TextTrack : EventTarget {
  readonly attribute TextTrackKind kind;
  readonly attribute DOMString label;
  readonly attribute DOMString language;

  readonly attribute DOMString id;
  readonly attribute DOMString inBandMetadataTrackDispatchType;

  attribute TextTrackMode mode;

  readonly attribute TextTrackCueList? cues;
  readonly attribute TextTrackCueList? activeCues;

  void addCue(TextTrackCue cue);
  void removeCue(TextTrackCue cue);

  attribute EventHandler oncuechange;
};

interface TextTrackCueList {
  readonly attribute unsigned long length;
  getter TextTrackCue (unsigned long index);
  TextTrackCue? getCueById(DOMString id);
};

interface TextTrackCue : EventTarget {
  readonly attribute TextTrack? track;

  attribute DOMString id;
  attribute double startTime;
  attribute double endTime;
  attribute boolean pauseOnExit;

  attribute EventHandler onenter;
  attribute EventHandler onexit;
};

[Constructor(double startTime, double endTime, ArrayBuffer data)]
interface DataCue : TextTrackCue {
  attribute ArrayBuffer data;
};

interface TimeRanges {
  readonly attribute unsigned long length;
  double start(unsigned long index);
  double end(unsigned long index);
};

[Constructor(DOMString type, optional TrackEventInit eventInitDict)]
interface TrackEvent : Event {
  readonly attribute (VideoTrack or AudioTrack or TextTrack)? track;
};

dictionary TrackEventInit : EventInit {
  (VideoTrack or AudioTrack or TextTrack)? track;
};

interface HTMLMapElement : HTMLElement {
  attribute DOMString name;
  [SameObject] readonly attribute HTMLCollection areas;
  [SameObject] readonly attribute HTMLCollection images;
};

interface HTMLAreaElement : HTMLElement {
  attribute DOMString alt;
  attribute DOMString coords;
  attribute DOMString shape;
  attribute DOMString target;
  attribute DOMString download;
  attribute DOMString rel;
  readonly attribute DOMTokenList relList;
  attribute DOMString hreflang;
  attribute DOMString type;
};
HTMLAreaElement implements HTMLHyperlinkElementUtils;

[NoInterfaceObject]
interface HTMLHyperlinkElementUtils {
  stringifier attribute USVString href;
  readonly attribute USVString origin;
  attribute USVString protocol;
  attribute USVString username;
  attribute USVString password;
  attribute USVString host;
  attribute USVString hostname;
  attribute USVString port;
  attribute USVString pathname;
  attribute USVString search;
  attribute USVString hash;
};

interface HTMLTableElement : HTMLElement {
  attribute HTMLTableCaptionElement? caption;
  HTMLTableCaptionElement createCaption();
  void deleteCaption();
  attribute HTMLTableSectionElement? tHead;
  HTMLTableSectionElement createTHead();
  void deleteTHead();
  attribute HTMLTableSectionElement? tFoot;
  HTMLTableSectionElement createTFoot();
  void deleteTFoot();
  [SameObject] readonly attribute HTMLCollection tBodies;
  HTMLTableSectionElement createTBody();
  [SameObject] readonly attribute HTMLCollection rows;
  HTMLTableRowElement insertRow(optional long index = -1);
  void deleteRow(long index);
};

interface HTMLTableCaptionElement : HTMLElement {};

interface HTMLTableColElement : HTMLElement {
  attribute unsigned long span;
};

interface HTMLTableSectionElement : HTMLElement {
  [SameObject] readonly attribute HTMLCollection rows;
  HTMLElement insertRow(optional long index = -1);
  void deleteRow(long index);
};

interface HTMLTableRowElement : HTMLElement {
  readonly attribute long rowIndex;
  readonly attribute long sectionRowIndex;
  [SameObject] readonly attribute HTMLCollection cells;
  HTMLElement insertCell(optional long index = -1);
  void deleteCell(long index);
};

interface HTMLTableDataCellElement : HTMLTableCellElement {};

interface HTMLTableHeaderCellElement : HTMLTableCellElement {
  attribute DOMString scope;
  attribute DOMString abbr;
};

interface HTMLTableCellElement : HTMLElement {
  attribute unsigned long colSpan;
  attribute unsigned long rowSpan;
  [PutForwards=value] readonly attribute DOMTokenList headers;
  readonly attribute long cellIndex;
};

[OverrideBuiltins]
interface HTMLFormElement : HTMLElement {
  attribute DOMString acceptCharset;
  attribute DOMString action;
  attribute DOMString autocomplete;
  attribute DOMString enctype;
  attribute DOMString encoding;
  attribute DOMString method;
  attribute DOMString name;
  attribute boolean noValidate;
  attribute DOMString target;

  [SameObject] readonly attribute HTMLFormControlsCollection elements;
  readonly attribute unsigned long length;
  getter Element (unsigned long index);
  getter (RadioNodeList or Element) (DOMString name);

  void submit();
  void reset();
  boolean checkValidity();
  boolean reportValidity();
};

interface HTMLLabelElement : HTMLElement {
  readonly attribute HTMLFormElement? form;
  attribute DOMString htmlFor;
  readonly attribute HTMLElement? control;
};

interface HTMLInputElement : HTMLElement {
  attribute DOMString accept;
  attribute DOMString alt;
  attribute DOMString autocomplete;
  attribute boolean autofocus;
  attribute boolean defaultChecked;
  attribute boolean checked;
  attribute DOMString dirName;
  attribute boolean disabled;
  readonly attribute HTMLFormElement? form;
  readonly attribute FileList? files;
  attribute DOMString formAction;
  attribute DOMString formEnctype;
  attribute DOMString formMethod;
  attribute boolean formNoValidate;
  attribute DOMString formTarget;
  attribute unsigned long height;
  attribute boolean indeterminate;
  attribute DOMString inputMode;
  readonly attribute HTMLElement? list;
  attribute DOMString max;
  attribute long maxLength;
  attribute DOMString min;
  attribute long minLength;
  attribute boolean multiple;
  attribute DOMString name;
  attribute DOMString pattern;
  attribute DOMString placeholder;
  attribute boolean readOnly;
  attribute boolean required;
  attribute unsigned long size;
  attribute DOMString src;
  attribute DOMString step;
  attribute DOMString type;
  attribute DOMString defaultValue;
  [TreatNullAs=EmptyString] attribute DOMString value;
  attribute object? valueAsDate;
  attribute unrestricted double valueAsNumber;
  attribute unsigned long width;

  void stepUp(optional long n = 1);
  void stepDown(optional long n = 1);

  readonly attribute boolean willValidate;
  readonly attribute ValidityState validity;
  readonly attribute DOMString validationMessage;
  boolean checkValidity();
  boolean reportValidity();
  void setCustomValidity(DOMString error);

  [SameObject] readonly attribute NodeList labels;

  void select();
  attribute unsigned long selectionStart;
  attribute unsigned long selectionEnd;
  attribute DOMString selectionDirection;
  void setRangeText(DOMString replacement);
  void setRangeText(DOMString replacement, unsigned long start, unsigned long end, optional SelectionMode selectionMode = "preserve");
  void setSelectionRange(unsigned long start, unsigned long end, optional DOMString direction);
};

interface HTMLButtonElement : HTMLElement {
  attribute boolean autofocus;
  attribute boolean disabled;
  readonly attribute HTMLFormElement? form;
  attribute DOMString formAction;
  attribute DOMString formEnctype;
  attribute DOMString formMethod;
  attribute boolean formNoValidate;
  attribute DOMString formTarget;
  attribute DOMString name;
  attribute DOMString type;
  attribute DOMString value;
  attribute HTMLMenuElement? menu;

  readonly attribute boolean willValidate;
  readonly attribute ValidityState validity;
  readonly attribute DOMString validationMessage;
  boolean checkValidity();
  boolean reportValidity();
  void setCustomValidity(DOMString error);

  [SameObject] readonly attribute NodeList labels;
};

interface HTMLSelectElement : HTMLElement {
  attribute DOMString autocomplete;
  attribute boolean autofocus;
  attribute boolean disabled;
  readonly attribute HTMLFormElement? form;
  attribute boolean multiple;
  attribute DOMString name;
  attribute boolean required;
  attribute unsigned long size;

  readonly attribute DOMString type;

  [SameObject] readonly attribute HTMLOptionsCollection options;
  attribute unsigned long length;
  getter Element? item(unsigned long index);
  HTMLOptionElement? namedItem(DOMString name);
  void add((HTMLOptionElement or HTMLOptGroupElement) element, optional (HTMLElement or long)? before = null);
  void remove(); // ChildNode overload
  void remove(long index);
  setter void (unsigned long index, HTMLOptionElement? option);

  [SameObject] readonly attribute HTMLCollection selectedOptions;
  attribute long selectedIndex;
  attribute DOMString value;

  readonly attribute boolean willValidate;
  readonly attribute ValidityState validity;
  readonly attribute DOMString validationMessage;
  boolean checkValidity();
  boolean reportValidity();
  void setCustomValidity(DOMString error);

  [SameObject] readonly attribute NodeList labels;
};

interface HTMLDataListElement : HTMLElement {
  [SameObject] readonly attribute HTMLCollection options;
};

interface HTMLOptGroupElement : HTMLElement {
  attribute boolean disabled;
  attribute DOMString label;
};

[NamedConstructor=Option(optional DOMString text = "", optional DOMString value, optional boolean defaultSelected = false, optional boolean selected = false)]
interface HTMLOptionElement : HTMLElement {
  attribute boolean disabled;
  readonly attribute HTMLFormElement? form;
  attribute DOMString label;
  attribute boolean defaultSelected;
  attribute boolean selected;
  attribute DOMString value;

  attribute DOMString text;
  readonly attribute long index;
};

interface HTMLTextAreaElement : HTMLElement {
  attribute DOMString autocomplete;
  attribute boolean autofocus;
  attribute unsigned long cols;
  attribute DOMString dirName;
  attribute boolean disabled;
  readonly attribute HTMLFormElement? form;
  attribute DOMString inputMode;
  attribute long maxLength;
  attribute long minLength;
  attribute DOMString name;
  attribute DOMString placeholder;
  attribute boolean readOnly;
  attribute boolean required;
  attribute unsigned long rows;
  attribute DOMString wrap;

  readonly attribute DOMString type;
  attribute DOMString defaultValue;
  [TreatNullAs=EmptyString] attribute DOMString value;
  readonly attribute unsigned long textLength;

  readonly attribute boolean willValidate;
  readonly attribute ValidityState validity;
  readonly attribute DOMString validationMessage;
  boolean checkValidity();
  boolean reportValidity();
  void setCustomValidity(DOMString error);

  [SameObject] readonly attribute NodeList labels;

  void select();
  attribute unsigned long selectionStart;
  attribute unsigned long selectionEnd;
  attribute DOMString selectionDirection;
  void setRangeText(DOMString replacement);
  void setRangeText(DOMString replacement, unsigned long start, unsigned long end, optional SelectionMode selectionMode = "preserve");
  void setSelectionRange(unsigned long start, unsigned long end, optional DOMString direction);
};

interface HTMLKeygenElement : HTMLElement {
  attribute boolean autofocus;
  attribute DOMString challenge;
  attribute boolean disabled;
  readonly attribute HTMLFormElement? form;
  attribute DOMString keytype;
  attribute DOMString name;

  readonly attribute DOMString type;

  readonly attribute boolean willValidate;
  readonly attribute ValidityState validity;
  readonly attribute DOMString validationMessage;
  boolean checkValidity();
  boolean reportValidity();
  void setCustomValidity(DOMString error);

  [SameObject] readonly attribute NodeList labels;
};

interface HTMLOutputElement : HTMLElement {
  [SameObject, PutForwards=value] readonly attribute DOMTokenList htmlFor;
  readonly attribute HTMLFormElement? form;
  attribute DOMString name;

  readonly attribute DOMString type;
  attribute DOMString defaultValue;
  attribute DOMString value;

  readonly attribute boolean willValidate;
  readonly attribute ValidityState validity;
  readonly attribute DOMString validationMessage;
  boolean checkValidity();
  boolean reportValidity();
  void setCustomValidity(DOMString error);

  [SameObject] readonly attribute NodeList labels;
};

interface HTMLProgressElement : HTMLElement {
  attribute double value;
  attribute double max;
  readonly attribute double position;
  [SameObject] readonly attribute NodeList labels;
};

interface HTMLMeterElement : HTMLElement {
  attribute double value;
  attribute double min;
  attribute double max;
  attribute double low;
  attribute double high;
  attribute double optimum;
  [SameObject] readonly attribute NodeList labels;
};

interface HTMLFieldSetElement : HTMLElement {
  attribute boolean disabled;
  readonly attribute HTMLFormElement? form;
  attribute DOMString name;

  readonly attribute DOMString type;

  [SameObject] readonly attribute HTMLCollection elements;

  readonly attribute boolean willValidate;
  [SameObject] readonly attribute ValidityState validity;
  readonly attribute DOMString validationMessage;
  boolean checkValidity();
  boolean reportValidity();
  void setCustomValidity(DOMString error);
};

interface HTMLLegendElement : HTMLElement {
  readonly attribute HTMLFormElement? form;
};

enum SelectionMode {
  "select",
  "start",
  "end",
  "preserve" // default
};

interface ValidityState {
  readonly attribute boolean valueMissing;
  readonly attribute boolean typeMismatch;
  readonly attribute boolean patternMismatch;
  readonly attribute boolean tooLong;
  readonly attribute boolean tooShort;
  readonly attribute boolean rangeUnderflow;
  readonly attribute boolean rangeOverflow;
  readonly attribute boolean stepMismatch;
  readonly attribute boolean badInput;
  readonly attribute boolean customError;
  readonly attribute boolean valid;
};

interface HTMLDetailsElement : HTMLElement {
  attribute boolean open;
};

interface HTMLMenuElement : HTMLElement {
  attribute DOMString type;
  attribute DOMString label;
};

interface HTMLMenuItemElement : HTMLElement {
  attribute DOMString type;
  attribute DOMString label;
  attribute DOMString icon;
  attribute boolean disabled;
  attribute boolean checked;
  attribute DOMString radiogroup;
  attribute boolean default;
};

[Constructor(DOMString type, optional RelatedEventInit eventInitDict)]
interface RelatedEvent : Event {
  readonly attribute EventTarget? relatedTarget;
};

dictionary RelatedEventInit : EventInit {
  EventTarget? relatedTarget;
};

interface HTMLScriptElement : HTMLElement {
  attribute DOMString src;
  attribute DOMString type;
  attribute DOMString charset;
  attribute boolean async;
  attribute boolean defer;
  attribute DOMString? crossOrigin;
  attribute DOMString text;
  attribute DOMString nonce;
};

interface HTMLTemplateElement : HTMLElement {
  readonly attribute DocumentFragment content;
};

typedef (CanvasRenderingContext2D or WebGLRenderingContext) RenderingContext;

interface HTMLCanvasElement : HTMLElement {
  attribute unsigned long width;
  attribute unsigned long height;

  RenderingContext? getContext(DOMString contextId, any... arguments);
  boolean probablySupportsContext(DOMString contextId, any... arguments);

  DOMString toDataURL(optional DOMString type, any... arguments);
  void toBlob(BlobCallback _callback, optional DOMString type, any... arguments);
};

callback BlobCallback = void (Blob? blob);

[NoInterfaceObject]
interface ElementContentEditable {
  attribute DOMString contentEditable;
  readonly attribute boolean isContentEditable;
};

interface DataTransfer {
  attribute DOMString dropEffect;
  attribute DOMString effectAllowed;

  [SameObject] readonly attribute DataTransferItemList items;

  void setDragImage(Element image, long x, long y);

  /* old interface */
  [SameObject] readonly attribute DOMString[] types;
  DOMString getData(DOMString format);
  void setData(DOMString format, DOMString data);
  void clearData(optional DOMString format);
  [SameObject] readonly attribute FileList files;
};

interface DataTransferItemList {
  readonly attribute unsigned long length;
  getter DataTransferItem (unsigned long index);
  DataTransferItem? add(DOMString data, DOMString type);
  DataTransferItem? add(File data);
  void remove(unsigned long index);
  void clear();
};

interface DataTransferItem {
  readonly attribute DOMString kind;
  readonly attribute DOMString type;
  void getAsString(FunctionStringCallback? _callback);
  File? getAsFile();
};

callback FunctionStringCallback = void (DOMString data);

[Constructor(DOMString type, optional DragEventInit eventInitDict)]
interface DragEvent : MouseEvent {
  readonly attribute DataTransfer? dataTransfer;
};

dictionary DragEventInit : MouseEventInit {
  DataTransfer? dataTransfer = null;
};

[PrimaryGlobal, LegacyUnenumerableNamedProperties]
/*sealed*/ interface Window : EventTarget {
// the current browsing context
[Unforgeable] readonly attribute WindowProxy window;
[Replaceable] readonly attribute WindowProxy self;
[Unforgeable] readonly attribute Document document;
attribute DOMString name;
[PutForwards=href, Unforgeable] readonly attribute Location location;
readonly attribute History history;
[Replaceable] readonly attribute BarProp locationbar;
[Replaceable] readonly attribute BarProp menubar;
[Replaceable] readonly attribute BarProp personalbar;
[Replaceable] readonly attribute BarProp scrollbars;
[Replaceable] readonly attribute BarProp statusbar;
[Replaceable] readonly attribute BarProp toolbar;
attribute DOMString status;
void close();
readonly attribute boolean closed;
void stop();
void focus();
void blur();

// other browsing contexts
[Replaceable] readonly attribute WindowProxy frames;
[Replaceable] readonly attribute unsigned long length;
[Unforgeable] readonly attribute WindowProxy top;
attribute any opener;
[Replaceable] readonly attribute WindowProxy parent;
readonly attribute Element? frameElement;
WindowProxy open(optional DOMString url = "about:blank", optional DOMString target = "_blank", [TreatNullAs=EmptyString] optional DOMString features = "", optional boolean replace = false);
getter WindowProxy (unsigned long index);
getter object (DOMString name);

// the user agent
readonly attribute Navigator navigator;

// user prompts
void alert();
void alert(DOMString message);
boolean confirm(optional DOMString message = "");
DOMString? prompt(optional DOMString message = "", optional DOMString default = "");
void print();
any showModalDialog(DOMString url, optional any argument); // deprecated

unsigned long requestAnimationFrame(FrameRequestCallback callback);
void cancelAnimationFrame(unsigned long handle);
};
Window implements GlobalEventHandlers;
Window implements WindowEventHandlers;

callback FrameRequestCallback = void (DOMHighResTimeStamp time);

interface BarProp {
  readonly attribute boolean visible;
};

enum ScrollRestoration { "auto", "manual" };

interface History {
  readonly attribute unsigned long length;
  attribute ScrollRestoration scrollRestoration;
  readonly attribute any state;
  void go(optional long delta = 0);
  void back();
  void forward();
  void pushState(any data, DOMString title, optional DOMString? url = null);
  void replaceState(any data, DOMString title, optional DOMString? url = null);
};

[Unforgeable]
interface Location {
  stringifier attribute USVString href;
  readonly attribute USVString origin;
  attribute USVString protocol;
  attribute USVString host;
  attribute USVString hostname;
  attribute USVString port;
  attribute USVString pathname;
  attribute USVString search;
  attribute USVString hash;

  void assign(USVString url);
  void replace(USVString url);
  void reload();

  [SameObject] readonly attribute USVString[] ancestorOrigins;
};

[Constructor(DOMString type, optional PopStateEventInit eventInitDict), Exposed=(Window,Worker)]
interface PopStateEvent : Event {
  readonly attribute any state;
};

dictionary PopStateEventInit : EventInit {
  any state;
};

[Constructor(DOMString type, optional HashChangeEventInit eventInitDict), Exposed=(Window,Worker)]
interface HashChangeEvent : Event {
  readonly attribute DOMString oldURL;
  readonly attribute DOMString newURL;
};

dictionary HashChangeEventInit : EventInit {
  DOMString oldURL;
  DOMString newURL;
};

[Constructor(DOMString type, optional PageTransitionEventInit eventInitDict), Exposed=(Window,Worker)]
interface PageTransitionEvent : Event {
  readonly attribute boolean persisted;
};

dictionary PageTransitionEventInit : EventInit {
  boolean persisted;
};

interface BeforeUnloadEvent : Event {
  attribute DOMString returnValue;
};

[NoInterfaceObject, Exposed=(Window, Worker)]
interface NavigatorOnLine {
  readonly attribute boolean onLine;
};

[Constructor(DOMString type, optional ErrorEventInit eventInitDict), Exposed=(Window, Worker)]
interface ErrorEvent : Event {
  readonly attribute DOMString message;
  readonly attribute DOMString filename;
  readonly attribute unsigned long lineno;
  readonly attribute unsigned long colno;
  readonly attribute any error;
};

dictionary ErrorEventInit : EventInit {
  DOMString message = "";
  DOMString filename = "";
  unsigned long lineno = 0;
  unsigned long colno = 0;
  any error = null;
};

[Constructor(DOMString type, PromiseRejectionEventInit eventInitDict), Exposed=(Window,Worker)]
interface PromiseRejectionEvent : Event {
  readonly attribute Promise<any> promise;
  readonly attribute any reason;
};

dictionary PromiseRejectionEventInit : EventInit {
  required Promise<any> promise;
  any reason;
};

[TreatNonObjectAsNull]
callback EventHandlerNonNull = any (Event event);
typedef EventHandlerNonNull? EventHandler;

[TreatNonObjectAsNull]
callback OnErrorEventHandlerNonNull = any ((Event or DOMString) event, optional DOMString source, optional unsigned long lineno, optional unsigned long column, optional any error);
typedef OnErrorEventHandlerNonNull? OnErrorEventHandler;

[TreatNonObjectAsNull]
callback OnBeforeUnloadEventHandlerNonNull = DOMString? (Event event);
typedef OnBeforeUnloadEventHandlerNonNull? OnBeforeUnloadEventHandler;

[NoInterfaceObject]
interface GlobalEventHandlers {
  attribute EventHandler onabort;
  attribute EventHandler onblur;
  attribute EventHandler oncancel;
  attribute EventHandler oncanplay;
  attribute EventHandler oncanplaythrough;
  attribute EventHandler onchange;
  attribute EventHandler onclick;
  attribute EventHandler onclose;
  attribute EventHandler oncontextmenu;
  attribute EventHandler oncuechange;
  attribute EventHandler ondblclick;
  attribute EventHandler ondrag;
  attribute EventHandler ondragend;
  attribute EventHandler ondragenter;
  attribute EventHandler ondragexit;
  attribute EventHandler ondragleave;
  attribute EventHandler ondragover;
  attribute EventHandler ondragstart;
  attribute EventHandler ondrop;
  attribute EventHandler ondurationchange;
  attribute EventHandler onemptied;
  attribute EventHandler onended;
  attribute OnErrorEventHandler onerror;
  attribute EventHandler onfocus;
  attribute EventHandler oninput;
  attribute EventHandler oninvalid;
  attribute EventHandler onkeydown;
  attribute EventHandler onkeypress;
  attribute EventHandler onkeyup;
  attribute EventHandler onload;
  attribute EventHandler onloadeddata;
  attribute EventHandler onloadedmetadata;
  attribute EventHandler onloadstart;
  attribute EventHandler onmousedown;
  [LenientThis] attribute EventHandler onmouseenter;
  [LenientThis] attribute EventHandler onmouseleave;
  attribute EventHandler onmousemove;
  attribute EventHandler onmouseout;
  attribute EventHandler onmouseover;
  attribute EventHandler onmouseup;
  attribute EventHandler onwheel;
  attribute EventHandler onpause;
  attribute EventHandler onplay;
  attribute EventHandler onplaying;
  attribute EventHandler onprogress;
  attribute EventHandler onratechange;
  attribute EventHandler onreset;
  attribute EventHandler onresize;
  attribute EventHandler onscroll;
  attribute EventHandler onseeked;
  attribute EventHandler onseeking;
  attribute EventHandler onselect;
  attribute EventHandler onshow;
  attribute EventHandler onstalled;
  attribute EventHandler onsubmit;
  attribute EventHandler onsuspend;
  attribute EventHandler ontimeupdate;
  attribute EventHandler ontoggle;
  attribute EventHandler onvolumechange;
  attribute EventHandler onwaiting;
};

[NoInterfaceObject]
interface WindowEventHandlers {
  attribute EventHandler onafterprint;
  attribute EventHandler onbeforeprint;
  attribute OnBeforeUnloadEventHandler onbeforeunload;
  attribute EventHandler onhashchange;
  attribute EventHandler onlanguagechange;
  attribute EventHandler onmessage;
  attribute EventHandler onoffline;
  attribute EventHandler ononline;
  attribute EventHandler onpagehide;
  attribute EventHandler onpageshow;
  attribute EventHandler onrejectionhandled;
  attribute EventHandler onpopstate;
  attribute EventHandler onstorage;
  attribute EventHandler onunhandledrejection;
  attribute EventHandler onunload;
};

[NoInterfaceObject]
interface DocumentAndElementEventHandlers {
  attribute EventHandler oncopy;
  attribute EventHandler oncut;
  attribute EventHandler onpaste;
};

[NoInterfaceObject, Exposed=(Window, Worker)]
interface WindowBase64 {
  DOMString btoa(DOMString btoa);
  DOMString atob(DOMString atob);
};
Window implements WindowBase64;
WorkerGlobalScope implements WindowBase64;

[NoInterfaceObject, Exposed=(Window,Worker)]
interface WindowTimers {
  long setTimeout((Function or DOMString) handler, optional long timeout = 0, any... arguments);
  void clearTimeout(optional long handle = 0);
  long setInterval((Function or DOMString) handler, optional long timeout = 0, any... arguments);
  void clearInterval(optional long handle = 0);
};
Window implements WindowTimers;
WorkerGlobalScope implements WindowTimers;

[NoInterfaceObject]
interface WindowModal {
  readonly attribute any dialogArguments;
  attribute any returnValue;
};

interface Navigator {
  // objects implementing this interface also implement the interfaces given below
};
Navigator implements NavigatorID;
Navigator implements NavigatorLanguage;
Navigator implements NavigatorOnLine;
Navigator implements NavigatorContentUtils;
Navigator implements NavigatorCookies;
Navigator implements NavigatorPlugins;

[NoInterfaceObject, Exposed=(Window, Worker)]
interface NavigatorID {
  [Exposed=Window] readonly attribute DOMString appCodeName; // constant "Mozilla"
  readonly attribute DOMString appName; // constant "Netscape"
  readonly attribute DOMString appVersion;
  readonly attribute DOMString platform;
  [Exposed=Window]readonly attribute DOMString product; // constant "Gecko"
  readonly attribute DOMString userAgent;
};

[NoInterfaceObject, Exposed=(Window, Worker)]
interface NavigatorLanguage {
  readonly attribute DOMString? language;
  readonly attribute DOMString[] languages;
};

[NoInterfaceObject]
interface NavigatorContentUtils {
  // content handler registration
  void registerProtocolHandler(DOMString scheme, DOMString url, DOMString title);
  void unregisterProtocolHandler(DOMString scheme, DOMString url);
};

[NoInterfaceObject]
interface NavigatorCookies {
  readonly attribute boolean cookieEnabled;
};

[NoInterfaceObject]
  interface NavigatorPlugins {
  [SameObject] readonly attribute PluginArray plugins;
  [SameObject] readonly attribute MimeTypeArray mimeTypes;
  boolean javaEnabled();
};

interface PluginArray {
  void refresh(optional boolean reload = false);
  readonly attribute unsigned long length;
  getter Plugin? item(unsigned long index);
  getter Plugin? namedItem(DOMString name);
};

interface MimeTypeArray {
  readonly attribute unsigned long length;
  getter MimeType? item(unsigned long index);
  getter MimeType? namedItem(DOMString name);
};

interface Plugin {
  readonly attribute DOMString name;
  readonly attribute DOMString description;
  readonly attribute DOMString filename;
  readonly attribute unsigned long length;
  getter MimeType? item(unsigned long index);
  getter MimeType? namedItem(DOMString name);
};

interface MimeType {
  readonly attribute DOMString type;
  readonly attribute DOMString description;
  readonly attribute DOMString suffixes; // comma-separated
  readonly attribute Plugin enabledPlugin;
};

[Exposed=(Window, Worker)]
interface ImageBitmap {
  readonly attribute unsigned long width;
  readonly attribute unsigned long height;
};

typedef (HTMLImageElement or
        HTMLVideoElement or
        HTMLCanvasElement or
        Blob or
        ImageData or
        CanvasRenderingContext2D or
        ImageBitmap) ImageBitmapSource;

[NoInterfaceObject, Exposed=(Window, Worker)]
interface ImageBitmapFactories {
  Promise<ImageBitmap> createImageBitmap(ImageBitmapSource image);
  Promise<ImageBitmap> createImageBitmap(ImageBitmapSource image, long sx, long sy, long sw, long sh);
};
Window implements ImageBitmapFactories;
WorkerGlobalScope implements ImageBitmapFactories;

interface HTMLAppletElement : HTMLElement {
  attribute DOMString align;
  attribute DOMString alt;
  attribute DOMString archive;
  attribute DOMString code;
  attribute DOMString codeBase;
  attribute DOMString height;
  attribute unsigned long hspace;
  attribute DOMString name;
  attribute DOMString _object; // the underscore is not part of the identifier
  attribute unsigned long vspace;
  attribute DOMString width;
};

interface HTMLMarqueeElement : HTMLElement {
  attribute DOMString behavior;
  attribute DOMString bgColor;
  attribute DOMString direction;
  attribute DOMString height;
  attribute unsigned long hspace;
  attribute long loop;
  attribute unsigned long scrollAmount;
  attribute unsigned long scrollDelay;
  attribute boolean trueSpeed;
  attribute unsigned long vspace;
  attribute DOMString width;

  attribute EventHandler onbounce;
  attribute EventHandler onfinish;
  attribute EventHandler onstart;

  void start();
  void stop();
};

interface HTMLFrameSetElement : HTMLElement {
  attribute DOMString cols;
  attribute DOMString rows;
};
HTMLFrameSetElement implements WindowEventHandlers;

interface HTMLFrameElement : HTMLElement {
  attribute DOMString name;
  attribute DOMString scrolling;
  attribute DOMString src;
  attribute DOMString frameBorder;
  attribute boolean noResize;
  readonly attribute Document? contentDocument;
  readonly attribute WindowProxy? contentWindow;

  [TreatNullAs=EmptyString] attribute DOMString marginHeight;
  [TreatNullAs=EmptyString] attribute DOMString marginWidth;
};

[Exposed=(Window, SharedWorker)]
interface ApplicationCache : EventTarget {
  // update status
  const unsigned short UNCACHED = 0;
  const unsigned short IDLE = 1;
  const unsigned short CHECKING = 2;
  const unsigned short DOWNLOADING = 3;
  const unsigned short UPDATEREADY = 4;
  const unsigned short OBSOLETE = 5;
  readonly attribute unsigned short status;

  // updates
  void update();
  void abort();
  void swapCache();

  // events
  attribute EventHandler onchecking;
  attribute EventHandler onerror;
  attribute EventHandler onnoupdate;
  attribute EventHandler ondownloading;
  attribute EventHandler onprogress;
  attribute EventHandler onupdateready;
  attribute EventHandler oncached;
  attribute EventHandler onobsolete;
};

partial interface HTMLAnchorElement {
  attribute DOMString coords;
  attribute DOMString charset;
  attribute DOMString name;
  attribute DOMString shape;
};

partial interface HTMLAreaElement {
  attribute boolean noHref;
};

partial interface HTMLBodyElement {
  [TreatNullAs=EmptyString] attribute DOMString text;
  [TreatNullAs=EmptyString] attribute DOMString link;
  [TreatNullAs=EmptyString] attribute DOMString vLink;
  [TreatNullAs=EmptyString] attribute DOMString aLink;
  [TreatNullAs=EmptyString] attribute DOMString bgColor;
  attribute DOMString background;
};

partial interface HTMLBRElement {
  attribute DOMString clear;
};

partial interface HTMLTableCaptionElement {
  attribute DOMString align;
};

partial interface HTMLTableColElement {
  attribute DOMString align;
  attribute DOMString ch;
  attribute DOMString chOff;
  attribute DOMString vAlign;
  attribute DOMString width;
};

interface HTMLDirectoryElement : HTMLElement {
  attribute boolean compact;
};

partial interface HTMLDivElement {
  attribute DOMString align;
};

partial interface HTMLDListElement {
  attribute boolean compact;
};

partial interface HTMLEmbedElement {
  attribute DOMString align;
  attribute DOMString name;
};

interface HTMLFontElement : HTMLElement {
  [TreatNullAs=EmptyString] attribute DOMString color;
  attribute DOMString face;
  attribute DOMString size;
};

partial interface HTMLHeadingElement {
  attribute DOMString align;
};

partial interface HTMLHRElement {
  attribute DOMString align;
  attribute DOMString color;
  attribute boolean noShade;
  attribute DOMString size;
  attribute DOMString width;
};

partial interface HTMLHtmlElement {
  attribute DOMString version;
};

partial interface HTMLIFrameElement {
  attribute DOMString align;
  attribute DOMString scrolling;
  attribute DOMString frameBorder;

  [TreatNullAs=EmptyString] attribute DOMString marginHeight;
  [TreatNullAs=EmptyString] attribute DOMString marginWidth;
};

partial interface HTMLImageElement {
  attribute DOMString name;
  attribute DOMString lowsrc;
  attribute DOMString align;
  attribute unsigned long hspace;
  attribute unsigned long vspace;

  [TreatNullAs=EmptyString] attribute DOMString border;
};

partial interface HTMLInputElement {
  attribute DOMString align;
  attribute DOMString useMap;
};

partial interface HTMLLegendElement {
  attribute DOMString align;
};

partial interface HTMLLIElement {
  attribute DOMString type;
};

partial interface HTMLLinkElement {
  attribute DOMString charset;
  attribute DOMString target;
};

partial interface HTMLMenuElement {
  attribute boolean compact;
};

partial interface HTMLMetaElement {
  attribute DOMString scheme;
};

partial interface HTMLObjectElement {
  attribute DOMString align;
  attribute DOMString archive;
  attribute DOMString code;
  attribute boolean declare;
  attribute unsigned long hspace;
  attribute DOMString standby;
  attribute unsigned long vspace;
  attribute DOMString codeBase;
  attribute DOMString codeType;
  attribute DOMString useMap;

  [TreatNullAs=EmptyString] attribute DOMString border;
};

partial interface HTMLOListElement {
  attribute boolean compact;
};

partial interface HTMLParagraphElement {
  attribute DOMString align;
};

partial interface HTMLParamElement {
  attribute DOMString type;
  attribute DOMString valueType;
};

partial interface HTMLPreElement {
  attribute long width;
};

partial interface HTMLScriptElement {
  attribute DOMString event;
  attribute DOMString htmlFor;
};

partial interface HTMLTableElement {
  attribute DOMString align;
  attribute DOMString border;
  attribute DOMString frame;
  attribute DOMString rules;
  attribute DOMString summary;
  attribute DOMString width;

  [TreatNullAs=EmptyString] attribute DOMString bgColor;
  [TreatNullAs=EmptyString] attribute DOMString cellPadding;
  [TreatNullAs=EmptyString] attribute DOMString cellSpacing;
};

partial interface HTMLTableSectionElement {
  attribute DOMString align;
  attribute DOMString ch;
  attribute DOMString chOff;
  attribute DOMString vAlign;
};

partial interface HTMLTableCellElement {
  attribute DOMString align;
  attribute DOMString axis;
  attribute DOMString height;
  attribute DOMString width;

  attribute DOMString ch;
  attribute DOMString chOff;
  attribute boolean noWrap;
  attribute DOMString vAlign;

  [TreatNullAs=EmptyString] attribute DOMString bgColor;
};

partial interface HTMLTableDataCellElement {
  attribute DOMString abbr;
};

partial interface HTMLTableRowElement {
  attribute DOMString align;
  attribute DOMString ch;
  attribute DOMString chOff;
  attribute DOMString vAlign;

  [TreatNullAs=EmptyString] attribute DOMString bgColor;
};

partial interface HTMLUListElement {
  attribute boolean compact;
  attribute DOMString type;
};

partial interface Document {
  [TreatNullAs=EmptyString] attribute DOMString fgColor;
  [TreatNullAs=EmptyString] attribute DOMString linkColor;
  [TreatNullAs=EmptyString] attribute DOMString vlinkColor;
  [TreatNullAs=EmptyString] attribute DOMString alinkColor;
  [TreatNullAs=EmptyString] attribute DOMString bgColor;

  [SameObject] readonly attribute HTMLCollection anchors;
  [SameObject] readonly attribute HTMLCollection applets;

  void clear();
  void captureEvents();
  void releaseEvents();

  [SameObject] readonly attribute HTMLAllCollection all;
};

partial interface Window {
  void captureEvents();
  void releaseEvents();

  [Replaceable, SameObject] readonly attribute External external;
};

[NoInterfaceObject]
interface External {
  void AddSearchProvider();
  void IsSearchProviderInstalled();
};

References

Normative References

[ABNF]
D. Crocker, Ed.; P. Overell. Augmented BNF for Syntax Specifications: ABNF. January 2008. Internet Standard. URL: https://tools.ietf.org/html/rfc5234
[BCP47]
A. Phillips; M. Davis. Tags for Identifying Languages. September 2009. IETF Best Current Practice. URL: https://tools.ietf.org/html/bcp47
[BIDI]
Mark Davis; Aharon Lanin; Andrew Glass. Unicode Bidirectional Algorithm. 5 June 2014. Unicode Standard Annex #9. URL: http://www.unicode.org/reports/tr9/
[CANVAS-2D]
Rik Cabanier; et al. HTML Canvas 2D Context. 19 November 2015. REC. URL: https://www.w3.org/TR/2dcontext/
[CLDR]
Unicode Common Locale Data Repository. URL: http://cldr.unicode.org/
[COOKIES]
A. Barth. HTTP State Management Mechanism. April 2011. Proposed Standard. URL: https://tools.ietf.org/html/rfc6265
[CSP3]
Mike West. Content Security Policy Level 3. 13 September 2016. WD. URL: https://www.w3.org/TR/CSP3/
[CSS-2015]
Tab Atkins Jr.; Elika Etemad; Florian Rivoal. CSS Snapshot 2015. 13 October 2015. NOTE. URL: https://www.w3.org/TR/css-2015/
[CSS-COLOR-4]
Tab Atkins Jr.; Chris Lilley. CSS Color Module Level 4. 5 July 2016. WD. URL: https://www.w3.org/TR/css-color-4/
[CSS-DISPLAY-3]
Tab Atkins Jr.; Elika Etemad. CSS Display Module Level 3. 15 October 2015. WD. URL: https://www.w3.org/TR/css-display-3/
[CSS-FONT-LOADING-3]
Tab Atkins Jr.. CSS Font Loading Module Level 3. 22 May 2014. LCWD. URL: https://www.w3.org/TR/css-font-loading-3/
[CSS-FONTS-3]
John Daggett. CSS Fonts Module Level 3. 3 October 2013. CR. URL: https://www.w3.org/TR/css-fonts-3/
[CSS-OVERFLOW-4]
CSS Overflow Module Level 4 URL: https://drafts.csswg.org/css-overflow-4/
[CSS-SIZING-4]
CSS Intrinsic & Extrinsic Sizing Module Level 4 URL: https://drafts.csswg.org/css-sizing-4/
[CSS-STYLE-ATTR]
Tantek Çelik; Elika Etemad. CSS Style Attributes. 7 November 2013. REC. URL: https://www.w3.org/TR/css-style-attr
[CSS-SYNTAX-3]
Tab Atkins Jr.; Simon Sapin. CSS Syntax Module Level 3. 20 February 2014. CR. URL: https://www.w3.org/TR/css-syntax-3/
[CSS-TEXT-3]
Elika Etemad; Koji Ishii. CSS Text Module Level 3. 10 October 2013. LCWD. URL: https://www.w3.org/TR/css-text-3/
[CSS-TRANSITIONS-1]
CSS Transitions Module Level 1 URL: https://www.w3.org/TR/css3-transitions/
[CSS-UI-3]
Tantek Çelik; Florian Rivoal. CSS Basic User Interface Module Level 3 (CSS3 UI). 7 July 2015. CR. URL: https://www.w3.org/TR/css-ui-3/
[CSS-UI-4]
Florian Rivoal. CSS Basic User Interface Module Level 4. 22 September 2015. WD. URL: https://www.w3.org/TR/css-ui-4/
[CSS-VALUES]
Tab Atkins Jr.; Elika Etemad. CSS Values and Units Module Level 3. 29 September 2016. CR. URL: https://www.w3.org/TR/css-values-3/
[CSS-WRITING-MODES-3]
Elika Etemad; Koji Ishii. CSS Writing Modes Level 3. 15 December 2015. CR. URL: https://www.w3.org/TR/css-writing-modes-3/
[CSS2]
Bert Bos; et al. Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification. 7 June 2011. REC. URL: https://www.w3.org/TR/CSS2
[CSS22]
Bert Bos. Cascading Style Sheets Level 2 Revision 2 (CSS 2.2) Specification. 12 April 2016. WD. URL: https://www.w3.org/TR/CSS22/
[CSS3-CONTENT]
Elika Etemad; Dave Cramer. CSS Generated Content Module Level 3. 2 June 2016. WD. URL: https://www.w3.org/TR/css-content-3/
[CSS3-IMAGES]
Elika Etemad; Tab Atkins Jr.. CSS Image Values and Replaced Content Module Level 3. 17 April 2012. CR. URL: https://www.w3.org/TR/css3-images/
[CSS3-RUBY]
Elika Etemad; Koji Ishii. CSS Ruby Layout Module Level 1. 5 August 2014. WD. URL: https://www.w3.org/TR/css-ruby-1/
[CSS3-SELECTORS]
Tantek Çelik; et al. Selectors Level 3. 29 September 2011. REC. URL: https://www.w3.org/TR/css3-selectors/
[CSS3COLOR]
Tantek Çelik; Chris Lilley; David Baron. CSS Color Module Level 3. 7 June 2011. REC. URL: https://www.w3.org/TR/css3-color
[CSSOM]
Simon Pieters; Glenn Adams. CSS Object Model (CSSOM). 17 March 2016. WD. URL: https://www.w3.org/TR/cssom-1/
[CSSOM-VIEW]
Simon Pieters. CSSOM View Module. 17 March 2016. WD. URL: https://www.w3.org/TR/cssom-view-1/
[DOM]
Anne van Kesteren. DOM Standard. Living Standard. URL: https://dom.spec.whatwg.org/
[DOM-Parsing]
Travis Leithead. DOM Parsing and Serialization. 17 May 2016. WD. URL: https://www.w3.org/TR/DOM-Parsing/
[ECMA-262]
ECMAScript Language Specification. URL: https://tc39.github.io/ecma262/
[ENCODING]
Anne van Kesteren. Encoding Standard. Living Standard. URL: https://encoding.spec.whatwg.org/
[EVENTSOURCE]
Ian Hickson. Server-Sent Events. 3 February 2015. REC. URL: https://www.w3.org/TR/eventsource/
[FETCH]
Anne van Kesteren. Fetch Standard. Living Standard. URL: https://fetch.spec.whatwg.org/
[FILEAPI]
Arun Ranganathan; Jonas Sicking. File API. 21 April 2015. WD. URL: https://www.w3.org/TR/FileAPI/
[FULLSCREEN]
Anne van Kesteren. Fullscreen API Standard. Living Standard. URL: https://fullscreen.spec.whatwg.org/
[GEOMETRY-1]
Simon Pieters; Dirk Schulze; Rik Cabanier. Geometry Interfaces Module Level 1. 25 November 2014. CR. URL: https://www.w3.org/TR/geometry-1/
[HR-TIME-2]
Ilya Grigorik; James Simonsen; Jatinder Mann. High Resolution Time Level 2. 8 October 2016. WD. URL: https://www.w3.org/TR/hr-time-2/
[HTML-AAM-1.0]
Steve Faulkner; et al. HTML Accessibility API Mappings 1.0. 3 December 2015. WD. URL: https://www.w3.org/TR/html-aam-1.0/
[HTML-ARIA]
Steve Faulkner. ARIA in HTML. 5 October 2016. WD. URL: https://www.w3.org/TR/html-aria/
[HTTP]
HTTP is the union of a set of RFCs:
[IANAPERMHEADERS]
Permanent Message Header Field Names. IANA.
[ISO3166]
ISO 3166: Codes for the representation of names of countries and their subdivisions. ISO.
[ISO4217]
ISO 4217: Codes for the representation of currencies and funds. ISO.
[JLREQ]
Yasuhiro Anan; et al. Requirements for Japanese Text Layout. 3 April 2012. NOTE. URL: https://www.w3.org/TR/jlreq/
[JPEG]
Eric Hamilton. JPEG File Interchange Format. September 1992. URL: https://www.w3.org/Graphics/JPEG/jfif3.pdf
[MATHML]
Patrick D F Ion; Robert R Miner. Mathematical Markup Language (MathML) 1.01 Specification. 7 July 1999. REC. URL: https://www.w3.org/TR/MathML/
[MEDIA-FRAGS]
Raphaël Troncy; et al. Media Fragments URI 1.0 (basic). 25 September 2012. REC. URL: https://www.w3.org/TR/media-frags/
[MEDIA-SOURCE]
Matthew Wolenetz; et al. Media Source Extensions™. 4 October 2016. PR. URL: https://www.w3.org/TR/media-source/
[MEDIACAPTURE-STREAMS]
Daniel Burnett; et al. Media Capture and Streams. 19 May 2016. CR. URL: https://www.w3.org/TR/mediacapture-streams/
[MEDIAQ]
Florian Rivoal; et al. Media Queries. 19 June 2012. REC. URL: https://www.w3.org/TR/css3-mediaqueries/
[MEDIAQUERIES-4]
Florian Rivoal; Tab Atkins Jr.. Media Queries Level 4. 6 July 2016. WD. URL: https://www.w3.org/TR/mediaqueries-4/
[MFREL]
Microformats Wiki: existing rel values. Microformats.
[MIMESNIFF]
Gordon P. Hemsley. MIME Sniffing Standard. Living Standard. URL: https://mimesniff.spec.whatwg.org/
[MPEG2TS]
Information technology -- Generic coding of moving pictures and associated audio information: Systems ITU-T Rec. H.222.0 / ISO/IEC 13818-1:2013. URL: http://www.itu.int/rec/T-REC-H.222.0-201206-I
[MPEG4]
ISO/IEC 14496-12: ISO base media file format. ISO/IEC.
[MPEGDASH]
ISO/IEC 23009-1:2014 Information technology -- Dynamic adaptive streaming over HTTP (DASH) -- Part 1: Media presentation description and segment formats. URL: http://standards.iso.org/ittf/PubliclyAvailableStandards/c065274_ISO_IEC_23009-1_2014.zip
[OGGSKELETON]
Ogg Skeleton 4 Message Headers. 17 March 2014. URL: http://wiki.xiph.org/SkeletonHeaders
[ORIGIN]
A. Barth. The Web Origin Concept. December 2011. Proposed Standard. URL: https://tools.ietf.org/html/rfc6454
[PAGE-VISIBILITY]
Jatinder Mann; Arvind Jain. Page Visibility (Second Edition). 29 October 2013. REC. URL: https://www.w3.org/TR/page-visibility/
[PNG]
Tom Lane. Portable Network Graphics (PNG) Specification (Second Edition). 10 November 2003. REC. URL: https://www.w3.org/TR/PNG
[POINTERLOCK]
Vincent Scheib. Pointer Lock. 30 August 2016. PR. URL: https://www.w3.org/TR/pointerlock/
[PROGRESS-EVENTS]
Anne van Kesteren; Charles McCathie Nevile; Jungkee Song. Progress Events. 11 February 2014. REC. URL: https://www.w3.org/TR/progress-events/
[PROMISES-GUIDE]
Domenic Denicola. Writing Promise-Using Specifications. 16 February 2016. Finding of the W3C TAG. URL: https://www.w3.org/2001/tag/doc/promises-guide
[PSL]
Public Suffix List. Mozilla Foundation.
[RESOURCE-HINTS]
Ilya Grigorik. Resource Hints. 27 May 2016. WD. URL: https://www.w3.org/TR/resource-hints/
[RFC1034]
P.V. Mockapetris. Domain names - concepts and facilities. November 1987. Internet Standard. URL: https://tools.ietf.org/html/rfc1034
[RFC1123]
R. Braden, Ed.. Requirements for Internet Hosts - Application and Support. October 1989. Internet Standard. URL: https://tools.ietf.org/html/rfc1123
[RFC2046]
N. Freed; N. Borenstein. Multipurpose Internet Mail Extensions (MIME) Part Two: Media Types. November 1996. Draft Standard. URL: https://tools.ietf.org/html/rfc2046
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Best Current Practice. URL: https://tools.ietf.org/html/rfc2119
[RFC2318]
H. Lie; B. Bos; C. Lilley. The text/css Media Type. March 1998. Informational. URL: https://tools.ietf.org/html/rfc2318
[RFC2397]
L. Masinter. The "data" URL scheme. August 1998. Proposed Standard. URL: https://tools.ietf.org/html/rfc2397
[RFC2483]
M. Mealling; R. Daniel. URI Resolution Services Necessary for URN Resolution. January 1999. Experimental. URL: https://tools.ietf.org/html/rfc2483
[RFC3279]
L. Bassham; W. Polk; R. Housley. Algorithms and Identifiers for the Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile. April 2002. Proposed Standard. URL: https://tools.ietf.org/html/rfc3279
[RFC3447]
J. Jonsson; B. Kaliski. Public-Key Cryptography Standards (PKCS) #1: RSA Cryptography Specifications Version 2.1. February 2003. Informational. URL: https://tools.ietf.org/html/rfc3447
[RFC4648]
S. Josefsson. The Base16, Base32, and Base64 Data Encodings. October 2006. Proposed Standard. URL: https://tools.ietf.org/html/rfc4648
[RFC5280]
D. Cooper; et al. Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile. May 2008. Proposed Standard. URL: https://tools.ietf.org/html/rfc5280
[RFC5322]
P. Resnick, Ed.. Internet Message Format. October 2008. Draft Standard. URL: https://tools.ietf.org/html/rfc5322
[RFC5724]
E. Wilde; A. Vaha-Sipila. URI Scheme for Global System for Mobile Communications (GSM) Short Message Service (SMS). January 2010. Proposed Standard. URL: https://tools.ietf.org/html/rfc5724
[RFC5988]
M. Nottingham. Web Linking. October 2010. Proposed Standard. URL: https://tools.ietf.org/html/rfc5988
[RFC6068]
M. Duerst; L. Masinter; J. Zawinski. The 'mailto' URI Scheme. October 2010. Proposed Standard. URL: https://tools.ietf.org/html/rfc6068
[RFC6266]
J. Reschke. Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP). June 2011. Proposed Standard. URL: https://tools.ietf.org/html/rfc6266
[RFC6381]
R. Gellens; D. Singer; P. Frojdh. The 'Codecs' and 'Profiles' Parameters for "Bucket" Media Types. August 2011. Proposed Standard. URL: https://tools.ietf.org/html/rfc6381
[RFC6455]
I. Fette; A. Melnikov. The WebSocket Protocol. December 2011. Proposed Standard. URL: https://tools.ietf.org/html/rfc6455
[RFC6694]
S. Moonesamy, Ed.. The "about" URI Scheme. August 2012. Informational. URL: https://tools.ietf.org/html/rfc6694
[RFC7230]
R. Fielding, Ed.; J. Reschke, Ed.. Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing. June 2014. Proposed Standard. URL: https://tools.ietf.org/html/rfc7230
[RFC7231]
R. Fielding, Ed.; J. Reschke, Ed.. Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content. June 2014. Proposed Standard. URL: https://tools.ietf.org/html/rfc7231
[RFC7232]
R. Fielding, Ed.; J. Reschke, Ed.. Hypertext Transfer Protocol (HTTP/1.1): Conditional Requests. June 2014. Proposed Standard. URL: https://tools.ietf.org/html/rfc7232
[RFC7234]
R. Fielding, Ed.; M. Nottingham, Ed.; J. Reschke, Ed.. Hypertext Transfer Protocol (HTTP/1.1): Caching. June 2014. Proposed Standard. URL: https://tools.ietf.org/html/rfc7234
[RFC7303]
H. Thompson; C. Lilley. XML Media Types. July 2014. Proposed Standard. URL: https://tools.ietf.org/html/rfc7303
[RFC7578]
L. Masinter. Returning Values from Forms: multipart/form-data. July 2015. Proposed Standard. URL: https://tools.ietf.org/html/rfc7578
[RFC7595]
D. Thaler, Ed.; T. Hansen; T. Hardie. Guidelines and Registration Procedures for URI Schemes. June 2015. Best Current Practice. URL: https://tools.ietf.org/html/rfc7595
[SELECTION-API]
Ryosuke Niwa. Selection API. 21 September 2016. WD. URL: https://www.w3.org/TR/selection-api/
[SELECTORS-4]
Selectors Level 4 URL: https://www.w3.org/TR/selectors4/
[SERVICE-WORKERS]
Alex Russell; et al. Service Workers 1. 11 October 2016. WD. URL: https://www.w3.org/TR/service-workers-1/
[SRGB]
Amendment 1 - Multimedia systems and equipment - Colour measurement and management - Part 2-1: Colour management - Default RGB colour space - sRGB. URL: https://webstore.iec.ch/publication/6168
[SVG]
Jon Ferraiolo. Scalable Vector Graphics (SVG) 1.0 Specification. 4 September 2001. REC. URL: https://www.w3.org/TR/SVG/
[SVG11]
Erik Dahlström; et al. Scalable Vector Graphics (SVG) 1.1 (Second Edition). 16 August 2011. REC. URL: https://www.w3.org/TR/SVG11/
[SVG2]
Nikos Andronikos; et al. Scalable Vector Graphics (SVG) 2. 15 September 2016. CR. URL: https://www.w3.org/TR/SVG2/
[SVGTiny12]
Ola Andersson; et al. Scalable Vector Graphics (SVG) Tiny 1.2 Specification. 22 December 2008. REC. URL: https://www.w3.org/TR/SVGTiny12/
[TOUCH-EVENTS]
Doug Schepers; et al. Touch Events. 10 October 2013. REC. URL: https://www.w3.org/TR/touch-events/
[UIEVENTS]
Gary Kacmarcik; Travis Leithead. UI Events. 4 August 2016. WD. URL: https://www.w3.org/TR/uievents/
[UNICODE]
The Unicode Standard. URL: http://www.unicode.org/versions/latest/
[URL]
Anne van Kesteren. URL Standard. Living Standard. URL: https://url.spec.whatwg.org/
[URN]
R. Moats. URN Syntax. May 1997. Proposed Standard. URL: https://tools.ietf.org/html/rfc2141
[WAI-ARIA]
James Craig; Michael Cooper; et al. Accessible Rich Internet Applications (WAI-ARIA) 1.0. 20 March 2014. REC. URL: https://www.w3.org/TR/wai-aria/
[WEB-BLUETOOTH]
Jeffrey Yasskin. Web Bluetooth. Draft Community Group Report. URL: https://webbluetoothcg.github.io/web-bluetooth/
[WEBGL]
Chris Marrin (Apple Inc.). WebGL Specification, Version 1.0. 10 February 2011. URL: https://www.khronos.org/registry/webgl/specs/1.0/
[WEBIDL]
Cameron McCormack; Boris Zbarsky. WebIDL Level 1. 15 September 2016. PR. URL: https://www.w3.org/TR/WebIDL-1/
[WEBM]
WebM Container Guidelines. 26 April 2016. URL: https://www.webmproject.org/docs/container/
[WEBSTORAGE]
Ian Hickson. Web Storage (Second Edition). 19 April 2016. REC. URL: https://www.w3.org/TR/webstorage/
[WEBWORKERS]
Ian Hickson. Web Workers. 24 September 2015. WD. URL: https://www.w3.org/TR/workers/
[X690]
Recommendation X.690 — Information Technology — ASN.1 Encoding Rules — Specification of Basic Encoding Rules (BER), Canonical Encoding Rules (CER), and Distinguished Encoding Rules (DER). International Telecommunication Union.
[XHR]
Anne van Kesteren. XMLHttpRequest Standard. Living Standard. URL: https://xhr.spec.whatwg.org/
[XML]
Tim Bray; et al. Extensible Markup Language (XML) 1.0 (Fifth Edition). 26 November 2008. REC. URL: https://www.w3.org/TR/xml
[XML-NAMES]
Tim Bray; et al. Namespaces in XML 1.0 (Third Edition). 8 December 2009. REC. URL: https://www.w3.org/TR/xml-names
[XML-STYLESHEET]
James Clark; Simon Pieters; Henry Thompson. Associating Style Sheets with XML documents 1.0 (Second Edition). 28 October 2010. REC. URL: https://www.w3.org/TR/xml-stylesheet
[XMLBASE]
Jonathan Marsh. XML Base (Second Edition). 28 January 2009. REC. URL: https://www.w3.org/TR/xmlbase/
[XPATH]
James Clark; Steven DeRose. XML Path Language (XPath) Version 1.0. 16 November 1999. REC. URL: https://www.w3.org/TR/xpath
[XPTR-XMLNS]
Steven DeRose; et al. XPointer xmlns() Scheme. 25 March 2003. REC. URL: https://www.w3.org/TR/xptr-xmlns/

Informative References

[APNG]
S. Parmenter; V. Vukicevic; A. Smith. APNG Specification. URL: https://wiki.mozilla.org/APNG_Specification
[ATAG20]
Jan Richards; Jeanne F Spellman; Jutta Treviranus. Authoring Tool Accessibility Guidelines (ATAG) 2.0. 24 September 2015. REC. URL: https://www.w3.org/TR/ATAG20/
[BATTERY-STATUS]
Anssi Kostiainen; Mounir Lamouri. Battery Status API. 7 July 2016. CR. URL: https://www.w3.org/TR/battery-status/
[BOCU1]
M. Scherer; M. Davis. UTN #6: BOCU-1: MIME-Compatible Unicode Compression. URL: http://www.unicode.org/notes/tn6/
[CESU8]
T. Phipps. UTR #26: Compatibility Encoding Scheme For UTF-16: 8-BIT (CESU-8). URL: http://www.unicode.org/reports/tr26/
[CHARMOD]
Martin Dürst; et al. Character Model for the World Wide Web 1.0: Fundamentals. 15 February 2005. REC. URL: https://www.w3.org/TR/charmod/
[COMPUTABLE]
A. Turing. On computable numbers, with an application to the Entscheidungsproblem, Proceedings of the London Mathematical Society, series 2, volume 42,. 1937. URL: http://www.turingarchive.org/browse.php/B/12
[CSS-CASCADE-4]
Elika Etemad; Tab Atkins Jr.. CSS Cascading and Inheritance Level 4. 14 January 2016. CR. URL: https://www.w3.org/TR/css-cascade-4/
[CSS-IMAGES-4]
CSS Image Values and Replaced Content Module Level 4 URL: https://www.w3.org/TR/css4-images/
[CSS-LISTS-3]
Tab Atkins Jr.. CSS Lists and Counters Module Level 3. 20 March 2014. WD. URL: https://www.w3.org/TR/css-lists-3/
[CSS3-ANIMATIONS]
Dean Jackson; et al. CSS Animations. 19 February 2013. WD. URL: https://www.w3.org/TR/css3-animations/
[CSS3-TRANSITIONS]
Dean Jackson; et al. CSS Transitions. 19 November 2013. WD. URL: https://www.w3.org/TR/css3-transitions/
[DOT]
The DOT Language. URL: http://www.graphviz.org/content/dot-language
[EDITING]
A. Gregor. HTML Editing APIs. URL: https://dvcs.w3.org/hg/editing/raw-file/tip/editing.html
[GIF]
Graphics Interchange Format. 31 July 1990. URL: https://www.w3.org/Graphics/GIF/spec-gif89a.txt
[GRAPHICS]
Computer Graphics: Principles and Practice in C, Second Edition, J. Foley, A. van Dam, S. Feiner, J. Hughes. Addison-Wesley. ISBN 0-201-84840-6.
[GREGORIAN]
Inter Gravissimas, A. Lilius, C. Clavius. Gregory XIII Papal Bull, February 1582.
[HTML-POLYGLOT]
Eliot Graff; Leif Halvard Silli. Polyglot Markup: A robust profile of the HTML5 vocabulary. 29 September 2015. NOTE. URL: https://www.w3.org/TR/html-polyglot/
[HTML5]
Ian Hickson; et al. HTML5. 28 October 2014. REC. URL: https://www.w3.org/TR/html5/
[HTML5-DIFF]
Simon Pieters. HTML5 Differences from HTML4. 9 December 2014. NOTE. URL: https://www.w3.org/TR/html5-diff/
[INBANDTRACKS]
Sourcing In-band Media Resource Tracks from Media Containers into HTML (URL: http://dev.w3.org/html5/html-sourcing-inband-tracks/), S. Pfeiffer, B. Lund. W3C.
[IndexedDB]
Nikunj Mehta; et al. Indexed Database API. 8 January 2015. REC. URL: https://www.w3.org/TR/IndexedDB/
[ISO8601]
Representation of dates and times. International Organization for Standardization. 2004. ISO 8601:2004. URL: http://www.iso.org/iso/catalogue_detail?csnumber=40874
[MNG]
MNG (Multiple-image Network Graphics) Format. G. Randers-Pehrson.
[NPAPI]
Gecko Plugin API Reference. Mozilla.
[OPENSEARCH]
Autodiscovery in HTML/XHTML. In OpenSearch 1.1 Draft 4, Section 4.6.2. OpenSearch.org.
[PDF]
Document management — Portable document format — Part 1: PDF. ISO.
[PPUTF8]
The Properties and Promises of UTF-8, M. Dürst. University of Zürich. In Proceedings of the 11th International Unicode Conference.
[RFC2152]
D. Goldsmith; M. Davis. UTF-7 A Mail-Safe Transformation Format of Unicode. May 1997. Informational. URL: https://tools.ietf.org/html/rfc2152
[RFC3676]
R. Gellens. The Text/Plain Format and DelSp Parameters. February 2004. Proposed Standard. URL: https://tools.ietf.org/html/rfc3676
[RFC4287]
M. Nottingham, Ed.; R. Sayre, Ed.. The Atom Syndication Format. December 2005. Proposed Standard. URL: https://tools.ietf.org/html/rfc4287
[RFC4329]
B. Hoehrmann. Scripting Media Types. April 2006. Informational. URL: https://tools.ietf.org/html/rfc4329
[RUBY-UC]
Richard Ishida. Use Cases & Exploratory Approaches for Ruby Markup. 8 October 2013. NOTE. URL: https://www.w3.org/TR/ruby-use-cases/
[SCSU]
UTR #6: A Standard Compression Scheme For Unicode, M. Wolf, K. Whistler, C. Wicksteed, M. Davis, A. Freytag, M. Scherer. Unicode Consortium.
[TIMEZONE]
Addison Phillips; et al. Working with Time Zones. 5 July 2011. NOTE. URL: https://www.w3.org/TR/timezone
[TOR]
Tor.
[TZDATABASE]
Time Zone Database. IANA.
[UAAG20]
James Allan; et al. User Agent Accessibility Guidelines (UAAG) 2.0. 15 December 2015. NOTE. URL: https://www.w3.org/TR/UAAG20/
[UNDO]
Ryosuke Niwa. UndoManager and DOM Transaction. ED. URL: https://dvcs.w3.org/hg/undomanager/raw-file/tip/undomanager.html
[UNICODE-SECURITY]
Mark Davis; Michel Suignard. Unicode Security Considerations. URL: http://www.unicode.org/reports/tr36/
[UNIVCHARDET]
A composite approach to language/encoding detection, S. Li, K. Momoi. Netscape. In Proceedings of the 19th International Unicode Conference.
[UTF8DET]
Multilingual form encoding, M. Dürst. W3C.
[WAI-ARIA-1.1]
Joanmarie Diggs; et al. Accessible Rich Internet Applications (WAI-ARIA) 1.1. 21 July 2016. WD. URL: https://www.w3.org/TR/wai-aria-1.1/
[WCAG20]
Ben Caldwell; et al. Web Content Accessibility Guidelines (WCAG) 2.0. 11 December 2008. REC. URL: https://www.w3.org/TR/WCAG20/
[WEBVTT]
Simon Pieters. WebVTT: The Web Video Text Tracks Format. 8 December 2015. WD. URL: https://www.w3.org/TR/webvtt1/
[WHATWGWIKI]
The WHATWG Wiki. WHATWG.
[XML-ENTITY-NAMES]
David Carlisle; Patrick D F Ion. XML Entity Definitions for Characters (2nd Edition). 10 April 2014. REC. URL: https://www.w3.org/TR/xml-entity-names/
[XSLT]
James Clark. XSL Transformations (XSLT) Version 1.0. 16 November 1999. REC. URL: https://www.w3.org/TR/xslt

Changes

This section summarises substantial substantive changes between this specification and [HTML5].

Features added

Features removed

Changes to existing features

Acknowledgements

Thanks to Tim Berners-Lee for inventing HTML, without which none of this would exist, Dan Connolly, the many who worked to standardise HTML over the last couple of decades or so, and the many more who worked on ideas subsequently incorporated into HTML.

For inestimable work, and the drive to keep HTML up to date, particular thanks are due to Ian Hickson, and the other editors of the WHATWG: Anne van Kesteren, Domenic Denicola, Philip Jägenstedt, Simon Pieters.

Thanks to the participants of the Responsive Images Community Group and the WHATWG for helping to develop the picture element, the srcset attribute, and the sizes attribute. Special thanks to Bruce Lawson for originally suggesting, Edward O’Connor and Ian Hickson for writing the original srcset specification, and Adrian Bateman for providing the group with guidance. Contributions also from: David Newton, Ilya Grigorik, John Schoenick, and Leon de Rijke.

With apologies to people who have undeservedly not been named, thanks to

Aankhen, Aaron Boodman, Aaron Leventhal, Adam Barth, Adam de Boor, Adam Hepton, Adam Klein, Adam Roben, Addison Phillips, Adele Peterson, Adrian Bateman, Adrian Roselli, Adrian Sutton, Agustín Fernández, Aharon (Vladimir) Lanin, Ajai Tirumali, Akatsuki Kitamura, Alan Plum, Alastair Campbell, Alejandro G. Castro, Alex Bishop, Alex Nicolaou, Alex Plescan, Alex Rousskov, Alexander Farkas, Alexander J. Vincent, Alexander Surkov, Alexandre Morgaut, Alexey Feldgendler, Алексей Проскуряков (Alexey Proskuryakov), Alexis Deveria, Alice Boxhall, Allan Clements, Ami Fischman, Amos Jeffries, Anders Carlsson, André E. Veltstra, Andrea Rendine, Andreas, Andreas Kling, Andrei Popescu, Andres Gomez, Andrew Barfield, Andrew Clover, Andrew Gove, Andrew Grieve, Andrew Oakley, Andrew Sidwell, Andrew Simons, Andrew Smith, Andrew W. Hagen, Andrey V. Lukyanov, Andry Rendy, Andy Earnshaw, Andy Heydon, Andy Palay, Anjana Vakil, Anna Belle Leiserson, Anthony Boyd, Anthony Bryan, Anthony Hickson, Anthony Ramine, Anthony Ricaud, Antonio Olmo Titos, Antti Koivisto, Arkadiusz Michalski, Arne Thomassen, Aron Spohr, Arphen Lin, Arron Eicholz, Arthur Stolyar, Arun Patole, Aryeh Gregor, Asbjørn Ulsberg, Ashley Gullen, Ashley Sheridan, Atsushi Takayama, Aurelien Levy, Ave Wrigley, Axel Dahmen, B Lingafelter, Bart Humphries, Ben Boyle, Ben Buchanan, Ben Godfrey, Ben Lerner, Ben Leslie, Ben Meadowcroft, Ben Millard, Benjamin Carl Wiley Sittler, Benjamin Hawkes-Lewis, Benoit Ren, Bert Bos, Bijan Parsia, Bil Corry, Bill Mason, Bill McCoy, Billy Wong, Bjartur Thorlacius, Björn Höhrmann, Blake Frantz, Bob Lund, Bob Owen, Bobby Holly, Boris Zbarsky, Brad Fults, Brad Neuberg, Brad Spencer, Brady Eidson, Brendan Eich, Brenton Simpson, Brett Wilson, Brett Zamir, Brian Blakely, Brian Campbell, Brian Korver, Brian Kuhn, Brian M. Dube, Brian Ryner, Brian Smith, Brian Wilson, Bryan Sullivan, Bruce Bailey, Bruce D’Arcus, Bruce Lawson, Bruce Miller, C. Williams, Cameron McCormack, Cameron Zemek, Cao Yipeng, Carlos Amengual, Carlos Gabriel Cardona, Carlos Perelló Marín, Casey Leask, Cătălin Mariș, Chaals McCathie Nevile, Chao Cai, 윤석찬 (Channy Yun), Charl van Niekerk, Charles Iliya Krempeaux, Charu Pandhi, Chris Apers, Chris Cressman, Chris Evans, Chris Morris, Chris Pearce, Chris Peterson, Chris Weber, Christian Biesinger, Christian Johansen, Christian Schmidt, Christoph Päper, Christophe Dumez, Christopher Aillon, Christopher Ferris, Chriswa, Clark Buehler, Cole Robison, Colin Fine, Collin Jackson, Corey Farwell, Corprew Reed, Craig Cockburn, Csaba Gabor, Csaba Marton, Cynthia Shelly, Dan Brickley, Dan Yoder, Daniel Barclay, Daniel Bratell, Daniel Brooks, Daniel Brumbaugh Keeney, Daniel Cheng, Daniel Davis, Daniel Glazman, Daniel Peng, Daniel Schattenkirchner, Daniel Spång, Daniel Steinberg, Daniel Trebbien, Danny Sullivan, Darin Adler, Darin Fisher, Darxus, Dave Camp, Dave Hodder, Dave Lampton, Dave Singer, Dave Townsend, David Baron, David Bloom, David Bruant, David Carlisle, David E. Cleary, David Egan Evans, David Fink, David Flanagan, David Gerard, David Håsäther, David Hyatt, David I. Lehn, David John Burrowes, David Kendal, David MacDonald, David Matja, David Remahl, David Smith, David Storey, David Vest, David Woolley, DeWitt Clinton, Dean Edridge, Dean Edwards, Debi Orton, Derek Featherstone, Devarshi Pant, Devdatta, Dimitri Glazkov, Dimitry Golubovsky, Dirk Pranke, Dirk Schulze, Dirkjan Ochtman, Divya Manian, Dmitry Titov, dolphinling, Dominic Mazzoni, Dominique Hazaël-Massieux, Don Brutzman, Doron Rosenberg, Doug Kramer, Doug Simpkinson, Drew Wilson, Dylan Barrell, Edmund Lai, Eduard Pascual, Eduardo Vela, Edward O’Connor, Edward Welbourne, Edward Z. Yang, Ehsan Akhgari, Eira Monstad, Eitan Adler, Eliot Graff, Elisabeth Robson, Elizabeth Castro, Elliott Regan, Elliott Sprehn, Elliotte Harold, Eric Carlson, Eric Casler, Eric Lawrence, Eric Rescorla, Eric Semling, Erik Arvidsson, Erik Rose, Evan Jacobs, Evan Martin, Evan Prodromou, Evan Stade, Evert, fantasai, Felix Sasaki, Francesco Schwarz, Francis Brosnan Blazquez, Franck "Shift" Quélain, François Remy, Frank Barchard, Frank Liberato, Frank Olivier, Fredrik Söderquist, 鵜飼文敏 (Fumitoshi Ukai), Futomi Hatano, Gavin Carothers, Gavin Kistner, Gareth Rees, Gary Kačmarčík, Garrett Smith, Geoff Richards, Geoffrey Garen, Geoffrey Sneddon, Gez Lemon, George Lund, George Ornbo, Gianmarco Armellin, Giovanni Campagna, Giuseppe Pascale, Glenn Adams, Glenn Maynard, Graham Klyne, Greg Botten, Greg Houston, Greg Wilkins, Gregg Tavares, Gregory J. Rosmaita, Grey, Guilherme Johansson Tramontina, Gytis Jakutonis, Håkon Wium Lie, Habib Virji, Hallvord Reiar Michaelsen Steen, Hans S. Tømmerhalt, Hans Stimer, Harald Alvestrand, Henri Sivonen, Henrik Lied, Henry Mason, Henry Story, Heydon Pickering, Hugh Guiney, Hugh Winkler, Ian Bicking, Ian Clelland, Ian Davis, Ian Devlin, Ian Fette, Ian Kilpatrick, Ido Green, Ignacio Javier, Ivan Enderlin, Ivo Emanuel Gonçalves, J. King, Jacob Davies, Jacques Distler, Jake Verbaten, Jakub Łopuszański, Jakub Wilk, James Craig, James Graham, James Greene, James Justin Harrell, James Kozianski, James M Snell, James Perrett, James Robinson, Jamie Lokier, Jan Molnár, Janusz Majnert, Jan-Klaas Kollhof, Jared Jacobs, Jason Duell, Jason Kersey, Jason Kiss, Jason Lustig, Jason White, Jasper Bryant-Greene, Jasper St. Pierre, Jatinder Mann, Jdsmith3000, Jed Hartman, Jeff Balogh, Jeff Cutsinger, Jeff Schiller, Jeff Walden, Jeffrey Yasskin, Jeffrey Zeldman, 胡慧鋒 (Jennifer Braithwaite), Jens Bannmann, Jens Fendler, Jens Lindström, Jens Meiert, Jer Noble, Jeremey Hustman, Jeremy Keith, Jeremy Orlow, Jerry Smith, Jeroen van der Meer, Jesse Renée Beach, Jian Li, Jim Jewett, Jim Ley, Jim Meehan, Jim Michaels, Jirka Kosek, Jjgod Jiang, João Eiras, Jochen Eisinger, Joe Clark, Joe Gregorio, Joel Spolsky, Joel Verhagen, Johan Herland, John Boyer, John Bussjaeger, John Carpenter, John Daggett, John Fallows, John Foliot, John Harding, John Keiser, John Snyders, John Stockton, John-Mark Bell, Johnny Stenback, Jon Ferraiolo, Jon Gibbins, Jon Gunderson, Jon Ribbins, Jon Perlow, Jonas Sicking, Jonathan Cook, Jonathan Kingston, Jonathan Rees, Jonathan Watt, Jonathan Worent, Jonny Axelsson, Jordan Tucker, Jorgen Horstink, Jorunn Danielsen Newth, Joseph Kesselman, Joseph Mansfield, Joseph Pecoraro, Josh Aas, Josh Hart, Josh Levenberg, Josh Matthews, Joshua Bell, Joshua Berenhaus, Joshua Randall, Jukka K. Korpela, Jules Clément-Ripoche, Julian Reschke, Julio Lopez, Junkee Song, Jürgen Jeka, Justin Lebar, Justin Novosad, Justin Rogers, Justin Schuh, Justin Sinclair, Ka-Sing Chou, Kai Hendry, 呂康豪 (KangHao Lu), Karl Dubost, Karl Groves, Kartikaya Gupta, Kathy Walton, Keith Hall, Keith Yeung, Kelly Ford, Kelly Norton, Kevin Benson, Kevin Gadd, Kevin Cole, Kinuko Yasuda Kornél Pál, Kornel Lesinski, Kris Northfield, Kristof Zelechovski, Krzysztof Maczyński, 黒澤剛志 (Kurosawa Takeshi), Kyle Barnhart, Kyle Hofmann, Kyle Huey, Léonard Bouchet, Lachlan Hunt, Larry Masinter, Larry Page, Lars Gunther, Lars Solberg, Laura Carlson, Laura Granka, Laura L. Carlson, Laura Wisewell, Laurens Holst, Lawrence Forooghian, Lea Verou, Lee Kowalkowski, Leif Halvard Silli, Leif Kornstaedt, Lenny Domnitser, Leonard Rosenthol, Léonie Watson, Leons Petrazickis, Lobotom Dysmon, Logan, Loune, Łukasz Pilorz, Luke Kenneth Casson Leighton, Maciej Stachowiak, Magnus Kristiansen, Maik Merten, Majid Valipour, Malcolm Rowe, Manu Sporny, Manuel Strehl, Manish Tripathi, Mallory van Achterberg, Marat Talanin, Marc Hoyois, Marcus Bointon, Mark Birbeck, Mark Davis, Mark Miller, Mark Nottingham, Mark Pilgrim, Mark Rogers, Mark Rowe, Mark Schenk, Mark Vickers, Mark Wilton-Jones, Marquish, Martijn Wargers, Martin Atkins, Martin Dürst, Martin Honnen, Martin Janecke, Martin Kutschker, Martin Nilsson, Martin Thomson, Masataka Yakura, Masatoshi Kimura, Matheus Martins, Mathias Bynens, Mathieu Henri, Matias Larsson, Matt Falkenhagen, Matt Garrish, Matt May, Matt Rakow, Matt Schmidt, Matt Wright, Matthew Gregan, Matthew Mastracci, Matthew Noorenberghe, Matthew Raymond, Matthew Thomas, Mattias Waldau, Max Romantschuk, Menachem Salomon, Menno van Slooten, Mia Lipner, Micah Dubinko, Michael "Ratt" Iannarelli, Michael A. Nachbaur, Michael A. Puls II, Michael Carter, Michael Daskalov, Michael Day, Michael Dyck, Michael Enright, Michael Gratton, Michael Nordman, Michael Powers, Michael Rakowski, Michael(tm) Smith, Michael Walmsley, Michal Zalewski, Michel Fortin, Michelangelo De Simone, Michiel Bijl, Michiel van der Blonk, Mihai Şucan, Mihai Parparita, Mike Brown, Mike Dierken, Mike Dixon, Mike Hearn, Mike Schinkel, Mike Shaver, Mikko Rantalainen, Mohamed Zergaoui, Mohammad Al Houssami, Momdo Nakamura, Mounir Lamouri, Mount-root-yy, Ms2ger, Nadia Heninger, Nhan, NARUSE Yui, Neil Deakin, Neil Rashbrook, Neil Soiffer, Nicholas Shanks, Nicholas Stimpson, Nicholas Zakas, Nick Levinson, Nickolay Ponomarev, Nicolas Gallagher, Noah Mendelsohn, Noah Slater, Noel Gordon, Nolan Waite, NoozNooz42, Norbert Lindenberg, Ojan Vafai, Olaf Hoffmann, Olav Junker Kjær, Oldřich Vetešník, Oli Studholme, Oliver Hunt, Oliver Rigby, Olivier Gendrin, Olli Pettay, oSand, Pablo Flouret, Patrick Garies, Patrick H. Lauke, Patrik Persson, Paul Adenot, Paul Cotton, Paul Norman, Per-Erik Brodin, Perry Smith, Peter Beverloo, Peter Karlsson, Peter Kasting, Peter Lemieux, Peter Moulder, Peter Occil, Peter Stark, Peter Van der Beken, Peter Winnberg, Peter-Paul Koch, Phil Pickering, Philip Taylor, Philip TAYLOR, Philippe De Ryck, Prateek Rungta, Pravir Gupta, Prayag Verma, 李普君 (Pujun Li), Rabab Gomaa, Rachid Finge, Rachel White, Rafael Weinstein, Rafał Miłecki, Raj Doshi, Rajas Moonka, Ralf Stoltze, Ralph Giles, Raphael Champeimont, Rebeca Ruiz, Remci Mizkur, Remco, Remy Sharp, Rene Saarsoo, Rene Stach, Ric Hardacre, Rich Clark, Rich Doughty, Richa Rupela, Richard Ishida, Richard Schwerdtfeger, Rigo Wenning, Rikkert Koppes, Rimantas Liubertas, Riona Macnamara, Rob Ennals, Rob Jellinghaus, Rob S, Robert Blaut, Robert Collins, Robert Kieffer, Robert Millan, Robert O’Callahan, Robert Sayre, Robin Berjon, Robin Schaufler, Rodger Combs, Rodney Rehm, Roland Steiner, Roma Matusevich, Roman Ivanov, Roy Fielding, Ruud Steltenpool, Ryan King, Ryan Rion, Ryosuke Niwa, S. Mike Dierken, Sailesh Panchang, Salvatore Loreto, Sam Dutton, Sam Kuper, Sam Ruby, Sam Weinig, Samuel Bronson, Samy Kamkar, Sander van Lambalgen, Sarven Capadisli, 佐藤雅之 (SATO Masayuki), Scott González, Scott Hess, Sean Fraser, Sean Hayes, Sean Hogan, Sean Knapp, Sebastian Markbåge, Sebastian Schnitzenbaumer, Seth Call, Seth Dillingham, Shannon Moeller, Shanti Rao, Shaun Inman, Shiki Okasaka, Shubheksha Jalan, Sierk Bornemann, Sigbjørn Finne, Sigbjørn Vik, Silver Ghost, Silvia Pfeiffer, Šime Vidas, Simo Sutela, Simon Montagu, Simon Spiegel, skeww, Smylers, Srirama Chandra Sekhar Mogali, Stanton McCandlish, Stefan Götz, Stefan Håkansson, Stefan Haustein, Stefan Santesson, Stefan Schumacher, Stefan Weiss, Steffen Meschkat, Stephane Corlosquet, Stephen Cunliffe, Stephen Ma, Stephen White, Steve Comstock, Steve Runyon, Steven Bennett, Steven Garrity, Steven Tate, Steven Wood, Stewart Brodie, Stuart Ballard, Stuart P Bentley, Stuart Langridge, Stuart Parmenter, Subramanian Peruvemba, Sunava Dutta, Susan Borgrink, Susan Lesch, Sylvain Pasche, T. J. Crowder, Tab Atkins-Bittner, Taiju Tsuiki, Takeshi Kurosawa, Takeshi Yoshino, Tantek Çelik, 田村健人 (TAMURA Kent), Taylor Hunt, Ted Mielczarek, Terrence Wood, Thijs van der Vossen, Thomas Broyer, Thomas Koetter, Thomas O’Connor, Tim Baxter, Tim Altman, Tim Johansson, TJ VanToll, Toby Inkster, Tobi Reif, Todd Moody, Tom Baker, Tom Pike, Tommy Thorsen, Tony Ross, Tooru Fujisawa, Travis Leithead, Trevor Saunders, triple-underscore, Tyler Close, Unor, Victor Carbune, Vipul Snehadeep Chawathe, Vitya Muhachev, Vladimir Katardjiev, Vladimir Vukićević, voracity, Wakaba, Wayne Carr, Wayne Pollock, Wellington Fernando de Macedo, Wes, Weston Ruter, Wilhelm Joys Andersen, Will Levine, William Chen, William Swanson, Wladimir Palant, Wojciech Mach, Wolfram Kriesing, Xan Gregg, xenotheme, Yang Chen, Yaroslaw, Ye-Kui Wang, Yehuda Katz, Yi-An Huang, Yngve Nysaeter Pettersen, Yoav Weiss, Yonathan Randolph, Yuzo Fujishima, Zhenbin Xu, Zoltan Herczeg, and Øistein E. Andersen,

for their useful comments, both large and small, that have led to changes to this specification over the years.

Thanks also to everyone who has ever posted about HTML to their blogs, public mailing lists, or forums, including all the contributors to the various W3C HTML WG lists and the various WHATWG lists.

The image in the introduction is based on a photo by Wonderlane. (CC BY 2.0)

The image of the wolf in the embedded content introduction is based on a photo by Barry O’Neill. (Public domain)

The image of the kettlebell swing in the embedded content introduction is based on a photo by kokkarina. (CC0 1.0)

The image of two cute kittens in a basket used in the context menu example is based on a photo by Alex G. (CC BY 2.0)

The Blue Robot Player sprite used in the canvas demo is based on a work by JohnColburn. (CC BY-SA 3.0)

The photograph of robot 148 climbing the tower at the FIRST Robotics Competition 2013 Silicon Valley Regional is based on a work by Lenore Edman. (CC BY 2.0)

Parts of this specification are © Copyright 2004-2014 Apple Inc., Mozilla Foundation, and Opera Software ASA. You are granted a license to use, reproduce and create derivative works of this document.