1. 인프라스트럭처
이 명세는 Infra Standard에 의존합니다. [INFRA]
이 명세서에서 사용되는 일부 용어는 Encoding, Selectors, Trusted Types, Web IDL, XML 및 Namespaces in XML에서 정의되어 있습니다. [ENCODING] [SELECTORS4] [TRUSTED-TYPES] [WEBIDL] [XML] [XML-NAMES]
확장이 필요할 때 DOM 표준은 그에 따라 업데이트할 수 있으며, 또는 새로운 표준을 작성하여 적용 가능한 명세에 대한 제공된 확장성 훅에 연결할 수 있습니다.
1.1. 트리
트리는 유한한 계층 트리 구조입니다. 트리 순서는 트리의 전위, 깊이 우선 탐색 방식입니다.
트리에 참여하는 객체는 트리 내에서 부모를 가지며, 이는 null이거나 객체입니다. 또한 자식을 가지는데, 이는 객체들의 순서가 있는 집합입니다. 객체 A의 부모가 객체 B라면, A는 B의 자식입니다.
객체의 루트는 부모가 null이면 자기 자신이고, 그렇지 않으면 부모의 루트입니다. 트리의 루트는 해당 트리에 참여하는 객체 중 부모가 null인 객체입니다.
객체 A가 객체 B의 후손이라고 부르려면, A가 B의 자식이거나, C의 자식이면서 C가 B의 후손인 경우입니다.
포함 후손은 객체 자신 또는 그의 후손 중 하나입니다.
객체 A가 객체 B의 조상이라고 부르려면, B가 A의 후손인 경우에만 해당합니다.
포함 조상은 객체 자신 또는 그의 조상 중 하나입니다.
객체 A가 객체 B의 형제이라고 부르려면, B와 A가 동일한 null이 아닌 부모를 공유해야 합니다.
포함 형제는 객체 자신 또는 그의 형제 중 하나입니다.
객체 A가 객체 B보다 앞선 객체라고 하려면, A와 B가 동일한 트리에 있고, A가 B보다 트리 순서상 먼저 나와야 합니다.
객체 A가 객체 B의 다음 객체라고 하려면, A와 B가 동일한 트리에 있고, A가 B보다 트리 순서상 나중에 나와야 합니다.
객체의 첫 번째 자식은 첫 번째 자식이거나 자식이 없으면 null입니다.
객체의 마지막 자식은 마지막 자식이거나 자식이 없으면 null입니다.
객체의 이전 형제는 첫 번째 앞선 형제이거나, 앞선 형제가 없으면 null입니다.
객체의 다음 형제는 첫 번째 다음 형제이거나, 다음 형제가 없으면 null입니다.
객체의 인덱스는 그 객체의 앞선 형제의 개수이며, 없으면 0입니다.
1.2. 순서가 있는 집합
순서가 있는 집합 파서는 문자열 input을 받아 다음 단계들을 수행합니다:
-
inputTokens를 ASCII 공백 문자로 input을 분할한 결과로 설정합니다.
-
tokens를 새로운 순서가 있는 집합으로 설정합니다.
- tokens를 반환합니다.
순서가 있는 집합 직렬화기는 set을 받아 U+0020 공백 문자로 set을 이어붙여 반환합니다.
1.3. 셀렉터
셀렉터 문자열 범위 일치 작업은 문자열 selectors를 노드 node에 대해 수행한다:
-
selector를 셀렉터 파싱 selectors의 결과로 한다. [SELECTORS4]
-
만약 selector가 실패라면, throw "
SyntaxError"DOMException을 던진다. -
셀렉터 트리 매칭을 selector와 node의 루트를 스코핑 루트 node와 함께 사용하여 그 결과를 반환한다. [SELECTORS4].
셀렉터 내 네임스페이스 지원은 계획되어 있지 않으며 추가되지 않을 예정입니다.
1.4. 이름 검증
문자열이 유효한 네임스페이스 접두사이려면, 해당 길이가 최소 1 이상이어야 하며, ASCII 공백, U+0000 NULL, U+002F (/), U+003E (>)를 포함하지 않아야 합니다.
문자열이 유효한 속성 로컬 이름이려면, 해당 길이가 최소 1 이상이어야 하며, ASCII 공백, U+0000 NULL, U+002F (/), U+003D (=), U+003E (>)를 포함하지 않아야 합니다.
문자열 name이 유효한 요소 로컬 이름이려면, 다음 단계들이 true를 반환해야 합니다:
-
만약 name의 길이가 0이면 false를 반환합니다.
-
만약 name의 0번째 코드 포인트가 ASCII 알파벳인 경우:
-
만약 name이 ASCII 공백, U+0000 NULL, U+002F (/), U+003E (>)를 포함하면 false를 반환합니다.
-
true를 반환합니다.
-
-
만약 name의 0번째 코드 포인트가 U+003A (:), U+005F (_), 또는 U+0080~U+10FFFF 범위에 없다면 false를 반환합니다.
-
만약 name의 그 이후 코드 포인트들이 ASCII 알파벳, ASCII 숫자, U+002D (-), U+002E (.), U+003A (:), U+005F (_), 또는 U+0080~U+10FFFF 범위에 있지 않다면 false를 반환합니다.
-
true를 반환합니다.
이 개념은 DOM API로 요소 로컬 이름을 생성할 때 검증에 사용됩니다. HTML 파서로 생성할 수 있는 모든 이름(첫 번째 코드 포인트가 ASCII 알파벳인 경우)과 추가적인 가능성을 허용하려는 의도입니다. 추가적인 가능성의 경우, ASCII 범위는 역사적 이유로 제한되지만, ASCII를 넘어서는 것은 모두 허용됩니다.
다음 자바스크립트 호환 정규식은 유효한 요소 로컬 이름의 구현입니다:
/^(?:[A-Za-z][^\0\t\n\f\r\u0020/>]*|[:_\u0080-\u{10FFFF}][A-Za-z0-9-.:_\u0080-\u{10FFFF}]*)$/u
문자열은 유효한 doctype 이름입니다 만약 ASCII 공백, U+0000 NULL, 또는 U+003E (>)를 포함하지 않는 경우입니다.
빈 문자열도 유효한 doctype 이름입니다.
유효성 검사 및 추출을 위해 namespace와 qualifiedName을 context와 함께 수행합니다:
-
namespace가 빈 문자열이면 null로 설정합니다.
-
prefix를 null로 설정합니다.
-
localName을 qualifiedName으로 설정합니다.
-
qualifiedName에 U+003A (:)가 포함되어 있다면:
-
qualifiedName과 U+003A (:)를 사용하여 strictly split을 실행한 결과를 splitResult로 둡니다.
-
prefix를 splitResult[0]으로 설정합니다.
-
localName을 splitResult[1]로 설정합니다.
-
prefix가 유효한 네임스페이스 접두사가 아니면, "
InvalidCharacterError"DOMException을 throw합니다.
-
-
Assert: prefix는 null이거나 유효한 네임스페이스 접두사입니다.
-
context가 "
attribute"이고 localName이 유효한 속성 로컬 이름이 아니면, "InvalidCharacterError"DOMException을 throw합니다. -
context가 "
element"이고 localName이 유효한 요소 로컬 이름이 아니면, "InvalidCharacterError"DOMException을 throw합니다. -
prefix가 null이 아니고 namespace가 null이면, "
NamespaceError"DOMException을 throw합니다. -
prefix가 "
xml"이고 namespace가 XML 네임스페이스가 아니면, "NamespaceError"DOMException을 throw합니다. -
qualifiedName 또는 prefix가 "
xmlns"이고 namespace가 XMLNS 네임스페이스가 아니면, "NamespaceError"DOMException을 throw합니다. -
namespace가 XMLNS 네임스페이스이고 qualifiedName과 prefix 모두 "
xmlns"가 아니면, "NamespaceError"DOMException을 throw합니다. -
(namespace, prefix, localName)을 반환합니다.
이 명세의 다양한 API들은 이전에는 네임스페이스 접두어, 속성 로컬 이름, 요소 로컬 이름, 그리고 doctype 이름을 더 엄격하게 검증했습니다. 이는 다양한 XML 관련 명세와 일치하는 방식이었습니다. (하지만 모든 규칙이 적용된 것은 아니었습니다.)
웹 개발자들에게 불편하게 여겨졌으며, 특히 HTML 파서로 생성할 수 있지만 DOM API로는 생성할 수 없는 이름이 존재하게 되었습니다. 그래서 위에서 설명한 수준으로 검증이 완화되었습니다.
2. 이벤트
2.1. "DOM 이벤트" 소개
웹 플랫폼 전반에서 이벤트는 객체에 디스패치되어 네트워크
활동이나 사용자 상호작용과 같은
발생을 알립니다. 이러한 객체들은
EventTarget
인터페이스를 구현하며, 따라서 이벤트 리스너를 추가해 이벤트를 관찰할 수 있습니다. addEventListener()를
호출합니다:
obj. addEventListener( "load" , imgFetched) function imgFetched( ev) { // great success …}
이벤트
리스너는
removeEventListener()
메서드를 사용해, 동일한 인자를 전달하여 제거할 수 있습니다.
또는 이벤트 리스너를
AbortSignal
을 addEventListener()에
전달하고, 시그널을 소유한 컨트롤러에서 abort()를
호출하여 제거할 수도 있습니다.
이벤트도 객체이며,
Event 인터페이스(또는 파생
인터페이스)를 구현합니다. 위 예시에서
ev는 이벤트입니다.
ev는
이벤트
리스너의 콜백
(일반적으로 위와 같이 자바스크립트 함수)로 전달됩니다.
이벤트
리스너는
이벤트의
type
속성 값
("load" 위 예시)로 동작합니다.
이벤트의
target
속성 값은
이벤트가 디스패치된 객체(obj 위 예시)를
반환합니다.
일반적으로 이벤트는 사용자 에이전트가 사용자 상호작용 또는 작업 완료의 결과로 디스패치하지만, 애플리케이션도 흔히 합성 이벤트(synthetic events)라 불리는 이벤트 디스패치를 직접 할 수 있습니다:
// 적절한 이벤트 리스너 추가 obj. addEventListener( "cat" , function ( e) { process( e. detail) }) // 이벤트 생성 및 디스패치 var event= new CustomEvent( "cat" , { "detail" : { "hazcheeseburger" : true }}) obj. dispatchEvent( event)
신호 전달 외에도 이벤트는
때때로 애플리케이션이 작업의 다음 단계를 제어하도록 사용되기도 합니다. 예를 들어 폼 제출 과정에서
type
속성 값이
"submit"인 이벤트가
디스패치됩니다.
만약 이 이벤트의
preventDefault()
메서드가 호출되면, 폼 제출이 중단됩니다. 애플리케이션이 합성 이벤트(디스패치된 이벤트)를 통해 이 기능을 사용하려면
dispatchEvent()
메서드의 반환값을 활용할 수 있습니다:
if ( obj. dispatchEvent( event)) { // 이벤트가 취소되지 않았으니, 이제 뭔가 마법을 실행할 차례 …}
이벤트가 디스패치
될 때, 트리에
참여하는 객체(예: 요소)에
도달하면
그 객체의 조상에 등록된
이벤트 리스너에도
도달할 수 있습니다.
즉, 해당 객체의 포함 조상에 등록된 이벤트 리스너 중
capture가
true인 리스너가 트리 순서대로
호출됩니다. 그리고
이벤트의 bubbles
가 true이면, 해당 객체의 포함 조상 이벤트 리스너 중 capture가
false인 리스너가
이제 역순 트리 순서대로 호출됩니다.
이벤트가 트리에서 어떻게 동작하는지 예시를 살펴봅시다:
<!doctype html> < html > < head > < title > Boring example</ title > </ head > < body > < p > Hello< span id = x > world</ span > !</ p > < script > function test( e) { debug( e. target, e. currentTarget, e. eventPhase) } document. addEventListener( "hey" , test, { capture: true }) document. body. addEventListener( "hey" , test) var ev= new Event( "hey" , { bubbles: true }) document. getElementById( "x" ). dispatchEvent( ev) </ script > </ body > </ html >
debug 함수는 두 번 호출됩니다. 두 번 모두 이벤트의
target
속성 값은 span 요소입니다. 첫 번째는
currentTarget
속성 값이 document이고, 두 번째는
body 요소입니다.
eventPhase
속성 값은
CAPTURING_PHASE
에서 BUBBLING_PHASE로
전환됩니다.
만약 span 요소에
이벤트 리스너가
등록되어 있었다면,
eventPhase
속성 값은 AT_TARGET이었을
것입니다.
2.2. 인터페이스 Event
[Exposed=*]interface {Event (constructor DOMString ,type optional EventInit = {});eventInitDict readonly attribute DOMString type ;readonly attribute EventTarget ?target ;readonly attribute EventTarget ?srcElement ; // legacyreadonly attribute EventTarget ?currentTarget ;sequence <EventTarget >composedPath ();const unsigned short NONE = 0;const unsigned short CAPTURING_PHASE = 1;const unsigned short AT_TARGET = 2;const unsigned short BUBBLING_PHASE = 3;readonly attribute unsigned short eventPhase ;undefined stopPropagation ();attribute boolean cancelBubble ; // legacy alias of .stopPropagation()undefined stopImmediatePropagation ();readonly attribute boolean bubbles ;readonly attribute boolean cancelable ;attribute boolean returnValue ; // legacyundefined preventDefault ();readonly attribute boolean defaultPrevented ;readonly attribute boolean composed ; [LegacyUnforgeable ]readonly attribute boolean isTrusted ;readonly attribute DOMHighResTimeStamp timeStamp ;undefined initEvent (DOMString ,type optional boolean =bubbles false ,optional boolean =cancelable false ); // legacy };dictionary {EventInit boolean =bubbles false ;boolean =cancelable false ;boolean =composed false ; };
Event 객체는 간단히 이벤트라고 부릅니다. 이는 어떤 일이 발생했음을
알릴 수 있도록 해줍니다. 예를 들어 이미지 다운로드가 완료되었음을 신호할 때 사용됩니다.
잠재적 이벤트 타겟은 null
또는 EventTarget
객체입니다.
이벤트는 연관된 타겟(잠재적 이벤트 타겟)을 가집니다. 별도의 언급이 없으면 null입니다.
이벤트는 연관된 relatedTarget(잠재적 이벤트 타겟)을 가집니다. 별도의 언급이 없으면 null입니다.
다른 명세들에서는 relatedTarget을 정의하기 위해 relatedTarget 속성을 사용합니다. [UIEVENTS]
이벤트는 연관된 터치 타겟 리스트(0개 이상의 잠재적 이벤트 타겟의 리스트)를 가집니다. 별도의 언급이 없으면 빈 리스트입니다.
터치 타겟 리스트는 TouchEvent
인터페이스와 관련 인터페이스 정의에만 사용됩니다. [TOUCH-EVENTS]
이벤트는 연관된 경로(path)를
가집니다. 경로는 구조체(struct)의 리스트입니다. 각 구조체는
호출 타겟(invocation target)(EventTarget
객체),
섀도우 트리 내 호출 타겟(불리언),
섀도우 조정된 타겟(잠재적 이벤트 타겟),
relatedTarget(잠재적 이벤트 타겟),
터치 타겟 리스트(잠재적 이벤트 타겟의 리스트),
닫힌 트리의 루트(불리언),
닫힌 트리 내 슬롯(불리언)으로 구성됩니다. 경로는 처음에는 빈 리스트입니다.
event = new Event(type [, eventInitDict])- 새로운 event를 반환하며,
type속성 값이 type으로 설정됩니다. eventInitDict 인자를 통해bubbles와cancelable속성을 같은 이름의 객체 멤버로 설정할 수 있습니다. event .type- event의 타입을 반환합니다. 예: "
click", "hashchange", "submit" 등. event .target- event가 디스패치된 객체(즉, 타겟)를 반환합니다.
event .currentTarget- 현재 실행 중인 이벤트 리스너의 콜백이 호출되는 객체를 반환합니다.
event .composedPath()- event의 호출 타겟 객체를 경로에서 반환합니다(리스너가 호출될 객체들). 단, 섀도우 트리에 속한 노드 중 섀도우 루트의 mode가 "
closed"이고 event의currentTarget에서 접근할 수 없는 경우는 제외됩니다. event .eventPhase- event의 단계(phase)를 반환합니다. 값은
NONE,CAPTURING_PHASE,AT_TARGET,BUBBLING_PHASE중 하나입니다. event . stopPropagation()- 트리 내에서 디스패치될 때, 이 메서드를 호출하면 event가 현재 객체 외 다른 객체에는 도달하지 못하게 합니다.
event . stopImmediatePropagation()- 이 메서드를 호출하면 현재 리스너 실행 이후 등록된 이벤트 리스너에는 도달하지 않으며, 트리 내 디스패치 중이면 다른 객체에도 도달하지 않습니다.
event .bubbles- event가 어떻게 초기화되었는지에 따라 true 또는 false를 반환합니다. true라면 event가 타겟의 조상을 역순 트리 순서로 거칩니다. 아니면 false입니다.
event .cancelable- event가 어떻게 초기화되었는지에 따라 true 또는 false를 반환합니다. 반환값은 항상 의미가 있진 않지만, true인 경우 event가
디스패치된
작업의 일부를
preventDefault()호출로 취소할 수 있음을 나타냅니다. event . preventDefault()cancelable속성 값이 true이고 event의 리스너 실행 중passive가 false로 설정되어 있으면, event를 디스패치하게 한 작업에 취소 신호를 보냅니다.event .defaultPreventedpreventDefault()가 성공적으로 호출되어 취소되었음을 나타내면 true, 아니면 false를 반환합니다.event .composed- event가 어떻게 초기화되었는지에 따라 true 또는 false를 반환합니다. true라면 event가
ShadowRoot노드를 넘어 리스너를 실행하며, 해당 노드가 event의 루트인 경우에만 해당합니다. 아니면 false입니다. event .isTrusted- event가 사용자 에이전트에 의해 디스패치되면 true, 그렇지 않으면 false입니다.
event .timeStamp- event의 타임스탬프를 반환하며, 발생 시점을 기준으로 측정된 밀리초 단위 숫자입니다.
type 속성은 초기화된 값을 반환해야 합니다. 이벤트가 생성될 때 이 속성은 빈 문자열로 초기화되어야 합니다.
target getter 단계는 this의
target을 반환합니다.
srcElement getter 단계는
this의 target을 반환합니다.
currentTarget 속성은 초기화된 값을 반환해야 합니다. 이벤트가 생성될 때 이 속성은 null로
초기화되어야 합니다.
composedPath() 메서드 단계는 다음과 같습니다:
-
composedPath를 빈 리스트로 설정합니다.
-
path가 비어 있다면, composedPath를 반환합니다.
-
currentTarget을 this의
currentTarget속성 값으로 설정합니다. -
단언: currentTarget은
EventTarget객체여야 합니다. -
Append currentTarget을 composedPath에 추가합니다.
-
currentTargetIndex를 0으로 설정합니다.
-
currentTargetHiddenSubtreeLevel을 0으로 설정합니다.
-
index를 path의 크기 − 1로 설정합니다.
-
index가 0 이상인 동안:
-
path[index]의 root-of-closed-tree가 true라면, currentTargetHiddenSubtreeLevel을 1 증가시킵니다.
-
path[index]의 invocation target이 currentTarget이면, currentTargetIndex를 index로 설정하고, break합니다.
-
path[index]의 slot-in-closed-tree가 true라면, currentTargetHiddenSubtreeLevel을 1 감소시킵니다.
-
index를 1 감소시킵니다.
-
-
currentHiddenLevel과 maxHiddenLevel을 currentTargetHiddenSubtreeLevel로 설정합니다.
-
index를 currentTargetIndex − 1로 설정합니다.
-
index가 0 이상인 동안:
-
path[index]의 root-of-closed-tree가 true라면, currentHiddenLevel을 1 증가시킵니다.
-
currentHiddenLevel이 maxHiddenLevel 이하라면, prepend path[index]의 invocation target을 composedPath에 앞에 추가합니다.
-
path[index]의 slot-in-closed-tree가 true라면:
-
currentHiddenLevel을 1 감소시킵니다.
-
currentHiddenLevel이 maxHiddenLevel 미만이면 maxHiddenLevel을 currentHiddenLevel로 설정합니다.
-
-
index를 1 감소시킵니다.
-
-
currentHiddenLevel과 maxHiddenLevel을 currentTargetHiddenSubtreeLevel로 설정합니다.
-
index를 currentTargetIndex + 1로 설정합니다.
-
index가 path의 크기 미만인 동안:
-
path[index]의 slot-in-closed-tree가 true라면, currentHiddenLevel을 1 증가시킵니다.
-
currentHiddenLevel이 maxHiddenLevel 이하라면, append path[index]의 invocation target을 composedPath에 추가합니다.
-
path[index]의 root-of-closed-tree가 true라면:
-
currentHiddenLevel을 1 감소시킵니다.
-
currentHiddenLevel이 maxHiddenLevel 미만이면 maxHiddenLevel을 currentHiddenLevel로 설정합니다.
-
-
index를 1 증가시킵니다.
-
-
composedPath를 반환합니다.
eventPhase 속성은 초기화된 값을 반환해야 하며, 다음 중 하나여야 합니다:
NONE(숫자값 0)- 현재 디스패치되지 않은 이벤트는 이 단계에 있습니다.
CAPTURING_PHASE(숫자값 1)- 이벤트가 디스패치되어 트리에 참여하는 객체에 도달하기 전에 이 단계에 있습니다.
AT_TARGET(숫자값 2)- 이벤트가 디스패치되어 타겟에 도달했을 때 이 단계에 있습니다.
BUBBLING_PHASE(숫자값 3)- 이벤트가 디스패치되어 트리에 참여하는 객체에 도달한 이후 이 단계에 있습니다.
초기에는 속성이 NONE으로
초기화되어야 합니다.
각 이벤트는 다음과 같은 연관 플래그를 가지며, 모두 처음에는 해제 상태입니다:
- 전파 중단 플래그(stop propagation flag)
- 즉시 전파 중단 플래그(stop immediate propagation flag)
- 취소됨 플래그(canceled flag)
- 패시브 리스너 플래그(in passive listener flag)
- composed 플래그
- 초기화됨 플래그(initialized flag)
- 디스패치 플래그(dispatch flag)
stopPropagation() 메서드 단계는
this의 전파 중단 플래그를
설정하는 것입니다.
cancelBubble getter 단계는
this의 전파 중단 플래그가
설정되어 있으면 true, 아니면 false를 반환합니다.
cancelBubble
setter 단계는, 주어진 값이 true인 경우 this의 전파 중단 플래그를 설정하고, 아니면 아무 것도 하지 않습니다.
stopImmediatePropagation() 메서드 단계는
this의 전파 중단 플래그와 this의
즉시 전파 중단 플래그를 설정합니다.
bubbles와
cancelable 속성은 초기화된 값을 반환해야 합니다.
취소 플래그 설정은 이벤트 event를 받아서,
event의 cancelable
속성이 true이고 event의 패시브 리스너 플래그가 해제되어 있다면 event의 취소됨 플래그를 설정하고, 아니면 아무 것도 하지
않습니다.
returnValue getter 단계는
this의 취소됨 플래그가 설정되어 있으면 false, 아니면
true를 반환합니다.
returnValue
setter 단계는, 주어진 값이 false이면 취소 플래그 설정을 this에 대해 실행하고, 아니면 아무 것도 하지 않습니다.
preventDefault() 메서드 단계는
취소 플래그 설정을 this에 대해 실행하는
것입니다.
preventDefault()를
호출해도 아무 효과가 없는 상황이 있을 수 있습니다. 사용자 에이전트는 이러한 원인을 개발자 콘솔에 정확하게 기록해 디버깅을 돕는 것이 권장됩니다.
defaultPrevented getter 단계는
this의 취소됨 플래그가 설정되어 있으면 true, 아니면
false를 반환합니다.
composed getter 단계는
this의 composed 플래그가 설정되어 있으면 true,
아니면 false를 반환합니다.
isTrusted 속성은 초기화된 값을 반환해야 합니다. 이벤트가 생성될 때 이 속성은 false로 초기화되어야 합니다.
isTrusted는
이벤트가
사용자 에이전트에 의해 디스패치되었는지(즉 dispatchEvent()를
사용한 경우가 아닌지) 편리하게 알 수 있게 해줍니다. 유일한 레거시 예외는 click()이며,
이는 사용자 에이전트가 이벤트를 디스패치할 때
isTrusted
속성을 false로 초기화하게 만듭니다.
timeStamp 속성은 초기화된 값을 반환해야 합니다.
이벤트 초기화(initialize)를 event에 대해, type, bubbles, cancelable와 함께 수행하려면 다음 단계들을 실행합니다:
-
event의 초기화됨 플래그를 설정합니다.
-
event의 전파 중단 플래그, 즉시 전파 중단 플래그, 취소됨 플래그를 해제합니다.
-
event의
isTrusted속성을 false로 설정합니다. -
event의 target을 null로 설정합니다.
-
event의
type속성을 type으로 설정합니다. -
event의
bubbles속성을 bubbles로 설정합니다. -
event의
cancelable속성을 cancelable로 설정합니다.
initEvent(type, bubbles, cancelable)
메서드 단계는 다음과 같습니다:
initEvent()는
이벤트 생성자와 중복되며 composed
속성을 설정할 수 없습니다. 레거시 콘텐츠 지원을 위해 반드시 구현되어야 합니다.
2.3.
Window
인터페이스에 대한 레거시 확장
partial interface Window { [Replaceable ]readonly attribute (Event or undefined )event ; // legacy };
각 Window
객체는 연관된 현재 이벤트(current event)(undefined 또는 Event 객체)을 가집니다. 별도 언급이
없으면 undefined입니다.
event getter 단계는 this의
현재 이벤트를 반환합니다.
웹 개발자는 이벤트 리스너에 전달되는 Event 객체를 사용하는 것이 더 이식성
높은 코드를 작성할 수 있으므로 이를 권장합니다. 이 속성은 worker나 worklet에서는 사용할 수 없으며, 섀도우 트리에서 디스패치된 이벤트에는 정확하지 않습니다.
2.4. 인터페이스 CustomEvent
[Exposed=*]interface :CustomEvent Event {(constructor DOMString ,type optional CustomEventInit = {});eventInitDict readonly attribute any detail ;undefined initCustomEvent (DOMString ,type optional boolean =bubbles false ,optional boolean =cancelable false ,optional any =detail null ); // legacy };dictionary :CustomEventInit EventInit {any =detail null ; };
이벤트는 CustomEvent
인터페이스를 사용해 커스텀 데이터를 전달할 수 있습니다.
event = new CustomEvent(type [, eventInitDict])Event의 생성자와 유사하게 동작하지만, eventInitDict 인자를 통해detail속성도 설정할 수 있습니다.event .detail- event가 생성될 때 포함된 커스텀 데이터를 반환합니다. 주로 합성 이벤트에서 사용됩니다.
detail 속성은 초기화된 값을 반환해야 합니다.
initCustomEvent(type, bubbles, cancelable, detail)
메서드 단계는 다음과 같습니다:
2.5. 이벤트 생성
명세는 모든 또는 일부
이벤트에 대해 이벤트 생성 단계를
정의할 수 있습니다. 이 알고리즘은 event
event와 EventInit
eventInitDict를 내부 이벤트 생성 단계에서 넘겨받습니다.
이 구조는 초기화용 딕셔너리 멤버와 IDL 속성 간 1:1 대응이 아닌 더 복잡한 구조를 가진 Event 서브클래스에서 사용할 수
있습니다.
Event 인터페이스 또는
Event 인터페이스를 상속한
인터페이스의 생성자가 호출될 때, type과 eventInitDict 인자를 받아 다음
단계들을 실행해야 합니다:
-
event를 이 인터페이스, null, now, eventInitDict로 내부 이벤트 생성 단계를 실행한 결과로 설정합니다.
-
event의
type속성을 type으로 초기화합니다. -
event를 반환합니다.
eventInterface를 사용하여 이벤트 생성을 하려면,
eventInterface는 Event이거나 이를 상속한
인터페이스여야 하며, 선택적으로 realm realm을 받아 다음 단계들을 실행합니다:
-
realm이 주어지지 않았다면 null로 설정합니다.
-
dictionary를 JavaScript 값 undefined를 eventInterface의 생성자가 받아들이는 딕셔너리 타입으로 변환한 결과로 설정합니다. (이 딕셔너리 타입은
EventInit또는 이를 상속한 딕셔너리입니다.)멤버가 필수일 때는 동작하지 않습니다. whatwg/dom#600 참조.
-
event를 eventInterface, realm, 이벤트가 신호하는 발생 시각, dictionary로 내부 이벤트 생성 단계를 실행한 결과로 설정합니다.
-
event의
isTrusted속성을 true로 초기화합니다. -
event를 반환합니다.
이벤트 생성은 단순히 이벤트 발생이 아닌, 다른 명세에서 이벤트를 개별적으로 생성하고 디스패치해야 할 때 사용됩니다. 이 과정은 이벤트의 속성이 올바른 기본값으로 초기화되도록 보장합니다.
내부 이벤트 생성 단계는 eventInterface, realm, time, dictionary를 받아 다음과 같이 실행됩니다:
-
event를 eventInterface를 사용하여 새 객체를 생성한 결과로 설정합니다. realm이 null이 아니면 해당 realm을 사용하고, 그렇지 않으면 Web IDL에서 정의된 기본 동작을 사용합니다.
작성 시점 기준 Web IDL은 아직 기본 동작을 정의하지 않았음. whatwg/webidl#135 참조.
-
event의 초기화됨 플래그를 설정합니다.
-
event의
timeStamp속성을 time과 event의 관련 글로벌 객체를 이용한 상대 고해상도 근사 시간으로 초기화합니다. -
dictionary의 각 멤버 member → value에 대해: event에 identifier가 member인 속성이 있다면 해당 속성을 value로 초기화합니다.
-
이벤트 생성 단계를 event와 dictionary로 실행합니다.
-
event를 반환합니다.
2.6. 이벤트 인터페이스 정의
일반적으로 Event를 상속하는 새로운
인터페이스를 정의할 때는 반드시
WHATWG 또는 W3C WebApps WG
커뮤니티에 피드백을 요청하세요.
CustomEvent
인터페이스를 시작점으로 사용할 수 있습니다.
하지만 init*Event()와 같은 메서드는 생성자와 중복되므로 도입하지 마세요. Event
인터페이스를 상속한 인터페이스 중 이런 메서드를 가진 경우는 오직 역사적 이유 때문입니다.
2.7. 인터페이스 EventTarget
[Exposed=*]interface {EventTarget constructor ();undefined addEventListener (DOMString ,type EventListener ?,callback optional (AddEventListenerOptions or boolean )= {});options undefined removeEventListener (DOMString ,type EventListener ?,callback optional (EventListenerOptions or boolean )= {});options boolean dispatchEvent (Event ); };event callback interface {EventListener undefined (handleEvent Event ); };event dictionary {EventListenerOptions boolean =capture false ; };dictionary :AddEventListenerOptions EventListenerOptions {boolean ;passive boolean =once false ;AbortSignal ; };signal
EventTarget
객체는 어떤 일이 발생했을 때 event를 디스패치할 수 있는
타겟을 나타냅니다.
각 EventTarget
객체는 연관된 이벤트 리스너 목록(리스트로, 0개 이상의 이벤트 리스너를 포함)을 가집니다. 초기에는 빈
리스트입니다.
이벤트 리스너 는 특정 event를 관찰하는 데 사용되며 다음으로 구성됩니다:
- type (문자열)
- callback (null 또는
EventListener객체) - capture (불리언, 초기값 false)
- passive (null 또는 불리언, 초기값 null)
- once (불리언, 초기값 false)
- signal (null 또는
AbortSignal객체) - removed (기록용 불리언, 초기값 false)
callback은 EventListener
객체이지만, 이벤트
리스너는 위에서 볼 수 있듯 더 넓은 개념입니다.
각 EventTarget
객체는 또한 연관된 get the parent
알고리즘을 가지며, 이는 event
event를 받아 EventTarget
객체를 반환합니다. 별도 언급이 없으면 null을 반환합니다.
노드, 섀도우 루트 및 문서는 get the parent 알고리즘을 재정의합니다.
각 EventTarget
객체는 연관된 활성화 동작(activation behavior) 알고리즘을 가질 수 있습니다. 활성화 동작 알고리즘은 event를 받아 디스패치 알고리즘에서 실행됩니다.
이는 사용자 에이전트가 특정 EventTarget
객체(예:
area
요소)에 대해 합성 MouseEvent
이벤트의 type
속성이 click일 때 특정 동작을 수행하기 때문입니다. 웹 호환성 때문에 제거할 수 없었으며, 이제는 활성화를 정의하는 공식적인 방법으로 간주됩니다. [HTML]
활성화 동작을 가진 EventTarget
객체는 추가로 레거시 사전 활성화 동작 알고리즘과 레거시 취소된 활성화 동작 알고리즘 두 개를 모두 가질 수 있습니다.
이 알고리즘은 체크박스 및 라디오
input
요소에만 존재하며, 다른 용도로 사용되어서는 안 됩니다. [HTML]
target = new EventTarget();-
새로운
EventTarget객체를 생성하며, 개발자가 디스패치하고 이벤트를 수신하는 데 사용할 수 있습니다. target . addEventListener(type, callback [, options])-
이벤트 리스너를 이벤트의
type속성값이 type인 경우에 대해 추가합니다. callback 인자는 callback을 설정하며, 이는 이벤트가 디스패치될 때 호출됩니다.options 인자는 리스너별 옵션을 설정합니다. 호환성을 위해 이는 불리언일 수 있으며, 이 경우 메서드는 options의
capture로 지정된 값처럼 동작합니다.만약 options의
capture가 true로 설정되면, callback은 이벤트의eventPhase속성값이BUBBLING_PHASE일 때 호출되지 않습니다. false (또는 지정되지 않은 경우)에는 callback은 이벤트의eventPhase속성값이CAPTURING_PHASE일 때 호출되지 않습니다. 어느 경우든, callback은 이벤트의eventPhase속성값이AT_TARGET일 때 호출됩니다.만약 options의
passive가 true로 설정되면, callback은preventDefault()를 호출하여 이벤트를 취소하지 않습니다. 이는 § 2.8 이벤트 리스너 관찰에 설명된 성능 최적화를 가능하게 합니다.만약 options의
once가 true로 설정되면, callback은 한 번만 호출되며, 그 후 이벤트 리스너는 제거됩니다.만약 options의
signal에AbortSignal이 전달되면, signal이 중단될 때 이벤트 리스너는 제거됩니다.해당 이벤트 리스너는 target의 이벤트 리스너 목록에 추가되며, 동일한 type, callback, 및 capture를 가진 경우에는 추가되지 않습니다.
target . removeEventListener(type, callback [, options])-
target의 이벤트 리스너 목록에서 동일한 type, callback, options를 가진 이벤트 리스너를 제거합니다.
target . dispatchEvent(event)-
합성 이벤트 event를 target에 디스패치하며, event의
cancelable속성값이 false이거나,preventDefault()메서드가 호출되지 않은 경우 true를 반환하고, 그렇지 않으면 false를 반환합니다.
options를 평탄화(flatten)하려면, 다음 단계를 실행합니다:
-
options가 불리언이면, options를 반환합니다.
-
options["
capture"]를 반환합니다.
options를 더 평탄화(flatten more)하려면, 다음 단계를 실행합니다:
-
capture를 평탄화(flatten) options의 결과로 설정합니다.
-
once를 false로 설정합니다.
-
passive와 signal을 null로 설정합니다.
-
options가 딕셔너리(dictionary)인 경우:
-
capture, passive, once, signal을 반환합니다.
new EventTarget()
생성자의 단계는 아무것도 하지 않습니다.
다른 곳에서 명시된 기본값 때문에, 반환된 EventTarget의
get the parent 알고리즘은 null을
반환하며,
활성화 동작, 레거시 사전 활성화 동작,
또는 레거시 취소된 활성화 동작을 가지지 않습니다.
미래에는 사용자 지정 get the parent 알고리즘을 허용할 수도 있습니다. 이것이 귀하의 프로그램에 유용할지 알려주세요.
현재로서는, 모든 작성자가 생성한 EventTarget은
트리 구조에 참여하지 않습니다.
기본 passive 값은
이벤트 타입 type과 EventTarget
eventTarget이 주어졌을 때 다음과 같이 결정됩니다:
EventTarget
객체 eventTarget과 이벤트 리스너 listener가 주어졌을 때 이벤트 리스너 추가를
수행하려면 다음 단계를 실행합니다:
-
만약 eventTarget이
ServiceWorkerGlobalScope객체이고, 해당 서비스 워커의 스크립트 리소스의 평가된 적 있음 플래그가 설정되어 있고, listener의 type이type속성값 중 하나와 일치한다면, 콘솔에 경고를 출력합니다. [SERVICE-WORKERS] -
만약 listener의 callback이 null이라면, 종료합니다.
-
만약 listener의 passive가 null이라면, listener의 type과 eventTarget을 기반으로 기본 passive 값으로 설정합니다.
-
만약 eventTarget의 이벤트 리스너 목록이 포함하지 않는 경우, 이벤트 리스너 listener를 추가합니다.
-
만약 listener의 signal이 null이 아니라면, 다음 중단 단계를 추가합니다:
- 이벤트 리스너 제거를 eventTarget과 listener를 사용하여 실행합니다.
이 이벤트 리스너 추가 개념은 이벤트 핸들러가 동일한 코드 경로를 사용하도록 보장하기 위해 존재합니다. [HTML]
addEventListener(type, callback, options)
메서드 단계는 다음과 같습니다:
-
capture, passive, once, signal을 더 평탄화(flattening more) options의 결과로 설정합니다.
-
이벤트 리스너 추가를 this와 다음 속성을 가진 이벤트 리스너로 실행합니다: type은 type, callback은 callback, capture는 capture, passive는 passive, once는 once, signal은 signal.
이벤트 리스너 제거를
EventTarget
객체 eventTarget과 이벤트 리스너 listener를 사용하여 실행하려면 다음 단계를 수행합니다:
-
eventTarget이
ServiceWorkerGlobalScope객체이고, 해당 서비스 워커의 처리할 이벤트 타입 집합이 listener의 type을 포함한다면, 콘솔에 경고를 출력합니다. [SERVICE-WORKERS] -
listener의 제거됨 플래그를 true로 설정하고, 제거합니다. listener를 eventTarget의 이벤트 리스너 목록에서 제거합니다.
HTML 명세에서는 이 기능을 이벤트 핸들러 정의에 사용합니다. [HTML]
모든 이벤트 리스너
제거를 EventTarget
객체 eventTarget를 사용하여 실행하려면: 각
listener에 대해 eventTarget의 이벤트 리스너
목록에서: 이벤트 리스너 제거를 실행합니다.
HTML 명세에서는 이 기능을 document.open() 정의에 사용합니다. [HTML]
removeEventListener(type, callback, options)
메서드 단계는 다음과 같습니다:
-
capture를 평탄화(flattening) options의 결과로 설정합니다.
-
this의 이벤트 리스너 목록이 포함하는 경우, 이벤트 리스너 listener를 이벤트 리스너 제거를 사용하여 제거합니다.
이벤트 리스너 목록은 동일한 type, callback, capture 값을 가진 여러 이벤트 리스너를 포함하지 않습니다. 이는 이벤트 리스너 추가가 이를 방지하기 때문입니다.
dispatchEvent(event) 메서드의 단계는 다음과
같습니다:
-
event의 디스패치 플래그가 설정되어 있거나, 초기화 플래그가 설정되어 있지 않으면, "
InvalidStateError"DOMException을 throw합니다. -
event의
isTrusted속성을 false로 초기화합니다.
2.8. 이벤트 리스너 관찰
일반적으로 개발자는 이벤트 리스너의 존재가 관찰 가능한 것으로 기대하지 않습니다. 이벤트 리스너의 영향은 콜백에 의해 결정됩니다. 즉, 개발자가 아무런 동작을 하지 않는 이벤트 리스너를 추가하더라도 부작용이 없을 것으로 기대합니다.
불행히도, 일부 이벤트 API는 효율적으로 구현하기 위해 이벤트 리스너를 관찰해야만 하는 방식으로 설계되었습니다. 이는 리스너의 존재를 관찰 가능하게 만들며,
심지어 빈 리스너조차도 응용 프로그램의 동작에 극적인 성능 영향을 미칠 수 있습니다. 예를 들어, 비동기 스크롤링을 차단할 수 있는 터치 및 휠 이벤트가 있습니다.
어떤 경우에는 이벤트가 적어도 하나의 비-패시브(passive)
리스너가 있을 때만 취소 가능(cancelable)
하도록 지정함으로써 이 문제를 완화할 수 있습니다. 예를 들어, 비-패시브(passive)
TouchEvent
리스너는 스크롤링을 차단해야 하지만, 모든 리스너가 패시브(passive)
라면, TouchEvent
를 취소 불가능하게 만들어 스크롤링을 병렬로 시작할 수 있게 할 수 있습니다 (즉, preventDefault()
호출을 무시). 따라서 이벤트를 디스패치하는 코드는 비-패시브(passive)
리스너가 없는 것을 관찰하고, 이를 사용하여 디스패치되는 이벤트의 취소 가능(cancelable)
속성을 지울 수 있습니다.
이상적으로는, 새로운 이벤트 API는 이러한 특성을 필요로 하지 않도록 정의되어야 합니다. (whatwg/dom에서 논의에 참여하세요.)
레거시-서비스 워커 fetch 이벤트 리스너 콜백
얻기를
ServiceWorkerGlobalScope
global을 사용하여 실행하려면 다음 단계를 따릅니다. 이 단계는 리스트를 반환하며,
EventListener
객체를 포함합니다.
2.9. 이벤트 디스패치
디스패치를 위해 event를 target에, 선택적으로 legacy target override flag와 선택적으로 legacyOutputDidListenersThrowFlag와 함께 디스패치하려면, 다음 단계들을 실행한다:
-
event의 디스패치 플래그를 설정한다.
-
targetOverride를 target으로 한다. 만약 legacy target override flag가 주어지지 않았다면, 그리고 target의 연관된
Document로 한다. [HTML]legacy target override flag는 HTML에서만 사용되며, target이
Window객체일 때만 사용된다. -
activationTarget를 null로 한다.
-
relatedTarget를 리타게팅 event의 relatedTarget을 target에 대해 수행한 결과로 한다.
-
clearTargets를 false로 한다.
-
만약 target이 relatedTarget이 아니거나 target이 event의 relatedTarget이라면:
-
touchTargets를 새로운 리스트로 한다.
-
각각의 touchTarget을 event의 touch target list에서: append한다. 리타게팅 touchTarget을 target에 대해 수행한 결과를 touchTargets에 추가한다.
-
이벤트 경로에 추가한다. event, target, targetOverride, relatedTarget, touchTargets, 그리고 false를 사용한다.
-
isActivationEvent를 true로 한다. 만약 event가
MouseEvent객체이고 event의type속성이 "click"이면, 아니면 false로 한다. -
만약 isActivationEvent가 true이고 target이 activation behavior를 가진다면, activationTarget를 target으로 한다.
-
slottable를 target으로 한다. 만약 target이 슬로터블 이고 할당됨이라면, 아니면 null로 한다.
-
slot-in-closed-tree를 false로 한다.
-
parent를 target의 get the parent를 event로 호출한 결과로 한다.
-
parent가 null이 아닐 때까지 반복한다:
-
slottable이 null이 아니라면:
-
relatedTarget를 리타게팅 event의 relatedTarget을 parent에 대해 수행한 결과로 한다.
-
touchTargets를 새로운 리스트로 한다.
-
각각의 touchTarget을 event의 touch target list에서: append한다. 리타게팅 touchTarget을 parent에 대해 수행한 결과를 touchTargets에 추가한다.
-
parent가
Window객체이거나, parent가 노드이고 target의 루트가 섀도 포함 포괄 조상 이라면:-
isActivationEvent가 true이고, event의
bubbles속성이 true이고, activationTarget이 null이고, parent가 activation behavior를 가진다면, activationTarget를 parent로 한다. -
이벤트 경로에 추가한다. event, parent, null, relatedTarget, touchTargets, 그리고 slot-in-closed-tree를 사용한다.
-
-
그렇지 않고 parent가 relatedTarget이라면, parent를 null로 한다.
-
그 밖의 경우:
-
target을 parent로 한다.
-
isActivationEvent가 true이고, activationTarget이 null이고, target이 activation behavior를 가진다면, activationTarget를 target으로 한다.
-
이벤트 경로에 추가한다. event, parent, target, relatedTarget, touchTargets, 그리고 slot-in-closed-tree를 사용한다.
-
-
parent가 null이 아니라면, parent를 parent의 get the parent를 event로 호출한 결과로 한다.
-
slot-in-closed-tree를 false로 한다.
-
-
clearTargetsStruct를 event의 경로에서 shadow-adjusted target이 null이 아닌 마지막 구조체로 한다.
-
만약 clearTargetsStruct의 shadow-adjusted target, clearTargetsStruct의 relatedTarget, 또는
EventTarget객체가 clearTargetsStruct의 touch target list에 있고, 노드이며 루트가 섀도 루트라면, clearTargets를 true로 한다. -
activationTarget이 null이 아니고 activationTarget이 legacy-pre-activation behavior를 가진다면, activationTarget의 legacy-pre-activation behavior를 실행한다.
-
각각의 struct을 event의 경로에서, 역순으로:
-
struct의 shadow-adjusted target 이 null이 아니라면, event의
eventPhase속성을AT_TARGET으로 설정한다. -
그 밖의 경우, event의
eventPhase속성을CAPTURING_PHASE로 설정한다. -
Invoke를 struct, event, "
capturing", 그리고 legacyOutputDidListenersThrowFlag가 주어졌다면 그것과 함께 호출한다.
-
-
-
struct의 shadow-adjusted target 이 null이 아니라면, event의
eventPhase속성을AT_TARGET으로 설정한다. -
그 밖의 경우:
-
event의
eventPhase속성을BUBBLING_PHASE로 설정한다.
-
Invoke를 struct, event, "
bubbling", 그리고 legacyOutputDidListenersThrowFlag가 주어졌다면 그것과 함께 호출한다.
-
-
-
event의
eventPhase속성을NONE로 설정한다. -
event의
currentTarget속성을 null로 설정한다. -
event의 경로를 빈 리스트로 한다.
-
event의 디스패치 플래그, stop propagation 플래그, 그리고 stop immediate propagation 플래그를 해제한다.
-
clearTargets가 true라면:
-
event의 target을 null로 한다.
-
event의 relatedTarget을 null로 한다.
-
event의 touch target list를 빈 리스트로 한다.
-
-
activationTarget이 null이 아니라면:
-
event의 canceled 플래그가 해제되어 있다면, activationTarget의 activation behavior를 event와 함께 실행한다.
-
그 밖의 경우, activationTarget이 legacy-canceled-activation behavior를 가진다면, activationTarget의 legacy-canceled-activation behavior를 실행한다.
-
-
event의 canceled 플래그가 설정되어 있다면 false를 반환하고, 아니면 true를 반환한다.
이벤트 경로에 추가하려면, event, invocationTarget, shadowAdjustedTarget, relatedTarget, touchTargets, 그리고 slot-in-closed-tree가 주어졌을 때, 다음 단계들을 실행한다:
-
invocationTargetInShadowTree를 false로 한다.
-
invocationTarget이 노드이고 그 루트가 섀도 루트라면, invocationTargetInShadowTree를 true로 한다.
-
root-of-closed-tree를 false로 한다.
-
invocationTarget이 섀도 루트이고 mode 가 "
closed"라면, root-of-closed-tree를 true로 한다. -
Append를 사용하여 새로운 struct를 event의 경로에 추가한다. 이 struct의 invocation target은 invocationTarget, invocation-target-in-shadow-tree는 invocationTargetInShadowTree, shadow-adjusted target은 shadowAdjustedTarget, relatedTarget은 relatedTarget, touch target list는 touchTargets, root-of-closed-tree는 root-of-closed-tree, 그리고 slot-in-closed-tree는 slot-in-closed-tree이다.
invoke를 위해, struct, event, phase, 그리고 선택적으로 legacyOutputDidListenersThrowFlag가 주어졌을 때, 다음 단계들을 실행한다:
-
event의 target을 shadow-adjusted target으로 설정한다. 이 값은 event의 경로에서 struct 또는 그 이전의 struct 중 shadow-adjusted target이 null이 아닌 마지막 struct의 값이다.
-
event의 relatedTarget을 struct의 relatedTarget으로 설정한다.
-
event의 touch target list를 struct의 touch target list로 설정한다.
-
event의 stop propagation 플래그가 설정되어 있다면, return한다.
-
event의
currentTarget속성을 struct의 invocation target으로 초기화한다. -
listeners를 clone하여 event의
currentTarget속성 값의 event listener list를 복제한다.이렇게 하면 이 시점 이후에 추가된 event listener가 실행되지 않는다. 단, 삭제는 removed 필드로 인해 영향을 준다.
-
invocationTargetInShadowTree를 struct의 invocation-target-in-shadow-tree로 한다.
-
found를 inner invoke를 event, listeners, phase, invocationTargetInShadowTree, 그리고 legacyOutputDidListenersThrowFlag가 주어졌다면 그것과 함께 실행한 결과로 한다.
-
found가 false이고 event의
isTrusted속성이 true라면:-
originalEventType을 event의
type속성 값으로 한다. -
event의
type속성 값이 아래 표의 첫 번째 열에 있는 문자열과 일치하면, event의type속성 값을 같은 행의 두 번째 열의 문자열로 설정하고, 아니면 return한다.이벤트 타입 레거시 이벤트 타입 " animationend"" webkitAnimationEnd"" animationiteration"" webkitAnimationIteration"" animationstart"" webkitAnimationStart"" transitionend"" webkitTransitionEnd" -
inner invoke를 event, listeners, phase, invocationTargetInShadowTree, 그리고 legacyOutputDidListenersThrowFlag가 주어졌다면 그것과 함께 실행한다.
-
event의
type속성 값을 originalEventType로 설정한다.
-
inner invoke를 위해, event, listeners, phase, invocationTargetInShadowTree, 그리고 선택적으로 legacyOutputDidListenersThrowFlag가 주어졌을 때, 다음 단계들을 실행한다:
-
found를 false로 한다.
-
각각의 listener를 listeners에서, 그 removed가 false인 경우에 대해:
-
found를 true로 한다.
-
phase가 "
capturing"이고 listener의 capture가 false라면, continue한다. -
listener의 once가 true라면, remove an event listener를 event의
currentTarget속성 값과 listener로 실행한다. -
global을 listener의 callback의 associated realm의 global object로 한다.
-
currentEvent를 undefined로 한다.
-
global이
Window객체라면:-
currentEvent를 global의 current event로 한다.
-
invocationTargetInShadowTree가 false라면, global의 current event를 event로 설정한다.
-
-
listener의 passive가 true라면, event의 in passive listener flag를 설정한다.
-
global이
Window객체라면, 이벤트 리스너의 타이밍 정보 기록를 event와 listener로 실행한다. -
사용자 객체의 operation 호출을 listener의 callback, "
handleEvent", « event », 그리고 event의currentTarget속성 값으로 실행한다. 만약 예외 exception이 발생하면:-
예외 보고를 exception과 listener의 callback의 해당 JavaScript 객체의 associated realm의 global object로 실행한다.
-
legacyOutputDidListenersThrowFlag가 주어졌다면 설정한다.
legacyOutputDidListenersThrowFlag는 Indexed Database API에서만 사용된다. [INDEXEDDB]
-
-
event의 in passive listener flag를 해제한다.
-
global이
Window객체라면, global의 current event를 currentEvent로 설정한다. -
event의 stop immediate propagation flag가 설정되어 있다면, break한다.
-
found를 반환한다.
2.10. 이벤트 발생
이벤트 발생을 위해 e라는 이름의 이벤트를 target에서, 선택적으로 eventConstructor를 사용하여, IDL 속성 초기화 방법의 설명과 legacy target override flag와 함께, 다음 단계들을 실행한다:
-
eventConstructor가 주어지지 않았다면, eventConstructor를
Event로 한다. -
event를 이벤트 생성을 eventConstructor와 target의 관련 realm에서 실행한 결과로 한다.
-
event의
type속성을 e로 초기화한다. -
이 알고리즘 호출에서 설명된 대로 event의 다른 IDL 속성들도 초기화한다.
이렇게 하면
isTrusted속성을 false로 설정할 수도 있다. -
디스패치를 event와 target에 대해 실행한 결과를 반환한다. legacy target override flag가 설정되어 있다면 함께 사용한다.
DOM에서 fire는 생성, 초기화, 그리고 디스패치를 의미한다. 이벤트 발생은 이 과정을 더 쉽게 기술할 수 있게 해준다.
이벤트의
bubbles
또는 cancelable
속성을 초기화해야 한다면,
"submit이라는 이름의
이벤트를 target에서 발생시키고,
cancelable
속성을 true로 초기화한다"고 쓸 수 있다.
또는, 커스텀 생성자가 필요할 때는, "click이라는 이름의 이벤트를
target에서 MouseEvent
생성자를 사용하여 발생시키고, detail
속성을 1로 초기화한다"고 쓸 수 있다.
가끔 반환값이 중요할 때가 있다:
-
doAction을 이벤트 발생을
like라는 이름으로 target에서 실행한 결과로 한다. -
doAction이 true라면 …
2.11. 동작과 발생의 차이
이벤트는
동작이 아니라 발생을 의미한다. 다시 말해,
알고리즘에서의 알림을 나타내며, 그 알고리즘의 향후 진행에 영향을 줄 수 있다
(예: preventDefault()
호출).
이벤트는
어떤 알고리즘을 시작시키는 동작이나 트리거로 사용되어서는 안 된다. 그것이 이벤트의 목적이 아니다.
이 부분을 명확히 하는 이유는 이전 DOM 버전에서는 이벤트에 "기본 동작" 개념이 있었기 때문에 오해가 많았다. 이벤트는 동작을 나타내거나 유발하지 않으며, 진행 중인 동작에만 영향을 줄 수 있다.
3. 진행 중인 작업 중단
프라미스에는 내장된 중단 메커니즘이 없지만, 이를 사용하는 많은 API는 중단 의미론을 필요로 한다. AbortController
는 abort()
메서드를 제공하여 해당 AbortSignal
객체의 상태를 토글함으로써 이러한 요구를 지원한다.
중단을 지원하고자 하는 API는 AbortSignal
객체를 받아 그 상태를 참고하여 동작을 결정할 수 있다.
AbortController
를 사용하는 API는 abort()
호출 시, 해결되지 않은 프라미스를 AbortSignal의
중단 이유로
reject하는 것이 권장된다.
가상의 doAmazingness({ ... }) 메서드는 중단을 지원하기 위해 AbortSignal
객체를 다음과 같이 받을 수 있다:
const controller = new AbortController();
const signal = controller. signal;
startSpinner();
doAmazingness({ ..., signal })
. then( result => ...)
. catch ( err => {
if ( err. name == 'AbortError' ) return ;
showUserErrorMessage();
})
. then(() => stopSpinner());
// …
controller. abort();
doAmazingness는 다음과 같이 구현할 수 있다:
function doAmazingness({ signal}) {
return new Promise(( resolve, reject) => {
signal. throwIfAborted();
// 놀라운 작업을 시작하고, 완료 시 resolve(result)를 호출한다.
// 또한, 시그널을 감시한다:
signal. addEventListener( 'abort' , () => {
// 놀라운 작업을 중단하고:
reject( signal. reason);
});
});
}
프라미스를 반환하지 않는 API는 동등하게 반응하거나 AbortSignal의
중단 이유를
노출하지 않을 수도 있다. addEventListener()
는 후자의 예시이다.
더 세밀한 제어가 필요한 API는 AbortController
와
AbortSignal
객체를 필요에 따라 확장할 수 있다.
3.1.
인터페이스 AbortController
[Exposed=*]interface {AbortController constructor (); [SameObject ]readonly attribute AbortSignal signal ;undefined abort (optional any ); };reason
controller = new AbortController()- 새로운 controller를 반환하며, 그
signal은 새로 생성된AbortSignal객체로 설정된다. controller . signal- 이 객체와 연관된
AbortSignal객체를 반환한다. controller . abort(reason)- 이 메서드를 호출하면 reason이 이 객체의
AbortSignal의 중단 이유에 저장되고, 관련 작업이 중단되어야 함을 관찰자에게 알린다. reason이 undefined라면, "AbortError"DOMException이 저장된다.
AbortController
객체는 signal (즉,
AbortSignal
객체)을 가진다.
new AbortController()
생성자 단계는 다음과 같다:
-
signal을 새로운
AbortSignal객체로 한다.
signal getter 단계는
this의 signal을
반환한다.
abort(reason) 메서드 단계는
signal abort를 this와 reason으로
실행한다(주어졌을 경우).
signal abort를 AbortController
controller와 선택적 reason으로 실행하려면, signal abort를
controller의 signal과 reason으로 실행한다(주어졌을 경우).
3.2. 인터페이스 AbortSignal
[Exposed=*]interface :AbortSignal EventTarget { [NewObject ]static AbortSignal abort (optional any ); [reason Exposed =(Window ,Worker ),NewObject ]static AbortSignal timeout ([EnforceRange ]unsigned long long ); [milliseconds NewObject ]static AbortSignal _any (sequence <AbortSignal >);signals readonly attribute boolean aborted ;readonly attribute any reason ;undefined throwIfAborted ();attribute EventHandler onabort ; };
AbortSignal . abort(reason)AbortSignal인스턴스를 반환하며, 중단 이유가 reason으로 설정된다(정의되지 않은 경우 제외); 그렇지 않으면 "AbortError"DOMException이 설정된다.AbortSignal . any(signals)AbortSignal인스턴스를 반환하며, signals 중 하나라도 중단되면 해당 인스턴스도 중단된다. 중단 이유는 중단을 유발한 signals 중 하나의 이유로 설정된다.AbortSignal . timeout(milliseconds)AbortSignal인스턴스를 반환하며, milliseconds 밀리초 후 중단된다. 중단 이유는 "TimeoutError"DOMException으로 설정된다.signal . aborted- signal의
AbortController가 중단을 알렸으면 true, 아니면 false를 반환한다. signal . reason- signal의 중단 이유를 반환한다.
signal . throwIfAborted()- signal의 중단 이유를 던진다. signal의
AbortController가 중단을 알렸을 때만 동작하며, 그렇지 않으면 아무 것도 하지 않는다.
AbortSignal
객체는 연관된 중단 이유(JavaScript 값)를 가지며, 초기값은 undefined이다.
AbortSignal
객체는 연관된 중단 알고리즘(중단될 때 실행될 알고리즘의 집합)을 가지며, 초기에는 비어 있다.
중단 알고리즘은 복잡한 요구사항을 가진 API가 abort()에
합리적으로 반응할 수 있게 해준다.
예를 들어, 특정 API의 중단
이유는 서비스 워커와 같은 스레드 간 환경으로 전파되어야 할 수 있다.
AbortSignal
객체는 의존적인(불리언 값) 속성을 가지며, 초기값은 false이다.
AbortSignal
객체는 연관된 소스 신호(객체의 중단된 상태에 의존하는 AbortSignal
객체의 약한 집합)를 가지며, 초기에는 비어 있다.
AbortSignal
객체는 연관된 의존 신호(객체의 중단된 상태에 의존하는 AbortSignal
객체의 약한 집합)를 가지며, 초기에는 비어 있다.
정적 abort(reason) 메서드 단계는 다음과 같다:
-
signal을 새로운
AbortSignal객체로 한다. -
signal의 중단 이유를 reason이 주어졌으면 그것으로 설정하고, 그렇지 않으면 새로운 "
AbortError"DOMException으로 설정한다. - signal을 반환한다.
정적 timeout(milliseconds) 메서드
단계는 다음과 같다:
-
signal을 새로운
AbortSignal객체로 한다. -
global을 signal의 관련 전역 객체로 한다.
-
타임아웃 후 단계 실행을 global, "
AbortSignal-timeout", milliseconds, 그리고 다음 단계와 함께 실행한다:-
전역 태스크 큐에 추가를 타이머 태스크 소스에 global과 함께 실행하여, 중단 신호를 signal과 새로운 "
TimeoutError"DOMException으로 보낸다.
이 타임아웃 기간 동안, signal에
abort이벤트에 대한 이벤트 리스너가 등록되어 있다면, global에서 signal로의 강한 참조가 있어야 한다. -
-
signal을 반환한다.
정적 any(signals) 메서드
단계는 의존적인 중단 신호 생성을 signals로부터 AbortSignal
과 현재
realm을 사용하여 실행한 결과를 반환하는 것이다.
aborted getter 단계는 this가 중단되었다면 true를,
그렇지 않으면 false를 반환하는 것이다.
reason getter 단계는 this의
중단
이유를 반환하는 것이다.
throwIfAborted() 메서드 단계는 this가 중단되었다면 this의
중단
이유를 던지는 것이다.
이 메서드는 AbortSignal을
받는 함수가 AbortSignal을
다른 메서드에 전달하는 대신 특정 체크포인트에서 예외를 던지거나(또는 거부된 프라미스를 반환) 싶을 때 주로 유용하다. 예를 들어, 다음 함수는 조건 폴링 시도 사이에 중단을 허용한다.
이는 실제 비동기 작업(즉, )이
AbortSignal을
받지 않더라도 폴링 프로세스를 중단할 기회를 제공한다.
async function waitForCondition( func, targetValue, { signal} = {}) { while ( true ) { signal? . throwIfAborted(); const result= await func(); if ( result=== targetValue) { return ; } } }
onabort 속성은 onabort
이벤트 핸들러에 대한 이벤트 핸들러 IDL 속성이며, 이벤트 핸들러 이벤트 타입은
abort이다.
AbortSignal
객체의 변경은 해당 AbortController
객체의 의도를 나타내지만, AbortSignal
객체를 관찰하는 API는 이를 무시할 수 있다. 예를 들어, 작업이 이미 완료된 경우이다.
AbortSignal
객체는 그 중단
이유가 undefined가 아닐 때 중단된 것이다.
알고리즘 algorithm을 AbortSignal
객체 signal에 추가하려면:
알고리즘 algorithm을 AbortSignal
signal에서 제거하려면, algorithm을
signal의 중단 알고리즘에서 제거한다.
AbortSignal
객체 signal과 선택적 reason이 주어졌을 때, 중단 신호를 보내려면:
-
signal이 중단되었다면, 반환한다.
-
signal의 중단 이유를 reason이 주어졌으면 그것으로 설정하고, 그렇지 않으면 새로운 "
AbortError"DOMException으로 설정한다. -
dependentSignalsToAbort를 새로운 리스트로 한다.
-
signal에 대해 중단 단계를 실행한다.
-
dependentSignalsToAbort의 각 dependentSignal에 대해 반복하며, dependentSignal에 대해 중단 단계를 실행한다.
AbortSignal
signal에 대해 중단 단계 실행하려면:
AbortSignal
객체 목록 signals로부터, AbortSignal
또는 이를 상속하는 인터페이스여야 하는 signalInterface와 realm을 사용하여 의존적인 중단 신호 생성하려면:
3.2.1. 가비지 컬렉션
중단되지 않은 의존적인
AbortSignal
객체는 소스
신호가 비어있지 않고 abort
이벤트에 대한 등록된 이벤트 리스너가 있거나 중단 알고리즘이 비어있지 않은 동안에는 가비지 컬렉션되어서는 안 된다.
3.3.
API에서 AbortController
와 AbortSignal
객체 사용하기
중단될 수 있는 작업을 나타내기 위해 프라미스를 사용하는 모든 웹 플랫폼 API는 다음을 준수해야 한다:
signal딕셔너리 멤버를 통해AbortSignal객체를 받는다.AbortSignal객체의 중단 이유로 프라미스를 거부하여 작업이 중단되었음을 전달한다.AbortSignal이 이미 중단되었다면 즉시 거부하고, 그렇지 않으면:- 중단 알고리즘 메커니즘을 사용하여
AbortSignal객체의 변경사항을 관찰하되, 다른 관찰자들과 충돌하지 않는 방식으로 한다.
프라미스를 반환하는 메서드 doAmazingness(options)의 메서드 단계는 다음과 같을 수 있다:
-
p를 새로운 프라미스로 한다.
-
options["
signal"]이 존재한다면: -
다음 단계를 병렬로 실행한다:
-
amazingResult를 놀라운 일을 수행한 결과로 한다.
-
global과 함께 놀라운 태스크 소스에서 전역 태스크를 큐에 추가하여 amazingResult로 p를 이행한다.
-
-
p를 반환한다.
프라미스를 사용하지 않는 API도 가능한 한 위의 내용을 준수해야 한다.
4. 노드
4.1. "DOM" 소개
원래 의미에서 "DOM"은 문서(특히 HTML 및 XML 문서)에 접근하고 조작하기 위한 API입니다. 이 명세에서 "문서"라는 용어는 짧은 정적 문서부터 풍부한 멀티미디어를 가진 긴 에세이 또는 보고서, 그리고 완전한 인터랙티브 애플리케이션까지 모든 마크업 기반 리소스를 의미합니다.
이러한 각 문서는 노드 트리로 표현됩니다. 노드 중 일부는 트리에서 자식을 가질 수 있고, 다른 노드는 항상 리프(끝)입니다.
예를 들어, 다음 HTML 문서를 생각해보세요:
<!DOCTYPE html> < html class = e > < head >< title > Aliens?</ title ></ head > < body > Why yes.</ body > </ html >
이 문서는 다음과 같이 표현됩니다:
HTML 파싱의 마법 덕분에 모든 ASCII 공백이 텍스트 노드로 변환되는 것은 아니지만, 일반적인 개념은 분명합니다. 마크업이 들어가고, 트리와 노드가 생성됩니다.
아주 훌륭한 Live DOM Viewer 를 사용하여 이 내용을 더 자세히 탐색할 수 있습니다.
4.2. 노드 트리
노드는 Node를 구현하는
객체이다.
노드는 노드 트리로 알려진 트리에 참여한다.
실제로는 더 구체적인 객체들을 다룬다.
Node를 구현하는 객체들은 또한 상속된 인터페이스도 구현한다: Document,
DocumentType,
DocumentFragment,
Element,
CharacterData,
또는 Attr.
DocumentFragment를
구현하는 객체들은 때때로 ShadowRoot도
구현한다.
Element를 구현하는
객체들은 또한
일반적으로 HTMLAnchorElement와
같은 상속된 인터페이스를 구현한다.
CharacterData를
구현하는 객체들은
또한 상속된 인터페이스를 구현한다: Text,
ProcessingInstruction,
또는 Comment.
Text를 구현하는 객체들은 때때로
CDATASection도
구현한다.
따라서 모든 노드의 주 인터페이스는 다음 중 하나이다: Document,
DocumentType,
DocumentFragment,
ShadowRoot,
Element 또는
Element의 상속된
인터페이스,
Attr, Text, CDATASection,
ProcessingInstruction,
또는 Comment.
간결함을 위해, 이 명세는 Node와 상속된
인터페이스 NodeInterface를 구현하는 객체를
NodeInterface 노드라고 부른다.
노드 트리는 노드와 그 가능한 자식 간의 관계로 표현되는 다음과 같은 제약을 받는다:
Document-
트리 순서로:
-
0개 이상의
ProcessingInstruction또는Comment노드. -
선택적으로 하나의
DocumentType노드. -
0개 이상의
ProcessingInstruction또는Comment노드. -
0개 이상의
ProcessingInstruction또는Comment노드.
-
DocumentFragmentElement-
0개 이상의
Element또는CharacterData노드. DocumentTypeCharacterDataAttr-
자식 없음.
Attr 노드는 역사적인 이유로 트리에 참여하지만, 절대 (null이 아닌) 부모나 어떤 자식도 가지지 않으므로 트리 내에서 단독으로 존재한다.
노드 node의 길이를 결정하려면, 다음 단계를 수행한다:
-
만약 node가
DocumentType또는Attr노드라면, 0을 반환한다. -
만약 node가
CharacterData노드라면, node의 data의 길이를 반환한다. -
node의 자식의 개수를 반환한다.
4.2.1. 문서 트리
문서의 문서 요소는 부모가 해당 문서인 요소이다. 존재한다면; 그렇지 않으면 null이다.
노드 트리 제약에 따라, 그러한 요소는 하나만 있을 수 있다.
노드는 문서 트리에 속함이면 문서에 속함 이다. 문서에 속함 이라는 용어는 더 이상 사용되지 않습니다. 이 용어가 쓰인 표준은 섀도우 트리를 고려하도록 업데이트되지 않았음을 의미합니다.
4.2.2. 섀도 트리
섀도 루트는 그 호스트를 통해 항상 다른 노드 트리에 연결된다. 따라서 섀도 트리는 혼자 있지 않는다. 섀도 루트의 호스트의 노드 트리는 때때로 라이트 트리라고 불린다.
섀도 트리에 대응하는 라이트 트리는 그 자체로 섀도 트리일 수 있다.
노드는 그 섀도 포함 루트가 문서일 때 연결되었다고 한다.
4.2.2.1. 슬롯
슬롯은
HTML의
slot
요소를 통해서만 생성될 수 있다.
슬롯은 연관된 이름(문자열)을 가진다. 달리 명시되지 않는 한 빈 문자열이다.
슬롯의 이름을 업데이트하기 위해 다음 속성 변경 단계를 사용한다:
-
element가 슬롯이고, localName이
name이며, namespace가 null이라면:-
value가 oldValue와 같다면, 반환한다.
-
value가 null이고 oldValue가 빈 문자열이라면, 반환한다.
-
value가 빈 문자열이고 oldValue가 null이라면, 반환한다.
-
value가 null이거나 빈 문자열이라면, element의 이름을 빈 문자열로 설정한다.
-
그렇지 않으면, element의 이름을 value로 설정한다.
-
element의 루트와 함께 트리에 대한 슬롯 가능한 요소 할당을 실행한다.
-
섀도 트리에서 트리 순서로 첫 번째 슬롯이고 이름이 빈 문자열인 것은 때때로 "기본 슬롯"으로 알려져 있다.
슬롯은 연관된 할당된 노드(슬롯 가능한 요소의 목록)를 가진다. 달리 명시되지 않는 한 비어있다.
4.2.2.2. 슬롯 가능한 요소
Element와 Text 노드는
슬롯 가능한
요소이다.
슬롯 가능한 요소는 연관된 이름(문자열)을 가진다. 달리 명시되지 않는 한 빈 문자열이다.
슬롯 가능한 요소의 이름을 업데이트하기 위해 다음 속성 변경 단계를 사용한다:
-
localName이
slot이고 namespace가 null이라면:
슬롯 가능한 요소는 연관된 할당된 슬롯(null 또는 슬롯)을 가진다. 달리 명시되지 않는 한 null이다. 슬롯 가능한 요소는 그 할당된 슬롯이 non-null일 때 할당되었다고 한다.
슬롯 가능한 요소는 연관된 수동 슬롯 할당(null 또는 슬롯)을 가진다. 달리 명시되지 않는 한 null이다.
슬롯 가능한 요소의 수동 슬롯 할당은 이 변수가 스크립트에서 직접 접근 가능하지 않기 때문에 슬롯에 대한 약한 참조를 사용하여 구현될 수 있다.
4.2.2.3. 슬롯과 슬롯 가능한 요소 찾기
주어진 슬롯 가능한 요소 slottable과 선택적 불리언 open(기본값 false)에 대해 슬롯 찾기를 하려면:
주어진 슬롯 slot에 대해 슬롯 가능한 요소 찾기를 하려면:
주어진 슬롯 slot에 대해 평면화된 슬롯 가능한 요소 찾기를 하려면:
-
result를 « »로 한다.
-
slottables를 slot을 주어서 슬롯 가능한 요소를 찾은 결과로 한다.
-
slottables가 빈 목록이라면, slot의 각 슬롯 가능한 요소 자식을 트리 순서로 slottables에 추가한다.
-
slottables의 각 node에 대해:
-
-
temporaryResult를 node를 주어서 평면화된 슬롯 가능한 요소를 찾은 결과로 한다.
-
temporaryResult의 각 슬롯 가능한 요소를 순서대로 result에 추가한다.
-
-
그렇지 않으면, node를 result에 추가한다.
-
-
result를 반환한다.
4.2.2.4. 슬롯 가능한 요소와 슬롯 할당
슬롯 slot에 대해 슬롯 가능한 요소 할당을 하려면:
-
slottables를 slot에 대해 슬롯 가능한 요소를 찾은 결과로 한다.
-
slottables와 slot의 할당된 노드가 동일하지 않다면, slot에 대해 슬롯 변경 신호를 실행한다.
-
slot의 할당된 노드를 slottables로 설정한다.
-
slottables의 각 slottable에 대해: slottable의 할당된 슬롯을 slot으로 설정한다.
주어진 노드 root에 대해 트리에 대한 슬롯 가능한 요소 할당을 하려면, root의 포함 후손의 각 슬롯에 대해 트리 순서로 슬롯 가능한 요소 할당을 실행한다.
주어진 슬롯 가능한 요소 slottable에 대해 슬롯 할당을 하려면:
-
slot을 slottable과 함께 슬롯을 찾은 결과로 한다.
-
slot이 non-null이라면, slot에 대해 슬롯 가능한 요소 할당을 실행한다.
4.2.2.5. 슬롯 변경 신호
각 유사 출처 윈도우 에이전트는 신호 슬롯(슬롯의 집합)을 가지며, 이는 초기에 비어있다. [HTML]
슬롯 slot에 대해 슬롯 변경 신호를 하려면:
4.2.3. 변경 알고리즘
다음은 사전 삽입 유효성 확인을 위해 노드 node를 노드 parent에 null 또는 노드 child 앞에 넣기 전에 수행할 절차입니다:
-
만약 parent가
Document,DocumentFragment, 또는Element노드가 아니라면, HierarchyRequestError "HierarchyRequestError"DOMException을 던집니다. -
만약 node가 host-including inclusive ancestor로서 parent의 조상이라면, HierarchyRequestError을 던집니다. "
HierarchyRequestError"DOMException. -
만약 child가 null이 아니고 그 parent가 parent가 아니라면, NotFoundError를 던집니다. "
NotFoundError"DOMException. -
만약 node가
DocumentFragment,DocumentType,Element, 또는CharacterData노드가 아니라면, HierarchyRequestError를 던집니다. "HierarchyRequestError"DOMException. -
만약 node가
Text노드이고 parent가 document인 경우, 또는 node가 doctype이고 parent가 document가 아닌 경우, HierarchyRequestError를 던집니다. "HierarchyRequestError"DOMException. -
만약 parent가 document이고, 아래의 문장들(인터페이스 node가 implements인지에 따라 전환됨) 중 어느 하나라도 참이면, HierarchyRequestError를 던집니다. "
HierarchyRequestError"DOMException.DocumentFragment-
만약 node가 요소 element인 자식을 두 개 이상 가지고 있거나,
Text노드를 자식으로 가지고 있다면 참입니다.그렇지 않고, 만약 node가 하나의 요소 element 자식를 가지고 있고, 동시에 parent가 이미 요소 element 자식를 가지고 있거나, child가 doctype이거나, child가 null이 아니고 doctype이 following인 경우에도 참입니다.
Element-
parent가 이미 요소 element 자식를 가지고 있거나, child가 doctype이거나, child가 null이 아니고 doctype가 following인 경우이면 참입니다.
DocumentType-
parent가 doctype 자식를 가지고 있거나, child가 null이 아니고 요소 element가 preceding인 경우, 또는 child가 null이고 parent가 요소 element 자식를 가지고 있다면 참입니다.
다음은 사전 삽입을 수행하는 절차입니다. 노드 node를 노드 parent에 null 또는 노드 child 앞에 삽입하려면:
-
사전 삽입 유효성 확인을 node가 parent에 child 앞에 들어갈 수 있는지에 대해 수행합니다.
-
referenceChild를 child로 정합니다.
-
만약 referenceChild가 node라면, referenceChild를 node의 다음 형제로 설정합니다.
-
삽입을 실행하여 node를 parent의 referenceChild 앞에 삽입합니다.
-
node를 반환합니다.
다른 관련 명세들은 일부 또는 모든 삽입 단계를 정의할 수 있습니다. 이 알고리즘은 아래의 insert 알고리즘에서 보이는 바와 같이 insertedNode를 전달받습니다. 이 단계들은 insertedNode가 참여하는 노드 트리를 변경하거나, browsing contexts를 생성하거나, 이벤트를 발화하거나, 자바스크립트를 실행해서는 안 됩니다. 다만 이러한 일들을 비동기적으로 수행하기 위해 작업을 큐에 넣을 수는 있습니다.
비록 삽입 단계들이 자바스크립트(등)를 실행할 수는 없지만, 실제로는 스크립트에서 관찰 가능한 결과를 가져옵니다. 아래 예를 보십시오:
const h1 = document. querySelector( 'h1' );
const fragment = new DocumentFragment();
const script = fragment. appendChild( document. createElement( 'script' ));
const style = fragment. appendChild( document. createElement( 'style' ));
script. innerText= 'console.log(getComputedStyle(h1).color)' ; // Logs 'rgb(255, 0, 0)'
style. innerText = 'h1 {color: rgb(255, 0, 0);}' ;
document. body. append( fragment);
위 예제의 스크립트는 를 로그로 출력합니다. 그 이유는
다음 일이 순서대로 발생하기 때문입니다:
다른 관련 명세들은 일부 또는 모든 post-connection 단계들을 정의할 수 있습니다. 이 알고리즘은 아래의 insert 알고리즘에서 보이는 바와 같이 connectedNode를 전달받습니다.
참고: post-connection 단계들의 목적은 노드들이 연결 관련 작업을 수행하여 노드 트리를 수정하거나, browsing contexts를 생성하거나, 자바스크립트를 실행할 기회를 제공하는 것입니다. 이 단계들은 노드들의 배치를 스크립트 관점에서 원자적으로 삽입할 수 있게 하며, 모든 주요 부작용이 노드 트리로의 배치 삽입이 완료된 후에 발생하도록 합니다. 이는 모든 보류 중인 노드 트리 삽입이 완료된 후에야 추가 삽입이 발생하도록 보장합니다.
다른 관련 명세들은 일부 또는 모든 children changed 단계들을 정의할 수 있습니다. 이 알고리즘은 인수를 받지 않으며 insert, remove, 및 replace data에서 호출됩니다.
다음은 삽입을 수행하는 절차입니다. 노드 node를 노드 parent에 null 또는 노드 child 앞에, 선택적 불리언 suppressObservers(기본값 false)와 함께 삽입하려면:
-
만약 node가
DocumentFragment노드라면, nodes를 node의 자식들로 설정합니다; 그렇지 않으면 « node »로 설정합니다. -
count를 nodes의 크기로 정합니다.
-
만약 count가 0이면, 반환합니다.
-
만약 node가
DocumentFragment노드라면:-
그 자식들을 children에서 suppressObservers를 true로 설정하여 제거합니다.
-
트리 변화 기록을 큐에 추가합니다: 대상은 node이고 인수는 « », nodes, null, null 입니다.
참고: 이 단계는 의도적으로 suppressObservers를 무시합니다.
-
-
만약 child가 null이 아니면:
-
previousSibling를 child의 이전 형제로 정하거나, 만약 child가 null이면 parent의 마지막 자식으로 정합니다.
-
nodes의 각 node에 대해, 트리 순서로 다음을 수행합니다:
-
그렇지 않으면, insert로 node를 parent의 children에 child의 인덱스 앞에 삽입합니다.
-
만약 parent가 shadow host이고 그 shadow root의 slot assignment가 "
named"이며 node가 slottable이면, assign a slot을 실행합니다. -
만약 parent의 루트가 shadow root이고, parent가 slot이며 그 assigned nodes가 빈 목록이면, signal a slot change를 parent에 대해 실행합니다.
-
assign slottables for a tree를 node의 루트로 실행합니다.
-
node의 모든 shadow-including inclusive descendant인 inclusiveDescendant들에 대해, shadow-including 트리 순서로 다음을 수행합니다:
-
insertion steps을 inclusiveDescendant에 대해 실행합니다.
-
만약 inclusiveDescendant가 element이고 inclusiveDescendant의 custom element registry가 null이 아니면:
-
만약 inclusiveDescendant의 custom element registry의 is scoped가 true이면, append로 inclusiveDescendant의 노드 문서를 해당 custom element registry의 scoped document set에 추가합니다.
-
만약 inclusiveDescendant가 custom이면, enqueue a custom element callback reaction을 inclusiveDescendant에 대해, 콜백 이름 "
connectedCallback", 그리고 « »로 호출합니다. -
그렇지 않으면, try to upgrade를 inclusiveDescendant에 대해 수행합니다.
참고: 만약 이것이 inclusiveDescendant를 성공적으로 업그레이드하면, 그
connectedCallback은 자동으로 upgrade an element 알고리즘 동안 큐에 추가됩니다.
-
-
그렇지 않고, 만약 inclusiveDescendant가 shadow root이고, 그 inclusiveDescendant의 custom element registry가 null이 아니며, 그 registry의 is scoped가 true이면, append로 inclusiveDescendant의 노드 문서를 해당 shadow root의 custom element registry의 scoped document set에 추가합니다.
-
-
만약 suppressObservers가 false이면, 트리 변화 기록을 큐에 추가합니다: 대상은 parent, 인수는 nodes, « », previousSibling, 그리고 child입니다.
-
children changed 단계들을 parent에 대해 실행합니다.
-
staticNodeList를 빈 리스트로 초기화합니다.
참고: 우리는 어떤 노드들에 대해 post-connection 단계들을 호출하기 전에 모든 노드들을 수집합니다. 이는 post-connection 단계들이 트리 구조를 변경할 수 있어 라이브 순회가 안전하지 않고, 같은 노드에 대해 중복 호출되는 것을 방지하기 위함입니다.
-
nodes의 각 node에 대해, 트리 순서로 다음을 수행합니다:
-
shadow-including inclusive descendant인 inclusiveDescendant를 shadow-including 트리 순서로 staticNodeList에 append합니다.
-
-
각 staticNodeList의 node에 대해: 만약 node가 connected라면, post-connection 단계들을 해당 node에 대해 실행합니다.
다음은 append을 수행하는 절차입니다. 노드 node를 노드 parent에 추가하려면: pre-insert로 node를 parent의 null 앞에 삽입합니다.
다른 관련 명세들은 일부 또는 모든 moving 단계들을 정의할 수 있습니다. 이 알고리즘은 노드 movedNode와 node-또는-null oldParent를 전달받습니다(아래 move 알고리즘 참조). 삽입 단계들과 마찬가지로, 이 단계들은 movedNode가 참여하는 노드 트리를 변경하거나, browsing contexts를 생성하거나, 이벤트를 발화하거나, 자바스크립트를 실행해서는 안 됩니다. 다만 이러한 일들을 비동기적으로 수행하기 위해 작업을 큐에 넣을 수는 있습니다.
다음은 move를 수행하는 절차입니다. 노드 node를 노드 newParent에 null 또는 노드 child 앞에 이동하려면:
-
만약 newParent의 shadow-including root가 node의 shadow-including root와 같지 않다면, HierarchyRequestError를 던집니다. "
HierarchyRequestError"DOMException.참고: 이것은 newParent의 connected가 node의 connected인지 확인하는 부수 효과를 가집니다.
-
만약 node가 host-including inclusive ancestor로서 newParent의 조상이라면, HierarchyRequestError를 던집니다. "
HierarchyRequestError"DOMException. -
만약 child가 null이 아니고 그 parent가 newParent가 아니라면, NotFoundError를 던집니다. "
NotFoundError"DOMException. -
만약 node가
Element도 아니고CharacterData도 아니라면, HierarchyRequestError를 던집니다. "HierarchyRequestError"DOMException. -
만약 node가
Text노드이고 newParent가 document이면, HierarchyRequestError를 던집니다. "HierarchyRequestError"DOMException. -
만약 newParent가 document이고, node가
Element노드이며, 또한 newParent가 이미 요소 element 자식을 가지고 있거나, child가 doctype이거나, child가 null이 아니고 doctype가 following인 경우라면, HierarchyRequestError를 던집니다. "HierarchyRequestError"DOMException. -
oldParent를 node의 parent로 정합니다.
-
Assert: oldParent는 null이 아닙니다.
-
live range pre-remove steps를 node에 대해 실행합니다.
-
각
NodeIterator객체 iterator에 대해, 그 root의 노드 문서가 node의 노드 문서와 같다면,NodeIteratorpre-remove steps를 node와 iterator에 대해 실행합니다. -
oldPreviousSibling를 node의 이전 형제로 정합니다.
-
oldNextSibling를 node의 다음 형제로 정합니다.
-
만약 node가 assigned되어 있다면, assign slottables를 node의 assigned slot에 대해 실행합니다.
-
만약 oldParent의 루트가 shadow root이고, oldParent가 slot이며 그 assigned nodes가 비어 있다면, signal a slot change를 oldParent에 대해 실행합니다.
-
만약 node가 inclusive descendant를 가지고 있고, 그 중에 slot이 있다면:
-
assign slottables for a tree를 oldParent의 루트에 대해 실행합니다.
-
assign slottables for a tree를 node에 대해 실행합니다.
-
-
만약 child가 null이 아니면:
-
만약 시작 노드가 newParent이고 시작 오프셋이 child의 인덱스보다 큰 라이브 범위가 있다면, 그 시작 오프셋을 1만큼 증가시킵니다.
-
만약 끝 노드가 newParent이고 끝 오프셋이 child의 인덱스보다 큰 라이브 범위가 있다면, 그 끝 오프셋을 1만큼 증가시킵니다.
-
-
newPreviousSibling를 child의 이전 형제로 정하거나, child가 null이면 newParent의 마지막 자식으로 정합니다.
-
그렇지 않으면, insert로 node를 newParent의 children에 child의 인덱스 앞에 삽입합니다.
-
만약 newParent가 shadow host이고 그 shadow root의 slot assignment가 "
named"이며 node가 slottable이면, assign a slot을 실행합니다. -
만약 newParent의 루트가 shadow root이고, newParent가 slot이며 그 assigned nodes가 비어 있다면, signal a slot change를 newParent에 대해 실행합니다.
-
assign slottables for a tree를 node의 루트에 대해 실행합니다.
-
node의 모든 shadow-including inclusive descendant인 inclusiveDescendant들에 대해, shadow-including 트리 순서로 다음을 수행합니다:
-
만약 inclusiveDescendant가 node라면, moving 단계들을 inclusiveDescendant와 oldParent에 대해 실행합니다. 그렇지 않으면 그 단계들을 inclusiveDescendant와 null에 대해 실행합니다.
참고: move 알고리즘은 insert 및 remove와는 별개의 원시 연산이므로, 전통적인 insertion 단계들이나 removing 단계들을 inclusiveDescendant에 대해 호출하지 않습니다.
-
만약 inclusiveDescendant가 custom이고 newParent가 connected라면, enqueue a custom element callback reaction를 inclusiveDescendant에 대해, 콜백 이름 "
connectedMoveCallback", 그리고 « »로 호출합니다.
-
-
트리 변화 기록을 큐에 추가합니다: 대상은 oldParent이고 인수는 « », « node », oldPreviousSibling, 및 oldNextSibling입니다.
-
트리 변화 기록을 큐에 추가합니다: 대상은 newParent이고 인수는 « node », « », newPreviousSibling, 및 child입니다.
다음은 교체를 수행하는 절차입니다. 노드 child를 노드 node로 대체하려면, 노드 parent 내에서:
-
만약 parent가
Document,DocumentFragment, 또는Element노드가 아니라면, HierarchyRequestError를 던집니다. "HierarchyRequestError"DOMException. -
만약 node가 host-including inclusive ancestor로서 parent의 조상이라면, HierarchyRequestError를 던집니다. "
HierarchyRequestError"DOMException. -
만약 child의 parent가 parent가 아니라면, NotFoundError를 던집니다. "
NotFoundError"DOMException. -
만약 node가
DocumentFragment,DocumentType,Element, 또는CharacterData노드가 아니라면, HierarchyRequestError를 던집니다. "HierarchyRequestError"DOMException. -
만약 node가
Text노드이고 parent가 document이면, 또는 node가 doctype이고 parent가 document가 아닌 경우, HierarchyRequestError를 던집니다. "HierarchyRequestError"DOMException. -
만약 parent가 document이고, 아래의 문장들(인터페이스 node가 implements인지에 따라 전환됨) 중 어느 하나라도 참이면, HierarchyRequestError를 던집니다. "
HierarchyRequestError"DOMException.DocumentFragment-
만약 node가 요소 element인 자식을 두 개 이상 가지고 있거나,
Text를 자식으로 가지고 있다면 참입니다.그렇지 않고, 만약 node가 하나의 요소 element 자식을 가지고 있고, 동시에 parent가 요소 element 자식을 가지고 있거나 그 자식이 child가 아니거나, 또는 doctype가 following인 경우 참입니다.
Element-
parent가 요소 element 자식을 가지고 있고 그 자식이 child가 아니거나, doctype가 following인 경우 참입니다.
DocumentType-
parent가 doctype 자식을 가지고 있고 그 자식이 child가 아니거나, 또는 요소 element가 preceding인 경우 참입니다.
참고: 위의 문장들은 pre-insert 알고리즘과 다릅니다.
-
referenceChild를 child의 다음 형제로 정합니다.
-
만약 referenceChild가 node이면, referenceChild를 node의 다음 형제로 설정합니다.
-
previousSibling를 child의 이전 형제로 정합니다.
-
removedNodes를 빈 집합으로 정합니다.
-
만약 child의 parent가 null이 아니면:
-
removedNodes를 « child »로 설정합니다.
-
Remove로 child를 제거하되, suppressObservers를 true로 설정합니다.
위의 조건은 child가 node인 경우에만 거짓이 될 수 있습니다.
-
-
nodes를 만약 node가
DocumentFragment노드라면 그 자식들로 설정하고, 그렇지 않으면 « node »로 설정합니다. -
Insert로 node를 parent의 referenceChild 앞에 삽입하되, suppressObservers를 true로 설정합니다.
-
트리 변화 기록을 큐에 추가합니다: 대상은 parent이고 인수는 nodes, removedNodes, previousSibling, 및 referenceChild입니다.
-
child를 반환합니다.
다음은 모두 교체를 수행하는 절차입니다. 노드 또는 null node로 노드 parent 내의 모든 자식을 대체하려면:
-
removedNodes를 parent의 children으로 정합니다.
-
addedNodes를 빈 집합으로 정합니다.
-
만약 node가
DocumentFragment노드라면, addedNodes를 node의 children으로 설정합니다. -
그렇지 않고, 만약 node가 null이 아니면 addedNodes를 « node »로 설정합니다.
-
Remove로 parent의 모든 children을 트리 순서로 제거하되, suppressObservers를 true로 설정합니다.
-
만약 node가 null이 아니면, insert로 node를 parent의 null 앞에 삽입하되, suppressObservers를 true로 설정합니다.
-
만약 addedNodes 또는 removedNodes가 비어있지 않다면, 트리 변화 기록을 큐에 추가합니다: 대상은 parent이고 인수는 addedNodes, removedNodes, null, null 입니다.
참고: 이 알고리즘은 노드 트리 제약에 관한 검사를 수행하지 않습니다. 명세 작성자는 이를 신중히 사용해야 합니다.
다음은 사전 제거를 수행하는 절차입니다. 노드 child를 노드 parent에서 제거하려면:
-
만약 child의 parent가 parent가 아니라면, NotFoundError를 던집니다. "
NotFoundError"DOMException. -
Remove로 child를 제거합니다.
-
child를 반환합니다.
다른 관련 명세들은 일부 또는 모든 removing 단계들을 정의할 수 있습니다. 이 알고리즘은 아래의 remove 알고리즘에서 보이는 바와 같이 removedNode와 node-또는-null oldParent를 전달받습니다.
다음은 제거를 수행하는 절차입니다. 노드 node를 제거하려면, 선택적 불리언 suppressObservers(기본값 false)를 사용합니다:
-
parent를 node의 parent로 정합니다.
-
단언: parent는 null이 아닙니다.
-
live range pre-remove steps를 node에 대해 실행합니다.
-
각
NodeIterator객체 iterator에 대해, 그 root의 노드 문서가 node의 노드 문서와 같다면,NodeIteratorpre-remove steps를 node와 iterator에 대해 실행합니다. -
oldPreviousSibling를 node의 이전 형제로 정합니다.
-
oldNextSibling를 node의 다음 형제로 정합니다.
-
만약 node가 assigned되어 있다면, assign slottables를 node의 assigned slot에 대해 실행합니다.
-
만약 parent의 루트가 shadow root이고, parent가 slot이며 그 assigned nodes가 비어 있다면, signal a slot change를 parent에 대해 실행합니다.
-
만약 node가 inclusive descendant를 가지고 있고, 그 중에 slot이 있다면:
-
assign slottables for a tree를 parent의 루트에 대해 실행합니다.
-
assign slottables for a tree를 node에 대해 실행합니다.
-
-
removing 단계들을 node와 parent에 대해 실행합니다.
-
isParentConnected를 parent의 connected 값으로 정합니다.
-
만약 node가 custom이고 isParentConnected가 true이면, enqueue a custom element callback reaction를 node에 대해, 콜백 이름 "
disconnectedCallback", 그리고 « »로 호출합니다.참고: 현재는 custom elements에게 parent를 전달하지 않는 것이 의도적입니다. 필요에 따라 향후 변경될 수 있습니다.
-
node의 모든 shadow-including descendant인 descendant들에 대해, shadow-including 트리 순서로 다음을 수행합니다:
-
removing 단계들을 descendant와 null에 대해 실행합니다.
-
만약 descendant가 custom이고 isParentConnected가 true이면, enqueue a custom element callback reaction를 descendant에 대해, 콜백 이름 "
disconnectedCallback", 그리고 « »로 호출합니다.
-
-
각 inclusive ancestor인 inclusiveAncestor에 대해, 그리고 그 inclusiveAncestor의 registered observer list의 각 registered에 대해, 만약 registered의 options["
subtree"]가 true이면, append로 새로운 transient registered observer를 추가합니다. 이 새로운 옵저버의 observer는 registered의 observer이고, options은 registered의 options, 그리고 source는 registered가 node의 registered observer list에 대해 등록한 것입니다. -
만약 suppressObservers가 false이면, 트리 변화 기록을 큐에 추가합니다: 대상은 parent이고 인수는 « », « node », oldPreviousSibling, 및 oldNextSibling입니다.
-
children changed 단계들을 parent에 대해 실행합니다.
4.2.4.
믹스인 NonElementParentNode
웹 호환성으로 인해 getElementById()
메서드는 요소에서(따라서 ParentNode에서도)
노출되지 않습니다.
interface mixin {NonElementParentNode Element ?getElementById (DOMString ); };elementId Document includes NonElementParentNode ;DocumentFragment includes NonElementParentNode ;
getElementById(elementId)
메서드 단계는 트리 순서로
this의 자손
중에서
elementId라는 ID를 가진 첫
번째
요소를 반환합니다. 그런 요소가 없다면
null을 반환합니다.
4.2.5.
믹스인 DocumentOrShadowRoot
interface mixin {DocumentOrShadowRoot readonly attribute CustomElementRegistry ?customElementRegistry ; };Document includes DocumentOrShadowRoot ;ShadowRoot includes DocumentOrShadowRoot ;
registry = documentOrShadowRoot .customElementRegistry-
documentOrShadowRoot의
CustomElementRegistry객체를 반환합니다. 없다면 null을 반환합니다.
customElementRegistry
getter 단계는 다음과 같습니다:
-
this가 문서라면, this의 커스텀 요소 레지스트리를 반환합니다.
-
Assert: this는
ShadowRoot노드입니다. -
this의 커스텀 요소 레지스트리를 반환합니다.
DocumentOrShadowRoot
믹스인은 문서와
섀도우 루트 사이에서
API를 공유하려는 다른 표준에서도 사용할 것으로 예상됩니다.
4.2.6. 믹스인 ParentNode
노드들을 하나의 노드로 변환하기를 수행하려면, 리스트 형태의 노드들과 문자열 nodes, 그리고 document document가 주어졌을 때:
-
nodes의 각 문자열을 새로운
Text노드로 대체한다. 이 노드의 data는 해당 문자열이고, 노드 document는 document이다. -
nodes의 크기가 1이면, nodes[0]을 반환한다.
-
fragment를 새로운
DocumentFragment노드로 생성한다. 이 노드의 노드 document는 document이다. -
nodes의 각 node에 대해: append node를 fragment에 추가한다.
-
fragment를 반환한다.
interface mixin { [ParentNode SameObject ]readonly attribute HTMLCollection children ;readonly attribute Element ?firstElementChild ;readonly attribute Element ?lastElementChild ;readonly attribute unsigned long childElementCount ; [CEReactions ,Unscopable ]undefined prepend ((Node or DOMString )...); [nodes CEReactions ,Unscopable ]undefined append ((Node or DOMString )...); [nodes CEReactions ,Unscopable ]undefined replaceChildren ((Node or DOMString )...); [nodes CEReactions ]undefined moveBefore (Node ,node Node ?);child Element ?querySelector (DOMString ); [selectors NewObject ]NodeList querySelectorAll (DOMString ); };selectors Document includes ParentNode ;DocumentFragment includes ParentNode ;Element includes ParentNode ;
collection = node .children- 자식 요소들을 반환합니다.
element = node .firstElementChild- 첫 번째 자식이 요소라면 이를, 아니라면 null을 반환합니다.
element = node .lastElementChild- 마지막 자식이 요소라면 이를, 아니라면 null을 반환합니다.
node . prepend(nodes)-
nodes를 node의 첫 번째 자식 앞에 삽입합니다. nodes 안의 문자열은 동등한
Text노드로 변환되어 삽입됩니다.Throws 만약 HierarchyRequestError
DOMException발생 조건은 노드 트리의 제약이 위반될 경우입니다. node . append(nodes)-
nodes를 node의 마지막 자식 뒤에 삽입합니다. nodes 안의 문자열은 동등한
Text노드로 변환되어 삽입됩니다.Throws 만약 HierarchyRequestError
DOMException발생 조건은 노드 트리의 제약이 위반될 경우입니다. node . replaceChildren(nodes)-
node의 모든 자식을 nodes로 교체합니다. nodes 안의 문자열은 동등한
Text노드로 변환되어 교체됩니다.Throws 만약 HierarchyRequestError
DOMException발생 조건은 노드 트리의 제약이 위반될 경우입니다. node . moveBefore(movedNode, child)-
제거하지 않고 movedNode를 node 안에서 child 뒤에 이동시킵니다. child가 null이면 node의 마지막 자식 뒤에 이동합니다. 이 메서드는 movedNode와 연결된 상태를 보존합니다.
Throws 만약 HierarchyRequestError
DOMException발생 조건은 노드 트리 제약 위반이나 이동된 노드와 연결된 상태를 보존할 수 없을 경우입니다. node . querySelector(selectors)node . querySelectorAll(selectors)
children getter의 단계는 HTMLCollection
컬렉션을 반환합니다. 이
컬렉션은 this를
루트로 하며,
오직 요소 자식만을 매칭합니다.
prepend(nodes) 메서드 단계:
-
node를 노드들을 하나의 노드로 변환하기의 결과로 설정합니다. nodes와 this의 노드 문서를 인자로 넘깁니다.
-
Pre-insert node를 this에, this의 첫 번째 자식 앞에 삽입합니다.
append(nodes) 메서드 단계:
-
node를 노드들을 하나의 노드로 변환하기의 결과로 설정합니다. nodes와 this의 노드 문서를 인자로 넘깁니다.
replaceChildren(nodes) 메서드 단계:
-
node를 노드들을 하나의 노드로 변환하기의 결과로 설정합니다. nodes와 this의 노드 문서를 인자로 넘깁니다.
-
Ensure pre-insert validity를 확인하여 node를 this에 null 앞에 삽입 가능한지 검사합니다.
-
Replace all을 통해 node로 this의 모든 자식을 교체합니다.
moveBefore(node, child)
메서드 단계:
querySelector(selectors) 메서드
단계는 scope-match a
selectors string을 selectors와 this에 대해 실행한 결과 첫 번째 값을 반환합니다.
결과가 빈 리스트면 null을 반환합니다.
querySelectorAll(selectors)
메서드 단계는 static 결과로
scope-match a selectors string을
selectors와 this에 대해 실행한 결과를 반환합니다.
4.2.7. 믹스인 NonDocumentTypeChildNode
웹 호환성으로 인해 previousElementSibling
및
nextElementSibling
특성은 doctype에서(따라서 ChildNode에서도)
노출되지 않습니다.
interface mixin {NonDocumentTypeChildNode readonly attribute Element ?previousElementSibling ;readonly attribute Element ?nextElementSibling ; };Element includes NonDocumentTypeChildNode ;CharacterData includes NonDocumentTypeChildNode ;
element = node .previousElementSibling- 첫 번째 앞선 형제 중 요소를 반환합니다. 없으면 null.
element = node .nextElementSibling- 첫 번째 이후 형제 중 요소를 반환합니다. 없으면 null.
4.2.8. 믹스인 ChildNode
interface mixin { [ChildNode CEReactions ,Unscopable ]undefined before ((Node or DOMString )...); [nodes CEReactions ,Unscopable ]undefined after ((Node or DOMString )...); [nodes CEReactions ,Unscopable ]undefined replaceWith ((Node or DOMString )...); [nodes CEReactions ,Unscopable ]undefined remove (); };DocumentType includes ChildNode ;Element includes ChildNode ;CharacterData includes ChildNode ;
node .before(...nodes)-
nodes를 node 바로 앞에 삽입합니다. nodes 내의 문자열은 동등한
Text노드로 변환되어 삽입됩니다.Throws "
HierarchyRequestError"DOMException예외는 노드 트리의 제약이 위반되는 경우 발생합니다. node .after(...nodes)-
nodes를 node 바로 뒤에 삽입합니다. nodes 내의 문자열은 동등한
Text노드로 변환되어 삽입됩니다.Throws "
HierarchyRequestError"DOMException예외는 노드 트리의 제약이 위반되는 경우 발생합니다. node .replaceWith(...nodes)-
node를 nodes로 교체합니다. nodes 내의 문자열은 동등한
Text노드로 변환되어 삽입됩니다.Throws "
HierarchyRequestError"DOMException예외는 노드 트리의 제약이 위반되는 경우 발생합니다. node .remove()- node를 제거합니다.
before(nodes) 메서드 단계:
-
parent가 null이면 반환합니다.
-
viablePreviousSibling를 this의 이전 형제 중 nodes에 포함되지 않은 첫 번째로 설정합니다. 없다면 null입니다.
-
node를 노드들을 하나의 노드로 변환하기 결과로 설정합니다. nodes와 this의 노드 문서를 인자로 넘깁니다.
-
viablePreviousSibling가 null이면, parent의 첫 번째 자식으로 설정합니다. null이 아니라면, viablePreviousSibling의 다음 형제로 설정합니다.
-
Pre-insert node를 parent에, viablePreviousSibling 앞에 삽입합니다.
after(nodes) 메서드 단계:
-
parent가 null이면 반환합니다.
-
viableNextSibling를 this의 다음 형제 중 nodes에 포함되지 않은 첫 번째로 설정합니다. 없다면 null입니다.
-
node를 노드들을 하나의 노드로 변환하기 결과로 설정합니다. nodes와 this의 노드 문서를 인자로 넘깁니다.
-
Pre-insert node를 parent에, viableNextSibling 앞에 삽입합니다.
replaceWith(nodes) 메서드 단계:
-
parent가 null이면 반환합니다.
-
viableNextSibling를 this의 다음 형제 중 nodes에 포함되지 않은 첫 번째로 설정합니다. 없다면 null입니다.
-
node를 노드들을 하나의 노드로 변환하기 결과로 설정합니다. nodes와 this의 노드 문서를 인자로 넘깁니다.
-
this의 부모가 parent라면, replace를 사용하여 this를 parent 내에서 node로 교체합니다.
this가 node에 삽입된 경우일 수 있습니다.
-
그렇지 않으면, pre-insert node를 parent에, viableNextSibling 앞에 삽입합니다.
4.2.9. 믹스인 Slottable
interface mixin {Slottable readonly attribute HTMLSlotElement ?assignedSlot ; };Element includes Slottable ;Text includes Slottable ;
assignedSlot
getter 단계는 find a slot을 this와 true를
인자로 하여 실행한 결과를 반환합니다.
4.2.10.
구식 컬렉션: NodeList 및
HTMLCollection
컬렉션은 노드들의 리스트를 나타내는 객체입니다. 컬렉션은 라이브일 수도 있고, 정적일 수도 있습니다. 달리 명시되지 않는 한, 컬렉션은 라이브여야 합니다.
컬렉션이 라이브일 경우, 해당 객체의 속성과 메서드는 데이터의 스냅샷이 아닌 실제 기반 데이터에 대해 작동해야 합니다.
컬렉션이 생성될 때, 필터와 루트가 연결됩니다.
컬렉션은 컬렉션이 나타내는 루트로 하는 서브트리 뷰를 나타내며, 필터에 부합하는 노드만 포함합니다. 이 뷰는 선형적입니다. 별도 요구사항이 없다면, 컬렉션 내의 노드들은 트리 순서로 정렬되어야 합니다.
4.2.10.1.
인터페이스 NodeList
NodeList
객체는 컬렉션이며 노드들로 구성되어 있습니다.
[Exposed =Window ]interface {NodeList getter Node ?item (unsigned long );index readonly attribute unsigned long length ;iterable <Node >; };
- collection .
length - 컬렉션 안에 있는 노드의 개수를 반환합니다.
- element = collection .
item(index)- element = collection[index]
- 컬렉션에서 index에 해당하는 노드를 반환합니다. 노드들은 트리 순서로 정렬되어 있습니다.
객체의 지원되는 프로퍼티 인덱스는 0부터 컬렉션이 실제로 나타내는 노드 수보다 하나 작은 값까지의 숫자입니다. 이런 요소가 없으면 지원되는 프로퍼티 인덱스도 없습니다.
length 속성은 컬렉션이 실제로 나타내는 노드의 개수를
반환해야 합니다.
item(index) 메서드는 컬렉션에서 index번째 노드를 반환해야 합니다. 컬렉션에
index번째 노드가 없다면,
메서드는 null을 반환해야 합니다.
4.2.10.2.
인터페이스 HTMLCollection
[Exposed =Window ,LegacyUnenumerableNamedProperties ]interface {HTMLCollection readonly attribute unsigned long length ;getter Element ?item (unsigned long );index getter Element ?(namedItem DOMString ); };name
HTMLCollection
객체는 컬렉션이며 요소들로 구성되어 있습니다.
HTMLCollection
은 웹에서 제거할 수 없는 역사적 유물입니다.
개발자가 계속 사용해도 되지만, 새로운 API 표준 설계자는 이를 사용하지 않는 것이 좋습니다 (IDL에서 sequence<T> 사용 권장).
- collection .
length - 컬렉션 내 요소의 개수를 반환합니다.
- element = collection .
item(index)- element = collection[index]
- 컬렉션에서 인덱스 index에 해당하는 요소를 반환합니다. 요소는 트리 순서로 정렬됩니다.
- element = collection .
namedItem(name)- element = collection[name]
- 컬렉션에서 name과 ID 또는 name이 일치하는 첫 번째 요소를 반환합니다.
이 객체의 지원되는 프로퍼티 인덱스는 0부터 요소의 개수-1까지의 숫자입니다. 해당 요소가 없으면 지원되는 프로퍼티 인덱스가 없습니다.
length getter 단계는
컬렉션이 나타내는 노드의 개수를 반환합니다.
item(index) 메서드 단계는
컬렉션 내
index번째 요소를
반환합니다. 만약 index번째 요소가 없으면 null을 반환해야 합니다.
지원되는 프로퍼티 이름은 아래 단계에서 반환된 리스트의 값들입니다:
-
result를 빈 리스트로 설정합니다.
-
result를 반환합니다.
namedItem(key) 메서드 단계는:
-
key가 빈 문자열이면 null을 반환합니다.
-
아래 중 하나라도 true인 컬렉션 내 첫 번째 요소를 반환합니다:
- 해당 요소가 ID가 key인 경우
- HTML 네임스페이스에 있고, name 특성이 있고, value가 key인 경우
해당 요소가 없다면 null을 반환합니다.
4.3. 변이 옵저버(Mutation observers)
각 동일 출처 윈도우 에이전트(similar-origin window agent)는 변이 옵저버 마이크로태스크 대기(mutation observer microtask queued) (불리언) 값을 가지고 있으며, 초기값은 false입니다. [HTML]
각 동일 출처 윈도우 에이전트는 또한
대기 중인 변이 옵저버(pending
mutation
observers) (0개 이상의 집합(set)
MutationObserver
객체)도 가지고 있으며, 초기값은 빈 집합입니다.
변이 관찰자 마이크로태스크를 큐에 추가하다를 수행하려면:
-
주변 에이전트의 변이 관찰자 마이크로태스크 큐에 추가됨이 true이면, 반환한다.
-
주변 에이전트의 변이 관찰자 마이크로태스크 큐에 추가됨을 true로 설정한다.
-
마이크로태스크를 큐에 넣고 마이크로태스크를 변이 관찰자에게 알림에 할당한다.
변이 관찰자에게 알림을 수행하려면:
-
주변 에이전트의 변이 관찰자 마이크로태스크 큐에 추가됨을 false로 설정한다.
-
notifySet을 복제한 주변 에이전트의 대기 중인 변이 관찰자 목록을 사용해 만든다.
-
각 mo를 notifySet에서 반복:
-
각 slot을 signalSet에서 반복: 이벤트를 발생시킨다. 이름은
slotchange이고,bubbles속성은 true로, slot에서 발생한다.
각 노드는 등록된 옵저버 목록을 갖는다(즉 리스트이며, 0개 이상의 등록된 옵저버를 포함한다). 이 목록은 처음에는 비어 있다.
등록 옵저버(registered
observer)는
observer (MutationObserver
객체)와
옵션(options) (MutationObserverInit
딕셔너리)로 이루어집니다.
임시 등록 옵저버(transient registered observer)는 등록 옵저버에 source (등록 옵저버)가 추가된 것입니다.
임시
등록 옵저버는
주어진 노드의 후손에 대한
변이를 추적하기 위해 사용됩니다.
노드가 제거된 이후에도,
subtree가
노드의 부모에서 true로 설정되었을 때
옵저버가 소실되지 않도록 합니다.
4.3.1.
인터페이스 MutationObserver
[Exposed =Window ]interface {MutationObserver constructor (MutationCallback );callback undefined observe (Node ,target optional MutationObserverInit = {});options undefined disconnect ();sequence <MutationRecord >takeRecords (); };callback =MutationCallback undefined (sequence <MutationRecord >,mutations MutationObserver );observer dictionary {MutationObserverInit boolean =childList false ;boolean ;attributes boolean ;characterData boolean =subtree false ;boolean ;attributeOldValue boolean ;characterDataOldValue sequence <DOMString >; };attributeFilter
MutationObserver
객체는 트리의 노드에서 발생하는 변경(mutation)을 감시하는 데 사용할 수 있습니다.
각 MutationObserver
객체에는 다음의 개념이 연관됩니다:
- 생성 시 설정되는 콜백
- 노드 리스트(리스트, 노드에 대한 약한 참조들의 집합) 처음에는 비어 있습니다.
-
레코드 큐(큐, 0개 이상의
MutationRecord객체의 집합) 처음에는 비어 있습니다.
observer = newMutationObserver(callback)-
MutationObserver객체를 생성하고, 콜백에 callback을 설정합니다. callback은 첫 번째 인자로MutationRecord객체의 리스트를, 두 번째 인자로 생성된MutationObserver객체를 받아 호출됩니다. 이 콜백은observe()메서드로 등록된 노드에 변이가 발생할 때마다 호출됩니다. observer .observe(target, options)-
주어진 target(노드)에
대한 변이를 options(객체)의 기준에 따라 감시할 것을 사용자 에이전트에 지시합니다.
options 인자는 객체의 속성으로 변이 감시 옵션을 설정할 수 있습니다. 사용할 수 있는 속성은 다음과 같습니다:
childList- target의 자식에 대한 변이를 감시하려면 true로 설정합니다.
attributes- target의 속성에 대한 변이를 감시하려면 true로 설정합니다.
attributeOldValue나attributeFilter가 지정된 경우 생략할 수 있습니다. characterData- target의 데이터에 대한 변이를 감시하려면 true로 설정합니다.
characterDataOldValue가 지정된 경우 생략할 수 있습니다. subtree- target뿐 아니라 target의 후손까지의 변이를 감시하려면 true로 설정합니다.
attributeOldValue-
attributes가 true 또는 생략된 경우, 변이 발생 이전의 target 속성 값을 기록하려면 true로 설정합니다. characterDataOldValue-
characterData가 true 또는 생략된 경우, 변이 발생 이전의 target 데이터를 기록하려면 true로 설정합니다. attributeFilter- 모든 속성 변이를
감시할 필요가 없고,
attributes가 true 또는 생략된 경우, 속성 로컬 이름(네임스페이스 없이)을 리스트로 설정합니다.
observer .disconnect()-
observer의 변이 감시를 중지합니다.
observe()메서드를 다시 사용하기 전까지는 observer의 콜백이 호출되지 않습니다. observer .takeRecords()- 레코드 큐를 비우고, 그 안에 있었던 값을 반환합니다.
observe(target, options)
메서드 단계는 다음과 같다:
-
options["
attributeOldValue"] 또는 options["attributeFilter"] 존재하고, options["attributes"] 가 존재하지 않으면, options["attributes"] 를 true로 설정한다. -
options["
characterDataOldValue"] 존재하고 options["characterData"] 가 존재하지 않으면, options["characterData"] 를 true로 설정한다. -
options["
childList"], options["attributes"], options["characterData"] 중 true인 항목이 없으면, TypeError를 발생시킨다. -
options["
attributeOldValue"] 가 true이고 options["attributes"] 가 false이면, TypeError를 발생시킨다. -
options["
attributeFilter"] 가 있고, options["attributes"] 가 false이면, TypeError를 발생시킨다. -
options["
characterDataOldValue"] 가 true이고, options["characterData"] 가 false이면, TypeError를 발생시킨다. -
각 registered를 target의 등록된 관찰자 목록에서 반복한다: 만약 registered의 observer가 this라면,
-
그렇지 않으면:
disconnect() 메서드 단계는 다음과 같다:
4.3.2. 변이 레코드 큐잉
변이 레코드를 큐에 추가하다를 type에 대해, target과 name, namespace, oldValue, addedNodes, removedNodes, previousSibling, nextSibling을 가지고 수행하려면:
-
interestedObservers를 빈 map으로 둔다.
-
nodes를 target의 포함 조상(포함 상위 노드 전부)들로 둔다.
-
각 node를 nodes에서 반복하고, 각 registered를 node의 등록된 관찰자 목록에서 반복한다:
-
options를 registered의 options로 둔다.
-
아래 내용이 모두 false일 경우
- node가 target이 아니고
options["
subtree"]가 false이다 - type이 "
attributes"이고 options["attributes"]가 존재하지 않거나 false이다 - type이 "
attributes"이고, options["attributeFilter"]가 존재하고, options["attributeFilter"]가 name을 포함하지 않거나 namespace가 null이 아님 - type이 "
characterData"이고 options["characterData"]가 존재하지 않거나 false이다 - type이 "
childList"이고 options["childList"]가 false이다
라면 다음을 수행한다:
-
mo를 registered의 observer로 둔다.
-
interestedObservers[mo]가 존재하지 않으면 interestedObservers[mo]에 null을 할당한다.
-
만약 type이 "
attributes"이고 options["attributeOldValue"]가 true이거나, type이 "characterData"이고 options["characterDataOldValue"]가 true이면 interestedObservers[mo]에 oldValue를 할당한다.
- node가 target이 아니고
options["
-
-
각 observer → mappedOldValue를 interestedObservers에서 반복하여:
-
record를 새
MutationRecord객체로,type은 type,target은 target,attributeName은 name,attributeNamespace는 namespace,oldValue는 mappedOldValue,addedNodes는 addedNodes,removedNodes는 removedNodes,previousSibling은 previousSibling,nextSibling은 nextSibling으로 설정한다. -
record를 observer의 record queue에 큐잉한다.
-
observer를 surrounding agent의 pending mutation observers에 추가한다.
-
트리 구조 변이 레코드를 큐에 추가하다를 target과 addedNodes, removedNodes, previousSibling, nextSibling으로 수행하려면:
-
변이 레코드를 큐에 추가하다를 "
childList" 타입으로, target에 대해, null, null, null, addedNodes, removedNodes, previousSibling, nextSibling과 함께 수행한다.
4.3.3.
인터페이스 MutationRecord
[Exposed =Window ]interface {MutationRecord readonly attribute DOMString type ; [SameObject ]readonly attribute Node target ; [SameObject ]readonly attribute NodeList addedNodes ; [SameObject ]readonly attribute NodeList removedNodes ;readonly attribute Node ?previousSibling ;readonly attribute Node ?nextSibling ;readonly attribute DOMString ?attributeName ;readonly attribute DOMString ?attributeNamespace ;readonly attribute DOMString ?oldValue ; };
record .type- "
attributes"는 속성 변이가 발생한 경우 반환됩니다. "characterData"는CharacterData노드에 변이가 발생한 경우 반환됩니다. 그리고 "childList"는 트리의 노드에 변이가 발생한 경우 반환됩니다. record .target-
type에 따라 변경된 노드를 반환합니다. "attributes"인 경우, 속성이 변경된 요소입니다. "characterData"인 경우,CharacterData노드입니다. "childList"인 경우, 자식이 변화한 노드입니다. record .addedNodesrecord .removedNodes- 추가된 노드들과 제거된 노드들을 각각 반환합니다.
record .previousSiblingrecord .nextSibling- 추가되거나 제거된 노드의 이전 형제와 다음 형제를 각각 반환합니다. 없으면 null입니다.
record .attributeName- 변경된 속성의 로컬 이름을 반환합니다. 없으면 null입니다.
record .attributeNamespace- 변경된 속성 네임스페이스를 반환합니다. 없으면 null입니다.
record .oldValue- 반환값은
type에 따라 다릅니다. "attributes"일 때는, 변경된 속성값의 변경 전 값을 반환합니다. "characterData"일 때는, 변경된 노드의 데이터의 변경 전 값을 반환합니다. "childList"일 때는 null입니다.
type, target,
addedNodes,
removedNodes,
previousSibling,
nextSibling,
attributeName,
attributeNamespace, 그리고
oldValue 특성은 초기화된 값을 반환해야 합니다.
4.4. 인터페이스 Node
[Exposed =Window ]interface :Node EventTarget {const unsigned short ELEMENT_NODE = 1;const unsigned short ATTRIBUTE_NODE = 2;const unsigned short TEXT_NODE = 3;const unsigned short CDATA_SECTION_NODE = 4;const unsigned short = 5; // legacyENTITY_REFERENCE_NODE const unsigned short = 6; // legacyENTITY_NODE const unsigned short PROCESSING_INSTRUCTION_NODE = 7;const unsigned short COMMENT_NODE = 8;const unsigned short DOCUMENT_NODE = 9;const unsigned short DOCUMENT_TYPE_NODE = 10;const unsigned short DOCUMENT_FRAGMENT_NODE = 11;const unsigned short = 12; // legacyNOTATION_NODE readonly attribute unsigned short nodeType ;readonly attribute DOMString nodeName ;readonly attribute USVString baseURI ;readonly attribute boolean isConnected ;readonly attribute Document ?ownerDocument ;Node getRootNode (optional GetRootNodeOptions = {});options readonly attribute Node ?parentNode ;readonly attribute Element ?parentElement ;boolean hasChildNodes (); [SameObject ]readonly attribute NodeList childNodes ;readonly attribute Node ?firstChild ;readonly attribute Node ?lastChild ;readonly attribute Node ?previousSibling ;readonly attribute Node ?nextSibling ; [CEReactions ]attribute DOMString ?nodeValue ; [CEReactions ]attribute DOMString ?textContent ; [CEReactions ]undefined normalize (); [CEReactions ,NewObject ]Node cloneNode (optional boolean =subtree false );boolean isEqualNode (Node ?);otherNode boolean isSameNode (Node ?); // legacy alias of ===otherNode const unsigned short DOCUMENT_POSITION_DISCONNECTED = 0x01;const unsigned short DOCUMENT_POSITION_PRECEDING = 0x02;const unsigned short DOCUMENT_POSITION_FOLLOWING = 0x04;const unsigned short DOCUMENT_POSITION_CONTAINS = 0x08;const unsigned short DOCUMENT_POSITION_CONTAINED_BY = 0x10;const unsigned short DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 0x20;unsigned short compareDocumentPosition (Node );other boolean contains (Node ?);other DOMString ?lookupPrefix (DOMString ?);namespace DOMString ?lookupNamespaceURI (DOMString ?);prefix boolean isDefaultNamespace (DOMString ?); [namespace CEReactions ]Node insertBefore (Node ,node Node ?); [child CEReactions ]Node appendChild (Node ); [node CEReactions ]Node replaceChild (Node ,node Node ); [child CEReactions ]Node removeChild (Node ); };child dictionary {GetRootNodeOptions boolean =composed false ; };
Node는 모든 노드에서 사용되는 추상 인터페이스입니다. 직접
인스턴스를 생성할 수 없습니다.
각 노드에는 생성 시 설정되는 노드 문서가 연결되어 있으며, 그 값은 문서입니다.
노드의 노드 문서는 adopt 알고리즘을 통해 변경될 수 있습니다.
노드의 부모 가져오기 알고리즘은 event가 주어졌을 때, 노드가 할당된 슬롯이 있으면, 즉 할당됨 상태라면 그 슬롯을 반환합니다; 그렇지 않으면 부모를 반환합니다.
각 노드는 등록된 옵저버 목록도 가지고 있습니다.
node .nodeType-
node의 타입에 따라 적절한 숫자를 반환합니다:
Element(1)Node.ELEMENT_NODEAttr(2)Node.ATTRIBUTE_NODE- exclusive
Textnode (3)Node.TEXT_NODECDATASection(4)Node.CDATA_SECTION_NODEProcessingInstruction(7)Node.PROCESSING_INSTRUCTION_NODEComment(8)Node.COMMENT_NODEDocument(9)Node.DOCUMENT_NODEDocumentType(10)Node.DOCUMENT_TYPE_NODEDocumentFragment(11)Node.DOCUMENT_FRAGMENT_NODE
node .nodeName-
node의 타입에 따라 적절한 문자열을 반환합니다:
Element- HTML-대문자화된 정규 이름(qualified name)
Attr- 정규 이름(qualified name)
- exclusive
Textnode - "
#text" CDATASection- "
#cdata-section" ProcessingInstruction- target
Comment- "
#comment" Document- "
#document" DocumentType- name
DocumentFragment- "
#document-fragment"
nodeType getter 단계는 인터페이스 this가 implements하는 것에 따라 처음으로
일치하는 경우를 반환합니다:
ElementELEMENT_NODE(1)AttrATTRIBUTE_NODE(2)- exclusive
Textnode TEXT_NODE(3)CDATASectionCDATA_SECTION_NODE(4)ProcessingInstructionPROCESSING_INSTRUCTION_NODE(7)CommentCOMMENT_NODE(8)DocumentDOCUMENT_NODE(9)DocumentTypeDOCUMENT_TYPE_NODE(10)DocumentFragmentDOCUMENT_FRAGMENT_NODE(11)
nodeName getter 단계는 인터페이스 this가 implements하는 것에 따라 처음으로
일치하는 경우를 반환합니다:
Element- 자신의 HTML-대문자화된 정규 이름
Attr- 자신의 정규 이름
- exclusive
Textnode - "
#text" CDATASection- "
#cdata-section" ProcessingInstruction- 자신의 target
Comment- "
#comment" Document- "
#document" DocumentType- 자신의 name
DocumentFragment- "
#document-fragment"
node .baseURI- node의 노드 문서의 문서 기본 URL(document base URL)을 반환합니다.
baseURI getter 단계는 this의
노드 문서의 문서 기본 URL을 직렬화(serialized)하여 반환합니다.
node .isConnected-
node가 연결됨(connected)이면 true, 아니면 false를 반환합니다.
node .ownerDocument- 노드 문서(node document)를 반환합니다. 문서(document)일 경우 null을 반환합니다.
node .getRootNode()- node의 루트(root)를 반환합니다.
node . getRootNode({ composed:true })- node의 섀도우 포함 루트(shadow-including root)를 반환합니다.
node .parentNode- 부모(parent)를 반환합니다.
node .parentElement- 부모 요소(parent element)를 반환합니다.
node .hasChildNodes()- node에 자식(children)이 있는지 반환합니다.
node .childNodes- 자식(children)을 반환합니다.
node .firstChild- 첫 번째 자식(first child)을 반환합니다.
node .lastChild- 마지막 자식(last child)을 반환합니다.
node .previousSibling- 이전 형제(previous sibling)를 반환합니다.
node .nextSibling- 다음 형제(next sibling)를 반환합니다.
isConnected getter의 단계는
this가 connected인 경우 true를 반환하고, 그렇지 않으면
false를 반환합니다.
ownerDocument getter의 단계는
this가 document이면 null을 반환하고,
그렇지 않으면 this의 노드 문서를
반환합니다.
document의 노드 문서는 그 document 자신입니다. 모든 노드는 항상 노드 문서를 가지고 있습니다.
getRootNode(options) 메서드 단계는
options["composed"]가
true면 this의 섀도우 포함 루트(shadow-including root)를 반환하고, 아니면 this의 루트(root)를 반환합니다.
parentNode getter 단계는 this의 부모(parent)를 반환합니다.
parentElement getter 단계는 this의 부모 요소(parent element)를 반환합니다.
hasChildNodes() 메서드 단계는 this가 자식(children)이 있으면 true, 아니면 false를
반환합니다.
childNodes getter 단계는 this를 루트로 하고 자식(children)만 일치하는 NodeList를 반환합니다.
firstChild getter 단계는 this의 첫 번째
자식(first child)을 반환합니다.
lastChild getter 단계는 this의 마지막 자식(last child)을 반환합니다.
previousSibling getter 단계는 this의 이전 형제(previous
sibling)를 반환합니다.
nextSibling getter 단계는 this의 다음 형제(next sibling)를
반환합니다.
nodeValue getter 단계는 인터페이스 this가 implements하는 것에 따라 아래를
반환합니다:
Attr- this의 값(value)
CharacterData- this의 데이터(data)
- 그 외에는
- Null
nodeValue
setter 단계는, 주어진 값이 null이면 빈 문자열로 취급한 후, 인터페이스 this
implements에 따라 아래를 실행합니다:
Attr-
기존 속성 값 설정(Set an existing attribute value)을 this 및 주어진 값으로 실행합니다.
CharacterData- 그 외에는
-
아무 것도 하지 않습니다.
get text content는 노드(node) node에 대해, 인터페이스 node가 implements하는 것에 따라 다음을 반환합니다:
DocumentFragmentElement- node의 자손 텍스트 내용(descendant text content)
Attr- node의 값(value)
CharacterData- node의 데이터(data)
- 그 외에는
- Null
The textContent getter 단계는 get text content를 this와 함께 실행한 결과를 반환한다.
문자열 string으로 string replace all을 node parent 내에서 수행하려면, 다음 단계를 실행한다:
-
node를 null로 둔다.
-
만약 string이 빈 문자열이 아니면, node를 새로운
Textnode로 설정한다. 그 노드의 data는 string이고, node document는 parent의 node document이다. -
Replace all을 parent 내에서 node로 실행한다.
노드 node node와 문자열 value로 set text content을 수행하려면, 아래에 정의된 대로, 인터페이스 node가 implements하는 것에 따라 분기하여 실행한다:
DocumentFragmentElement-
String replace all을 node 내에서 value로 실행한다.
Attr-
Set an existing attribute value를 node와 value로 실행한다.
CharacterData- 그 외
-
아무 작업도 하지 않는다.
textContent
setter 단계는, 주어진 값이 null이면 대신 빈 문자열인 것처럼 동작하고, 그 다음 set text content를 this와 주어진 값으로 실행하는 것이다.
node .normalize()- 비어 있는 독점적인
Text노드를 제거하고, 남아 있는 연속된 독점적인Text노드의 data를 해당 노드 중 첫 번째에 연결합니다.
normalize() 메서드 단계는
독점적인
Text 노드 node를
this의 모든 하위
노드에 대해 다음을 수행합니다:
-
length를 node의 길이로 설정합니다.
-
만약 length가 0이면, node를 제거하고 다음 독점적인
Text노드로 진행합니다(있다면). -
data를 연결된 문자열로 만드는데, node의 연속된 독점적인
Text노드(자기 자신은 제외)의 data를 트리 순서로 합칩니다. -
데이터를 교체 — node의 length, 0, 그리고 data로 교체합니다.
-
currentNode를 node의 다음 형제로 설정합니다.
-
currentNode가 독점적인
Text노드인 동안 다음을 반복합니다:-
시작 노드가 currentNode인 live range 각각에 대해: 그 start offset에 length를 더하고, start node를 node로 설정합니다.
-
끝 노드가 currentNode인 live range 각각에 대해: end offset에 length를 더하고 end node를 node로 설정합니다.
-
시작 노드가 currentNode의 부모이고, 시작 offset이 currentNode의 인덱스인 live range 각각에 대해: 그 start node를 node로, start offset을 length로 설정합니다.
-
끝 노드가 currentNode의 부모이고, 끝 offset이 currentNode의 인덱스인 live range 각각에 대해: 그 end node를 node로, end offset을 length로 설정합니다.
-
currentNode의 길이를 length에 더합니다.
-
currentNode를 그 다음 형제로 설정합니다.
-
-
node의 연속된 독점적인
Text노드(본인 제외)를 트리 순서로 제거합니다.
node . cloneNode([subtree = false])- node의 복사본을 반환합니다. 만약 subtree가 true이면, 복사본에는 node의 하위 노드도 포함됩니다.
node . isEqualNode(otherNode)- node와 otherNode가 동일한 속성을 가지는지 반환합니다.
HTML은
input,
script,
template
등 여러 요소에 대해 클론 단계를 정의합니다. SVG는
script
요소에 대해 동일하게 해야 하지만, 아직 정의하지 않았습니다.
노드 복제하기에 대한 절차:
노드 node와
선택적 document document (기본값은 node의 노드 문서),
불리언 subtree (기본값 false),
노드 또는 null parent (기본값 null),
그리고 null이나 CustomElementRegistry
객체 fallbackRegistry
(기본값 null)가 주어졌을 때:
-
copy를 단일 노드 복제하기로 얻는다. 인자는 node, document, fallbackRegistry이다.
-
node에 대해 복제 단계(적용 가능한 다른 명세에 정의된 단계)들을, node, copy, subtree를 인자로 실행한다.
-
parent가 null이 아니면 append를 이용해 copy를 parent에 추가한다.
-
subtree가 true면, node의 자식들 각각에 대해 트리 순서로: 노드 복제하기를 그 child와 document=document, subtree=subtree, parent=copy, fallbackRegistry=fallbackRegistry로 실행한다.
-
node가 요소이고, 섀도우 호스트이며, node의 섀도우 루트의 복제 가능이 true일 때:
-
Assert: copy는 섀도우 호스트가 아니다.
-
shadowRootRegistry를 node의 섀도우 루트의 custom element registry로 설정.
-
shadowRootRegistry가 글로벌 custom element registry이면, shadowRootRegistry를 document의 실질 글로벌 custom element registry로 변경.
-
섀도우 루트 붙이기를 실행: 인자는 copy, node의 섀도우 루트의 모드, true, node의 섀도우 루트의 serializable, node의 섀도우 루트의 delegates focus, node의 섀도우 루트의 slot assignment, 그리고 shadowRootRegistry.
-
copy의 섀도우 루트의 declarative를 node의 섀도우 루트의 declarative 값으로 설정.
-
node의 섀도우 루트의 자식들 각각에 대해 트리 순서로: 노드 복제하기를 child와 document=document, subtree=subtree, parent=copy의 섀도우 루트로 실행한다.
여기서는 fallbackRegistry 인자를 넘기지 않는다.
-
-
copy를 반환.
단일 노드 복제하기에 대한
절차:
노드 node,
document
document,
null 또는 CustomElementRegistry
객체 fallbackRegistry가 주어졌을 때:
-
copy를 null로 설정한다.
-
node가 요소라면:
-
registry를 node의 custom element registry로 설정.
-
registry가 null이라면 fallbackRegistry로 설정.
-
registry가 글로벌 custom element registry이면, registry를 document의 실질 글로벌 custom element registry로 변경.
-
copy를 요소 생성 결과로 설정. 인자는 document, node의 로컬 이름, node의 네임스페이스, node의 네임스페이스 접두사, node의
is값, false, 그리고 registry이다. -
각 attribute에 대해 node의 속성 리스트를 순회한다:
-
copyAttribute를 단일 노드 복제하기 결과로 설정(인자: attribute, document, null).
-
append를 사용해서 copyAttribute를 copy에 추가한다.
-
-
-
그 외의 경우, copy를 노드로 설정하되, node가 구현하는 인터페이스에 따라 다음 사항을 적용:
Document-
-
copy의 encoding, content type, URL, origin, type, mode, allow declarative shadow roots를 node의 값을 복사한다.
-
node의 custom element registry의 is scoped가 true이면 copy의 custom element registry를 node의 custom element registry 값으로 설정.
-
DocumentTypeAttr-
copy의 네임스페이스, 네임스페이스 접두사, 로컬 이름, 값을 node로부터 복사.
TextComment-
copy의 data를 node의 값으로 설정.
ProcessingInstruction- 그 외의 경우
-
아무 것도 하지 않음.
-
node가 document면 document를 copy로 설정.
-
copy의 노드 문서를 document로 설정.
-
copy를 반환.
cloneNode(subtree) 메서드 절차:
-
this가 섀도우 루트라면, throw "
NotSupportedError"DOMException을 발생시킨다.
isEqualNode(otherNode) 메서드 절차:
otherNode가 null이 아니고 this가 같다(equals)면 true를 반환하고, 그렇지 않으면 false를 반환한다.
isSameNode(otherNode) 메서드 절차:
otherNode가 this와 같으면 true를, 그렇지 않으면 false를 반환한다.
node .compareDocumentPosition(other)-
other가 node에 대해 어떤 위치에 있는지 비트마스크로 반환합니다. 설정될 수 있는 비트는 다음과 같습니다:
(1)Node.DOCUMENT_POSITION_DISCONNECTED- node와 other가 동일한 트리(tree)에 속하지 않을 때 설정됩니다.
(2)Node.DOCUMENT_POSITION_PRECEDING- other가 node의 이전(preceding)에 있을 때 설정됩니다.
(4)Node.DOCUMENT_POSITION_FOLLOWING- other가 node의 다음(following)에 있을 때 설정됩니다.
(8)Node.DOCUMENT_POSITION_CONTAINS- other가 node의 조상(ancestor)일 때 설정됩니다.
(16, 10진수로 16, 16진수로 10)Node.DOCUMENT_POSITION_CONTAINED_BY- other가 node의 자손(descendant)일 때 설정됩니다.
node .contains(other)- other가 node의 포함 자손(inclusive descendant)이면 true를, 아니면 false를 반환합니다.
아래는 compareDocumentPosition()
이 마스크로 반환하는 상수들입니다:
DOCUMENT_POSITION_DISCONNECTED(1);DOCUMENT_POSITION_PRECEDING(2);DOCUMENT_POSITION_FOLLOWING(4);DOCUMENT_POSITION_CONTAINS(8);DOCUMENT_POSITION_CONTAINED_BY(16, 16진수로 10);DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC(32, 16진수로 20).
compareDocumentPosition(other)
메서드 단계:
-
만약 this가 other이면, 0을 반환한다.
-
node1을 other로, node2를 this로 둔다.
-
attr1와 attr2를 null로 둔다.
-
만약 node1가 attribute이면, attr1를 node1로 설정하고 node1를 attr1의 element로 설정한다.
-
만약 node2가 attribute이면:
-
attr2를 node2로 설정하고 node2를 attr2의 element로 설정한다.
-
만약 attr1와 node1가 null이 아니고, node2가 node1이면:
-
For each attr에 대해 node2의 attribute list:
-
만약 attr가 equals attr1이면,
DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC와DOCUMENT_POSITION_PRECEDING를 더한 결과를 반환한다. -
만약 attr가 equals attr2이면,
DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC와DOCUMENT_POSITION_FOLLOWING를 더한 결과를 반환한다.
-
-
-
-
만약 node1 또는 node2가 null이거나, node1의 root가 node2의 root가 아니면,
DOCUMENT_POSITION_DISCONNECTED,DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC, 그리고DOCUMENT_POSITION_PRECEDING또는DOCUMENT_POSITION_FOLLOWING중 하나를 더한 결과를 반환한다. 단, 이 선택은 일관되게 이루어져야 한다.어느 쪽을 반환할지는 보통 포인터 비교로 구현된다. JavaScript 구현에서는 캐시된
Math값을 사용할 수 있다.. random() -
만약 node1가 ancestor로서 node2의 상위 노드이고 attr1 가 null이거나, 또는 node1가 node2이고 attr2가 null이 아니면,
DOCUMENT_POSITION_CONTAINS를DOCUMENT_POSITION_PRECEDING에 더한 결과를 반환한다. -
만약 node1가 descendant로서 node2의 하위 노드이고 attr2 가 null이거나, 또는 node1가 node2이고 attr1가 null이 아니면,
DOCUMENT_POSITION_CONTAINED_BY를DOCUMENT_POSITION_FOLLOWING에 더한 결과를 반환한다. -
만약 node1가 preceding node2이면,
DOCUMENT_POSITION_PRECEDING를 반환한다.이 알고리즘에서 속성이 처리되는 방식 때문에, 이는 노드의 속성이 해당 노드의 앞에 존재하는 것으로 간주하게 됩니다. 이는 노드의 자식 보다 앞에 있는 것으로 취급됨을 의미합니다. 비록 속성이 동일한 트리에 참여하지 않더라도 그렇습니다.
-
마지막으로
DOCUMENT_POSITION_FOLLOWING를 반환한다.
contains(other) 메서드 단계는
other가 포함 자손(inclusive descendant)이면 true, 아니면 false를 반환합니다
(null일 때도 false).
네임스페이스 접두사 찾기(locate a namespace prefix) 를 element에서 namespace로 실행하려면 다음 단계를 수행합니다:
-
element의 네임스페이스(namespace)가 namespace와 같고, 네임스페이스 접두사(namespace prefix)가 null이 아니면, 네임스페이스 접두사를 반환합니다.
-
element가 다음 조건을 만족하는 속성(attribute)을 가지고 있으면: 속성(attribute)의 네임스페이스 접두사가 "
xmlns"이고, 값(value)이 namespace이면, element의 첫 번째 해당 속성(attribute)의 지역 이름(local name)을 반환합니다. -
element의 부모 요소(parent element)가 null이 아니면, 그 요소(element)에 대해 namespace로 네임스페이스 접두사 찾기를 실행한 결과를 반환합니다.
-
null을 반환합니다.
네임스페이스 찾기(locate a namespace)를 node에서 prefix로 실행하려면, node가 구현하는 인터페이스에 따라 다음을 실행합니다:
Element-
-
prefix가 "
xml"이면 XML 네임스페이스를 반환합니다. -
prefix가 "
xmlns"이면 XMLNS 네임스페이스를 반환합니다. -
네임스페이스가 null이 아니고, 네임스페이스 접두사가 prefix와 같으면 네임스페이스를 반환합니다.
-
다음 조건을 만족하는 속성(attribute)을 가지고 있으면: 속성(attribute)의 네임스페이스(namespace)가 XMLNS 네임스페이스이고, 네임스페이스 접두사가 "
xmlns"이고, 지역 이름(local name)이 prefix와 같거나, prefix가 null이고 다음 조건을 만족하는 속성(attribute)을 가지고 있으면: 속성(attribute)의 네임스페이스가 XMLNS 네임스페이스이고, 네임스페이스 접두사가 null이고, 지역 이름이 "xmlns"이면, 값이 빈 문자열이 아니면 그 값을 반환하고, 아니면 null을 반환합니다. -
부모 요소가 null이면 null을 반환합니다.
-
부모 요소에 대해 prefix로 네임스페이스 찾기를 실행한 결과를 반환합니다.
-
Document-
-
문서 요소(document element)가 null이면 null을 반환합니다.
-
문서 요소(document element)에 대해 prefix로 네임스페이스 찾기를 실행한 결과를 반환합니다.
-
DocumentTypeDocumentFragment-
null을 반환합니다.
Attr-
-
속성의 요소가 null이면 null을 반환합니다.
-
해당 요소에 대해 prefix로 네임스페이스 찾기를 실행한 결과를 반환합니다.
-
- 그 외의 경우
-
-
부모 요소가 null이면 null을 반환합니다.
-
부모 요소에 대해 prefix로 네임스페이스 찾기를 실행한 결과를 반환합니다.
-
lookupPrefix(namespace) 메서드 단계:
-
namespace가 null이거나 빈 문자열이면 null을 반환합니다.
-
this가 구현하는 인터페이스에 따라 다음을 실행합니다:
Element-
this에 대해 namespace로 네임스페이스 접두사 찾기를 실행한 결과를 반환합니다.
Document-
-
문서 요소(document element)가 null이면 null을 반환합니다.
-
문서 요소(document element)에 대해 namespace로 네임스페이스 접두사 찾기를 실행한 결과를 반환합니다.
-
DocumentTypeDocumentFragment-
null을 반환합니다.
Attr-
-
속성의 요소가 null이면 null을 반환합니다.
-
해당 요소에 대해 namespace로 네임스페이스 접두사 찾기를 실행한 결과를 반환합니다.
-
- 그 외의 경우
-
-
부모 요소가 null이면 null을 반환합니다.
-
부모 요소에 대해 namespace로 네임스페이스 접두사 찾기를 실행한 결과를 반환합니다.
-
lookupNamespaceURI(prefix) 메서드 단계:
-
prefix가 빈 문자열이면 null로 설정합니다.
-
this에 대해 prefix로 네임스페이스 찾기를 실행한 결과를 반환합니다.
isDefaultNamespace(namespace) 메서드 단계:
-
namespace가 빈 문자열이면 null로 설정합니다.
-
defaultNamespace를 null로 this에 대해 네임스페이스 찾기를 실행한 결과로 설정합니다.
-
defaultNamespace가 namespace와 같으면 true, 아니면 false를 반환합니다.
insertBefore(node, child) 메서드 단계는
child 앞에 node를 this에 pre-insert한 결과를 반환합니다.
appendChild(node) 메서드 단계는
node를 this에 append한 결과를 반환합니다.
replaceChild(node, child) 메서드 단계는
child를 node로 this 내에서 replace한 결과를 반환합니다.
removeChild(child) 메서드 단계는
child를 this에서 pre-remove한 결과를 반환합니다.
qualifiedName
qualifiedName를 가진 요소 목록(list of elements with qualified name)
은 노드(node) root에 대해
다음 알고리즘으로 얻은
HTMLCollection입니다:
-
qualifiedName이 U+002A(*)이면 root를 루트로 하고, 필터가 자손(descendant) 요소(elements)만 일치하는
HTMLCollection을 반환합니다. -
그 외에 root의 노드 문서(node document)가 HTML 문서이면, root를 루트로 하고 필터가 다음 자손(descendant) 요소(elements)만 일치하는
HTMLCollection을 반환합니다:-
네임스페이스가 HTML 네임스페이스이고, qualified name이 qualifiedName이고, ASCII 소문자로 일치하는 요소
-
네임스페이스가 HTML 네임스페이스가 아니고, qualified name이 qualifiedName인 요소
-
-
그 외의 경우, root를 루트로 하고 필터가 자손(descendant) 요소(elements) 중 qualified name이 qualifiedName인 요소만 일치하는
HTMLCollection을 반환합니다.
같은 인자로 호출하면, root의 노드 문서(node document)의
type이 변하지 않는
한,
이전 호출과 동일한 HTMLCollection
객체가 반환될 수 있습니다.
네임스페이스
namespace와 지역 이름(local name) localName을 가진 요소 목록(list of elements with namespace
and local name)
은 노드(node) root에 대해
다음 알고리즘으로 얻은
HTMLCollection입니다:
-
namespace가 빈 문자열이면 null로 설정합니다.
-
namespace와 localName이 모두 U+002A(*)이면, root를 루트로 하고 자손(descendant) 요소(elements)만 일치하는
HTMLCollection을 반환합니다. -
namespace가 U+002A(*)이면, root를 루트로 하고 자손(descendant) 요소(elements) 중 지역 이름(local name)이 localName인 요소만 일치하는
HTMLCollection을 반환합니다. -
localName이 U+002A(*)이면, root를 루트로 하고 자손(descendant) 요소(elements) 중 네임스페이스(namespace)가 namespace인 요소만 일치하는
HTMLCollection을 반환합니다. -
root를 루트로 하고 자손(descendant) 요소(elements) 중 네임스페이스(namespace)가 namespace이고, 지역 이름(local name)이 localName인 요소만 일치하는
HTMLCollection을 반환합니다.
같은 인자로 호출하면, 이전 호출과 동일한 HTMLCollection
객체가 반환될 수 있습니다.
classNames
classNames를 가진 요소 목록(list of elements with class names)
은 노드(node) root에 대해
다음 알고리즘으로 얻은
HTMLCollection입니다:
- classes를 classNames에 대해 ordered set parser를 실행한 결과로 설정합니다.
-
classes가 빈 집합이면, 빈
HTMLCollection을 반환합니다. -
root를 루트로 하고 필터가 자손(descendant) 요소(elements) 중 모든 클래스(class)가 classes에 포함된 요소만 일치하는
HTMLCollection을 반환합니다.클래스 비교는 root의 노드 문서(node document)의 mode가 "
quirks"이면 ASCII 대소문자 구분 없음으로 비교하고, 아니면 동일 문자열로 비교해야 합니다.
같은 인자로 호출하면, 이전 호출과 동일한 HTMLCollection
객체가 반환될 수 있습니다.
4.5. 인터페이스 Document
[Exposed =Window ]interface :Document Node {constructor (); [SameObject ]readonly attribute DOMImplementation implementation ;readonly attribute USVString URL ;readonly attribute USVString documentURI ;readonly attribute DOMString compatMode ;readonly attribute DOMString characterSet ;readonly attribute DOMString charset ; // legacy alias of .characterSetreadonly attribute DOMString inputEncoding ; // legacy alias of .characterSetreadonly attribute DOMString contentType ;readonly attribute DocumentType ?doctype ;readonly attribute Element ?documentElement ;HTMLCollection getElementsByTagName (DOMString );qualifiedName HTMLCollection getElementsByTagNameNS (DOMString ?,namespace DOMString );localName HTMLCollection getElementsByClassName (DOMString ); [classNames CEReactions ,NewObject ]Element createElement (DOMString ,localName optional (DOMString or ElementCreationOptions )= {}); [options CEReactions ,NewObject ]Element createElementNS (DOMString ?,namespace DOMString ,qualifiedName optional (DOMString or ElementCreationOptions )= {}); [options NewObject ]DocumentFragment createDocumentFragment (); [NewObject ]Text createTextNode (DOMString ); [data NewObject ]CDATASection createCDATASection (DOMString ); [data NewObject ]Comment createComment (DOMString ); [data NewObject ]ProcessingInstruction createProcessingInstruction (DOMString ,target DOMString ); [data CEReactions ,NewObject ]Node importNode (Node ,node optional (boolean or ImportNodeOptions )=options false ); [CEReactions ]Node adoptNode (Node ); [node NewObject ]Attr createAttribute (DOMString ); [localName NewObject ]Attr createAttributeNS (DOMString ?,namespace DOMString ); [qualifiedName NewObject ]Event createEvent (DOMString ); // legacy [interface NewObject ]Range createRange (); // NodeFilter.SHOW_ALL = 0xFFFFFFFF [NewObject ]NodeIterator createNodeIterator (Node ,root optional unsigned long = 0xFFFFFFFF,whatToShow optional NodeFilter ?=filter null ); [NewObject ]TreeWalker createTreeWalker (Node ,root optional unsigned long = 0xFFFFFFFF,whatToShow optional NodeFilter ?=filter null ); }; [Exposed =Window ]interface :XMLDocument Document {};dictionary {ElementCreationOptions CustomElementRegistry ?;customElementRegistry DOMString ; };is dictionary {ImportNodeOptions CustomElementRegistry ;customElementRegistry boolean =selfOnly false ; };
각 문서에는
해당 인코딩(인코딩),
콘텐츠 타입(문자열),
URL(URL),
origin(origin),
타입("xml" 또는 "html"),
모드("no-quirks", "quirks", 또는 "limited-quirks"),
declarative shadow root 허용(boolean 값),
커스텀 엘리먼트 레지스트리(null 혹은 CustomElementRegistry
객체)
라는 연관된 개념들이 있습니다.
[ENCODING]
[URL]
[HTML]
별도로 명시하지 않는 한, 문서의 인코딩은 utf-8 인코딩, 콘텐츠 타입은 "application/xml", URL은 "about:blank", origin은 불투명 origin, 타입은 "xml", 모드는 "no-quirks", declarative shadow root 허용은 false, 커스텀 엘리먼트 레지스트리는 null입니다.
document가
type 값이
"xml"인 경우,
XML 문서라 한다.
그렇지 않은 경우 HTML 문서라 한다.
document가
HTML 문서인지
XML 문서인지에 따라
일부 API의 동작이 달라진다.
문서는 no-quirks 모드일 때 모드가 "no-quirks"입니다. quirks 모드는 모드가 "quirks"일 때, limited-quirks 모드는 모드가 "limited-quirks"일 때입니다.
모드는 기본값에서 변경되는 상황은 문서를 HTML 파서가 DOCTYPE 문자열의 존재, 부재 또는 값에 따라 생성하는 경우와 새로운 브라우징 컨텍스트(초기 "about:blank")에서만입니다. [HTML]
no-quirks 모드는 원래 "standards mode"로 알려져 있었고, limited-quirks 모드는 한때 "almost standards mode"로 불렸습니다. 명칭이 변경된 이유는 현재 두 모드의 세부사항이 표준으로 정의되어 있기 때문입니다. (그리고 Ian Hickson이 원래 이름이 말이 되지 않는다고 반대했기 때문입니다.)
문서의 부모 가져오기 알고리즘은
event가 주어졌을 때,
event의 type
속성값이 "load"이거나 문서에 브라우징 컨텍스트가 없으면 null을 반환합니다. 그렇지 않으면 문서의 연관 글로벌 객체를 반환합니다.
document = newDocument()- 새로운 문서를 반환합니다.
document .implementation- document의
DOMImplementation객체를 반환합니다. document .URLdocument .documentURI- document의 URL을 반환합니다.
document .compatMode- document의 모드가 "quirks"이면 "BackCompat" 문자열을 반환하고, 그렇지 않으면 "CSS1Compat" 문자열을 반환합니다.
document .characterSet- document의 인코딩을 반환합니다.
document .contentType- document의 콘텐츠 타입을 반환합니다.
new Document() 생성자 단계는
this의 origin을
origin 값으로
설정합니다. 이 값은 current global object의 연관된 Document 객체의 origin입니다. [HTML]
createDocument()와는
달리, 이 생성자는 XMLDocument
객체를 반환하지 않고 문서(Document 객체)를
반환합니다.
implementation getter 단계는 this와 연관된 DOMImplementation
객체를 반환합니다.
URL 및 documentURI
getter 단계는 this의 URL의 직렬화된
값을 반환합니다.
compatMode getter 단계는 this의 모드가 "quirks"이면 "BackCompat"을, 아니면
"CSS1Compat"을 반환합니다.
characterSet, charset, inputEncoding getter 단계는 this의 인코딩의 name(이름)을
반환합니다.
contentType getter 단계는 this의 콘텐츠 타입을 반환합니다.
- document .
doctype - doctype를 반환하거나 없으면 null을 반환합니다.
- document .
documentElement - 문서 요소를 반환합니다.
collection = document . getElementsByTagName(qualifiedName)-
qualifiedName이 "
*"인 경우, 모든 후손 요소를 포함하는HTMLCollection을 반환합니다.그 외의 경우, qualifiedName이 주어진 qualified name과 일치하는 모든 후손 요소를 포함하는
HTMLCollection을 반환합니다. (요소가 HTML 네임스페이스에 속하고 HTML 문서 내에 있을 경우 대소문자 구분 없이 비교됩니다.) collection = document . getElementsByTagNameNS(namespace, localName)-
namespace와 localName이 "
*"인 경우, 모든 후손 요소를 포함하는HTMLCollection을 반환합니다.namespace만 "
*"인 경우, localName과 일치하는 모든 후손 요소를 포함하는HTMLCollection을 반환합니다.localName만 "
*"인 경우, namespace와 일치하는 모든 후손 요소를 포함하는HTMLCollection을 반환합니다.그 외의 경우, namespace와 localName 모두 일치하는 모든 후손 요소를 포함하는
HTMLCollection을 반환합니다. collection = document . getElementsByClassName(classNames)collection = element . getElementsByClassName(classNames)-
메서드를 실행한 객체(즉 문서 또는 요소) 내에서 classNames에 명시된 모든 클래스를 포함하는 요소들의
HTMLCollection을 반환합니다. classNames 인자는 띄어쓰기로 구분된 클래스들의 리스트입니다.
doctype getter 단계는 자식(child) 중
this가 doctype인 것을 반환하고, 없으면
null을 반환합니다.
documentElement getter 단계는 this의 문서 요소(document element)를 반환합니다.
getElementsByTagName(qualifiedName)
메서드 단계는 qualifiedName qualifiedName을 가진 요소 목록을 this에서 반환합니다.
즉, HTML 문서에서는
document
호출 시
<FOO> 요소(HTML 네임스페이스가 아닌 것)와 <foo> 요소(HTML 네임스페이스인 것)는 일치하지만,
<FOO> 요소(HTML 네임스페이스인 것)는 일치하지 않습니다.
getElementsByTagNameNS(namespace, localName)
메서드 단계는 네임스페이스 namespace 및 지역 이름 localName을 가진
요소 목록을 this에서 반환합니다.
getElementsByClassName(classNames)
메서드 단계는 classNames classNames을 가진 요소 목록을 this에서 반환합니다.
< div id = "example" >
< p id = "p1" class = "aaa bbb" />
< p id = "p2" class = "aaa ccc" />
< p id = "p3" class = "bbb ccc" />
</ div >
document
을 호출하면 HTMLCollection
객체에 p1과 p2 두 개의 단락이 포함됩니다.
getElementsByClassName
을 호출하면 p3 한 개의 노드만 반환됩니다. 또한
document
을 호출해도 같은 결과가 나옵니다.
getElementsByClassName
을 호출하면 아무 노드도 반환되지 않습니다. 위 요소들 중 aaa,bbb 클래스를 가진 것은 없습니다.
element = document . createElement(localName [, options])-
localName이 로컬 이름으로 설정된 요소를 반환합니다. (document가 HTML 문서라면, localName은 소문자로 변환됩니다.) 요소의 네임스페이스는 document가 HTML 문서이거나, document의 콘텐츠 타입이 "application/xhtml+xml"일 경우 HTML 네임스페이스가 되고, 그렇지 않으면 null입니다.
options의
customElementRegistry가 있으면,CustomElementRegistry를 설정하는 데 사용할 수 있습니다.options의
is가 있으면 커스텀 내장 요소를 생성하는 데 사용할 수 있습니다.localName이 올바른 요소 로컬 이름이 아니면, "
InvalidCharacterError"DOMException예외가 발생합니다.options에
customElementRegistry와is가 모두 제공되면, "NotSupportedError"DOMException예외가 발생합니다. element = document . createElementNS(namespace, qualifiedName [, options])-
namespace 네임스페이스를 가진 요소를 반환합니다. 네임스페이스 접두사는 qualifiedName에서 U+003A (:) 앞 부분 또는 null이고, 로컬 이름은 U+003A (:) 뒤 또는 qualifiedName 자체입니다.
options의
customElementRegistry가 포함되어 있으면CustomElementRegistry를 설정하는 데 사용할 수 있습니다.options의
is가 포함되어 있으면 커스텀 내장 요소를 생성하는 데 사용할 수 있습니다.qualifiedName이 (접두사가 있을 수도 있음) 올바른 요소 로컬 이름이 아니면, "
InvalidCharacterError"DOMException예외가 발생합니다.다음 조건 중 하나라도 해당되면, "
NamespaceError"DOMException예외가 발생합니다:- 네임스페이스 접두사가 null이 아니고 namespace가 빈 문자열인 경우
- 네임스페이스 접두사가 "xml"이고 namespace가 XML 네임스페이스가 아닐 경우
- qualifiedName 또는 네임스페이스 접두사가 "xmlns"이고 namespace가 XMLNS 네임스페이스가 아닌 경우
- namespace가 XMLNS 네임스페이스이고 qualifiedName과 네임스페이스 접두사가 모두 "xmlns"가 아닐 경우
options에
customElementRegistry와is가 모두 제공되면, "NotSupportedError"DOMException예외가 발생합니다. documentFragment = document .createDocumentFragment()DocumentFragment노드를 반환합니다.text = document .createTextNode(data)- 데이터가 data인
Text노드를 반환합니다. text = document .createCDATASection(data)- 데이터가 data인
CDATASection노드를 반환합니다. comment = document .createComment(data)- 데이터가 data인
Comment노드를 반환합니다. processingInstruction = document .createProcessingInstruction(target, data)-
ProcessingInstruction노드를 반환합니다. target은 target이고, data는 data입니다. target이Name생성식과 일치하지 않으면, "InvalidCharacterError"DOMException예외가 발생합니다. data에 "?>"가 포함되어 있으면, "InvalidCharacterError"DOMException예외가 발생합니다.
name과 namespace에 대해 특별한 언급이 없는 한 그 요소 인터페이스(element interface)는 Element입니다.
예를 들어 HTML 표준에서는 html 및 HTML 네임스페이스에 대해
HTMLHtmlElement
인터페이스를 사용한다고 정의합니다. [HTML]
createElement(localName, options)
메서드 단계는 다음과 같습니다:
-
localName이 유효한 요소 지역 이름(valid element local name)이 아니면 throw로 "
InvalidCharacterError"DOMException을 발생시킵니다. -
registry와 is를 요소 생성 옵션 평탄화(flattening element creation options)로 options와 this를 넘겨 얻습니다.
-
namespace를 HTML 네임스페이스로 설정합니다. this가 HTML 문서이거나 this의 콘텐츠 타입(content type)이 "
application/xhtml+xml"이면, 아니면 null로 합니다. -
요소 생성(creating an element)을 this, localName, namespace, null, is, true, registry로 실행한 결과를 반환합니다.
내부
createElementNS 단계는
document, namespace, qualifiedName, options을 받아 다음을 수행합니다:
-
(namespace, prefix, localName)를 "
element"로 네임스페이스와 qualifiedName의 유효성 검증 및 추출(validating and extracting)을 통해 얻습니다. -
registry와 is를 options와 this로 요소 생성 옵션 평탄화(flattening element creation options)를 실행해 얻습니다.
-
요소 생성(creating an element)을 document, localName, namespace, prefix, is, true, registry로 실행한 결과를 반환합니다.
createElementNS(namespace, qualifiedName, options)
메서드 단계는 내부 createElementNS 단계를
this,
namespace,
qualifiedName, options로 실행한 결과를 반환합니다.
문자열 또는 ElementCreationOptions
딕셔너리 options와 document document로
요소 생성
옵션 평탄화(flatten element creation options)를 하려면:
-
registry를 주어진 document에 대해 커스텀 엘리먼트 레지스트리를 조회한 결과로 둔다.
-
is를 null로 둔다.
-
만약 options가 딕셔너리이면:
-
만약 options["
customElementRegistry"] 존재하면:-
만약 is가 null이 아니면, 예외를 던진다 — "
NotSupportedError"DOMException. -
registry를 options["
customElementRegistry"]로 설정한다.
-
-
만약 registry가 null이 아니고, registry의 is scoped가 false이며, 그리고 registry가 document의 custom element registry가 아니면, 예외를 던진다 — "
NotSupportedError"DOMException.
-
registry와 is를 반환한다.
createElement()
와 createElementNS()의
options 매개변수는 웹 호환성을 위해 문자열도 허용됩니다.
createDocumentFragment() 메서드 단계는
새로운 DocumentFragment
노드를 반환하며, 이 노드의 노드 문서는
this입니다.
createTextNode(data) 메서드 단계는
Text
노드를 반환합니다. 이 노드의 data는 data이고,
노드 문서는 this입니다.
createCDATASection(data) 메서드 단계는 다음과
같습니다:
-
this 가 HTML 문서이면, "
NotSupportedError"DOMException을 throw합니다. -
data에 문자열 "
]]>"가 포함되어 있으면, "InvalidCharacterError"DOMException을 throw합니다. -
데이터가 data이고 노드 문서가 this인 새로운
CDATASection노드를 반환합니다.
createComment(data) 메서드 단계는
데이터가 data이고 노드 문서가 this인 새로운
Comment 노드를 반환합니다.
createProcessingInstruction(target, data)
메서드 단계:
- target이
Name생성식에 일치하지 않으면, "InvalidCharacterError"DOMException을 throw합니다. - data에 "
?>"가 포함되어 있으면, "InvalidCharacterError"DOMException을 throw합니다. - target을 target으로,
data를 data로,
노드 문서는 this로 한
ProcessingInstruction노드를 반환합니다.
clone = document . importNode(node [, options = false])-
node의 복사본을 반환합니다. options가 true이거나 options가
selfOnly가 false인 딕셔너리라면, 복사본에는 node의 후손도 포함됩니다.options의
customElementRegistry는CustomElementRegistry가 없는 요소에 설정할 수 있습니다.node가 문서거나 섀도우 루트이면, "
NotSupportedError"DOMException을 throw합니다. node = document . adoptNode(node)-
다른 문서에서 node를 이동시키고 반환합니다.
node가 문서면 "
NotSupportedError"DOMException예외가 발생하거나, node가 섀도우 루트이면 "HierarchyRequestError"DOMException예외가 발생합니다.
importNode(node, options)
메서드 단계:
-
node가 문서거나 섀도우 루트이면, "
NotSupportedError"DOMException을 throw합니다. -
subtree를 false로 설정합니다.
-
registry를 null로 설정합니다.
-
options가 불리언이면, subtree를 options로 설정합니다.
-
그 외의 경우:
-
subtree를 options["
selfOnly"]의 부정으로 설정합니다. -
options["
customElementRegistry"]가 존재하면 registry에 설정합니다. -
registry의 is scoped가 false이고 registry가 this의 custom element registry가 아니면, "
NotSupportedError"DOMException을 throw합니다.
-
-
registry가 null이면, custom element registry 조회를 사용해 this에 대해 값을 가져와 할당합니다.
-
노드 복제하기를 node와 document=this, subtree=subtree, fallbackRegistry=registry로 실행한 결과를 반환합니다.
노드 입양(adopt) 알고리즘: 노드 node를 document document 안으로 입양하려면,
-
oldDocument에 node의 노드 문서 값을 할당합니다.
-
document가 oldDocument와 다르면:
-
node의 모든 섀도우포함-포괄적 후손에 대해 (섀도우포함 트리순으로):
-
inclusiveDescendant의 노드 문서를 document로 설정합니다.
-
inclusiveDescendant가 섀도우 루트이고 아래 조건 중 하나라도 맞으면:
-
inclusiveDescendant의 custom element registry가 null이고 keep custom element registry null 값이 false일 때
-
inclusiveDescendant의 custom element registry가 글로벌 custom element registry일 때
위 조건 중 하나라도 맞으면 inclusiveDescendant의 custom element registry를 document의 실질적 글로벌 custom element registry로 설정합니다.
-
-
그 외, inclusiveDescendant가 요소이면:
-
inclusiveDescendant의 속성 리스트에 포함된 각 속성의 노드 문서를 document로 설정합니다.
-
inclusiveDescendant의 custom element registry가 null이거나 custom element registry의 is scoped가 false면, inclusiveDescendant의 custom element registry를 document의 실질적 글로벌 custom element registry로 설정합니다.
-
-
-
node의 모든 섀도우포함-포괄적 후손 중 custom인 것에 대해 (섀도우포함 트리순으로): custom element 콜백 반응 enqueue를 호출합니다. 인자는 inclusiveDescendant, 콜백명 "adoptedCallback", 그리고 « oldDocument, document ».
-
node의 모든 섀도우포함-포괄적 후손에 대해 (섀도우포함 트리순으로): adopting steps를 inclusiveDescendant, oldDocument로 실행합니다.
-
adoptNode(node) 메서드 단계:
-
node가 문서면 "
NotSupportedError"DOMException을 throw합니다. -
node가 섀도우 루트면, "
HierarchyRequestError"DOMException을 throw합니다. -
node가
DocumentFragment노드이고 host가 null이 아니라면, 반환합니다. -
node를 반환합니다.
null 또는 CustomElementRegistry
객체 registry가 있을 때,
global
custom element registry인지는
registry가 null이 아니고 registry의 is
scoped가 false일 경우입니다.
문서 document의 실질적 글로벌 custom element registry의 값은:
-
document의 custom element registry가 global custom element registry이면, document의 custom element registry를 반환합니다.
-
null을 반환합니다.
createAttribute(localName) 메서드 단계:
-
localName이 올바른 속성 로컬 이름이 아니라면, "
InvalidCharacterError"DOMException을 throw합니다. - 새로운 속성을 반환하는데, 그 값의 로컬 이름은 localName이고, 노드 문서는 this입니다.
createAttributeNS(namespace, qualifiedName)
메서드 단계:
-
(namespace, prefix, localName)를 검증 및 추출 알고리즘으로 namespace, qualifiedName 그리고 "
attribute"로부터 얻는다. -
새로운 속성을 반환하는데, 네임스페이스는 namespace, 네임스페이스 접두사는 prefix, 로컬 이름은 localName, 노드 문서는 this입니다.
createEvent(interface) 메서드 단계:
-
constructor를 null로 설정합니다.
-
interface가 아래 표의 첫 번째 열과 ASCII 대소문자 구분 없이 일치할 경우, constructor를 같은 행의 두 번째 열에 해당하는 인터페이스로 설정합니다:
문자열 인터페이스 비고 " beforeunloadevent"BeforeUnloadEvent[HTML] " compositionevent"CompositionEvent[UIEVENTS] " customevent"CustomEvent" devicemotionevent"DeviceMotionEvent[DEVICE-ORIENTATION] " deviceorientationevent"DeviceOrientationEvent" dragevent"DragEvent[HTML] " event"Event" events"" focusevent"FocusEvent[UIEVENTS] " hashchangeevent"HashChangeEvent[HTML] " htmlevents"Event" keyboardevent"KeyboardEvent[UIEVENTS] " messageevent"MessageEvent[HTML] " mouseevent"MouseEvent[UIEVENTS] " mouseevents"" storageevent"StorageEvent[HTML] " svgevents"Event" textevent"TextEvent[UIEVENTS] " touchevent"TouchEvent[TOUCH-EVENTS] " uievent"UIEvent[UIEVENTS] " uievents" -
constructor가 null이면, "
NotSupportedError"DOMException을 throw합니다. -
constructor가 가리키는 인터페이스가 relevant global object에 노출되어 있지 않다면, "
NotSupportedError"DOMException을 throw합니다.일반적으로 사용자 에이전트가 특정 설정에서 터치 이벤트 지원을 비활성화할 수 있습니다. 이런 경우 해당 인터페이스(
TouchEvent)가 위 절차에서 제외됩니다. -
event를 creating an event 알고리즘을 사용해 constructor로 얻는다.
-
event의
type속성을 빈 문자열로 초기화한다. -
event의
timeStamp속성을 current high resolution time을 this의 relevant global object로 호출한 결과로 초기화한다. -
event의
isTrusted속성을 false로 설정한다. -
event의 initialized flag를 해제한다.
-
event를 반환한다.
Event 생성자를 대신 쓰는 것이 좋습니다.
createRange() 메서드 단계는 (this, 0)을 start와 end로 하는 새로운 live range를 반환합니다.
Range()
생성자를 대신 사용할 수 있습니다.
createNodeIterator(root, whatToShow, filter)
메서드 단계는 다음과 같습니다:
-
iterator에 새로운
NodeIterator객체를 할당한다. -
iterator의 pointer before reference를 true로 설정한다.
-
iterator의 whatToShow를 whatToShow로 설정한다.
-
iterator의 filter를 filter로 설정한다.
-
iterator를 반환한다.
createTreeWalker(root, whatToShow, filter)
메서드 단계는 다음과 같습니다:
-
walker에 새로운
TreeWalker객체를 할당합니다. -
walker의 whatToShow를 whatToShow로 설정한다.
-
walker의 filter를 filter로 설정한다.
-
walker를 반환한다.
4.5.1.
인터페이스 DOMImplementation
사용자 에이전트는 문서(document)가
생성될 때마다 DOMImplementation
객체를 생성해야 하며, 해당 문서(document)에 연관시켜야 합니다.
[Exposed =Window ]interface { [DOMImplementation NewObject ]DocumentType createDocumentType (DOMString ,name DOMString ,publicId DOMString ); [systemId NewObject ]XMLDocument createDocument (DOMString ?, [namespace LegacyNullToEmptyString ]DOMString ,qualifiedName optional DocumentType ?=doctype null ); [NewObject ]Document createHTMLDocument (optional DOMString );title boolean hasFeature (); // useless; always returns true };
doctype = document .implementation.createDocumentType(name, publicId, systemId)-
주어진 name, publicId, systemId으로 doctype을 반환합니다.
name이 유효한 doctype 이름이 아니면, "
InvalidCharacterError"DOMException이 발생합니다. doc = document .implementation. createDocument(namespace, qualifiedName [, doctype = null])-
XMLDocument를 반환하고, 문서 요소(document element)의 지역 이름(local name)은 qualifiedName이고, 네임스페이스(namespace)는 namespace입니다 (단, qualifiedName이 빈 문자열일 경우는 예외), 그리고 doctype이 주어지면 doctype으로 사용합니다.이 메서드는
createElementNS()메서드와 동일한 예외를 namespace와 qualifiedName을 인자로 했을 때 발생시킵니다. doc = document .implementation. createHTMLDocument([title])-
문서(document)를 반환하며,
기본 트리(tree)가 이미 생성되어 있고
title요소도 포함됩니다(단, title 인자를 생략하면 포함되지 않습니다).
createDocumentType(name, publicId, systemId)
메서드 단계는 다음과 같습니다:
-
만약 name이 유효한 doctype 이름이 아니라면, "
InvalidCharacterError"DOMException예외를 던집니다. -
새로운 doctype을 반환합니다. name은 name, publicId은 public ID, systemId은 system ID가 되고, 노드 문서는 document (즉, this와 연관된 것)으로 설정합니다.
createDocument(namespace, qualifiedName, doctype)
메서드 단계는 다음과 같습니다:
-
document를 새로운
XMLDocument로 생성합니다. -
element를 null로 설정합니다.
-
qualifiedName이 빈 문자열이 아니라면, element를 internal
createElementNS단계를 document, namespace, qualifiedName, 빈 딕셔너리를 인수로 호출한 결과로 설정합니다. -
doctype가 null이 아니라면, append로 doctype을 document에 추가합니다.
-
element가 null이 아니라면, append로 element를 document에 추가합니다.
-
document의 content type은 namespace에 따라 결정됩니다:
- HTML 네임스페이스
application/xhtml+xml- SVG 네임스페이스
image/svg+xml- 그 외의 네임스페이스
application/xml
-
document를 반환합니다.
createHTMLDocument(title)
메서드 단계는 다음과 같습니다:
-
doc의 content type을 "
text/html"로 설정한다. -
새로운 doctype(name은 "
html"이고 노드 문서가 doc인 값)을 append하여 doc에 추가한다. -
append를 사용해 요소 생성하기(doc, "
html", HTML 네임스페이스) 결과를 doc에 추가한다. -
append로 요소 생성하기(doc, "
head", HTML 네임스페이스) 결과를 앞서 생성한html요소에 추가한다. -
title이 주어졌을 경우:
-
append로 요소 생성하기(doc, "
body", HTML 네임스페이스) 결과를 앞서 생성한html요소에 추가한다. -
doc를 반환한다.
hasFeature()
메서드 단계는 true를 반환하는 것입니다.
hasFeature()
는 원래 user agent가 특정 DOM 기능을 지원하는지 보고하도록 설계되었지만,
실제로는 원하는 객체, 속성, 메서드가 존재하는지 직접 확인하는 것이 훨씬 더 신뢰할 수 있고 구체적이라는 것이 입증되었습니다.
따라서 이 메서드는 더이상 사용하지 않아야 하며 단지 오래된 페이지의 동작이 멈추지 않도록 남아 있을 뿐(true만 반환함)입니다.
4.6. 인터페이스 DocumentType
[Exposed =Window ]interface :DocumentType Node {readonly attribute DOMString name ;readonly attribute DOMString publicId ;readonly attribute DOMString systemId ; };
DocumentType
노드는 간단히
doctype로 알려져 있습니다.
Doctype에는 연관된 이름, public ID, 그리고 system ID가 있습니다.
Doctype이 생성될 때, 이름은 항상 제공됩니다. Doctype이 생성될 때 명확하게 제공되지 않으면, public ID와 system ID는 빈 문자열이 됩니다.
name getter 단계는
this의
이름을 반환하는 것입니다.
publicId getter 단계는
this의
public
ID를 반환하는 것입니다.
systemId getter 단계는
this의
system
ID를 반환하는 것입니다.
4.7.
인터페이스 DocumentFragment
[Exposed =Window ]interface :DocumentFragment Node {constructor (); };
DocumentFragment
노드는
호스트(null 또는 다른 노드 트리에 속한
요소)라는 연관 값을 가진다.
별도의 명시가 없으면 이 값은 null이다.
객체 A가 객체 B의 호스트 포함-포괄적 조상이면, A가 B의 포괄적 조상이거나, B의 루트에 null이 아닌 호스트가 있고, A가 B의 루트의 호스트의 호스트 포함-포괄적 조상이면 성립한다.
DocumentFragment
노드의 호스트 개념은
HTML의
template
요소와
섀도우 루트에서 유용하며,
pre-insert
및
replace 알고리즘에
영향을 미친다.
tree = newDocumentFragment()- 새로운
DocumentFragment노드를 반환한다.
new DocumentFragment()
생성자 단계는 this의
노드 문서를
현재 글로벌 객체의
연결된 Document로 설정한다.
4.8. 인터페이스 ShadowRoot
[Exposed =Window ]interface :ShadowRoot DocumentFragment {readonly attribute ShadowRootMode mode ;readonly attribute boolean delegatesFocus ;readonly attribute SlotAssignmentMode slotAssignment ;readonly attribute boolean clonable ;readonly attribute boolean serializable ;readonly attribute Element host ;attribute EventHandler onslotchange ; };enum {ShadowRootMode ,"open" };"closed" enum {SlotAssignmentMode ,"manual" };"named"
ShadowRoot
노드는 단순히
섀도우
루트로 불린다.
섀도우 루트와 연관된 host는 결코 null이 아니다.
섀도우 루트는 연관된 mode ("open" 또는 "closed")를 가진다.
섀도우 루트는 연관된 delegates focus (불린 값)을 가진다. 최초 설정 값은 false다.
섀도우 루트는 연관된 element internals에 사용 가능 (불린 값)을 가진다. 최초 설정 값은 false다.
섀도우 루트는 연관된 declarative (불린 값)을 가진다. 최초 설정 값은 false다.
섀도우 루트는 연관된 slot assignment ("manual" 또는 "named")을
가진다.
섀도우 루트는 연관된 clonable (불린 값)을 가진다. 최초 설정 값은 false다.
섀도우 루트는 연관된 serializable (불린 값)을 가진다. 최초 설정 값은 false다.
섀도우 루트는 연관된 custom element registry (null 또는 CustomElementRegistry
객체)을 가진다. 최초 값은 null이다.
섀도우 루트는 연관된 keep custom element registry null (불린 값)을 가진다. 최초 설정 값은 false다.
이 값은 선언형 섀도우 루트와 조합될 때만 true가 될 수 있다. 그리고 이는 섀도우 루트의 custom element registry가 null일 때만 의미가 있다.
섀도우 루트의 get the parent 알고리즘은, event가 주어졌을 때 event의 composed flag가 설정되지 않았고 섀도우 루트가 event의 path의 첫 번째 구조체의 invocation target의 루트인 경우 null을 반환한다. 그렇지 않으면 섀도우 루트의 host를 반환한다.
mode getter 단계는 this의 mode를 반환하는 것이다.
delegatesFocus getter 단계는 this의 delegates focus를 반환하는
것이다.
slotAssignment getter 단계는 this의 slot assignment를 반환하는
것이다.
clonable getter 단계는 this의 clonable을 반환하는 것이다.
serializable getter 단계는 this의 serializable을 반환하는 것이다.
host getter 단계는 this의 host를 반환하는 것이다.
onslotchange 속성은 event handler IDL attribute로, onslotchange 이벤트 핸들러에 해당하며, event handler event type은 slotchange이다.
섀도우를 포함하는 트리 순서란 섀도우 포함 전위(Preorder) 깊이 우선 순회로 노드 트리를 순회하는 것이다. 섀도우 포함 전위 깊이 우선 순회는 노드 트리 tree의 전위, 깊이 우선 순회 방식으로, tree에서 섀도우 호스트를 만나면 그 요소의 섀도우 루트의 노드 트리를 바로 이어서 순회한다.
섀도우 포함 루트란 객체의 루트의 host의 섀도우 포함 루트가 해당 객체의 루트가 섀도우 루트인 경우이고, 아니라면 그 객체의 루트이다.
객체 A가 객체 B의 섀도우 포함 자손인 경우는 A가 자손이거나, A의 루트가 섀도우 루트이고 A의 루트의 host가 섀도우 포함 포함 자손인 경우다.
섀도우 포함 포함 자손은 객체 자신 또는 그 섀도우 포함 자손 중 하나다.
객체 A가 객체 B의 섀도우 포함 조상인 것은 B가 섀도우 포함 자손일 때뿐이다.
섀도우 포함 포함 조상은 객체 자신 또는 그 섀도우 포함 조상 중 하나다.
노드 A가 노드 B로부터 closed-shadow-hidden되려면 다음 모든 조건을 만족해야 한다:
-
A의 루트가 섀도우 포함 포함 조상이 B에 대하여 아니어야 한다.
-
A의 루트가 섀도우 루트이며 mode가 "
closed"이거나, A의 루트의 host가 된 경우여야 한다 (B에 대하여).
retarget 알고리즘은 객체 A를 객체 B에 대해 다음 과정을 반복하여 객체를 반환한다:
-
다음 조건 중 하나가 참이면
이 경우 A를 반환한다.
retargeting 알고리즘은 이벤트 디스패치와 Fullscreen과 같은 다른 명세에서 사용된다. [FULLSCREEN]
4.9. 인터페이스 Element
[Exposed =Window ]interface :Element Node {readonly attribute DOMString ?namespaceURI ;readonly attribute DOMString ?prefix ;readonly attribute DOMString localName ;readonly attribute DOMString tagName ; [CEReactions ]attribute DOMString id ; [CEReactions ]attribute DOMString className ; [SameObject ,PutForwards =value ]readonly attribute DOMTokenList classList ; [CEReactions ,Unscopable ]attribute DOMString slot ;boolean hasAttributes (); [SameObject ]readonly attribute NamedNodeMap attributes ;sequence <DOMString >getAttributeNames ();DOMString ?getAttribute (DOMString );qualifiedName DOMString ?getAttributeNS (DOMString ?,namespace DOMString ); [localName CEReactions ]undefined setAttribute (DOMString , (qualifiedName TrustedType or DOMString )); [value CEReactions ]undefined setAttributeNS (DOMString ?,namespace DOMString , (qualifiedName TrustedType or DOMString )); [value CEReactions ]undefined removeAttribute (DOMString ); [qualifiedName CEReactions ]undefined removeAttributeNS (DOMString ?,namespace DOMString ); [localName CEReactions ]boolean toggleAttribute (DOMString ,qualifiedName optional boolean );force boolean hasAttribute (DOMString );qualifiedName boolean hasAttributeNS (DOMString ?,namespace DOMString );localName Attr ?getAttributeNode (DOMString );qualifiedName Attr ?getAttributeNodeNS (DOMString ?,namespace DOMString ); [localName CEReactions ]Attr ?setAttributeNode (Attr ); [attr CEReactions ]Attr ?setAttributeNodeNS (Attr ); [attr CEReactions ]Attr removeAttributeNode (Attr );attr ShadowRoot attachShadow (ShadowRootInit );init readonly attribute ShadowRoot ?shadowRoot ;readonly attribute CustomElementRegistry ?customElementRegistry ;Element ?closest (DOMString );selectors boolean matches (DOMString );selectors boolean webkitMatchesSelector (DOMString ); // legacy alias of .matchesselectors HTMLCollection getElementsByTagName (DOMString );qualifiedName HTMLCollection getElementsByTagNameNS (DOMString ?,namespace DOMString );localName HTMLCollection getElementsByClassName (DOMString ); [classNames CEReactions ]Element ?insertAdjacentElement (DOMString ,where Element ); // legacyelement undefined insertAdjacentText (DOMString ,where DOMString ); // legacy };data dictionary {ShadowRootInit required ShadowRootMode ;mode boolean =delegatesFocus false ;SlotAssignmentMode = "named";slotAssignment boolean =clonable false ;boolean =serializable false ;CustomElementRegistry ?; };customElementRegistry
ShadowRootInit
다소 특이하게 undefined와 null 모두를 customElementRegistry
멤버에 전달할 수 있게 허용합니다. 이는 웹 개발자가 ShadowRoot
노드를 딕셔너리가 아닌 attachShadow()에
전달할 수 있도록 하기 위함입니다.
엘리먼트에는 다음과 같은 연관값이 있습니다:
- 네임스페이스
- null 또는 빈 문자열이 아닌 문자열입니다.
- 네임스페이스 접두어
- null 또는 빈 문자열이 아닌 문자열입니다.
- 로컬 이름
- 빈 문자열이 아닌 문자열입니다.
- 커스텀 엘리먼트 레지스트리
- null 또는
CustomElementRegistry객체입니다. - 커스텀 엘리먼트 상태
- "
undefined", "failed", "uncustomized", "precustomized", 또는 "custom"입니다. - 커스텀 엘리먼트 정의
- null 또는 커스텀 엘리먼트 정의입니다.
is값- null 또는 유효한 커스텀 엘리먼트 이름입니다.
사용자 정의 요소 상태가
"uncustomized" 또는 "custom"인 요소는
정의되었다(defined)고 합니다.
사용자 정의 요소 상태가 "custom"인 요소는
사용자 정의(custom)되었다고 합니다.
요소가 정의되었는지 여부는 :defined
의사 클래스의 동작을 결정하는 데 사용됩니다. 요소가 사용자 정의되었는지 여부는
변형 알고리즘의 동작을 결정하는 데 사용됩니다.
"failed" 및 "precustomized" 상태는
사용자 정의 요소 생성자가 처음 올바르게 실행되지 않을 경우,
업그레이드에 의해 다시 실행되지 않도록 하는 데 사용됩니다.
다음 코드는 각 네 가지 상태의 엘리먼트를 보여줍니다:
<!DOCTYPE html>
< script >
window. customElements. define( "sw-rey" , class extends HTMLElement {})
window. customElements. define( "sw-finn" , class extends HTMLElement {}, { extends : "p" })
window. customElements. define( "sw-kylo" , class extends HTMLElement {
constructor () {
// super() intentionally omitted for this example
}
})
</ script >
<!-- "undefined" (정의되지 않음, 커스텀 아님) -->
< sw-han ></ sw-han >
< p is = "sw-luke" ></ p >
< p is = "asdf" ></ p >
<!-- "failed" (정의되지 않음, 커스텀 아님) -->
< sw-kylo ></ sw-kylo >
<!-- "uncustomized" (정의됨, 커스텀 아님) -->
< p ></ p >
< asdf ></ asdf >
<!-- "custom" (정의됨, 커스텀) -->
< sw-rey ></ sw-rey >
< p is = "sw-finn" ></ p >
요소는 또한 연관된 그림자 루트(null 또는 그림자 루트)를 가집니다. 별도로 명시되지 않는 한 null입니다. 요소의 그림자 루트가 null이 아닌 경우 해당 요소는 그림자 호스트입니다.
요소의
정규화된 이름은 네임스페이스 접두사가
null인 경우 로컬 이름이고, 그렇지 않은 경우 네임스페이스 접두사,
":", 그리고
로컬
이름이 차례로 이어집니다.
요소의 HTML-대문자화된 정규화된 이름은 다음 단계의 반환 값입니다:
-
qualifiedName을 this의 qualified name으로 설정합니다.
-
this 가 HTML 네임스페이스에 있고, 노드 document가 HTML document라면, qualifiedName을 ASCII 대문자로 변환합니다.
- qualifiedName을 반환합니다.
User agent는 qualified name과 HTML 대문자화된 qualified name을 내부 슬롯에 저장하여 최적화할 수 있습니다.
엘리먼트 생성은 document
document, 문자열 localName, 문자열 또는 null namespace,
옵션으로 문자열 또는 null prefix(기본값 null), 문자열 또는 null is(기본값 null), boolean
synchronousCustomElements(기본값 false), 그리고 "default", null, 또는
CustomElementRegistry
객체 registry(기본값 "default")가 주어졌을 때:
-
result를 null로 설정합니다.
-
registry가 "
default"라면, registry를 커스텀 엘리먼트 레지스트리 조회 결과로 설정합니다(document 기준). -
definition을 커스텀 엘리먼트 정의 조회 결과로 설정합니다(registry, namespace, localName, is 기준).
-
definition이 null이 아니고, definition의 name이 local name과 다르다면(definition이 커스텀 빌트인 엘리먼트임):
-
interface를 엘리먼트 인터페이스(localName, HTML 네임스페이스)로 설정합니다.
-
result를 엘리먼트 내부 생성 결과로 설정합니다(document, interface, localName, HTML 네임스페이스, prefix, "
undefined", is, registry). -
synchronousCustomElements가 true라면, 예외를 캐치하면서 다음 단계를 실행합니다:
이 단계에서 예외 exception이 발생했다면:
-
definition의 생성자의 해당 JavaScript 객체의 연관된 영역의 전역 객체에 대해 exception을 보고합니다.
-
result의 커스텀 엘리먼트 상태를 "
failed"로 설정합니다.
-
-
그렇지 않으면 result와 definition으로 커스텀 엘리먼트 업그레이드 reaction을 큐에 넣습니다.
-
-
그 밖에 definition이 null이 아니면:
-
synchronousCustomElements가 true라면:
-
C를 definition의 constructor로 설정합니다.
-
주변 에이전트의 활성 사용자 정의 요소 생성자 맵[C]을 registry로 설정합니다.
-
예외를 캐치하면서 다음 단계를 실행합니다:
-
result를 C를 생성(인자 없음) 결과로 설정합니다.
-
Assert: result의 커스텀 엘리먼트 상태와 커스텀 엘리먼트 정의가 초기화됨.
-
Assert: result의 네임스페이스가 HTML 네임스페이스임.
IDL은 result가
HTMLElement객체임을 보장하며, 모두 HTML 네임스페이스를 사용합니다. -
result의 attribute list가 비어있지 않으면, NotSupportedError
NotSupportedErrorDOMException예외를 던집니다. -
result에 자식이 있다면, NotSupportedError
NotSupportedErrorDOMException예외를 던집니다. -
result의 부모가 null이 아니면, NotSupportedError
NotSupportedErrorDOMException예외를 던집니다. -
result의 노드 document가 document가 아니면, NotSupportedError
NotSupportedErrorDOMException예외를 던집니다. -
result의 로컬 이름이 localName과 다르면, NotSupportedError
NotSupportedErrorDOMException예외를 던집니다. -
result의 네임스페이스 접두어를 prefix로 설정합니다.
-
result의
is값을 null로 설정합니다. -
result의 커스텀 엘리먼트 레지스트리를 registry로 설정합니다.
이 단계 중 예외 exception이 발생했다면:
-
definition의 생성자의 해당 JavaScript 객체의 연관된 영역의 전역 객체에 대해 exception을 보고합니다.
-
result를 엘리먼트 내부 생성 결과로 재설정합니다(document,
HTMLUnknownElement, localName, HTML 네임스페이스, prefix, "failed", null, registry).
-
-
주변 에이전트의 활성 사용자 정의 요소 생성자 맵에서 [C]를 제거합니다.
일반적으로 이 시점에서는 이미 제거되어 있습니다.
-
-
그 밖에:
-
result를 엘리먼트 내부 생성 결과로 설정합니다(document,
HTMLElement, localName, HTML 네임스페이스, prefix, "undefined", null, registry).
-
-
-
그 밖에:
-
interface를 엘리먼트 인터페이스(localName, namespace)로 설정합니다.
-
result를 엘리먼트 내부 생성 결과로 설정합니다(document, interface, localName, namespace, prefix, "
uncustomized", is, registry). -
namespace가 HTML 네임스페이스이고, localName이 유효한 커스텀 엘리먼트 이름이거나 is가 null이 아니면, result의 커스텀 엘리먼트 상태를 "
undefined"로 설정합니다.
-
-
result를 반환합니다.
엘리먼트 내부 생성은
document
document, 인터페이스 interface, 문자열 localName, 문자열 또는 null namespace,
문자열 또는 null prefix, 문자열 state, 문자열 또는 null is, 그리고 null 또는 CustomElementRegistry
객체 registry가 주어졌을 때:
-
element를 interface를 구현하는 새로운 엘리먼트로 생성하고, 네임스페이스를 namespace로, 네임스페이스 접두어를 prefix로, 로컬 이름을 localName으로, 커스텀 엘리먼트 레지스트리를 registry로, 커스텀 엘리먼트 상태를 state로, 커스텀 엘리먼트 정의를 null로,
is값을 is로, 노드 document를 document로 설정합니다. -
Assert: element의 attribute list 가 비어 있음을 확인합니다.
-
element를 반환합니다.
엘리먼트는 또한
attribute list를 가지며,
리스트로,
NamedNodeMap을
통해 노출됩니다.
엘리먼트가 생성될 때 명확하게 지정되지 않으면
attribute
list는 비어 있습니다.
엘리먼트가 has attribute A를 가진다는 것은, attribute list에 A가 포함되어 있을 때를 의미합니다.
이것과 다른 명세들은 요소에 대한 속성 변경 단계를 정의할 수 있습니다. 이 알고리즘에는 element, localName, oldValue, value, 및 namespace가 전달됩니다.
element, oldValue, 및 newValue를 사용하여 속성 attribute의 속성 변경을 처리하려면 다음 단계를 실행합니다.
-
mutation record "
attributes"를 element에 대해 큐에 넣으며, attribute의 local name, attribute의 namespace, oldValue, « », « », null, null을 사용합니다. -
element가 커스텀이라면, 커스텀 엘리먼트 콜백 reaction을 큐에 넣습니다 (element, 콜백 이름 "
attributeChangedCallback", 그리고 « attribute의 local name, oldValue, newValue, attribute의 namespace »). -
attribute change steps를 element, attribute의 local name, oldValue, newValue, attribute의 namespace로 실행합니다.
attribute 변경은 attribute attribute를 value로 변경하는 과정으로, 다음 단계를 따릅니다:
-
oldValue를 attribute의 value로 설정합니다.
-
attribute의 value를 value로 설정합니다.
-
handle attribute changes를 attribute, attribute의 element, oldValue, value로 실행합니다.
attribute 추가은 attribute attribute를 엘리먼트 element에 추가하는 과정으로, 다음 단계를 따릅니다:
-
Append attribute를 element의 attribute list에 추가합니다.
-
attribute의 element를 element로 설정합니다.
-
attribute의 노드 document를 element의 노드 document로 설정합니다.
-
handle attribute changes를 attribute, element, null, attribute의 value로 실행합니다.
attribute 제거은 attribute attribute를 제거하는 과정으로, 다음 단계를 따릅니다:
-
element를 attribute의 element로 설정합니다.
- Remove attribute를 element의 attribute list에서 제거합니다.
-
attribute의 element를 null로 설정합니다.
-
handle attribute changes를 attribute, element, attribute의 value, null로 실행합니다.
attribute 교체는 attribute oldAttribute를 attribute newAttribute로 교체하는 과정입니다:
-
element를 oldAttribute의 element로 설정합니다.
-
Replace oldAttribute를 newAttribute로 element의 attribute list에서 교체합니다.
-
newAttribute의 element를 element로 설정합니다.
-
newAttribute의 노드 document를 element의 노드 document로 설정합니다.
-
oldAttribute의 element를 null로 설정합니다.
-
handle attribute changes를 oldAttribute, element, oldAttribute의 value, newAttribute의 value로 실행합니다.
이름으로 attribute 얻기는 문자열 qualifiedName과 엘리먼트 element가 주어졌을 때 다음과 같이 동작합니다:
-
element가 HTML 네임스페이스에 있고, 노드 document 가 HTML document라면, qualifiedName을 ASCII 소문자로 변환합니다.
-
element의 attribute list에서 attribute 중 qualified name이 qualifiedName과 같은 첫 번째 attribute를 반환하고, 없으면 null을 반환합니다.
네임스페이스와 로컬 이름으로 attribute 얻기는 null 또는 문자열 namespace, 문자열 localName, 엘리먼트 element가 주어졌을 때:
-
namespace가 빈 문자열이라면, null로 설정합니다.
-
element의 attribute list에서 attribute 중 namespace가 namespace이고 local name이 localName인 attribute를 반환하고, 없으면 null을 반환합니다.
attribute 값 얻기은 엘리먼트 element, 문자열 localName, 옵션으로 null 또는 문자열 namespace(기본값 null)가 주어졌을 때:
-
attr를 네임스페이스와 로컬 이름으로 attribute 얻기 결과로 설정합니다(namespace, localName, element).
-
attr가 null이면, 빈 문자열을 반환합니다.
-
attr의 value를 반환합니다.
속성 설정하기를 수행하려면, 속성 attr과 요소 element가 주어졌을 때 다음과 같이 한다:
-
verifiedValue에 attr의 get trusted type compliant attribute value를, attr의 로컬 이름, attr의 네임스페이스, element, 그리고 attr의 값으로 호출한 결과를 설정한다. [TRUSTED-TYPES]
-
attr의 element가 null이 아니고 element와 다르면, 예외를 던진다: "
InUseAttributeError"DOMException. -
oldAttr에, 속성 가져오기를 attr의 네임스페이스, attr의 로컬 이름, 그리고 element을 인자로 호출한 결과를 설정한다.
-
oldAttr이 attr과 같으면, attr을 반환한다.
-
attr의 값을 verifiedValue로 설정한다.
-
oldAttr이 null이 아니면, oldAttr을 attr로 교체한다.
-
그렇지 않으면, attr을 element에 추가한다.
-
oldAttr을 반환한다.
속성 값 설정하기를 요소 element, 문자열 localName, 문자열 value, 선택적 null 또는 문자열 prefix (기본값 null), 그리고 선택적 null 또는 문자열 namespace (기본값 null)이 주어졌을 때 다음과 같이 한다:
- attribute에 속성 가져오기를 namespace, localName, element을 인자로 호출한 결과를 설정한다.
- attribute가 null이면, 속성을 생성한다. 이때 네임스페이스는 namespace, 네임스페이스 접두사는 prefix, 로컬 이름은 localName, 값 은 value, 그리고 노드 문서는 element의 노드 문서로 한다. 그런 다음, 이 속성을 element에 추가하고, 반환한다.
이름으로 attribute 제거는 문자열 qualifiedName과 엘리먼트 element가 주어졌을 때:
-
attr를 이름으로 attribute 얻기 결과로 설정합니다(qualifiedName, element).
-
attr가 null이 아니면 attr 제거를 실행합니다.
-
attr를 반환합니다.
네임스페이스와 로컬 이름으로 attribute 제거는 null 또는 문자열 namespace, 문자열 localName, 엘리먼트 element가 주어졌을 때:
-
attr를 네임스페이스와 로컬 이름으로 attribute 얻기 결과로 설정합니다(namespace, localName, element).
-
attr가 null이 아니면 attr 제거를 실행합니다.
-
attr를 반환합니다.
엘리먼트는 연관된 고유 식별자(ID)를 가질 수 있습니다.
역사적으로 엘리먼트는 HTML id attribute와 DTD를 통해 여러 식별자를 가질 수 있었으나, 이
명세는 ID
를 DOM의 개념으로 만들고, 엘리먼트마다
하나만 허용하며 id attribute로 지정합니다.
attribute change steps를 사용하여 엘리먼트의 ID를 업데이트합니다:
-
localName이
id이고, namespace가 null이며, value가 null이거나 빈 문자열인 경우 element의 ID를 해제한다. -
그렇지 않고 localName이
id이고, namespace가 null인 경우 element의 ID를 value로 설정한다.
이 명세서는 class, id, slot
속성에 대한 요구 사항을
어떤 요소에도 정의하지만,
이를 사용하는 것이 적합(conforming)한지에 대해서는 어떠한 주장도 하지 않는다.
노드의 Element 타입의 부모는 그 노드의
부모 요소라고 한다. 만약 노드의 부모가 다른 타입이라면,
그 부모 요소는 null이다.
- namespace = element .
namespaceURI - 네임스페이스를 반환합니다.
- prefix = element .
prefix - 네임스페이스 접두어를 반환합니다.
- localName = element .
localName - 로컬 이름을 반환합니다.
- qualifiedName = element .
tagName - HTML 대문자화된 qualified name을 반환합니다.
namespaceURI getter 단계는
this의 네임스페이스를 반환합니다.
prefix getter 단계는
this의 네임스페이스 접두어를 반환합니다.
localName getter 단계는
this의 로컬
이름을 반환합니다.
tagName getter 단계는
this의 HTML 대문자화된 qualified name을 반환합니다.
element . id [ = value ]-
element의
id콘텐츠 attribute 값을 반환합니다. 값을 변경할 수도 있습니다. element . className [ = value ]-
element의
class콘텐츠 attribute 값을 반환합니다. 값을 변경할 수도 있습니다. element . classList-
element의
class콘텐츠 attribute를 공백으로 구분된 토큰 집합으로DOMTokenList객체를 통해 조작할 수 있습니다. element . slot [ = value ]-
element의
slot콘텐츠 attribute 값을 반환합니다. 값을 변경할 수도 있습니다.
문자열 name을 반영(reflect)하도록 정의된 IDL attribute는 다음 getter/setter 단계를 가져야 합니다:
- getter 단계
-
attribute 값 얻기를 this 와 name으로 실행한 결과를 반환합니다.
- setter 단계
-
attribute 값 설정을 this 와 name, 주어진 값으로 실행합니다.
id attribute는 반드시
"id"를 반영해야
합니다.
className attribute는 반드시
"class"를 반영해야
합니다.
classList getter 단계는
DOMTokenList
객체를 반환합니다. 이 객체의 연관 엘리먼트는 this이며, 연관 attribute의 로컬 이름이
class입니다. 이 DOMTokenList
객체의 토큰 집합은 엘리먼트의
클래스라고도 합니다.
slot attribute는 반드시
"slot"를 반영해야
합니다.
id, class, slot는 네임스페이스와 관계없이 어떤 엘리먼트에도 나타날 수
있으므로 사실상 슈퍼글로벌 attribute입니다.
element . hasAttributes()-
element에 속성이 있으면 true를 반환하고, 그렇지 않으면 false를 반환합니다.
element . getAttributeNames()-
element의 모든 qualified name의 속성을 반환합니다. 중복값이 포함될 수 있습니다.
element . getAttribute(qualifiedName)-
qualifiedName과 일치하는 element의 첫 번째 속성의 qualified name 값을 반환하며, 해당 속성이 없으면 null을 반환합니다.
element . getAttributeNS(namespace, localName)-
namespace가 namespace이고 local name이 localName인 element의 속성 값을 반환합니다. 해당 속성이 없으면 null을 반환합니다.
element . setAttribute(qualifiedName, value)element . setAttributeNS(namespace, localName, value)-
namespace가 namespace이고 local name이 localName인 element의 속성의 값을 value로 설정합니다.
element . removeAttribute(qualifiedName)-
qualifiedName과 일치하는 element의 첫 번째 속성을 제거합니다.
element . removeAttributeNS(namespace, localName)-
namespace가 namespace이고 local name이 localName인 element의 속성을 제거합니다.
element . toggleAttribute(qualifiedName [, force])-
force가 주어지지 않으면 qualifiedName 속성을 "토글"합니다. 즉, 있으면 제거하고 없으면 추가합니다. force가 true면 qualifiedName을 추가하고, false면 qualifiedName을 제거합니다.
qualifiedName이 현재 있으면 true, 그렇지 않으면 false를 반환합니다.
element . hasAttribute(qualifiedName)-
qualifiedName에 해당하는 속성이 element에 있으면 true, 그렇지 않으면 false를 반환합니다.
element . hasAttributeNS(namespace, localName)-
namespace가 namespace이고 local name이 localName인 속성이 element에 있으면 true를 반환합니다.
attributes getter의 단계는 연관된 NamedNodeMap을
반환하는 것입니다.
getAttributeNames() 메서드 단계는
qualified name을 속성들로부터 this의
속성
목록 순서대로 반환합니다. 그렇지 않으면 새로운 목록을 반환합니다.
이 이름들은 고유하지 않을 수 있습니다.
getAttribute(qualifiedName) 메서드 단계는 다음과
같습니다:
-
attr를 qualifiedName과 this를 이용하여 속성 얻기 결과로 정합니다.
-
attr가 null이면 null을 반환합니다.
-
attr의 값을 반환합니다.
getAttributeNS(namespace, localName)
메서드 단계는 다음과 같습니다:
-
attr를 getting an attribute에서 namespace, localName, this를 이용해 얻습니다.
-
attr가 null이면 null을 반환합니다.
-
attr의 값을 반환합니다.
setAttribute(qualifiedName, value)
메서드 단계는 다음과 같습니다:
-
qualifiedName이 유효한 속성 local name이 아니면 예외를 발생시키고, "
InvalidCharacterError"DOMException를 던집니다.파라미터의 명명과 관계없이, qualifiedName은 qualified name과 일치하는 속성이 이미 있을 때만 qualified name으로 사용됩니다. 그렇지 않으면 새로운 속성의 local name으로 사용됩니다. 후자의 경우에만 유효성 검사가 필요합니다.
-
this가 HTML namespace에 있고, node document가 HTML document라면 qualifiedName을 ASCII 소문자로 변환합니다.
-
verifiedValue를 get trusted type compliant attribute value를 qualifiedName, null, this, value로 호출하여 얻습니다. [TRUSTED-TYPES]
-
attribute를 속성 중 첫 번째로 qualified name이 qualifiedName인 값을 찾고, 없으면 null로 정합니다.
-
attribute가 null이 아니면, 속성 값을 변경 하고 verifiedValue로 설정한 뒤 반환합니다.
-
attribute를 새로운 속성으로 만들어 local name을 qualifiedName으로, 값은 verifiedValue, 노드 문서는 this의 노드 문서로 정합니다.
setAttributeNS(namespace, qualifiedName, value)
메서드 단계는 다음과 같습니다:
-
namespace와 qualifiedName을 "
attribute"로 검증 및 추출하여 (namespace, prefix, localName)로 정합니다. -
verifiedValue를 get trusted type compliant attribute value로 localName, namespace, this, value로 호출해 얻습니다. [TRUSTED-TYPES]
-
Set an attribute value를 this에 localName, verifiedValue, prefix, namespace로 사용합니다.
removeAttribute(qualifiedName)
메서드는 remove an attribute에서
qualifiedName과 this를 사용하여 속성을 제거한 뒤 undefined를 반환합니다.
removeAttributeNS(namespace, localName)
메서드는 remove an attribute에서
namespace, localName, this를 사용하여 속성을 제거하고 undefined를
반환합니다.
hasAttribute(qualifiedName) 메서드의 단계는 다음과
같습니다:
-
this가 HTML namespace에 속하고 node document가 HTML document이면 qualifiedName을 ASCII 소문자로 변환합니다.
-
this가 has 속성 중에서 qualified name이 qualifiedName과 일치하면 true, 그렇지 않으면 false를 반환합니다.
toggleAttribute(qualifiedName, force)
메서드 단계는 다음과 같습니다:
-
qualifiedName이 유효한 속성 local name이 아니면 예외를 발생시키고, "
InvalidCharacterError"DOMException을 던집니다.왜 local name으로 검사하는지에 대한 자세한 내용은 위의 설명을 참고하세요.
-
this가 HTML namespace에 있고 node document가 HTML document이면 qualifiedName을 ASCII 소문자로 만듭니다.
-
attribute를 속성 중에서 qualified name이 qualifiedName과 일치하는 요소의 첫 번째 값으로 가져오며, 없으면 null로 정합니다.
-
attribute가 null인 경우:
-
그 밖의 경우, force가 주어지지 않았거나 false면 remove an attribute를 qualifiedName과 this로 호출 후 false를 반환합니다.
-
true를 반환합니다.
hasAttributeNS(namespace, localName)
메서드 단계는 다음과 같습니다:
-
namespace가 빈 문자열이면 null로 설정합니다.
- this가 has 속성 중에서 namespace가 namespace이고, local name이 localName과 일치하면 true, 그렇지 않으면 false 반환.
getAttributeNode(qualifiedName)
메서드는 qualifiedName과 this로 속성 얻기의 결과를 반환합니다.
removeAttributeNode(attr) 메서드 단계는
다음과 같습니다:
-
this의 속성 목록에 attr이 포함되어 있지 않으면 예외를 발생시키고, "
NotFoundError"DOMException을 던집니다. -
attr을 제거합니다.
-
attr을 반환합니다.
shadow = element .attachShadow(init)-
element에 섀도우 루트를 생성하고 반환합니다.
shadow = element .shadowRoot-
element의 섀도우 루트를 반환하며, 섀도우 루트의 mode가 "
open"일 때만 반환, 아니면 null을 반환합니다.
유효한 섀도우 호스트 이름은 다음 중 하나입니다:
- 유효한 커스텀 엘리먼트 이름
- "
article", "aside", "blockquote", "body", "div", "footer", "h1", "h2", "h3", "h4", "h5", "h6", "header", "main", "nav", "p", "section", 또는 "span"
attachShadow(init) 메서드 단계는 다음과 같다:
-
this의 node document의 custom element registry를 registry로 한다.
-
만약 init["
customElementRegistry"] 존재하면, registry를 그 값으로 설정한다. -
만약 registry가 null이 아니고, registry의 is scoped가 false이며, registry가 this의 node document의 custom element registry가 아니면, 예외를 던진다 — "
NotSupportedError"DOMException. -
attach a shadow root를 다음과 함께 실행한다: this, init["
mode"], init["clonable"], init["serializable"], init["delegatesFocus"], init["slotAssignment"], 그리고 registry. -
this의 shadow root를 반환한다.
섀도우 루트
연결은 엘리먼트
element, 문자열 mode, 불린값 clonable,
불린값 serializable, 불린값 delegatesFocus, 문자열 slotAssignment, null 또는 CustomElementRegistry
객체 registry가 주어졌을 때:
-
element의 네임스페이스가 HTML 네임스페이스가 아니라면, NotSupportedError
NotSupportedErrorDOMException예외를 던집니다. -
element의 로컬 이름이 유효한 섀도우 호스트 이름이 아니면, NotSupportedError
NotSupportedErrorDOMException예외를 던집니다. -
element의 로컬 이름이 유효한 커스텀 엘리먼트 이름이거나, element의
is값이 null이 아니면:-
definition을 커스텀 엘리먼트 정의 조회 결과로 설정합니다(element의 커스텀 엘리먼트 레지스트리, 네임스페이스, 로컬 이름,
is값 기준). -
definition이 null이 아니고 definition의 disable shadow가 true면, NotSupportedError
NotSupportedErrorDOMException예외를 던집니다.
-
-
element가 섀도우 호스트라면:
-
currentShadowRoot를 element의 섀도우 루트로 설정합니다.
-
다음 중 하나라도 true이면:
-
currentShadowRoot의 declarative가 false
-
currentShadowRoot의 mode가 mode와 다름
그러면 NotSupportedError
NotSupportedErrorDOMException예외를 던집니다. -
-
그 밖의 경우:
-
currentShadowRoot의 모든 자식을 트리 순서로 제거합니다.
-
currentShadowRoot의 declarative를 false로 설정합니다.
-
리턴합니다.
-
-
-
shadow를 새로운 섀도우 루트로 설정한다. 이때 노드 문서는 element의 노드 문서이고, 호스트는 element이며, 모드는 mode이다.
-
shadow의 delegates focus를 delegatesFocus로 설정합니다.
-
element의 커스텀 엘리먼트 상태가 "
precustomized" 또는 "custom"이면 shadow의 available to element internals를 true로 설정합니다. -
shadow의 slot assignment를 slotAssignment로 설정합니다.
-
shadow의 declarative를 false로 설정합니다.
-
shadow의 clonable을 clonable로 설정합니다.
-
shadow의 serializable을 serializable로 설정합니다.
-
shadow의 커스텀 엘리먼트 레지스트리를 registry로 설정합니다.
-
element의 섀도우 루트를 shadow로 설정합니다.
shadowRoot getter 단계는 다음과 같다:
-
shadow를 this의 shadow root로 설정한다.
-
shadow가 null이거나 그 mode가 "
closed"이면 null을 반환한다. -
shadow를 반환한다.
-
registry = element .customElementRegistry -
element의
CustomElementRegistry객체가 있으면 반환하고, 없으면 null을 반환한다.
customElementRegistry getter 단계는
this의
custom element registry를 반환한다.
-
element .closest(selectors) - element부터 시작하여 포함 조상 중 selectors와 일치하는 첫 번째 요소를 반환하며, 없으면 null을 반환한다.
-
element .matches(selectors) - element의 root에서 selectors로 일치 검사 시 element가 일치하면 true, 아니면 false를 반환한다.
closest(selectors) 메서드 단계는 다음과 같다:
-
selector를 selectors로부터 셀렉터 파싱 결과로 정한다. [SELECTORS4]
-
만약 selector가 failure라면, throw "
SyntaxError"DOMException예외를 던진다. -
elements의 각 element에 대해: 셀렉터가 엘리먼트에 매치되는지 selector, element, 그리고 스코핑 루트 this를 이용해 검사해 성공이라면, element를 반환한다. [SELECTORS4]
-
null을 반환한다.
matches(selectors) 및
webkitMatchesSelector(selectors)
메서드 단계는 다음과 같다:
-
selector를 selectors로부터 셀렉터 파싱 결과로 정한다. [SELECTORS4]
-
만약 selector가 실패라면, throw "
SyntaxError"DOMException예외를 던진다. -
셀렉터가 엘리먼트에 매치되는지 selector, this, 스코핑 루트 this를 이용해 검사해 성공이면 true를, 그렇지 않으면 false를 반환한다. [SELECTORS4]
getElementsByTagName(qualifiedName)
메서드 단계는 qualifiedName을 가진 요소들의 리스트를 this에 대해 반환한다.
getElementsByTagNameNS(namespace, localName)
메서드 단계는 namespace와 localName을 가진 요소들의
리스트를 this에 대해 반환한다.
getElementsByClassName(classNames)
메서드 단계는 classNames를 가진 요소들의 리스트를
this에 대해 반환한다.
인접 삽입을 하려면, 요소 element, 문자열 where, 그리고 노드 node가 주어졌을 때, where와 첫 번째로 ASCII 대소문자 구분 없는 일치가 되는 단계의 절차를 실행한다:
- "
beforebegin" -
element의 부모가 null이면, null을 반환한다.
pre-inserting을 element의 부모에 대해 node를 element 앞에 삽입하는 것으로 실행한 결과를 반환한다.
- "
afterbegin" -
pre-inserting을 element에 대해 node를 element의 첫 번째 자식 앞에 삽입하는 것으로 실행한 결과를 반환한다.
- "
beforeend" -
pre-inserting을 element에 대해 node를 null 앞에 삽입하는 것으로 실행한 결과를 반환한다.
- "
afterend" -
element의 부모가 null이면, null을 반환한다.
pre-inserting을 element의 부모에 대해 node를 element의 다음 형제 앞에 삽입하는 것으로 실행한 결과를 반환한다.
- 그 외의 경우
insertAdjacentElement(where, element)
메서드 절차는 인접 삽입을 this,
where, element로 실행한 결과를 반환한다.
insertAdjacentText(where, data)
메서드 절차는 다음과 같다:
이 메서드는 존재하던 시점에 설계할 시간이 없었기 때문에 반환값이 없다.
4.9.1.
인터페이스 NamedNodeMap
[Exposed =Window ,LegacyUnenumerableNamedProperties ]interface {NamedNodeMap readonly attribute unsigned long length ;getter Attr ?item (unsigned long );index getter Attr ?getNamedItem (DOMString );qualifiedName Attr ?getNamedItemNS (DOMString ?,namespace DOMString ); [localName CEReactions ]Attr ?setNamedItem (Attr ); [attr CEReactions ]Attr ?setNamedItemNS (Attr ); [attr CEReactions ]Attr removeNamedItem (DOMString ); [qualifiedName CEReactions ]Attr removeNamedItemNS (DOMString ?,namespace DOMString ); };localName
NamedNodeMap
객체는
element
(즉, 요소)와 연관되어 있습니다.
NamedNodeMap
객체의
속성 리스트(attribute list)는
그 연관된
요소(element)의
속성
리스트(attribute list)입니다.
NamedNodeMap
객체의 지원되는 프로퍼티 인덱스는
0부터 속성 리스트의 크기 - 1까지의 숫자입니다.
단, 속성 리스트가 비어 있다면
지원되는 프로퍼티 인덱스는 없습니다.
length
getter 단계는 속성 리스트(attribute list)의 크기(size)를 반환합니다.
item(index)
메서드 단계:
NamedNodeMap
객체의 지원되는 프로퍼티 이름은 다음 단계의 반환값이다:
-
names를 이
NamedNodeMap객체의 속성 목록에 있는 속성들의 정규화된 이름 집합(중복 제거, 순서 유지)으로 설정한다. -
이
NamedNodeMap객체의 요소가 HTML 네임스페이스에 있고, 그 노드 문서가 HTML 문서이면, names의 각 name에 대해:-
lowercaseName을 name을 ASCII 소문자로 변환한 값으로 설정한다.
-
lowercaseName이 name과 다르면, name을 names에서 제거한다.
-
-
names를 반환한다.
getNamedItem(qualifiedName)
메서드 단계는 qualifiedName과 요소를 받아 속성
얻기의 결과를 반환하는 것입니다.
getNamedItemNS(namespace, localName)
메서드 단계는 namespace, localName, 그리고 요소를 받아 속성 얻기의 결과를 반환하는 것입니다.
setNamedItem(attr) 및
setNamedItemNS(attr) 메서드 단계는
attr와 요소를 받아 속성 설정의 결과를 반환하는
것입니다.
removeNamedItem(qualifiedName)
메서드 단계는 다음과 같습니다:
-
만약 attr가 null이면, throw "
NotFoundError"DOMException을 던져라. -
attr을 반환합니다.
removeNamedItemNS(namespace, localName)
메서드 단계는 다음과 같습니다:
-
만약 attr가 null이면, throw "
NotFoundError"DOMException을 던진다. -
attr을 반환합니다.
4.9.2. 인터페이스 Attr
[Exposed =Window ]interface :Attr Node {readonly attribute DOMString ?namespaceURI ;readonly attribute DOMString ?prefix ;readonly attribute DOMString localName ;readonly attribute DOMString name ; [CEReactions ]attribute DOMString value ;readonly attribute Element ?ownerElement ;readonly attribute boolean specified ; // useless; always returns true };
Attr 노드는 단순히
속성이라고 한다. 혼동을 피하기 위해 콘텐츠 속성이라고 부르는 경우도 있다(IDL 속성과 구분하기 위해).
속성은 네임스페이스 (null 또는 비어있지 않은 문자열), 네임스페이스 접두사 (null 또는 비어있지 않은 문자열), 로컬 이름 (비어있지 않은 문자열), 값 (문자열), 그리고 element (null 또는 요소)를 가진다.
오늘날 설계했다면 이름과 값만 가졌을 것이다. ☹
속성의
정규화된 이름은
네임스페이스 접두사가 null이면
로컬
이름이고,
null이 아니면 네임스페이스 접두사 + ":" + 로컬
이름이다.
User agent는 최적화를 위해 내부 슬롯으로 가질 수도 있다.
속성이 생성될 때 로컬 이름이 주어진다. 명시적으로 지정하지 않으면, 속성이 생성될 때 네임스페이스, 네임스페이스 접두사, element는 null로 설정되고, 값은 빈 문자열로 설정된다.
A 속성
은 속성 중
로컬
이름이
A이고,
네임스페이스와
네임스페이스 접두사가
null인 속성을 의미한다.
namespaceURI getter 단계는
this의 네임스페이스를 반환한다.
prefix getter 단계는 this의
네임스페이스 접두사를 반환한다.
localName getter 단계는
this의 로컬
이름을 반환한다.
name getter 단계는 this의
정규화된 이름을 반환한다.
value getter 단계는 this의
값을 반환한다.
기존 속성 값 설정하기는 속성 attribute와 문자열 value가 주어지면 다음 단계를 실행한다:
-
element를 attribute의 element로 설정한다.
-
verifiedValue에 get trusted type compliant attribute value를 attribute의 로컬 이름, attribute의 네임스페이스, element, value로 호출한 결과를 설정한다. [TRUSTED-TYPES]
-
attribute의 element가 null이면 attribute의 값을 verifiedValue로 설정하고 반환한다.
value
setter 단계는 기존 속성 값 설정하기를 this
와 주어진 값으로 실행한다.
ownerElement getter 단계는
this의 element를 반환한다.
specified getter 단계는 true를 반환한다.
4.10.
인터페이스 CharacterData
[Exposed =Window ]interface :CharacterData Node {attribute [LegacyNullToEmptyString ]DOMString data ;readonly attribute unsigned long length ;DOMString substringData (unsigned long ,offset unsigned long );count undefined appendData (DOMString );data undefined insertData (unsigned long ,offset DOMString );data undefined deleteData (unsigned long ,offset unsigned long );count undefined replaceData (unsigned long ,offset unsigned long ,count DOMString ); };data
CharacterData
는 추상 인터페이스입니다. 직접 인스턴스를 생성할 수 없습니다.
Text,
ProcessingInstruction,
Comment
노드들에서 사용됩니다.
노드가
CharacterData
인터페이스에서 상속받으면,
data라는 가변 문자열이 연관되어 있습니다.
데이터 교체를 위해 노드 node, 정수 offset, 정수 count, 문자열 data가 주어졌을 때:
-
length를 node의 length로 설정합니다.
-
offset이 length보다 크면, "
IndexSizeError"DOMException을 던집니다. -
offset + count가 length보다 크면, count를 length − offset으로 설정합니다.
-
"
characterData"에 대한 변이 기록 큐를 node에 대해 null, null, node의 data, « », « », null, null을 인자로 큐에 넣습니다. -
deleteOffset을 offset + data의 length로 설정합니다.
-
node를 start node로 하고, start offset이 offset 초과이고 offset + count 이하인 모든 live range에 대해, 그 start offset을 offset으로 설정합니다.
-
node를 end node로 하고, end offset이 offset 초과이고 offset + count 이하인 모든 live range에 대해, 그 end offset을 offset으로 설정합니다.
-
node를 start node로 하고, start offset이 offset + count 초과인 모든 live range에 대해, start offset을 data의 length만큼 증가시키고, count만큼 감소시킵니다.
-
node를 end node로 하고, end offset이 offset + count 초과인 모든 live range에 대해, end offset을 data의 length만큼 증가시키고, count만큼 감소시킵니다.
-
node의 부모가 null이 아니면, children changed steps를 그 parent에 대해 실행합니다.
데이터 서브스트링을 취하기 위해 노드 node, 정수 offset, 정수 count가 주어졌을 때:
-
length를 node의 length로 설정합니다.
-
offset이 length보다 크면, "
IndexSizeError"DOMException을 던집니다. -
offset + count가 length보다 크면, offset번째 코드 유닛부터 node의 data의 끝까지 반환합니다.
4.11. 인터페이스 Text
[Exposed =Window ]interface :Text CharacterData {constructor (optional DOMString = ""); [data NewObject ]Text splitText (unsigned long );offset readonly attribute DOMString wholeText ; };
text = new Text([data = ""])- data 값을 가진 새로운
Text노드를 반환합니다. text .splitText(offset)- 주어진 offset 위치에서 data를 분리하고, 나머지 부분을
Text노드로 반환합니다. text .wholeText- 모든 직접적인
Text노드 형제의 data를 합친 문자열을 반환합니다.
exclusive Text 노드란
Text 노드이며, CDATASection
노드가 아닌 경우입니다.
노드 node의 연속된 Text 노드는
node와, node의 이전 형제 Text 노드 (있는 경우), 그 연속된
Text 노드들, node의 다음 형제 Text 노드 (있는 경우), 그 연속된
Text 노드들, 중복은 제외한 값들입니다.
노드 node의 연속된
exclusive Text
노드는 node, node의 이전 형제 exclusive
Text 노드 (있는 경우), 그 연속된 exclusive Text 노드들,
node의 다음 형제 exclusive Text 노드 (있는
경우), 그 연속된 exclusive Text 노드들, 중복은 제외한
값들입니다.
Text
노드 node를 정수
offset으로 분리(split)하려면:
-
length를 node의 length로 설정합니다.
-
offset이 length보다 크면 "
IndexSizeError"DOMException를 throw합니다. -
count를 length − offset로 설정합니다.
-
newData를 substringing data를 node, offset, count에 대해 실행한 결과로 설정합니다.
-
newNode를 node의 노드 문서를 그대로 사용하고, data를 newData로 설정한 새로운
Text노드로 설정합니다. -
parent를 node의 부모로 설정합니다.
-
parent가 null이 아니면:
-
node가 start node이며 start offset이 offset초과인 live range 각각에 대해, start node를 newNode로, start offset을 offset만큼 감소시킵니다.
-
node가 end node이며 end offset이 offset초과인 live range 각각에 대해, end node를 newNode로, end offset을 offset만큼 감소시킵니다.
-
parent가 start node이며 start offset이 node의 index+1인 live range 각각에 대해, start offset을 1 증가시킵니다.
-
parent가 end node이며 end offset이 node의 index+1인 live range 각각에 대해, end offset을 1 증가시킵니다.
-
Replace data를 node, offset, count, 빈 문자열에 대해 실행합니다.
-
newNode를 반환합니다.
wholeText getter 단계는 concatenation 방식으로 연속된 Text 노드들의 data를 this에 대해
트리 순서로 합쳐
반환합니다.
4.12. 인터페이스 CDATASection
[Exposed =Window ]interface :CDATASection Text { };
4.13.
인터페이스 ProcessingInstruction
[Exposed =Window ]interface :ProcessingInstruction CharacterData {readonly attribute DOMString target ; };
ProcessingInstruction
노드는 연관된
target을 갖습니다.
4.14. 인터페이스 Comment
[Exposed =Window ]interface :Comment CharacterData {constructor (optional DOMString = ""); };data
comment = new Comment([data = ""])Comment노드를 반환하며, data는 data입니다.
5. 범위(Ranges)
5.1. "DOM Ranges" 소개
StaticRange
와 Range 객체(범위(range))는
노드 트리(node tree) 내의
콘텐츠 시퀀스를 나타냅니다. 각 범위는 시작점(start)과 끝점(end)을 가지며,
이는 경계점(boundary
points)입니다. 경계점은
튜플(tuple)로,
노드와 오프셋(offset)으로 구성됩니다. 다시 말해,
범위(range)는 노드 트리 내에서 두
경계점 사이의 콘텐츠 조각을 나타냅니다.
범위(range)는 편집 시 콘텐츠 선택 및 복사 등에 자주 사용됩니다.
-
Element:p
위 노드 트리(node tree)에서
범위(range)를 사용해 “syndata is
awes”라는 시퀀스를 나타낼 수 있습니다. p가
p 엘리먼트에,
em이 em
엘리먼트에 할당되었다고 가정하면, 다음과
같이 구현할 수 있습니다:
var range = new Range(),
firstText = p. childNodes[ 1 ],
secondText = em. firstChild
range. setStart( firstText, 9 ) // do not forget the leading space
range. setEnd( secondText, 4 )
// range now stringifies to the aforementioned quote
속성(attribute)들(src, alt 등)은
위 노드 트리에서 범위(range)로 표현할 수 없습니다. 범위(range)는 오직 노드에만 적용됩니다.
Range 객체는
StaticRange
객체와 달리 노드 트리(node
tree)의 변화에 영향을 받습니다. 그래서 라이브 범위(live range)라고도 부릅니다. 이런 변화(mutation)가 발생해도 범위는 무효화되지 않고,
동일한 콘텐츠 부분을 나타내려고 시도합니다.
반드시 라이브 범위(live
range) 자체도 콘텐츠 일부가 변경될 때 노드 트리 변화에 따라 수정될 수 있습니다.
삽입(insert) 및 제거(remove) 알고리즘, normalize()
메서드, 그리고 replace
data와 split
알고리즘에 대한 세부 내용은 해당 부분을 참고하세요.
라이브 범위(live range)를
노드 트리의 변화에 따라 업데이트하는
작업은 비용이 많이 들 수 있습니다. 노드 트리의 변경마다 영향을 받는 모든 Range 객체를 업데이트해야 합니다.
애플리케이션이 어떤 라이브 범위에
관심이 없더라도, 변화가 있을 때 최신 상태를 유지하는 비용을 지불해야 합니다.
StaticRange
객체는 범위(range)의 경량 버전이며,
노드 트리(node tree)가 변해도
업데이트되지 않습니다. 그래서 라이브
범위와 같은 유지 비용이 발생하지 않습니다.
5.2. 경계점(boundary points)
경계점(boundary point)은 튜플(tuple)로, 노드(node) (노드)와 오프셋(offset) (0 이상의 정수)로 구성됩니다.
올바른 경계점(boundary point)의 오프셋(offset)은 0과 해당 경계점(boundary point)의 노드(node)의 길이(length) 사이(포함)입니다.
경계점의 위치(position)는 경계점(boundary point) (nodeA, offsetA)가 경계점(boundary point) (nodeB, offsetB)에 대해 이전(before), 동일(equal), 또는 이후(after)인지 반환하는 단계입니다:
-
Assert: nodeA와 nodeB는 같은 루트(root)를 가집니다.
- nodeA가 nodeB와 같다면, offsetA와 offsetB가 같으면 동일(equal), offsetA가 offsetB보다 작으면 이전(before), offsetA가 offsetB보다 크면 이후(after)를 반환합니다.
-
nodeA가 nodeB를 뒤따르는(following) 노드라면, (nodeB, offsetB)와 (nodeA, offsetA)의 위치(position)가 이전(before)이면 이후(after), 이후(after)면 이전(before)을 반환합니다.
-
nodeA가 nodeB의 조상(ancestor)이라면:
-
child를 nodeB로 설정합니다.
-
child가 nodeA의 자식(child)이 아니라면, child를 부모(parent)로 설정합니다.
-
child의 인덱스(index)가 offsetA보다 작으면 이후(after)를 반환합니다.
-
-
이전(before)을 반환합니다.
5.3. 인터페이스 AbstractRange
[Exposed =Window ]interface {AbstractRange readonly attribute Node startContainer ;readonly attribute unsigned long startOffset ;readonly attribute Node endContainer ;readonly attribute unsigned long endOffset ;readonly attribute boolean collapsed ; };
AbstractRange
인터페이스를 구현하는 객체는
범위(range)라고 합니다.
범위(range)는 두 개의 경계점(boundary point) — 시작(start)과 끝(end) — 을 가집니다.
편의를 위해, 범위(range)의 시작 노드(start node)는 시작(start)의 노드(node)이고, 시작 오프셋(start offset)은 시작(start)의 오프셋(offset)이며, 끝 노드(end node)는 끝(end)의 노드(node), 그리고 끝 오프셋(end offset)은 끝(end)의 오프셋(offset)입니다.
range가 collapsed 상태란, start node와 end node가 같고, start offset과 end offset도 같을 때를 의미한다.
node = range . startContainer- range의 시작 노드(start node)를 반환합니다.
offset = range . startOffset- range의 시작 오프셋(start offset)을 반환합니다.
node = range . endContainer- range의 끝 노드(end node)를 반환합니다.
offset = range . endOffset- range의 끝 오프셋(end offset)을 반환합니다.
collapsed = range . collapsed- range가 접힘(collapsed) 상태이면 true, 아니면 false를 반환합니다.
startContainer
getter 단계는 this의 start node를 반환하는 것이다.
startOffset
getter 단계는 this의 start offset을 반환하는 것이다.
endOffset
getter 단계는 this의 end offset을 반환하는 것이다.
5.4. 인터페이스 StaticRange
dictionary {StaticRangeInit required Node ;startContainer required unsigned long ;startOffset required Node ;endContainer required unsigned long ; }; [endOffset Exposed =Window ]interface :StaticRange AbstractRange {constructor (StaticRangeInit ); };init
staticRange = new StaticRange(init)-
노드 트리(node tree)가 변경되어도 업데이트되지 않는 새로운 범위(range) 객체를 반환합니다.
new StaticRange(init)
생성자 단계는 다음과 같습니다:
-
만약 init["
startContainer"] 또는 init["endContainer"]가DocumentType또는Attr노드라면, "InvalidNodeTypeError"DOMException예외를 발생시킨다. -
this의 start를 (init["
startContainer"], init["startOffset"])로 설정하고, end를 (init["endContainer"], init["endOffset"])로 설정한다.
StaticRange
객체가 유효함(valid)이란 아래 모든 조건을 만족할 때를 말합니다:
-
start offset이 0 이상이며, start node의 길이 이하임.
-
end offset이 0 이상이며, end node의 길이 이하임.
5.5. 인터페이스 Range
[Exposed =Window ]interface :Range AbstractRange {constructor ();readonly attribute Node commonAncestorContainer ;undefined setStart (Node ,node unsigned long );offset undefined setEnd (Node ,node unsigned long );offset undefined setStartBefore (Node );node undefined setStartAfter (Node );node undefined setEndBefore (Node );node undefined setEndAfter (Node );node undefined collapse (optional boolean =toStart false );undefined selectNode (Node );node undefined selectNodeContents (Node );node const unsigned short = 0;START_TO_START const unsigned short = 1;START_TO_END const unsigned short = 2;END_TO_END const unsigned short = 3;END_TO_START short compareBoundaryPoints (unsigned short ,how Range ); [sourceRange CEReactions ]undefined deleteContents (); [CEReactions ,NewObject ]DocumentFragment extractContents (); [CEReactions ,NewObject ]DocumentFragment cloneContents (); [CEReactions ]undefined insertNode (Node ); [node CEReactions ]undefined surroundContents (Node ); [newParent NewObject ]Range cloneRange ();undefined detach ();boolean isPointInRange (Node ,node unsigned long );offset short comparePoint (Node ,node unsigned long );offset boolean intersectsNode (Node );node stringifier ; };
Range 인터페이스를 구현하는 객체는
라이브 범위(live range)라고
합니다.
트리(tree)를 변경하는 알고리즘(특히 삽입(insert), 제거(remove), 이동(move), 데이터 교체(replace data), 그리고 분할(split) 알고리즘)은 해당 트리에 연결된 라이브 범위(live range)도 수정합니다.
루트(root)는 라이브 범위(live range)의 시작 노드(start node)의 루트(root)입니다.
노드 node가 live range range에 포함되어 있다고 하는 조건은, node의 root가 range의 root와 같고, (node, 0)이 range의 start보다 뒤이며, (node, node의 length)가 range의 end보다 앞일 때입니다.
노드가 부분적으로 포함됨 상태란, 해당 노드가 라이브 범위의 시작 노드의 포괄 조상이지만 끝 노드의 포괄 조상이 아니거나, 그 반대인 경우를 뜻합니다.
이 정의들을 더 잘 이해할 수 있도록 몇 가지 사실:
-
일반적으로 사람들이 라이브 범위 내에 있다고 생각하는 내용은 모두 포함됨 노드 + 경우에 따라
CharacterData노드인 시작 노드, 끝 노드의 일부 내용도 포함합니다. -
노드들는 라이브 범위에 포함되어 있을 때 일반적으로 연속적이지 않습니다, 왜냐하면 부모가 포함된 노드의 경우 항상 포함되는 것은 아니기 때문입니다.
-
그러나, 자손은 포함된 노드의 경우 포함됩니다. 그리고 두 형제가 포함되어 있다면, 그들 사이에 있는 어떤 형제들도 포함됩니다.
-
첫 번째 포함됨 노드(있다면)는 항상 시작 노드 다음에 위치하며, 마지막 포함됨 노드는 끝 노드의 마지막 후손 이전 또는 동일한 위치에 있습니다.
-
commonAncestorContainer속성 값은 포함됨이나 부분적으로 포함됨 상태가 아닙니다. -
만약 시작 노드가 끝 노드의 조상이라면, 공통 포괄 조상은 시작 노드가 되며, 그 자식 중 하나만 부분적으로 포함됨 상태가 되고, 포함됨인 자식은 그 부분적으로 포함됨 자식보다 앞에 위치한 경우에만 해당됩니다. 반대로 끝 노드가 시작 노드의 조상이라면 반대의 경우가 됩니다.
-
만약 시작 노드가 포괄적 조상이 아니고 끝 노드도 마찬가지라면, 공통 포괄적 조상은 그 둘과는 구별되는 별개의 노드가 됩니다. 그 공통 자식들 중 정확히 두 개가 부분적으로 포함되며, 어떤 자식이 포함되는 것은 오직 그 두 자식 사이에 있을 때에만 해당합니다.
라이브 범위 사전 제거 단계는 노드 node가 주어졌을 때 다음과 같습니다:
-
parent를 node의 부모로 설정합니다.
-
Assert: parent는 null이 아닙니다.
-
index를 node의 인덱스로 설정합니다.
-
node의 포괄적 후손이 start node인 라이브 범위 각각에 대해, 해당 범위의 start 값을 (parent, index)로 설정합니다.
-
node의 포괄적 후손이 end node인 라이브 범위 각각에 대해, 해당 범위의 end 값을 (parent, index)로 설정합니다.
-
parent가 start node이고 start offset이 index보다 큰 라이브 범위 각각에 대해, start offset 값을 1 감소시킵니다.
-
parent가 end node이고 end offset이 index보다 큰 라이브 범위 각각에 대해, end offset 값을 1 감소시킵니다.
range = new Range()- 새로운 live range를 반환합니다.
new Range() 생성자 단계는
this의 start와
end를
(현재 글로벌 객체의 연관 Document, 0)로 설정하는 것입니다.
- container = range .
commonAncestorContainer - 문서로부터 가장 멀리 떨어진, range의 start node와 end node 둘 다의 조상인 노드를 반환합니다.
commonAncestorContainer getter 단계는 다음과
같습니다:
-
container를 start node로 설정합니다.
-
container가 end node의 포함 조상이 아닐 동안, container를 container의 부모로 재설정합니다.
-
container를 반환합니다.
set the start or end 알고리즘은 range의 시작 또는 끝을 경계점(boundary point) (node, offset)으로 설정한다:
-
만약 node가 doctype이면, "
InvalidNodeTypeError"DOMException예외를 발생시킨다. -
만약 offset이 node의 길이보다 크면, "
IndexSizeError"DOMException예외를 발생시킨다. -
boundaryPoint를 (node, offset)인 경계점으로 설정한다.
-
- 이 단계가 "set the start"로 호출된 경우
-
-
만약 range의 root가 node의 root와 다르거나, boundaryPoint가 range의 end 이후이면, range의 end를 boundaryPoint로 설정한다.
-
range의 start를 boundaryPoint로 설정한다.
-
- 이 단계가 "set the end"로 호출된 경우
-
-
만약 range의 root가 node의 root와 다르거나, boundaryPoint가 range의 start 이전이면, range의 start를 boundaryPoint로 설정한다.
-
range의 end를 boundaryPoint로 설정한다.
-
setStart(node, offset) 메서드 단계는
set the start
알고리즘으로, this의 시작을 (node, offset)으로 설정한다.
setEnd(node, offset) 메서드 단계는
set the end
알고리즘으로, this의 끝을 (node, offset)으로 설정한다.
setStartBefore(node) 메서드 단계:
-
parent를 node의 부모로 한다.
-
만약 parent가 null이면, "
InvalidNodeTypeError"DOMException예외를 발생시킨다. -
set the start 알고리즘으로 this의 시작을 (parent, node의 index)로 설정한다.
setStartAfter(node) 메서드 단계:
-
parent를 node의 부모로 한다.
-
만약 parent가 null이면, "
InvalidNodeTypeError"DOMException예외를 발생시킨다. -
set the start 알고리즘으로 this의 시작을 (parent, node의 index + 1)로 설정한다.
setEndBefore(node) 메서드 단계:
-
parent를 node의 부모로 한다.
-
만약 parent가 null이면, "
InvalidNodeTypeError"DOMException예외를 발생시킨다. -
set the end 알고리즘으로 this의 끝을 (parent, node의 index)로 설정한다.
setEndAfter(node) 메서드 단계:
-
parent를 node의 부모로 한다.
-
만약 parent가 null이면, "
InvalidNodeTypeError"DOMException예외를 발생시킨다. -
set the end 알고리즘으로 this의 끝을 (parent, node의 index + 1)로 설정한다.
range에서 선택하려면, 노드 node를 range range 내에서 선택합니다:
-
parent를 node의 부모로 한다.
-
만약 parent가 null이면, "
InvalidNodeTypeError"DOMException예외를 발생시킨다. -
index를 node의 index로 설정한다.
-
range의 start를 boundary point (parent, index)로 설정한다.
-
range의 end를 boundary point (parent, index + 1)로 설정한다.
selectNodeContents(node) 메서드 단계:
-
만약 node가 doctype이면, "
InvalidNodeTypeError"DOMException예외를 발생시킨다. -
length를 node의 길이로 한다.
-
start를 (node, 0)인 boundary point로 설정한다.
-
end를 (node, length)인 boundary point로 설정한다.
compareBoundaryPoints(how, sourceRange)
메서드 단계는 다음과 같다:
-
how가 다음 중 하나가 아니라면
그렇지 않으면 throw "
NotSupportedError"DOMException예외를 던진다. -
this의 root가 sourceRange의 root와 다르다면, throw "
WrongDocumentError"DOMException예외를 던진다. -
thisPoint와 sourcePoint를 null로 둔다.
-
how에 따라 다음을 수행한다:
START_TO_START:-
thisPoint를 this의 start로, sourcePoint를 sourceRange의 start로 설정한다.
START_TO_END:-
thisPoint를 this의 end로, sourcePoint를 sourceRange의 start로 설정한다.
END_TO_END:END_TO_START:-
thisPoint를 this의 start로, sourcePoint를 sourceRange의 end로 설정한다.
-
thisPoint가 sourcePoint와 상대적으로 갖는 position에 따라 다음을 수행한다:
deleteContents() 메서드의 단계:
-
originalStartNode, originalStartOffset, originalEndNode, originalEndOffset를 각각 this의 start node, start offset, end node, end offset로 설정합니다.
-
originalStartNode가 originalEndNode와 동일하며,
CharacterData노드인 경우:-
데이터 교체(replace data)를 originalStartNode에 대해 originalStartOffset, originalEndOffset − originalStartOffset, 빈 문자열로 실행합니다.
-
반환합니다.
-
-
nodesToRemove를 노드들 중 이 범위에 포함된 것만(부모가 범위 내에 포함된 노드는 생략), 트리 순서로 나열한 리스트로 저장합니다.
-
newNode와 newOffset을 null로 설정합니다.
-
originalStartNode가 포괄적 조상이라면, newNode를 originalStartNode로, newOffset을 originalStartOffset로 설정합니다.
-
그 외의 경우:
-
originalStartNode가
CharacterData노드라면, 데이터 교체를 originalStartNode에 대해 originalStartOffset, (originalStartNode의 length − originalStartOffset), 빈 문자열로 실행합니다. -
nodesToRemove의 각 node에 대해(트리 순서로): remove node를 실행합니다.
-
originalEndNode가
CharacterData노드라면, 데이터 교체를 originalEndNode에 대해 0, originalEndOffset, 빈 문자열로 실행합니다.
extract 라이브 범위 range의 단계:
-
fragment를 새로운
DocumentFragment노드(노드 문서는 range의 start node의 node document)로 설정합니다. -
range가 collapsed라면 fragment를 반환합니다.
-
originalStartNode, originalStartOffset, originalEndNode, originalEndOffset를 각각 range의 start node, start offset, end node, end offset로 설정합니다.
-
originalStartNode가 originalEndNode와 같고,
CharacterData노드일 경우:-
clone을 clone originalStartNode로 설정합니다.
-
clone의 data를 substringing data(originalStartNode, originalStartOffset, originalEndOffset − originalStartOffset) 결과로 설정합니다.
-
append로 clone을 fragment에 추가합니다.
-
데이터 교체(originalStartNode, originalStartOffset, originalEndOffset − originalStartOffset, 빈 문자열)를 실행합니다.
-
fragment를 반환합니다.
-
-
commonAncestor를 originalStartNode로 설정합니다.
-
commonAncestor가 originalEndNode의 포괄적 조상이 아니면, commonAncestor를 자신의 부모로 반복하여 설정합니다.
-
firstPartiallyContainedChild를 null로 설정합니다.
-
originalStartNode가 originalEndNode의 포괄적 조상이 아니면, firstPartiallyContainedChild를 commonAncestor의 자식 중 부분적으로 포함됨인 첫 번째로 설정합니다.
-
lastPartiallyContainedChild를 null로 설정합니다.
-
originalEndNode가 originalStartNode의 포괄적 조상이 아니면, lastPartiallyContainedChild를 commonAncestor의 자식 중 부분적으로 포함됨인 마지막으로 설정합니다.
이 변수 할당은 실제로 항상 타당합니다. 예를 들어, originalStartNode가 originalEndNode의 포괄적 조상이 아닌 경우, originalStartNode가 부분적으로 포함된 노드가 되고, commonAncestor의 자식까지 그 조상들이 모두 해당될 수 있습니다. 두 자식 변수가 모두 있을 때 서로 동일하지 않습니다.
-
containedChildren를 commonAncestor의 자식 중 range에 포함됨인 모든 것(트리 순서로) 리스트로 저장합니다.
-
containedChildren에 doctype이 포함되어 있으면, "
HierarchyRequestError"DOMException을 throw합니다.doctype은 부분적으로 포함될 수 없으므로 처음과 마지막 부분적으로 포함된 노드에 대해 걱정할 필요가 없습니다. 경계점에 위치할 수 없으며, 어떤 것의 조상이 될 수도 없습니다.
-
newNode와 newOffset을 null로 설정합니다.
-
originalStartNode가 originalEndNode의 포괄적 조상이면, newNode를 originalStartNode로, newOffset을 originalStartOffset로 설정합니다.
-
그 외의 경우:
-
referenceNode를 originalStartNode로 설정합니다.
-
referenceNode의 부모가 null이 아니고 originalEndNode의 포괄적 조상이 아니면, referenceNode를 referenceNode의 부모로 변경하는 것을 반복합니다.
-
newNode를 referenceNode의 부모로, newOffset을 referenceNode의 index + 1로 설정합니다.
만약 referenceNode의 부모가 null이면, 이는 range의 root가 되고, originalEndNode의 포괄적 조상이 되어 이 지점에 도달하지 않음.
-
-
firstPartiallyContainedChild가
CharacterData노드라면:이 경우 firstPartiallyContainedChild는 originalStartNode입니다.
-
clone을 clone originalStartNode로 설정합니다.
-
clone의 data를 substringing data(originalStartNode, originalStartOffset, originalStartNode의 length − originalStartOffset) 결과로 설정합니다.
-
append clone을 fragment에 추가합니다.
-
데이터 교체(originalStartNode, originalStartOffset, (originalStartNode의 length−originalStartOffset), 빈 문자열)를 실행합니다.
-
-
그 외, firstPartiallyContainedChild가 null이 아니면:
-
clone을 clone firstPartiallyContainedChild로 설정합니다.
-
append clone을 fragment에 추가합니다.
-
subrange를 새로운 live range로서 (originalStartNode, originalStartOffset)가 시작, (firstPartiallyContainedChild, firstPartiallyContainedChild의 length)가 종료이게 생성합니다.
-
subfragment를 extract subrange 결과로 설정합니다.
-
append subfragment를 clone에 추가합니다.
-
-
containedChildren의 각 contained child에 대해: append contained child를 fragment에 추가합니다.
-
lastPartiallyContainedChild가
CharacterData노드라면:이 경우 lastPartiallyContainedChild는 originalEndNode입니다.
-
clone을 clone originalEndNode로 설정합니다.
-
clone의 data를 substringing data(originalEndNode, 0, originalEndOffset) 결과로 설정합니다.
-
append clone을 fragment에 추가합니다.
-
데이터 교체(originalEndNode, 0, originalEndOffset, 빈 문자열)을 실행합니다.
-
-
그 외, lastPartiallyContainedChild가 null이 아니면:
-
clone을 clone lastPartiallyContainedChild로 설정합니다.
-
append clone을 fragment에 추가합니다.
-
subrange를 새로운 live range로서 (lastPartiallyContainedChild, 0)이 시작, (originalEndNode, originalEndOffset)이 종료가 되게 생성합니다.
-
subfragment를 extract subrange 결과로 설정합니다.
-
append subfragment를 clone에 추가합니다.
-
-
fragment를 반환합니다.
클론 내용 라이브 범위 range의 내용을 클론하기:
-
fragment를 새로운
DocumentFragment노드로, range의 start node의 node document를 가지고 생성합니다. -
range가 collapsed이면 fragment를 반환합니다.
-
originalStartNode, originalStartOffset, originalEndNode, originalEndOffset는 각각 range의 start node, start offset, end node, end offset입니다.
-
originalStartNode가 originalEndNode와 같고
CharacterData노드일 때:-
clone = clone(originalStartNode)
-
clone의 data를 substringing data(originalStartNode, originalStartOffset, originalEndOffset − originalStartOffset)로 설정합니다.
-
append(fragment, clone)
-
fragment를 반환합니다.
-
-
commonAncestor = originalStartNode
-
commonAncestor가 originalEndNode의 포괄 조상이 아닐 때, commonAncestor를 자신의 parent로 반복 설정
-
firstPartiallyContainedChild = null
-
originalStartNode가 originalEndNode의 포괄 조상이 아닌 경우 firstPartiallyContainedChild를 commonAncestor의 child 중 부분적으로 포함된 첫 번째로 설정
-
lastPartiallyContainedChild = null
-
originalEndNode가 originalStartNode의 포괄 조상이 아닌 경우 lastPartiallyContainedChild를 commonAncestor의 child 중 부분적으로 포함된 마지막으로 설정
위 변수 할당은 항상 논리적으로 맞습니다. 두 자식이 모두 정의되어 있을 때 같지 않습니다.
-
containedChildren = commonAncestor의 child 중 range에 포함된 모든 노드(트리 순서)
-
containedChildren 중 doctype이 있으면, "
HierarchyRequestError"DOMExceptionthrowdoctype은 부분적으로 포함될 수 없으므로 경계 걱정할 필요 없음
-
firstPartiallyContainedChild가
CharacterData노드일 경우:이 경우 firstPartiallyContainedChild == originalStartNode
-
clone = clone(originalStartNode)
-
clone의 data 를 substringing data(originalStartNode, originalStartOffset, originalStartNode의 length - originalStartOffset)로 설정
-
append(fragment, clone)
-
-
그 외 firstPartiallyContainedChild가 null이 아니면:
-
containedChildren의 각 contained child에 대해:
-
lastPartiallyContainedChild가
CharacterData노드일 경우:이 경우 lastPartiallyContainedChild == originalEndNode
-
clone = clone(originalEndNode)
-
clone의 data를 substringing data(originalEndNode, 0, originalEndOffset)로 설정
-
append(fragment, clone)
-
-
그 외 lastPartiallyContainedChild가 null이 아니면:
-
clone = clone(lastPartiallyContainedChild)
-
append(fragment, clone)
-
subrange = 새로운 live range(lastPartiallyContainedChild, 0 부터 originalEndNode, originalEndOffset까지)
-
subfragment = 범위 클론(subrange)
-
append(clone, subfragment)
-
-
fragment를 반환합니다.
삽입 노드 node를 라이브 범위 range에 삽입하기:
-
range의 start node가
ProcessingInstruction또는Comment노드이거나,Text노드 (그 parent가 null), 혹은 node라면 "HierarchyRequestError"DOMException을 throw합니다. -
referenceNode = null로 설정합니다.
-
range의 start node가
Text노드라면 referenceNode를 그 노드로 설정합니다. -
그 외의 경우, referenceNode를 range의 start node의 child 중 index가 range의 start offset인 노드(있으면 그 값, 없으면 null)로 설정합니다.
-
parent를 referenceNode가 null이면 range의 start node로, 아니면 referenceNode의 parent로 설정합니다.
-
Ensure pre-insert validity를 node를 parent에 referenceNode 앞에 넣는 경우에 대해 실행합니다.
-
range의 start node가
Text노드인 경우, offset은 range의 start offset을 사용하여 split 알고리즘(split)으로 referenceNode를 재설정합니다. -
node가 referenceNode와 같으면 referenceNode를 next sibling으로 설정합니다.
-
newOffset = parent의 length (만약 referenceNode가 null), 아니면 referenceNode의 index
-
node가
DocumentFragment노드이면 newOffset에 node의 length를 더하고, 아니면 1을 더합니다. -
pre-insert(node, parent, referenceNode) 실행합니다.
surroundContents(newParent) 메서드 단계는
다음과 같습니다:
-
비-
Text노드가 부분적으로 포함됨 상태로 this에 있으면, "InvalidStateError"DOMException을 throw합니다. -
newParent가
Document,DocumentType,DocumentFragment노드이면, "InvalidNodeTypeError"DOMException을 throw합니다.호환성 이유로
CharacterData노드는 여기서 체크하지 않으며, 이후 다른 곳에서 예외가 발생할 수 있습니다. -
fragment를 extracting this의 결과로 설정합니다.
-
newParent에 자식이 있다면, replace all을 null 값으로 실행하여 newParent 안의 자식을 모두 지웁니다.
-
Append로 fragment를 newParent에 추가합니다.
cloneRange() 메서드 단계는
live range를 하나
새로 만들되,
start와 end가 this와
동일하도록 한다.
detach() 메서드 단계는 아무 작업도 하지 않는다.
이 기능( Range 객체 비활성화)은
삭제되었고, 메서드만 호환성의 이유로 남아 있다.
- position = range .
comparePoint(node, offset) - 지정한 위치가 range 이전이면 −1, 범위 안이면 0, range 이후라면 1을 반환합니다.
- intersects = range .
intersectsNode(node) - range가 node와 교차하는지 여부를 반환합니다.
isPointInRange(node, offset)
메서드 단계는 다음과 같다:
-
node가 doctype이면, throw "
InvalidNodeTypeError"DOMException예외를 던진다. -
offset이 node의 length보다 크면, throw "
IndexSizeError"DOMException예외를 던진다. -
true를 반환한다.
comparePoint(node, offset)
메서드 단계는 다음과 같다:
-
node의 root가 this의 root와 다르면, throw "
WrongDocumentError"DOMException예외를 던진다. -
node가 doctype이면, throw "
InvalidNodeTypeError"DOMException예외를 던진다. -
offset이 node의 length보다 크면, throw "
IndexSizeError"DOMException예외를 던진다. -
(node, offset)이 start 앞이면 −1을 반환한다.
-
(node, offset)이 end 뒤면 1을 반환한다.
-
0을 반환한다.
intersectsNode(node) 메서드 단계는 다음과 같다:
문자열화 동작은 다음 단계들을 실행해야 합니다:
-
string을 빈 문자열로 설정합니다.
-
this의 start node가 this의 end node와 같고, 그것이
Text노드라면, 해당Text노드의 data를 this의 start offset부터 this의 end offset 이전까지의 부분 문자열로 반환합니다. -
this의 start node가
Text노드라면, 해당 노드의 data에서 this의 start offset부터 끝까지의 부분 문자열을 string에 추가합니다. -
연결(concatenate)된 값, 즉 data들의 조합을
Text노드 중에서 this에 포함된(Contained) 것을 트리 순서로 합쳐 string에 추가합니다. -
this의 end node가
Text노드라면, 해당 노드의 data 시작부터 this의 end offset까지의 부분 문자열을 string에 추가합니다. -
string을 반환합니다.
createContextualFragment(),
getClientRects(),
그리고 getBoundingClientRect()
메서드는 다른 명세에서 정의되어 있다.
[DOM-Parsing]
[CSSOM-VIEW]
6. 트래버설(Traversal)
NodeIterator와
TreeWalker
객체는 노드 트리를 필터링하고 순회하는 데 사용할 수 있습니다.
각 NodeIterator와
TreeWalker
객체에는
재귀적 호출을 방지하기 위한 부울 is active 값이 연결돼 있습니다. 초기 값은 false입니다.
각 NodeIterator와
TreeWalker
객체에는
root (노드), whatToShow (비트마스크), filter (콜백) 값들도 연결돼 있습니다.
필터링: NodeIterator
또는 TreeWalker
객체 traverser에서 노드 node를 필터링하려면:
-
traverser의 is active가 true라면, "
InvalidStateError"DOMException을 throw합니다. -
n을 node의
nodeType값에서 1을 뺀 값으로 설정합니다. -
traverser의 whatToShow에서 n번째 비트(0이 최하위 비트)가 설정되어 있지 않으면,
FILTER_SKIP을 반환합니다. -
traverser의 filter가 null이면,
FILTER_ACCEPT을 반환합니다. -
traverser의 is active를 true로 설정합니다.
-
result를 call a user object’s operation으로 traverser의 filter, "acceptNode", « node »를 호출한 반환값으로 설정합니다. 이때 예외가 발생하면 traverser의 is active를 false로 설정한 뒤 예외를 다시 throw합니다.
-
traverser의 is active를 false로 설정합니다.
-
result를 반환합니다.
6.1. 인터페이스 NodeIterator
[Exposed =Window ]interface { [NodeIterator SameObject ]readonly attribute Node root ;readonly attribute Node referenceNode ;readonly attribute boolean pointerBeforeReferenceNode ;readonly attribute unsigned long whatToShow ;readonly attribute NodeFilter ?filter ;Node ?nextNode ();Node ?previousNode ();undefined detach (); };
NodeIterator
객체는 Document
객체의 createNodeIterator()
메서드를 통해 생성할 수 있습니다.
각 NodeIterator
객체에는 iterator collection이 연관되어 있습니다. 이것은 NodeIterator
객체의 root에
기반한 collection이며,
필터는 어떤 노드에도 일치합니다.
각 NodeIterator
객체에는 reference (노드)와 pointer before
reference (불리언)이 연관되어 있습니다.
앞서 언급한 것처럼, NodeIterator
객체에는 is
active,
root,
whatToShow,
filter
값도 연관되어 있습니다.
NodeIterator 사전 제거 단계는 NodeIterator
객체 nodeIterator와 노드 toBeRemovedNode가 주어졌을 때:
-
만약 toBeRemovedNode가 nodeIterator의 reference의 포괄 조상이 아니거나, toBeRemovedNode가 nodeIterator의 root이면, 반환합니다.
-
만약 nodeIterator의 pointer before reference가 true라면:
-
nodeIterator의 reference를 toBeRemovedNode의 parent(만약 toBeRemovedNode의 previous sibling이 null이면)로, 아니면 toBeRemovedNode의 previous sibling의 포괄적 후손 중 트리 순서로 마지막에 나오는 노드로 설정합니다.
pointerBeforeReferenceNode
getter의 단계는
this의 pointer before reference를 반환합니다.
whatToShow getter의 단계는
this의 whatToShow를 반환합니다.
traverse: NodeIterator
객체 iterator와 "next" 또는 "previous" type이 주어졌을 때:
-
node를 iterator의 reference로 설정합니다.
-
beforeNode를 iterator의 pointer before reference로 설정합니다.
-
while (true):
-
type이 "
next"면:-
beforeNode가 false이면 node를 iterator의 iterator collection에서 node의 첫 번째 following 노드로 설정합니다(없으면 null).
-
beforeNode가 true이면 false로 설정합니다.
-
-
그 외의 경우:
-
beforeNode가 true이면 node를 iterator의 iterator collection에서 node의 첫 번째 preceding 노드로 설정합니다(없으면 null).
-
beforeNode가 false이면 true로 설정합니다.
-
-
result를 필터링 (node, iterator) 결과로 설정합니다.
-
result가
FILTER_ACCEPT라면 break 합니다.
-
-
iterator의 reference를 node로 설정합니다.
-
iterator의 pointer before reference를 beforeNode로 설정합니다.
-
node를 반환합니다.
detach() 메서드 단계는 아무것도 하지 않습니다.
이 기능(NodeIterator
객체의 비활성화)은 삭제되었으나, 메서드 자체는 호환성을 위해 남아 있습니다.
6.2. 인터페이스 TreeWalker
[Exposed =Window ]interface { [TreeWalker SameObject ]readonly attribute Node root ;readonly attribute unsigned long whatToShow ;readonly attribute NodeFilter ?filter ;attribute Node currentNode ;Node ?parentNode ();Node ?firstChild ();Node ?lastChild ();Node ?previousSibling ();Node ?nextSibling ();Node ?previousNode ();Node ?nextNode (); };
TreeWalker
객체는 createTreeWalker()
메서드를 Document
객체에서 사용하여 생성할 수 있습니다.
각 TreeWalker
객체는 current라는 연결된 값(하나의
노드)을 가집니다.
앞서 언급했듯이, TreeWalker
객체는
root,
whatToShow,
filter
속성을 가지고 있습니다.
whatToShow getter 단계는
this의
whatToShow를 반환한다.
currentNode
setter 단계는 this의
current를 주어진 값으로
설정한다.
parentNode() 메서드 단계는 다음과 같다:
자식 노드 탐색(traverse children)은
TreeWalker
객체 walker와 "first" 또는 "last" type이 주어졌을 때:
-
node를 walker의 current로 둔다.
-
node를 type이 "
first"이면 node의 first child로, 아니면 node의 last child로 설정한다. -
node가 null이 아닐 동안 반복한다:
-
result를 filtering node in walker의 결과로 한다.
-
result가
FILTER_ACCEPT이면, walker의 current를 node로 하고 node를 반환한다. -
result가
FILTER_SKIP이면:-
child를 type이 "
first"이면 node의 first child로, 아니면 node의 last child로 한다. -
child가 null이 아니면, node를 child로 하고 계속한다.
-
-
node가 null이 아니라면 다음을 반복한다:
-
sibling을 type이 "
first"이면 node의 next sibling으로, 아니면 node의 previous sibling으로 설정한다. -
sibling이 null이 아니면, node를 sibling으로 하고 반복 종료한다.
-
parent를 node의 parent로 한다.
-
parent가 null이거나, walker의 root이거나, walker의 current라면 null을 반환한다.
-
node를 parent로 한다.
-
-
-
null을 반환한다.
형제 노드
탐색(traverse siblings)은 TreeWalker
객체 walker와 "next" 또는 "previous" type이 주어졌을 때:
-
node를 walker의 current로 한다.
-
node가 root라면, null을 반환한다.
-
다음이 참인 동안 반복한다:
-
sibling을 type이 "
next"이면 node의 next sibling으로, 아니면 node의 previous sibling으로 한다. -
sibling이 null이 아닌 동안 반복한다:
-
node를 sibling으로 한다.
-
result를 filtering node in walker의 결과로 한다.
-
result가
FILTER_ACCEPT라면, walker의 current를 node로 하고 node를 반환한다. -
sibling을 type이 "
next"라면 node의 first child로, 아니면 node의 last child로 설정한다. -
result이
FILTER_REJECT거나 sibling이 null일 경우, sibling을 type이 "next"이면 node의 next sibling으로, 아니면 node의 previous sibling으로 설정한다.
-
-
node를 node의 parent로 한다.
-
node가 null이거나 walker의 root라면, null을 반환한다.
-
filtering node in walker의 반환값이
FILTER_ACCEPT라면, null을 반환한다.
-
previousNode() 메서드 단계는 다음과 같다:
-
-
sibling을 node의 previous sibling으로 한다.
-
sibling이 null이 아닌 동안 반복한다:
-
node를 sibling으로 한다.
-
result가
FILTER_REJECT가 아니고 node에 child가 있다면:-
node를 node의 last child로 한다.
-
-
result가
FILTER_ACCEPT라면, this의 current를 node로 하고 node를 반환한다. -
sibling을 node의 previous sibling으로 한다.
-
-
node를 node의 parent로 한다.
-
filtering node in this의 반환값이
FILTER_ACCEPT라면, this의 current를 node로 하고 node를 반환한다.
-
-
null을 반환한다.
nextNode() 메서드 단계는 다음과 같다:
-
result를
FILTER_ACCEPT로 둔다. -
다음이 참인 동안 반복한다:
-
result가
FILTER_REJECT가 아니고 node에 child가 있다면:-
node를 자신의 first child로 한다.
-
result가
FILTER_ACCEPT라면, this의 current를 node로 하고 node를 반환한다.
-
-
sibling을 null로 둔다.
-
temporary를 node로 둔다.
-
temporary가 null이 아닌 동안 반복한다:
-
sibling을 temporary의 next sibling으로 한다.
-
sibling이 null이 아니면, node를 sibling으로 하고 반복 종료한다.
-
temporary를 temporary의 parent로 한다.
-
result가
FILTER_ACCEPT라면, this의 current를 node로 하고 node를 반환한다.
-
6.3. 인터페이스 NodeFilter
[Exposed =Window ]callback interface { // Constants for acceptNode()NodeFilter const unsigned short FILTER_ACCEPT = 1;const unsigned short FILTER_REJECT = 2;const unsigned short FILTER_SKIP = 3; // Constants for whatToShowconst unsigned long SHOW_ALL = 0xFFFFFFFF;const unsigned long SHOW_ELEMENT = 0x1;const unsigned long SHOW_ATTRIBUTE = 0x2;const unsigned long SHOW_TEXT = 0x4;const unsigned long SHOW_CDATA_SECTION = 0x8;const unsigned long = 0x10; // legacySHOW_ENTITY_REFERENCE const unsigned long = 0x20; // legacySHOW_ENTITY const unsigned long SHOW_PROCESSING_INSTRUCTION = 0x40;const unsigned long SHOW_COMMENT = 0x80;const unsigned long SHOW_DOCUMENT = 0x100;const unsigned long SHOW_DOCUMENT_TYPE = 0x200;const unsigned long SHOW_DOCUMENT_FRAGMENT = 0x400;const unsigned long = 0x800; // legacySHOW_NOTATION unsigned short (acceptNode Node ); };node
NodeFilter
객체는 필터로서
NodeIterator
및 TreeWalker
객체에 사용할 수 있고,
whatToShow 비트마스크 상수를 제공합니다. NodeFilter
객체는 일반적으로 자바스크립트 함수로 구현됩니다.
이 상수들은 filter(필터) 반환값으로 사용할 수 있습니다:
FILTER_ACCEPT(1);FILTER_REJECT(2);FILTER_SKIP(3);
이 상수들은 whatToShow에 사용할 수 있습니다:
SHOW_ALL(4294967295, 16진수로 FFFFFFFF);SHOW_ELEMENT(1);SHOW_ATTRIBUTE(2);SHOW_TEXT(4);SHOW_CDATA_SECTION(8);SHOW_PROCESSING_INSTRUCTION(64, 16진수로 40);SHOW_COMMENT(128, 16진수로 80);SHOW_DOCUMENT(256, 16진수로 100);SHOW_DOCUMENT_TYPE(512, 16진수로 200);SHOW_DOCUMENT_FRAGMENT(1024, 16진수로 400);
7. 집합(Sets)
예, DOMTokenList
라는 이름은 유감스러운 레거시 오류입니다.
7.1. 인터페이스 DOMTokenList
[Exposed =Window ]interface {DOMTokenList readonly attribute unsigned long length ;getter DOMString ?item (unsigned long );index boolean contains (DOMString ); [token CEReactions ]undefined add (DOMString ...); [tokens CEReactions ]undefined remove (DOMString ...); [tokens CEReactions ]boolean toggle (DOMString ,token optional boolean ); [force CEReactions ]boolean replace (DOMString ,token DOMString );newToken boolean supports (DOMString ); [token CEReactions ]stringifier attribute DOMString value ;iterable <DOMString >; };
DOMTokenList
객체는 연관된
토큰 집합
(집합)을
가지며, 최초에는 비어 있습니다.
DOMTokenList
객체는 또한 연관된 엘리먼트
(엘리먼트)와
속성 이름
(속성의
로컬
이름)을 가집니다.
명세는
지원되는 토큰을
DOMTokenList의
엘리먼트와
속성
이름에
대해 정의할 수 있습니다.
DOMTokenList
객체 set의
검증 절차는
지정된 token에 대해 아래와 같습니다:
DOMTokenList
객체 set의
갱신 절차는 아래와 같습니다:
-
이름공간과 로컬 이름으로 속성 가져오기를 null, set의 속성 이름, set의 엘리먼트로 호출한 결과가 null이고 set의 토큰 집합이 비어 있다면, 반환합니다.
-
속성 값 설정을 set의 엘리먼트, set의 속성 이름, 순서 있는 집합 직렬화기를 set의 토큰 집합에 실행한 결과로 호출합니다.
DOMTokenList
객체 set의
직렬화 절차는
속성 값 가져오기를
set의 엘리먼트와
set의 속성 이름을 인자로 실행한 결과를 반환하는 것입니다.
DOMTokenList
객체 set은
속성 변경 절차를
set의 엘리먼트에 대해 가집니다:
DOMTokenList
객체 set이 생성될 때:
-
tokenlist .length -
토큰의 개수를 반환한다.
-
tokenlist .item(index)tokenlist[index] -
index에 해당하는 토큰을 반환한다.
-
tokenlist .contains(token) -
token이 있으면 true, 없으면 false를 반환한다.
-
tokenlist . add(tokens…) -
이미 포함된 것을 제외하고 인자로 받은 모든 토큰을 추가한다.
인자 중 하나가 빈 문자열이면 "
SyntaxError"DOMException을 던진다.인자 중 하나에 ASCII 공백이 포함되어 있다면 "
InvalidCharacterError"DOMException을 던진다. -
tokenlist . remove(tokens…) -
인자로 받은 토큰이 있으면 제거한다.
인자 중 하나가 빈 문자열이면 "
SyntaxError"DOMException을 던진다.인자 중 하나에 ASCII 공백이 포함되어 있다면 "
InvalidCharacterError"DOMException을 던진다. -
tokenlist . toggle(token [, force]) -
force가 주어지지 않았다면 token이 있으면 제거하고, 없으면 추가한다. force가 true이면 token을 추가(즉,
add()와 동일)한다. force가 false이면 token을 제거한다(즉,remove()와 동일).추가/제거 후 token이 있으면 true, 없으면 false를 반환한다.
token이 빈 문자열이면 "
SyntaxError"DOMException을 던진다.token에 공백이 포함되어 있으면 "
InvalidCharacterError"DOMException을 던진다. -
tokenlist . replace(token, newToken) -
token을 newToken으로 교체한다.
token이 newToken으로 교체되면 true, 그렇지 않으면 false를 반환한다.
인자 중 하나가 빈 문자열이면 "
SyntaxError"DOMException을 던진다.인자 중 하나에 ASCII 공백이 포함되어 있다면 "
InvalidCharacterError"DOMException을 던진다. -
tokenlist . supports(token) -
token이 연관된 attribute의 supported tokens에 있으면 true, 아니면 false를 반환한다.
연관된 attribute에 supported tokens가 정의되어 있지 않으면
TypeError를 던진다. -
tokenlist .value -
연관된 set을 문자열로 반환한다.
값을 설정하면 연관된 attribute가 변경된다.
객체의 지원되는 속성 인덱스는 0에서 객체의 토큰 집합의 크기 - 1 까지의 숫자이다. 단, 토큰 집합이 비어 있다면 지원되는 속성 인덱스가 존재하지 않는다.
add(tokens…)
메서드 단계는 다음과 같다:
-
각 token (in tokens)에 대해:
-
token이 빈 문자열이면 "SyntaxError"
SyntaxErrorDOMException을 던진다. -
token이 ASCII 공백을 포함하면 "InvalidCharacterError"
InvalidCharacterErrorDOMException을 던진다.
-
-
각 token (in tokens)에 대해: append token을 this의 token set에 추가한다.
-
update steps를 실행한다.
remove(tokens…)
메서드 단계는 다음과 같다:
-
각 token (in tokens)에 대해:
-
token이 빈 문자열이면 "SyntaxError"
SyntaxErrorDOMException을 던진다. -
token이 ASCII 공백을 포함하면 "InvalidCharacterError"
InvalidCharacterErrorDOMException을 던진다.
-
-
각 token (in tokens)에 대해: remove token을 this의 token set에서 제거한다.
-
update steps를 실행한다.
toggle(token, force)
메서드 단계는 다음과 같다:
-
token이 빈 문자열이면 "SyntaxError"
SyntaxErrorDOMException을 던진다. -
token이 ASCII 공백을 포함하면 "InvalidCharacterError"
InvalidCharacterErrorDOMException을 던진다. -
-
force가 주어지지 않았거나 false이면 remove token을 this의 token set에서 제거하고, update steps를 실행한 후 false를 반환한다.
-
true를 반환한다.
-
-
그렇지 않고 force가 주어지지 않았거나 true이면 append token을 this의 token set에 추가하고, update steps를 실행한 후 true를 반환한다.
-
false를 반환한다.
update steps는 웹 호환성을
위해 toggle()에
항상 실행되지 않는다.
replace(token, newToken)
메서드 단계는 다음과 같다:
-
token 또는 newToken이 빈 문자열이면 "SyntaxError"
SyntaxErrorDOMException을 던진다. -
token 또는 newToken이 ASCII 공백을 포함하면 "InvalidCharacterError"
InvalidCharacterErrorDOMException을 던진다. -
update steps를 실행한다.
-
true를 반환한다.
update steps는 웹 호환성을
위해 replace()에
항상 실행되지 않는다.
supports(token)
메서드 단계는 다음과 같다:
-
result를 validation steps를 token으로 호출한 반환값으로 둔다.
-
result를 반환한다.
value getter 단계는
this의 serialize
steps의 결과를 반환한다.
value setter 단계는
set an attribute value를 this의 element,
this의
attribute name과 주어진 값으로 실행하는 것이다.
8. XPath
DOM Level 3 XPath는 XPath 1.0 표현식을 평가하는 API를 정의했습니다. 이 API들은 널리 구현되어 있지만 유지 관리되고 있지 않습니다. 인터페이스 정의는 Web IDL이 변경될 때 업데이트할 수 있도록 여기에서 유지되고 있습니다. 이러한 API의 전체 정의는 여전히 필요하며, 관련 작업은 whatwg/dom#67에서 추적 및 기여할 수 있습니다. [DOM-Level-3-XPath] [XPath] [WEBIDL]
8.1. 인터페이스 XPathResult
[Exposed =Window ]interface {XPathResult const unsigned short = 0;ANY_TYPE const unsigned short = 1;NUMBER_TYPE const unsigned short = 2;STRING_TYPE const unsigned short = 3;BOOLEAN_TYPE const unsigned short = 4;UNORDERED_NODE_ITERATOR_TYPE const unsigned short = 5;ORDERED_NODE_ITERATOR_TYPE const unsigned short = 6;UNORDERED_NODE_SNAPSHOT_TYPE const unsigned short = 7;ORDERED_NODE_SNAPSHOT_TYPE const unsigned short = 8;ANY_UNORDERED_NODE_TYPE const unsigned short = 9;FIRST_ORDERED_NODE_TYPE readonly attribute unsigned short ;resultType readonly attribute unrestricted double ;numberValue readonly attribute DOMString ;stringValue readonly attribute boolean ;booleanValue readonly attribute Node ?;singleNodeValue readonly attribute boolean ;invalidIteratorState readonly attribute unsigned long ;snapshotLength Node ?();iterateNext Node ?(snapshotItem unsigned long ); };index
8.2.
인터페이스 XPathExpression
[Exposed =Window ]interface { // XPathResult.ANY_TYPE = 0XPathExpression XPathResult (evaluate Node ,contextNode optional unsigned short = 0,type optional XPathResult ?=result null ); };
8.3. 믹스인 XPathEvaluatorBase
callback interface {XPathNSResolver DOMString ?(lookupNamespaceURI DOMString ?); };prefix interface mixin { [XPathEvaluatorBase NewObject ]XPathExpression (createExpression DOMString ,expression optional XPathNSResolver ?=resolver null );Node createNSResolver (Node ); // legacy // XPathResult.ANY_TYPE = 0nodeResolver XPathResult (evaluate DOMString ,expression Node ,contextNode optional XPathNSResolver ?=resolver null ,optional unsigned short = 0,type optional XPathResult ?=result null ); };Document includes XPathEvaluatorBase ;
createNSResolver(nodeResolver)
메서드의 단계는 nodeResolver를 반환하는 것입니다.
이 메서드는 오직 역사적 이유로 존재합니다.
8.4. 인터페이스 XPathEvaluator
[Exposed =Window ]interface {XPathEvaluator (); };constructor XPathEvaluator includes XPathEvaluatorBase ;
역사적 이유로 XPathEvaluator를
직접 생성하거나,
Document에서 동일한
메서드에 접근할 수 있습니다.
9. XSLT
XSL Transformations (XSLT)는 XML 문서를 다른 XML 문서로 변환하는 언어입니다. 이 섹션에서 정의된 API는 널리 구현되어 있으며, Web IDL이 변경될 때 업데이트될 수 있도록 이곳에서 유지 관리됩니다. 이러한 API의 전체 정의는 여전히 필요하며, 관련 작업은 whatwg/dom#181에서 추적 및 기여할 수 있습니다. [XSLT]
9.1. 인터페이스 XSLTProcessor
[Exposed =Window ]interface {XSLTProcessor ();constructor undefined (importStylesheet Node ); [style CEReactions ]DocumentFragment (transformToFragment Node ,source Document ); [output CEReactions ]Document (transformToDocument Node );source undefined ([setParameter LegacyNullToEmptyString ]DOMString ,namespaceURI DOMString ,localName any );value any ([getParameter LegacyNullToEmptyString ]DOMString ,namespaceURI DOMString );localName undefined ([removeParameter LegacyNullToEmptyString ]DOMString ,namespaceURI DOMString );localName undefined ();clearParameters undefined (); };reset
10. 보안 및 개인정보 보호 고려 사항
이 표준에는 알려진 보안 또는 개인정보 보호 고려 사항이 없습니다.
11. 과거(Historical)
이 표준에는 제거된 여러 인터페이스와 인터페이스 멤버가 있었습니다.
아래 인터페이스들이 제거되었습니다:
DOMConfigurationDOMErrorDOMErrorHandlerDOMImplementationListDOMImplementationSourceDOMLocatorDOMObjectDOMUserDataEntityEntityReferenceMutationEventMutationNameEventNameListNotationRangeExceptionTypeInfoUserDataHandler
그리고 아래 인터페이스 멤버들이 제거되었습니다:
Attr-
schemaTypeInfoisId
Document-
createEntityReference()xmlEncodingxmlStandalonexmlVersionstrictErrorCheckingdomConfignormalizeDocument()renameNode()
DocumentType-
entitiesnotationsinternalSubset
DOMImplementation-
getFeature()
Element-
schemaTypeInfosetIdAttribute()setIdAttributeNS()setIdAttributeNode()
Node-
isSupportedgetFeature()getUserData()setUserData()
NodeIterator-
expandEntityReferences
Text-
isElementContentWhitespacereplaceWholeText()
TreeWalker-
expandEntityReferences
감사의 글
DOM의 상호운용성을 높이고 이 표준의 목표를 발전시키는 데 수많은 사람들이 오랜 세월 동안 도움을 주었습니다. 마찬가지로, 오늘날 이 표준이 이 자리에 오기까지 많은 분들이 기여해 주셨습니다.
이에 감사의 마음을 전합니다: Adam Klein, Adrian Bateman, Ahmid snuggs, Alex Komoroske, Alex Russell, Alexey Shvayka, Andreas Kling, Andreu Botella, Anthony Ramine, Arkadiusz Michalski, Arnaud Le Hors, Arun Ranganathan, Benjamin Gruenbaum, Björn Höhrmann, Boris Zbarsky, Brandon Payton, Brandon Slade, Brandon Wallace, Brian Kardell, C. Scott Ananian, Cameron McCormack, Chris Dumez, Chris Paris, Chris Rebert, Cyrille Tuzi, Dan Burzo, Daniel Clark, Daniel Glazman, Darien Maillet Valentine, Darin Fisher, David Baron, David Bruant, David Flanagan, David Håsäther, David Hyatt, Deepak Sherveghar, Dethe Elza, Dimitri Glazkov, Domenic Denicola, Dominic Cooney, Dominique Hazaël-Massieux, Don Jordan, Doug Schepers, Edgar Chen, Elisée Maurer, Elliott Sprehn, Emilio Cobos Álvarez, Eric Bidelman, Erik Arvidsson, François Daoust, François Remy, Gary Kacmarcik, Gavin Nicol, Giorgio Liscio, Glen Huang, Glenn Adams, Glenn Maynard, Hajime Morrita, Harald Alvestrand, Hayato Ito, Henri Sivonen, Hongchan Choi, Hunan Rostomyan, Ian Hickson, Igor Bukanov, Jacob Rossi, Jake Archibald, Jake Verbaten, James Graham, James Greene, James M Snell, James Robinson, Jayson Chen, Jeffrey Yasskin, Jens Lindström, Jeremy Davis, Jesse McCarthy, Jinho Bang, João Eiras, Joe Kesselman, John Atkins, John Dai, Jonas Sicking, Jonathan Kingston, Jonathan Robie, Joris van der Wel, Joshua Bell, J. S. Choi, Jungkee Song, Justin Summerlin, Kagami Sascha Rosylight, 呂康豪 (Kang-Hao Lu), 田村健人 (Kent TAMURA), Kevin J. Sung, Kevin Sweeney, Kirill Topolyan, Koji Ishii, Lachlan Hunt, Lauren Wood, Luca Casonato, Luke Zielinski, Magne Andersson, Majid Valipour, Malte Ubl, Manish Goregaokar, Manish Tripathi, Marcos Caceres, Mark Miller, Martijn van der Ven, Mason Freed, Mats Palmgren, Mounir Lamouri, Michael Stramel, Michael™ Smith, Mike Champion, Mike Taylor, Mike West, Nicolás Peña Moreno, Nidhi Jaju, Ojan Vafai, Oliver Nightingale, Olli Pettay, Ondřej Žára, Peter Sharpe, Philip Jägenstedt, Philippe Le Hégaret, Piers Wombwell, Pierre-Marie Dartus, prosody—Gab Vereable Context(, Rafael Weinstein, Rakina Zata Amni, Richard Bradshaw, Rick Byers, Rick Waldron, Robbert Broersma, Robin Berjon, Roland Steiner, Rune F. Halvorsen, Russell Bicknell, Ruud Steltenpool, Ryosuke Niwa, Sam Dutton, Sam Sneddon, Samuel Giles, Sanket Joshi, Scott Haseley, Sebastian Mayr, Seo Sanghyeon, Sergey G. Grekhov, Shiki Okasaka, Shinya Kawanaka, Simon Pieters, Simon Wülker, Stef Busking, Steve Byrne, Stig Halvorsen, Tab Atkins, Takashi Sakamoto, Takayoshi Kochi, Theresa O’Connor, Theodore Dubois, timeless, Timo Tijhof, Tobie Langel, Tom Pixley, Travis Leithead, Trevor Rowbotham, triple-underscore, Tristan Fraipont, Veli Şenol, Vidur Apparao, Warren He, Xidorn Quan, Yash Handa, Yehuda Katz, Yoav Weiss, Yoichi Osato, Yoshinori Sano, Yu Han, Yusuke Abe, and Zack Weinberg 여러분 모두 정말 훌륭합니다!
이 표준은 Anne van Kesteren (Apple, annevk@annevk.nl) 그리고 Aryeh Gregor(ayg@aryeh.name), Ms2ger(ms2ger@gmail.com)의 큰 기여로 작성되었습니다.
지적재산권(Intellectual property rights)
Copyright © WHATWG (Apple, Google, Mozilla, Microsoft). 이 저작물은 크리에이티브 커먼즈 저작자표시 4.0 국제 라이선스에 따라 이용할 수 있습니다. 일부가 소스 코드에 통합되는 경우, 해당 부분은 BSD 3-Clause License로 소스 코드에 적용됩니다.
이 문서는 Living Standard입니다. 특허 심사 버전에 관심 있는 분들은 Living Standard Review Draft를 참고하세요.