JavaScript의 document.head 속성이란?
JavaScript에서 document.head 속성을 사용하면 현재 문서의 <head> 태그 요소에 직접 접근할 수 있습니다. 이 속성은 HTMLHeadElement 객체를 반환하며, 이를 통해 head 요소의 id, 자식 노드 등 다양한 속성과 메서드를 활용할 수 있습니다.
예를 들어, document.head.id를 사용하면 <head> 태그에 설정된 id 값을 손쉽게 가져올 수 있습니다.
document.head 사용 예제
아래 코드는 document.head 속성을 활용하여 head 요소의 id를 출력하는 간단한 예제입니다.
<!DOCTYPE html>
<html>
<head id = "myid">
<title>JavaScript Example</title>
</head>
<body>
<h1>Employee Information</h1>
<form>
Name: <input type = "text" name = "name" value = "Amit"><br>
Subject: <input type = "text" name = "sub" value = "Java">
</form>
<script>
var a = document.head.id;
document.write("<br>Head element id? "+a);
</script>
</body>
</html>
코드 설명
<head> 태그에는 id="myid"가 지정되어 있습니다. 스크립트 부분에서 document.head.id를 호출하면 해당 id 값인 myid가 반환되며, document.write()를 통해 화면에 출력됩니다.
document.head 속성의 특징
- 읽기 전용: document.head 속성은 읽기 전용으로, 반환된 head 요소의 내용은 표준 DOM 메서드로 수정할 수 있습니다.
- 브라우저 호환성: Chrome, Firefox, Safari, Edge 등 주요 최신 브라우저와 Internet Explorer 9 이상에서 지원됩니다.
- 활용 사례: 동적으로
<meta>,<style>,<link>태그를 추가하거나 수정할 때 유용하게 사용됩니다.
이처럼 document.head 속성은 문서의 head 영역에 프로그래밍 방식으로 접근해야 할 때 매우 편리한 도구입니다.