Computer >> 컴퓨터 >  >> 프로그래밍 >> HTML

HTML DOM ownerDocument 속성 완벽 정리: 노드의 소유 문서 확인하기

HTML DOM의 ownerDocument 속성은 특정 노드가 속해 있는 소유 문서(owner document)를 나타내는 Document 객체를 반환합니다. 이 속성을 활용하면 어떤 노드가 현재 어느 문서에 소속되어 있는지 쉽게 확인할 수 있습니다.

문법(Syntax)

ownerDocument 속성의 기본 문법은 다음과 같습니다.

node.ownerDocument

예제(Example)

ownerDocument 속성의 동작 방식을 확인할 수 있는 예제 코드입니다.

<!DOCTYPE html>
<html>
<head>
<style>
   html{
      height:100%;
   }
   body{
      text-align:center;
      color:#fff;
      background: #ff7f5094;
      height:100%;
   }
   p{
      font-weight:700;
      font-size:1.2rem;
   }
   .btn{
      background:#0197F6;
      border:none;
      height:2rem;
      border-radius:2px;
      width:35%;
      margin:2rem auto;
      display:block;
      color:#fff;
      outline:none;
      cursor:pointer;
   }
   .show{
      font-size:1.5rem;
   }
</style>
</head>
<body>
<h1>DOM ownerDocument 속성 데모</h1>
<p>이 파란색 버튼의 소유자는 누구일까요?</p>
<button onclick="showOwner()" class="btn">소유자 확인</button>
<div class="show"></div>
<script>
   function showOwner() {
      document.querySelector(".show").innerHTML=document.querySelector(".btn").ownerDocument.nodeName
   }
</script>
</body>
</html>

실행 결과(Output)

위 코드를 실행하면 다음과 같은 화면이 출력됩니다.

HTML DOM ownerDocument 속성 완벽 정리: 노드의 소유 문서 확인하기

“소유자 확인(Get Owner)” 버튼을 클릭하면 ownerDocument 속성이 어떻게 동작하는지 결과를 확인할 수 있습니다.

HTML DOM ownerDocument 속성 완벽 정리: 노드의 소유 문서 확인하기

정리

ownerDocument 속성은 읽기 전용(read-only) 속성으로, 노드 자체가 문서 노드(document node)인 경우에는 null을 반환합니다. 버튼 클릭 시 ownerDocument.nodeName을 출력하면 해당 노드가 속한 문서의 노드 이름인 #document가 표시되는 것을 확인할 수 있습니다. 이 속성은 특히 여러 문서(예: iframe) 간에 노드를 이동하거나 참조할 때 유용하게 활용됩니다.